content
stringlengths 5
1.05M
|
---|
import numpy as np
def get_random_int():
return np.random.randn(10) |
# Dr. Kaputa
# pyqt pong example
import sys
from PyQt4 import QtGui, QtCore
class Pong(QtGui.QMainWindow):
Key_K = QtCore.pyqtSignal()
Key_M = QtCore.pyqtSignal()
Key_A = QtCore.pyqtSignal()
Key_Z = QtCore.pyqtSignal()
def __init__(self):
super(Pong, self).__init__()
self.statusBar().showMessage('Ready')
self.setWindowIcon(QtGui.QIcon('cool.jpg'))
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtGui.qApp.quit)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
self.hLayout = QtGui.QHBoxLayout()
self.leftScorebox = QtGui.QLabel("0")
self.rightScorebox = QtGui.QLabel("0")
self.rightScorebox.setAlignment(QtCore.Qt.AlignRight);
self.startButton = QtGui.QPushButton("Start")
self.hLayout.addWidget(self.leftScorebox)
self.hLayout.addWidget(self.startButton)
self.hLayout.addWidget(self.rightScorebox)
self.dockFrame = QtGui.QFrame()
self.dockFrame.setLayout(self.hLayout)
self.dock = QtGui.QDockWidget(self)
self.dock.setWidget(self.dockFrame)
self.addDockWidget(QtCore.Qt.DockWidgetArea(4), self.dock)
self.dock.setWindowTitle("Controls")
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.leftScore = 0
self.rightScore = 0
self.board = Board(self)
self.vLayout = QtGui.QVBoxLayout()
self.vLayout.addWidget(self.board)
self.frame = QtGui.QFrame(self)
self.frame.setLayout(self.vLayout)
self.setCentralWidget(self.frame)
self.setWindowTitle("Pong")
self.showMaximized()
self.show()
styleFile ="styleSheet.txt"
with open(styleFile,"r") as fh:
self.setStyleSheet(fh.read())
self.startButton.clicked.connect(lambda: self.board.startGame())
def keyPressEvent(self, event):
key = event.key()
if key == QtCore.Qt.Key_K:
self.Key_K.emit()
elif key == QtCore.Qt.Key_M:
self.Key_M.emit()
elif key == QtCore.Qt.Key_A:
self.Key_A.emit()
elif key == QtCore.Qt.Key_Z:
self.Key_Z.emit()
def updateScore(self,val):
if (val == 2):
self.leftScore = self.leftScore + 1
self.leftScorebox.setText(str(self.leftScore))
elif (val == 1):
self.rightScore = self.rightScore + 1
self.rightScorebox.setText(str(self.rightScore))
class Paddle(QtGui.QGraphicsItem):
def __init__(self,boardWidth,boardHeight):
super(Paddle, self).__init__()
self.color = QtGui.QColor(0,0,255)
self.boardWidth = boardWidth
self.boardHeight = boardHeight
def boundingRect(self):
return QtCore.QRectF(0,0,20,100)
def paint(self, painter, option, widget):
painter.setBrush(self.color)
painter.drawRect(0,0,20,100)
def moveDown(self):
y = self.y()
if (y < self.boardHeight - 100):
self.moveBy(0,50)
def moveUp(self):
y = self.y()
if (y > 0):
self.moveBy(0,-50)
class Ball(QtGui.QGraphicsItem):
def __init__(self,parent,boardWidth,boardHeight):
super(Ball, self).__init__()
self.color = QtGui.QColor(0,0,255)
self.xVel = 10
self.yVel = 5
self.ballWidth = 20
self.ballHeight = 20
self.boardWidth = boardWidth
self.boardHeight = boardHeight
self.parent = parent
def boundingRect(self):
return QtCore.QRectF(-self.ballWidth/2,-self.ballHeight/2,self.ballWidth,self.ballHeight)
def paint(self, painter, option, widget):
painter.setBrush(self.color)
painter.drawEllipse(-self.ballWidth/2,-self.ballHeight/2,self.ballWidth,self.ballHeight)
def reflectX(self):
self.xVel = self.xVel * -1
def reflectY(self):
self.yVel = self.yVel * -1
def move(self):
self.setX(self.x() + self.xVel)
if (self.x() >= self.boardWidth - self.ballWidth/2):
return 2
elif (self.x() <= self.ballWidth/2):
return 1
self.setY(self.y() + self.yVel)
if (self.y() >= self.boardHeight - self.ballHeight/2):
self.reflectY()
elif (self.y() <= self.ballHeight/2):
self.reflectY()
if self.collidesWithItem(self.parent.leftPaddle):
self.reflectX()
if self.collidesWithItem(self.parent.rightPaddle):
self.reflectX()
return 0
class Board(QtGui.QGraphicsView):
def __init__(self,parent):
super(Board, self).__init__()
self.parent = parent
self.scene = QtGui.QGraphicsScene(self)
self.setScene(self.scene)
self.setBackgroundBrush(QtGui.QBrush(QtGui.QPixmap('cool.jpg')))
self.boardWidth = 1000
self.boardHeight = 1000
# effectively sets the logical scene coordinates from 0,0 to 1000,1000
myFrame = self.scene.addRect(0,0,self.boardWidth,self.boardHeight)
self.leftPaddle = Paddle(self.boardWidth,self.boardHeight)
self.rightPaddle = Paddle(self.boardWidth,self.boardHeight)
self.ball = Ball(self,self.boardWidth,self.boardHeight)
self.scene.addItem(self.leftPaddle)
self.scene.addItem(self.rightPaddle)
self.scene.addItem(self.ball)
self.timer = QtCore.QBasicTimer()
self.leftPaddle.setPos(0,0)
self.rightPaddle.setPos(980,100)
self.ball.setPos(500,500)
self.parent.Key_M.connect(self.rightPaddle.moveDown)
self.parent.Key_K.connect(self.rightPaddle.moveUp)
self.parent.Key_Z.connect(self.leftPaddle.moveDown)
self.parent.Key_A.connect(self.leftPaddle.moveUp)
def startGame(self):
self.status = 0
self.ball.setPos(500,500)
self.timer.start(17, self)
def timerEvent(self, event):
if (self.status == 0):
self.status = self.ball.move()
else:
self.timer.stop()
self.parent.updateScore(self.status)
def resizeEvent(self, event):
super(Board, self).resizeEvent(event)
self.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio)
def main():
app = QtGui.QApplication(sys.argv)
app.setFont(QtGui.QFont("Helvetica", 10))
pong = Pong()
sys.exit(app.exec_())
if __name__ == '__main__':
main() |
from .face_analysis import *
|
# encoding: utf-8
import argparse
import qtciutil
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Build Arg Parser')
parser.add_argument('--pro_file', '-p', type=str, required=True,
help='pro path', metavar='$CI_PROJECT_DIR/test/something.pro')
parser.add_argument('--build_dir', '-b', type=str, required=True,
help='build directory', metavar='$CI_PROJECT_DIR/build')
parser.add_argument('--dist_dir', '-d', type=str, required=True,
help='dist directory', metavar='$CI_PROJECT_DIR/dist')
args = vars(parser.parse_args())
pro_file = args['pro_file']
build_dir = args['build_dir']
dist_dir = args['dist_dir']
qtciutil.unit_test(pro_file, build_dir, dist_dir)
# python test.py -p F:/workspace/l2m2/xxx/test/test.pro -b F:/workspace/l2m2/xxx/test/build -d F:/workspace/l2m2/xxx/dist |
import fenics as fe
import numpy as np
import matplotlib.pyplot as plt
import sys
plt.rcParams.update({'font.size': 12})
def matMult(A,x):
''' Multiply a 2by2 matrix with a 2by1 vector '''
return [ A[0][0]*x[0]+A[0][1]*x[1] , A[1][0]*x[0] + A[1][1]*x[1] ]
def prettyPrint(A):
''' Print arrays in a pretty way '''
import pandas as pd
pd.set_option("display.precision",8)
Table = pd.DataFrame(A)
Table.columns = ['']*Table.shape[1]
print(Table.to_string(index=False))
def str2lst(strs):
''' Convert a string of comma delimited numbers into a list of those numbers '''
lst = []
for s in strs.strip().split(","):
try:
lst.append(int(s))
except:
lst.append(float(s))
return lst
|
salario = 750
aumento = 15
print(salario + (salario*aumento/100)) |
import requests
import pandas as pd
# Runtime notes: ~8000 objects takes ~30 secs, ~65000 takes several minutes, 150k+ takes 10+ minutes
shop = 'YOUR SHOP NAME HERE' # Shop is what your shop is called in your homepage URL. EG. Shop called MyShop would be myshop.myshopify.com. Shop name = myshop
token = 'YOUR API PASSWORD HERE' # Token is the API Password
def getCustomerInfo():
headers = {
'Content-Type': 'application/json', # Need to tell the API that it is application/json
'X-Shopify-Access-Token': f'{token}',
}
# In the data variable we tell the Graphql request what exactly we want. In this case we want all the customers IDs, Emails, and the phone which can be located as a normal field or under the address property. Resources: https://shopify.dev/api/admin/graphql/reference
data = '''
mutation {
bulkOperationRunQuery(
query: """
{
customers(first: 10){
edges {
node {
id
email
phone
addresses {
phone
}
}
}
}
}
"""
) {
bulkOperation {
id
status
}
userErrors {
field
message
}
}
}
'''
response = requests.post(f'https://{shop}.myshopify.com/admin/api/2019-07/graphql.json', json={'query': data}, headers=headers)
return response.json()
def checkBulkStatus():
headers = {
'Content-Type': 'application/json', # Need to tell the API that it is application/json
'X-Shopify-Access-Token': f'{token}',
}
data = '''
query {
currentBulkOperation {
id
status
errorCode
createdAt
completedAt
objectCount
fileSize
url
partialDataUrl
}
}
'''
response = requests.post(f'https://{shop}.myshopify.com/admin/api/2019-07/graphql.json', json={'query': data}, headers=headers)
return response.json()
# Below here we are beginning our bulk operation with the Initializer, it will come back as a dict with a length of 2. We print off the ID and the status at the end.
bulkOperationInitializer = (getCustomerInfo())
print(bulkOperationInitializer['data']['bulkOperationRunQuery'])
# Here we are running the check of our bulk operation. It will also be a dict with the length of 2. We also print out the Status of the operation and the URL we will follow to get our JSON
bulkOperationCheck=(checkBulkStatus())
print(bulkOperationCheck['data']['currentBulkOperation']['status'])
print(bulkOperationCheck['data']['currentBulkOperation']['url'])
# # We need to follow the link that the bulk operation gives us. Download that link, and then put it into the folder where this application is located. Change the file path to match yours including the file name of the .jsonl file
efJSON = 'THE LOCATION OF THE DOWNLOADED FILE HERE' # Change to match json file name
df = pd.read_json(efJSON, lines = True)
print(df)
df['id'] = df['id'].str.replace('gid://shopify/Customer/', '') # Remove the gid added infront of the ID field
df.to_csv('THE NAME OF THE EXPORT FILE HERE', encoding='utf-8', index=False) # Here we create our csv file with the data we pulled, change the .csv name here to whatever you want to call the CSV
|
from typing import List
import pytest
from di import Container, Dependant, SyncExecutor
from di.typing import Annotated
class Request:
def __init__(self, value: int = 0) -> None:
self.value = value
def endpoint(r: Request) -> int:
return r.value
def test_bind():
container = Container()
class Test:
def __init__(self, v: int = 1) -> None:
self.v = v
dependant = Dependant(Test)
with container.enter_scope(None):
res = container.execute_sync(
container.solve(dependant), executor=SyncExecutor()
)
assert res.v == 1
with container.bind_by_type(Dependant(lambda: Test(2)), Test):
with container.enter_scope(None):
res = container.execute_sync(
container.solve(dependant), executor=SyncExecutor()
)
assert res.v == 2
with container.enter_scope(None):
res = container.execute_sync(
container.solve(dependant), executor=SyncExecutor()
)
assert res.v == 1
def test_bind_transitive_dependency_results_skips_subdpendencies():
"""If we bind a transitive dependency none of it's sub-dependencies should be executed
since they are no longer required.
"""
def raises_exception() -> None:
raise ValueError
def transitive(_: Annotated[None, Dependant(raises_exception)]) -> None:
...
def dep(t: Annotated[None, Dependant(transitive)]) -> None:
...
container = Container()
with container.enter_scope(None):
# we get an error from raises_exception
with pytest.raises(ValueError):
container.execute_sync(
container.solve(Dependant(dep)), executor=SyncExecutor()
)
# we bind a non-error provider and re-execute, now raises_exception
# should not execute at all
def not_error() -> None:
...
with container.bind_by_type(Dependant(not_error), transitive):
with container.enter_scope(None):
container.execute_sync(
container.solve(Dependant(dep)), executor=SyncExecutor()
)
# and this reverts when the bind exits
with container.enter_scope(None):
with pytest.raises(ValueError):
container.execute_sync(
container.solve(Dependant(dep)), executor=SyncExecutor()
)
def test_bind_with_dependencies():
"""When we bind a new dependant, we resolve it's dependencies as well"""
def return_one() -> int:
return 1
def return_two(one: Annotated[int, Dependant(return_one)]) -> int:
return one + 1
def return_three(one: Annotated[int, Dependant(return_one)]) -> int:
return one + 2
def return_four(two: Annotated[int, Dependant(return_two)]) -> int:
return two + 2
container = Container()
with container.enter_scope(None):
assert (
container.execute_sync(
container.solve(Dependant(return_four)), executor=SyncExecutor()
)
) == 4
container.register_bind_hook(
lambda param, dependant: None
if dependant.call is not return_two
else Dependant(return_three)
)
with container.enter_scope(None):
val = container.execute_sync(
container.solve(Dependant(return_four)), executor=SyncExecutor()
)
assert val == 5
def test_bind_covariant() -> None:
class Animal:
pass
class Dog(Animal):
pass
container = Container()
container.bind_by_type(
Dependant(lambda: Dog()),
Animal,
covariant=True,
)
# include a generic to make sure we are safe with
# isisntance checks and MRO checks
def dep(animal: Animal, generic: Annotated[List[int], Dependant(list)]) -> Animal:
return animal
solved = container.solve(Dependant(dep))
with container.enter_scope(None):
instance = container.execute_sync(solved, executor=SyncExecutor())
assert isinstance(instance, Dog)
|
arq = open("maneiro.txt", "r")
conteudo = arq.read()
for i in conteudo:
print(i, sep="", end="")
arq.close()
arq2 = open("maneirasso.txt", "w+")
arq2.write("Gororoba azul")
arq2.seek(0)
conteudo2 = arq2.read()
print("")
for i in conteudo2:
print(i, sep="", end="")
arq2.close()
|
from libctw import ctw
def create_model(deterministic=False, max_depth=None, num_factors=8):
cts = []
for i in xrange(num_factors):
cts.append(ctw.create_model(deterministic, max_depth))
return _Factored(cts)
def create_factored_model(bit_models):
"""Creates a factored model.
Bits on different positions will be predicted
by different models.
"""
return _Factored(bit_models)
class _Factored:
def __init__(self, cts):
self.cts = cts
self.offset = 0
def see_generated(self, bits):
for bit in bits:
for i, ct in enumerate(self.cts):
if i != self.offset:
ct.see_added([bit])
try:
self.cts[self.offset].see_generated([bit])
except ctw.ImpossibleHistoryError:
raise
finally:
self.offset = (self.offset + 1) % len(self.cts)
def see_added(self, bits):
for ct in self.cts:
ct.see_added(bits)
def predict_one(self):
return self.cts[self.offset].predict_one()
def switch_history(self):
self.offset = 0
for ct in self.cts:
ct.switch_history()
def revert_generated(self, num_bits):
for ignored in xrange(num_bits):
self.offset = (self.offset - 1) % len(self.cts)
for i, ct in enumerate(self.cts):
if i == self.offset:
ct.revert_generated(1)
else:
ct.revert_added(1)
def get_history_log_p(self):
return sum(ct.get_history_log_p() for ct in self.cts)
|
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.analytics_azure_output import AnalyticsAzureOutput
from bitmovin_api_sdk.models.response_envelope import ResponseEnvelope
from bitmovin_api_sdk.models.response_error import ResponseError
from bitmovin_api_sdk.analytics.outputs.azure.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.analytics.outputs.azure.analytics_azure_output_list_query_params import AnalyticsAzureOutputListQueryParams
class AzureApi(BaseApi):
@poscheck_except(2)
def __init__(self, api_key, tenant_org_id=None, base_url=None, logger=None):
# type: (str, str, str, BitmovinApiLoggerBase) -> None
super(AzureApi, self).__init__(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_url=base_url,
logger=logger
)
self.customdata = CustomdataApi(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_url=base_url,
logger=logger
)
def create(self, analytics_azure_output, **kwargs):
# type: (AnalyticsAzureOutput, dict) -> AnalyticsAzureOutput
"""Create Microsoft Azure Output
:param analytics_azure_output: The Microsoft Azure output to be created
:type analytics_azure_output: AnalyticsAzureOutput, required
:return: Microsoft Azure output
:rtype: AnalyticsAzureOutput
"""
return self.api_client.post(
'/analytics/outputs/azure',
analytics_azure_output,
type=AnalyticsAzureOutput,
**kwargs
)
def delete(self, output_id, **kwargs):
# type: (string_types, dict) -> AnalyticsAzureOutput
"""Delete Microsoft Azure Output
:param output_id: Id of the output
:type output_id: string_types, required
:return: Id of the output
:rtype: AnalyticsAzureOutput
"""
return self.api_client.delete(
'/analytics/outputs/azure/{output_id}',
path_params={'output_id': output_id},
type=AnalyticsAzureOutput,
**kwargs
)
def get(self, output_id, **kwargs):
# type: (string_types, dict) -> AnalyticsAzureOutput
"""Microsoft Azure Output Details
:param output_id: Id of the output
:type output_id: string_types, required
:return: Microsoft Azure output
:rtype: AnalyticsAzureOutput
"""
return self.api_client.get(
'/analytics/outputs/azure/{output_id}',
path_params={'output_id': output_id},
type=AnalyticsAzureOutput,
**kwargs
)
def list(self, query_params=None, **kwargs):
# type: (AnalyticsAzureOutputListQueryParams, dict) -> AnalyticsAzureOutput
"""List Microsoft Azure Outputs
:param query_params: Query parameters
:type query_params: AnalyticsAzureOutputListQueryParams
:return: List of Microsoft Azure outputs
:rtype: AnalyticsAzureOutput
"""
return self.api_client.get(
'/analytics/outputs/azure',
query_params=query_params,
pagination_response=True,
type=AnalyticsAzureOutput,
**kwargs
)
|
order = balanced.Order.fetch(order_href) |
from build.management.commands.build_complex_models import Command as BuildComplexModels
class Command(BuildComplexModels):
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Convert a Zettelkasten into a Setevi HTML page """
import os
import sys
from libzk2setevi.convert import Zk2Setevi
def is_valid_file(parser, arg):
arg = os.path.abspath(arg)
if not os.path.exists(arg):
parser.error("The path %s does not exist!" % arg)
else:
return arg
def get_parser():
"""Get parser object for script xy.py."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("input_folder",
type=lambda x: is_valid_file(parser, x),
help="Input: your Zettelkasten folder",
)
parser.add_argument("output_folder",
type=lambda x: is_valid_file(parser, x),
help="Output: Folder to write output HTML to",
)
parser.add_argument("-b", "--bibfile",
dest="bibfile",
type=lambda x: is_valid_file(parser, x),
help=".bib file to use for citations if none is in your Zettelkasten folder",
metavar="FILE")
parser.add_argument("-e", '--extension',
dest="extension",
default='.md',
type=str,
help="extension of your markdown files")
parser.add_argument("-l", '--linkstyle',
dest="linkstyle",
default='double',
choices=['single', 'double', '§'],
type=str,
help="link style: double=[[link]], single=[link], §=§link")
parser.add_argument("-p", '--parser',
dest="parser",
default='mmd',
type=str,
help="markdown parser: mmd=internal Multimarkdown, pandoc=pandoc, native=native")
parser.add_argument("-u", '--url',
dest="baseurl",
type=str,
default='',
help="Remote URL the HTML should be built for")
parser.add_argument('--from',
dest="timestamp_from",
type=str,
default='19000101',
metavar='FROM',
help="(optionally abbreviated) timestamp from: include only notes that are not younger than FROM")
parser.add_argument('--to',
dest="timestamp_until",
type=str,
default='22001231',
metavar='TO',
help="(optionally abbreviated) timestamp to: include only notes that are not older than TO")
parser.add_argument('--only-tags',
dest="tags_white",
type=str,
default='',
metavar='ONLY_TAGLIST',
help="only include notes tagged with tags from ONLY_TAGLIST")
parser.add_argument('--never-tags',
dest="tags_black",
type=str,
default='',
metavar='NEVER_TAGLIST',
help="never include notes tagged with tags from ONLY_TAGLIST")
return parser
argparser = get_parser()
if len(sys.argv) == 1:
argparser.print_help()
sys.exit()
args = get_parser().parse_args()
# try to find out our home
if getattr(sys, 'frozen', False):
# we are running in a bundle
if sys.platform == 'darwin':
# cx_freeze
bundle_dir = os.path.dirname(sys.executable)
else:
# pyinstaller
bundle_dir = sys._MEIPASS
else:
# we are running in a normal Python environment
bundle_dir = os.path.dirname(os.path.abspath(__file__))
converter = Zk2Setevi(home=bundle_dir, folder=args.input_folder, out_folder=args.output_folder,
bibfile=args.bibfile, extension=args.extension,
linkstyle=args.linkstyle, parser=args.parser, base_url=args.baseurl,
timestamp_from=args.timestamp_from, timestamp_until=args.timestamp_until,
white_tags=args.tags_white, black_tags=args.tags_black)
converter.create_html()
|
import pickle
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.simplefilter("ignore")
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from ..data.utils import get_public_df_ohe, get_train_df_ohe, get_class_names, are_all_imgs_present
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--obvious-staining", action='store_true')
parser.add_argument("--n-folds", default=5, type=int)
args = parser.parse_args()
OBVIOUS_STAINING_FLAG = args.obvious_staining
with open(f'input/negs_with_{"obvious_" if OBVIOUS_STAINING_FLAG else ""}staining_public.pkl', 'rb') as f:
negs_with_staining_pub = pickle.load(f)
negs_with_staining_pub_ids = {img_id_mask_i.split('__')[0] for img_id_mask_i in negs_with_staining_pub}
with open(f'input/negs_with_{"obvious_" if OBVIOUS_STAINING_FLAG else ""}staining.pkl', 'rb') as f:
negs_with_staining = pickle.load(f)
negs_with_staining_ids = {img_id_mask_i.split('__')[0] for img_id_mask_i in negs_with_staining}
train_df = get_train_df_ohe()
if OBVIOUS_STAINING_FLAG:
train_df = train_df[(train_df['Negative'] == 0) | train_df['ID'].isin(negs_with_staining_ids)]
img_paths_train = list(train_df['img_base_path'].values)
basepath_2_ohe_vector = {img:np.concatenate((vec, np.array([0]))) for img, vec in zip(train_df['img_base_path'], train_df.iloc[:, 2:].values)}
public_hpa_df_17 = get_public_df_ohe()
if OBVIOUS_STAINING_FLAG:
public_hpa_df_17 = public_hpa_df_17[(public_hpa_df_17['Negative'] == 0) | public_hpa_df_17['ID'].isin(negs_with_staining_pub_ids)]
public_basepath_2_ohe_vector = {img_path:np.concatenate((vec, np.array([1]))) for img_path, vec in zip(public_hpa_df_17['img_base_path'],
public_hpa_df_17.iloc[:, 2:].values)}
basepath_2_ohe_vector.update(public_basepath_2_ohe_vector)
# print(len(basepath_2_ohe_vector))
# basepath_2_ohe_vector = {key: val for key, val in basepath_2_ohe_vector.items() if are_all_imgs_present(key)}
# print(len(basepath_2_ohe_vector))
class_names = get_class_names()
all_labels = np.array(list(basepath_2_ohe_vector.values()))
sns.set(style="whitegrid")
plt.figure(figsize=(12, 6))
class_counts = all_labels.sum(axis=0)
class_counts = pd.DataFrame({'Label': class_names + ['public data'], 'Number of Images': class_counts})
g = sns.barplot(x="Label", y="Number of Images",
data=class_counts)
for item in g.get_xticklabels():
item.set_rotation(90)
item.set_fontsize(12)
g.set_title('Train Images', fontsize=24)
g.set_xlabel('Class', fontsize=17)
g.set_ylabel('Number of Images', fontsize=17)
plt.savefig(f'output/image_level_labels{"_obvious_staining" if OBVIOUS_STAINING_FLAG else ""}.png')
# splitting
label_combinations = list(basepath_2_ohe_vector.values())
img_paths_to_split_into_folds = list(basepath_2_ohe_vector.keys())
kf = MultilabelStratifiedKFold(n_splits=args.n_folds, shuffle=True, random_state=1905)
folds = []
for trn_indices, val_indices in kf.split(img_paths_to_split_into_folds, y=label_combinations):
trn_paths = [img_paths_to_split_into_folds[i] for i in trn_indices]
val_paths = [img_paths_to_split_into_folds[i] for i in val_indices]
folds.append([trn_paths, val_paths])
with open(f'input/imagelevel_folds{"_obvious_staining" if OBVIOUS_STAINING_FLAG else ""}_{args.n_folds}.pkl', 'wb') as f:
pickle.dump(folds, f) |
import dxr.plugins
def pre_process(tree, environ):
pass
def post_process(tree, conn):
pass
__all__ = dxr.plugins.indexer_exports()
|
import json
from aio_pubsub.interfaces import PubSub, Subscriber
from aio_pubsub.typings import Message
aioredis_installed = False
try:
import aioredis
aioredis_installed = True
except ImportError:
pass # pragma: no cover
class RedisSubscriber(Subscriber):
def __init__(self, sub, channel):
self.sub = sub
self.channel = channel
def __aiter__(self):
return self.channel.iter(encoding="utf-8", decoder=json.loads)
class RedisPubSub(PubSub):
def __init__(self, url: str) -> None:
if aioredis_installed is False:
raise RuntimeError("Please install `aioredis`") # pragma: no cover
self.url = url
self.connection = None
async def publish(self, channel: str, message: Message) -> None:
if self.connection is None:
self.connection = await aioredis.create_redis(self.url)
channels = await self.connection.pubsub_channels(channel)
for ch in channels:
await self.connection.publish_json(ch, message)
async def subscribe(self, channel) -> "RedisSubscriber":
if aioredis_installed is False:
raise RuntimeError("Please install `aioredis`") # pragma: no cover
sub = await aioredis.create_redis(self.url)
channel = await sub.subscribe(channel)
return RedisSubscriber(sub, channel[0])
|
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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.
from mock import MagicMock, patch
from django.test import TestCase
from coredb import executor
from coredb.executor.handlers.run import (
handle_run_created,
handle_run_stopped_triggered,
)
from polycommon import auditor
from polycommon.celeryp.tasks import CoreSchedulerCeleryTasks
from polycommon.events.registry import run as run_events
class States:
workers = None
class DummyWorkers:
@staticmethod
def send(task, **kwargs):
States.workers = {"task": task}
States.workers.update(kwargs)
class TestExecutorRecord(TestCase):
def setUp(self):
super().setUp()
from polycommon.events import auditor_subscriptions # noqa
from coredb.executor import subscriptions # noqa
executor.validate_and_setup()
auditor.validate_and_setup()
self.user = MagicMock(id=1)
self.owner = MagicMock(id=1, name="owner")
self.project = MagicMock(id=1, owner=self.owner, name="project")
@patch("coredb.executor.service.ExecutorService.record")
def test_create_run_creation_is_recorded_by_executor(self, executor_record):
run = MagicMock(project=self.project)
auditor.record(run_events.RUN_CREATED, instance=run)
assert executor_record.call_count == 1
call_args, call_kwargs = executor_record.call_args
assert call_kwargs["event_type"] == run_events.RUN_CREATED
class TestExecutorHandlers(TestCase):
def setUp(self):
super().setUp()
from polycommon.events import auditor_subscriptions # noqa
from coredb.executor import subscriptions # noqa
auditor.validate_and_setup()
self.user = MagicMock(id=1)
self.owner = MagicMock(id=1, name="owner")
self.project = MagicMock(id=1, owner=self.owner, name="project")
def test_create_run_handler_non_managed_run(self):
States.workers = None
event = MagicMock(data={"is_managed": False})
handle_run_created(None, event=event)
assert States.workers is None
def test_create_run_handler_pipeline_run(self):
States.workers = None
data = {"is_managed": True, "pipeline_id": 1}
event = MagicMock(data=data)
handle_run_created(None, event=event)
assert States.workers is None
def test_create_run_handler(self):
States.workers = None
data = {"id": 1, "is_managed": True, "pipeline_id": None}
event = MagicMock(data=data, instance=MagicMock(meta_info=None))
handle_run_created(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_PREPARE
States.workers = None
event = MagicMock(data=data, instance=MagicMock(meta_info={}))
handle_run_created(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_PREPARE
States.workers = None
event = MagicMock(
data=data, instance=MagicMock(meta_info={"is_approved": False})
)
handle_run_created(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_PREPARE
States.workers = None
event = MagicMock(
data=data, instance=MagicMock(meta_info={"is_approved": True})
)
handle_run_created(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_PREPARE
States.workers = None
event = MagicMock(data=data, instance=MagicMock(meta_info={"eager": False}))
handle_run_created(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_PREPARE
States.workers = None
event = MagicMock(data=data, instance=MagicMock(meta_info={"eager": True}))
handle_run_created(DummyWorkers, event=event)
assert States.workers is None
def test_stop_run_handler_managed_run(self):
States.workers = None
event = MagicMock(data={"id": 1, "is_managed": True})
handle_run_stopped_triggered(DummyWorkers, event=event)
assert States.workers["task"] == CoreSchedulerCeleryTasks.RUNS_STOP
|
from pathlib import Path
from typing import Optional
import numpy as np
from src.biota_models.coral.model.coral_model import Coral
from src.core.base_model import BaseModel
class Reef0D(BaseModel):
"""Implements the `HydrodynamicProtocol`."""
working_dir: Optional[Path] = None
definition_file: Optional[Path] = None
config_file: Optional[Path] = None
x_coordinates: Optional[np.ndarray] = None
y_coordinates: Optional[np.ndarray] = None
water_depth: Optional[np.ndarray] = None
@property
def settings(self):
"""Print settings of Reef0D-model."""
return "Not yet implemented."
@property
def xy_coordinates(self):
if self.x_coordinates is None or self.y_coordinates is None:
return None
return np.array(
[
[self.x_coordinates[i], self.y_coordinates[i]]
for i in range(len(self.x_coordinates))
]
)
@property
def space(self):
if self.xy_coordinates is None:
return None
return len(self.xy_coordinates)
def initiate(self):
"""Initiate hydrodynamic model."""
raise NotImplementedError
def update(self, coral: Coral, storm=False) -> tuple:
"""Update hydrodynamic model.
:param coral: coral animal
:param storm: storm conditions, defaults to False
:type coral: Coral
:type storm: bool, optional
"""
if storm:
# max(current_vel, wave_vel)
return None, None
# mean(current_vel, wave_vel, wave_per)
return None, None, None
def finalise(self):
"""Finalise hydrodynamic model."""
raise NotImplementedError
|
# We test the base and dummy together. |
import pytest
from pytest_mock import MockerFixture
from pystratis.api.collateralvoting import CollateralVoting
from pystratis.core.types import Address
from pystratis.core.networks import StraxMain
def test_all_strax_endpoints_implemented(strax_swagger_json):
paths = [key.lower() for key in strax_swagger_json['paths']]
for endpoint in paths:
if CollateralVoting.route + '/' in endpoint:
assert endpoint in CollateralVoting.endpoints
def test_all_cirrus_endpoints_implemented(cirrus_swagger_json):
paths = [key.lower() for key in cirrus_swagger_json['paths']]
for endpoint in paths:
if CollateralVoting.route + '/' in endpoint:
assert endpoint in CollateralVoting.endpoints
def test_all_interfluxstrax_endpoints_implemented(interfluxstrax_swagger_json):
paths = [key.lower() for key in interfluxstrax_swagger_json['paths']]
for endpoint in paths:
if CollateralVoting.route + '/' in endpoint:
assert endpoint in CollateralVoting.endpoints
def test_all_interfluxcirrus_endpoints_implemented(interfluxcirrus_swagger_json):
paths = [key.lower() for key in interfluxcirrus_swagger_json['paths']]
for endpoint in paths:
if CollateralVoting.route + '/' in endpoint:
assert endpoint in CollateralVoting.endpoints
@pytest.mark.parametrize('network', [StraxMain()], ids=['Main'])
def test_join_federation(mocker: MockerFixture, network, generate_p2pkh_address, generate_compressed_pubkey):
mocker.patch.object(CollateralVoting, 'post', return_value=None)
collateralvoting = CollateralVoting(network=network, baseuri=mocker.MagicMock(), session=mocker.MagicMock())
collateralvoting.schedulevote_kickfedmember(
pubkey_hex=generate_compressed_pubkey,
collateral_amount_satoshis=100000,
collateral_mainchain_address=Address(address=generate_p2pkh_address(network=network), network=network)
)
# noinspection PyUnresolvedReferences
collateralvoting.post.assert_called_once()
|
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, SearchField, DateTimeDyField, EnumDyField, SizeField
from spaceone.inventory.libs.schema.cloud_service_type import CloudServiceTypeResource, CloudServiceTypeResponse, \
CloudServiceTypeMeta
cst_sql_workspace = CloudServiceTypeResource()
cst_sql_workspace.name = 'SQLWorkspace'
cst_sql_workspace.provider = 'google_cloud'
cst_sql_workspace.group = 'BigQuery'
cst_sql_workspace.service_code = 'bigquery'
cst_sql_workspace.is_primary = True
cst_sql_workspace.is_major = True
cst_sql_workspace.labels = ['Analytics']
cst_sql_workspace.tags = {
'spaceone:icon': 'https://spaceone-custom-assets.s3.ap-northeast-2.amazonaws.com/console-assets/icons/cloud-services/google_cloud/Big_Query.svg',
}
cst_sql_workspace._metadata = CloudServiceTypeMeta.set_meta(
fields=[
TextDyField.data_source('Name', 'data.name'),
TextDyField.data_source('Location', 'data.location'),
TextDyField.data_source('Default Partition Expires', 'data.default_partition_expiration_ms_display'),
TextDyField.data_source('Default Table Expires', 'data.default_table_expiration_ms_display'),
EnumDyField.data_source('Visible on Console', 'data.visible_on_console', default_badge={
'indigo.500': ['true'], 'coral.600': ['false']
}),
DateTimeDyField.data_source('Creation Time', 'data.creation_time'),
DateTimeDyField.data_source('Last Modified Time', 'data.last_modified_time'),
],
search=[
SearchField.set(name='ID', key='data.id'),
SearchField.set(name='Name', key='data.name'),
SearchField.set(name='Location', key='data.location'),
SearchField.set(name='Creation Time', key='data.creation_time', data_type='datetime'),
SearchField.set(name='Last Modified Time', key='data.last_modified_time', data_type='datetime'),
]
)
CLOUD_SERVICE_TYPES = [
CloudServiceTypeResponse({'resource': cst_sql_workspace}),
]
|
import numpy as np
from pybind_isce3 import focus
def test_chirp():
T = 1.0
K = 0.0
fs = 1.0
chirp = focus.form_linear_chirp(K, T, fs)
assert np.allclose(chirp, [1+0j])
|
import re
import io
import os
import json
import uuid
import shutil
import random
import requests
from PIL import Image
from urllib import parse
from joblib import Parallel, delayed
ALL = None
CREATIVE_COMMONS = "Any"
PUBLIC_DOMAIN = "Public"
SHARE_AND_USE = "Share"
SHARE_AND_USE_COMMECIALLY = "ShareCommercially"
MODIFY_SHARE_AND_USE = "Modify"
MODIFY_SHARE_AND_USE_COMMERCIALLY = "ModifyCommercially"
_licenses = [
ALL,
CREATIVE_COMMONS,
PUBLIC_DOMAIN,
SHARE_AND_USE,
SHARE_AND_USE_COMMECIALLY,
MODIFY_SHARE_AND_USE,
MODIFY_SHARE_AND_USE_COMMERCIALLY
]
def download(query, folder='.', max_urls=None, thumbnails=False, parallel=False, shuffle=False, remove_folder=False, license=ALL):
if thumbnails:
urls = get_image_thumbnails_urls(query, license)
else:
urls = get_image_urls(query, license)
if shuffle:
random.shuffle(urls)
if max_urls is not None and len(urls) > max_urls:
urls = urls[:max_urls]
if remove_folder:
_remove_folder(folder)
_create_folder(folder)
if parallel:
return _parallel_download_urls(urls, folder)
else:
return _download_urls(urls, folder)
def _download(url, folder):
try:
filename = str(uuid.uuid4().hex)
while os.path.exists("{}/{}.jpg".format(folder, filename)):
filename = str(uuid.uuid4().hex)
response = requests.get(url, stream=True, timeout=5.0, allow_redirects=True)
with Image.open(io.BytesIO(response.content)) as im:
with open("{}/{}.jpg".format(folder, filename), 'wb') as out_file:
im.save(out_file)
return True
except:
return False
def _download_urls(urls, folder):
downloaded = 0
for url in urls:
if _download(url, folder):
downloaded += 1
return downloaded
def _parallel_download_urls(urls, folder):
downloaded = 0
with Parallel(n_jobs=os.cpu_count()) as parallel:
results = parallel(delayed(_download)(url, folder) for url in urls)
for result in results:
if result:
downloaded += 1
return downloaded
def get_image_urls(query, license):
token = _fetch_token(query)
return _fetch_search_urls(query, token, license)
def get_image_thumbnails_urls(query, license):
token = _fetch_token(query)
return _fetch_search_urls(query, token, license, what="thumbnail")
def _fetch_token(query, URL="https://duckduckgo.com/"):
res = requests.post(URL, data={'q': query})
if res.status_code != 200:
return ""
match = re.search(r"vqd='([\d-]+)'", res.text, re.M|re.I)
if match is None:
return ""
return match.group(1)
def _fetch_search_urls(q, token, license, URL="https://duckduckgo.com/", what="image"):
query = {
"vqd": token,
"q": q,
"l": "us-en",
"o": "json",
"f": ",,,,,",
"p": "1",
"s": "100",
"u": "bing"
}
if license is not None and license in _licenses:
query["f"] = f",,,,,license:{license}"
urls = []
_urls, next = _get_urls(f"{URL}i.js", query, what)
urls.extend(_urls)
while next is not None:
query.update(parse.parse_qs(parse.urlsplit(next).query))
_urls, next = _get_urls(f"{URL}i.js", query, what)
urls.extend(_urls)
return urls
def _get_urls(URL, query, what):
urls = []
res = requests.get(
URL,
params=query,
headers={
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36"
}
)
if res.status_code != 200:
return urls
data = json.loads(res.text)
for result in data["results"]:
urls.append(result[what])
return urls, data["next"] if "next" in data else None
def _remove_folder(folder):
if os.path.exists(folder):
shutil.rmtree(folder, ignore_errors=True)
def _create_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
|
import numpy as np
import util.np
import util.rand
import util.mod
import util.dec
@util.dec.print_test
def test_flatten():
a = util.rand.rand(3, 5, 2)
b = util.np.flatten(a, 2)
b = np.reshape(b, a.shape)
assert util.np.sum_all(b == a) == np.prod(a.shape)
@util.dec.print_test
def test_arcsin():
pi = np.pi
# max/min, 1st phase, 2nd and 3rd phase, 4th phase
sins = [
[1, -1],
[1/np.sqrt(2), np.sqrt(3)/2],
[0.5, -0.5],
[-1/np.sqrt(2), -np.sqrt(3)/2]
]
xs = [
[0, 0],
[1, 1],
[-1, -1],
[1, 1]
]
arcs = [
[pi / 2, pi * 3 / 2],
[pi / 4, pi / 3],
[pi* 5 / 6, pi * 7 / 6],
[pi * 7 / 4, pi * 5 / 3]
]
np.testing.assert_almost_equal(util.np.arcsin(sins = sins, xs = xs), arcs)
@util.dec.print_test
def test_sin():
# when angles are provided
angles = util.rand.rand(3, 5)
assert util.np.sum_all(util.np.sin(angles = angles) == np.sin(angles)) == np.prod(angles.shape)
xs = util.rand.rand(4, 6)
ys = util.rand.rand(4, 6)
ys[0, :] = 0
lengths = np.sqrt(xs ** 2 + ys ** 2)
# when lengths are not provided
sins = util.np.sin(xs = xs, ys = ys)
assert util.np.sum_all(sins == 0) == 6
# when lengths are provided
sins = util.np.sin(ys = ys, lengths = lengths)
assert util.np.sum_all(sins == 0) == 6
# scalar sin
assert util.np.sin(ys = 0, lengths = 1) == 0
np.testing.assert_almost_equal(util.np.sin(xs = 1, ys = 1) , np.sqrt(2) / 2)
@util.dec.print_test
def test_norm():
v = np.arange(3)
norm2 = 1 + 4 + 9
norm1 = np.sqrt(norm2)
np.testing.assert_almost_equal(norm1, util.np.norm1(v))
np.testing.assert_almost_equal(norm2, util.np.norm2(v))
@util.dec.print_test
def test_empty_list():
l = util.np.empty_list(3, list)
l[0].append(1)
np.testing.assert_(l[0] is not l[1])
if util.mod.is_main(__name__):
# test_flatten()
# test_arcsin()
# test_sin()
# test_norm()
test_empty_list()
|
#!/usr/bin/env python
import os
from setuptools import setup
# Since masakari-controller does not own its own repo
# it can not derives the version of a package from the git tags.
# Therfore, we use PBR_VERSION=1.2.3
# to sikp all version calculation logics in pbr.
os.environ["PBR_VERSION"] = "1.2.3"
setup(
setup_requires=['pbr'],
pbr=True,
)
|
from app.main import bp
from flask import render_template, url_for
from flask_login import login_required, current_user
from app.models import User, Task, Schedule
from datetime import datetime
@bp.route('/')
@bp.route('/index')
@login_required
def index():
schedules = Schedule.get_schedule(current_user, start_date=datetime.utcnow())
return render_template('index.html', title='Home', upcoming_schedules=schedules) |
#coding=utf-8
print '# map'
def _pow(num):
return num * num;
print 'map[1-10],获取每个元素自身平方运算的结果', map(_pow, range(1, 11))
print 'map[1-10],将每个元素转换为字符串', map(str, range(1, 11))
def _capitalize(s):
return s.capitalize()
ls0 = ['anit', 'tac', 'cisum']
print 'map%s,将每个元素首字母转换为大写 %s' % (ls0, map(_capitalize, ls0))
print
print '# reduce'
def _sum(result, element):
return result + element
print 'reduce[1-100]求和', reduce(_sum, range(1, 101))
ls1 = [1, 3, 5, 6, 8, 13]
def str_and_join(result, element):
return str(result) + str(element)
print 'reduce%s,将每个元素转换为字符串并拼接 %s' % (ls1, reduce(str_and_join, ls1))
def _prod(result, element):
return result * element
print 'reduce[1-10]求积', reduce(_prod, range(1, 10))
|
"""
Operations Mixins.
"""
from eventstore_grpc import operations
from eventstore_grpc.proto import operations_pb2, operations_pb2_grpc, shared_pb2
class Operations:
"""Handles Operations."""
def merge_indexes(self, **kwargs) -> shared_pb2.Empty:
"""Merges indexes."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.merge_indexes(stub, **kwargs)
return result
def resign_node(self, **kwargs) -> shared_pb2.Empty:
"""Resigns node."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.resign_node(stub, **kwargs)
return result
def restart_persistent_subscriptions(self, **kwargs) -> shared_pb2.Empty:
"""Restarts persistent subscriptions."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.restart_persistent_subscriptions(stub, **kwargs)
return result
def set_node_priority(self, priority: int, **kwargs) -> shared_pb2.Empty:
"""Sets node priority."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.set_node_priority(stub, priority, **kwargs)
return result
def shutdown(self, **kwargs) -> shared_pb2.Empty:
"""Shuts the node down.""" # TODO: or the db?
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.shutdown(stub, **kwargs)
return result
def start_scavenge(
self, thread_count: int, start_from_chunk: int, **kwargs
) -> operations_pb2.ScavengeResp:
"""Starts a scavenge operation."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.start_scavenge(
stub, thread_count=thread_count, start_from_chunk=start_from_chunk, **kwargs
)
return result
def stop_scavenge(self, scavenge_id: str, **kwargs) -> operations_pb2.ScavengeResp:
"""Stops a scavenge operation."""
stub = operations_pb2_grpc.OperationsStub(self.channel)
result = operations.stop_scavenge(stub, scavenge_id=scavenge_id, **kwargs)
return result
|
class Flight:
def __init__(self, origin_short_name, destination_short_name, departure_time, fare_with_taxes, currency, status):
"""
Initialize Flight
:param origin_short_name: string - departure city
:param destination_short_name: string - destination city
:param departure_time: datetime - departure time
:param fare_with_taxes: float - price or the fare incl. tax
:param currency: str - currency
:param status: string - status, eg.: Available
"""
self.origin_short_name = origin_short_name
self.destination_short_name = destination_short_name
self.departure_time = departure_time
self.fare_with_taxes = fare_with_taxes
self.currency = currency
self.status = status
def __str__(self):
return "{0} {1} {2} {3} {4} {5}".format(self.origin_short_name.encode('utf8'),
self.destination_short_name.encode('utf8'),
self.departure_time,
self.fare_with_taxes,
self.currency,
self.status)
|
from django.db import models
class Cowsay(models.Model):
cowsay_string = models.TextField()
def __str__(self):
return self.cowsay_string
|
import cv2
import numpy as np
# Dynamic constants
CAM_PATH = 6 # "http://192.168.43.156:4747/video"
TESTER = "sanket"
WHICH_SYSTEM = "sanket"
# Independent constants
BAUD_RATE = 115200 # sampeling speed
CAR_BELOW_Y = 25 # y coordinate of car below max y coordinate
LIMIT_CONE = 100 # threshold after which detections won't be considered -> 'y' coordinate
MIDPOINT_ONE_BOUNDARY = 100 # one side is empty of cones, this is used as offset X coordinate
P = 2.115
MAX_CONELESS_FRAMES = 30
ARDUINO_CONNECTED = False
RATE = 1
TOP_VIEW_IMAGE_DIMESNION = (416, 285) # inv map output-image size (w, h) = (x, y)
FRONT_VIEW_IMAGE_DIMESNION = (416, 416) # (w, h) = (x, y)
FRONT_VIEW_POINTS = [(0 , 100),# camera
(-600, 416),
(416 , 100),
(1016, 416)]
# Dependent constants
TOP_VIEW_POINTS = [(0 , 0 ),
(0 , TOP_VIEW_IMAGE_DIMESNION[1]),
(TOP_VIEW_IMAGE_DIMESNION[0], 0 ),
(TOP_VIEW_IMAGE_DIMESNION[0], TOP_VIEW_IMAGE_DIMESNION[1])]
M = cv2.getPerspectiveTransform( np.float32(FRONT_VIEW_POINTS), np.float32(TOP_VIEW_POINTS) )
TOP_VIEW_CAR_COORDINATE = (TOP_VIEW_IMAGE_DIMESNION[0]//2, TOP_VIEW_IMAGE_DIMESNION[1] + CAR_BELOW_Y) # car coordinates on image
MS = 1/RATE
# Pure pursuit constants
k = 0.1 # lookahead distance coefficient
Lfc = R = 180.0 # lookahead distance
Kp = 2.15 # Speed P controller coefficient
L = 65 # Vehicle wheelbase, unit:pixel
def log_constants():
return {
"log_constants" : {
"CAM_PATH" : CAM_PATH,
"BAUD_RATE" : BAUD_RATE,
"CAR_BELOW_Y" : CAR_BELOW_Y,
"LIMIT_CONE" : LIMIT_CONE,
"MIDPOINT_ONE_BOUNDARY" : MIDPOINT_ONE_BOUNDARY,
"P" : P,
"MAX_CONELESS_FRAMES" : MAX_CONELESS_FRAMES,
"ARDUINO_CONNECTED" : ARDUINO_CONNECTED,
"RATE" : RATE,
"TESTER" : TESTER,
"WHICH_SYSTEM" : WHICH_SYSTEM,
"TOP_VIEW_IMAGE_DIMESNION" : TOP_VIEW_IMAGE_DIMESNION,
"FRONT_VIEW_POINTS" : FRONT_VIEW_POINTS,
"Lookahead_Distance" : Lfc
}
}
|
class DieException(BaseException):
pass
# def __init__(self, *args, **kwargs):
# super().__init__(args, kwargs)
# self.message = args[0] |
class CodonUsage():
def __init__(self):
self.counts = None
self.codon_usage = None
|
from wegene.Controllers.WeGeneUser import *
from wegene.Controllers.Allele import *
from wegene.Controllers.Health import *
from wegene.Controllers.Athletigen import *
from wegene.Controllers.Skin import *
from wegene.Controllers.Psychology import *
from wegene.Controllers.Risk import *
from wegene.Controllers.Haplogroups import *
from wegene.Controllers.Ancestry import *
from wegene.Controllers.Demographics import *
|
import pytest
def test_import_order():
# monkeypatching tf.keras caused import issue
WandbCallback = pytest.importorskip(
"wandb.keras.WandbCallback", reason="imports tensorflow"
)
tf = pytest.importorskip(
"tensorflow", minversion="2.6.2", reason="only relevant for tf>=2.6"
)
keras = pytest.importorskip(
"keras", minversion="2.6", reason="only relevant for keras>=2.6"
)
assert isinstance(tf.keras.Model(), keras.Model)
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright Irshad Ahmad Bhat 2016.
# Copyright Arjuna Rao Chavala 2018
# IT3 mapping Checked for Telugu and works for other languages
from __future__ import unicode_literals
import io
import os
import re
from six import unichr
class IT3():
"""it3-converter for UTF to it3 conversion of Indic scripts and vice-versa.
Parameters
----------
lang : str, default: hin
Input script
order : str, default: utf2it3
Order of conversion
rmask : bool, default: True
If True masks/unmasks Roman text in Indic scripts
norm : bool, default: False
If True returns normalized text without it3-Conversion
"""
def __init__(self, lang='tel', order='utf2it3', rmask=True, norm=False):
self.norm = norm
self.order = order
self.lang = lang.lower()
self.rmask = rmask and (not norm)
self.fit()
def fit(self):
file_path = os.path.dirname(os.path.abspath(__file__))
self.punctuation = r'!"#$%&\'()*+,-./;<=>?@\[\\\]^_`{|}'
# Handle iscii characters
self.iscii_num = dict(
zip(
[unichr(i) for i in range(161, 252)],
['\x03%s\x04' % (unichr(i)) for i in range(300, 391)]))
self.num_iscii = dict(
zip(
['\x03%s\x04' % (unichr(i)) for i in range(300, 391)],
[unichr(i) for i in range(161, 252)]))
self.mask_isc = re.compile('([\xA1-\xFB])')
self.unmask_isc = re.compile('(%s)' % '|'.join(
['\x03%s\x04' % (unichr(i)) for i in range(300, 391)]))
if self.order == "utf2it3":
if self.lang == 'urd':
self.norm_tbl = dict()
self.trans_tbl = dict()
with io.open('%s/mapping/norm_urd.map' % file_path,
encoding='utf-8') as fp:
for line in fp:
sr, tg = line.split()
self.norm_tbl[ord(sr)] = tg
with io.open('%s/mapping/urd-it3.map' % file_path,
encoding='utf-8') as fp:
for line in fp:
sr, tg = line.split()
self.trans_tbl[ord(sr)] = tg
else:
self.initialize_utf2it3_hash()
elif self.order == "it32utf":
if self.lang == 'urd':
self.trans_tbl = dict()
with io.open('%s/mapping/it3-urd.map' % file_path,
encoding='utf-8') as fp:
for line in fp:
sr, tg = line.split()
self.trans_tbl[ord(sr)] = tg
else:
self.initialize_it32utf_hash()
else:
raise ValueError('invalid source/target encoding\n')
# Mask Roman text in Indic scripts
self.mask_rom = re.compile(
r'([0-9%s]*[a-zA-Z][0-9a-zA-Z%s]*)' %
((self.punctuation,) * 2))
# Unask Roman text in Indic scripts
self.unmask_rom = re.compile(r'(_[a-zA-Z0-9%s]+_)' % self.punctuation)
def initialize_it32utf_hash(self):
# CONSONANTS
self.hashc_om2i = {
"k": "\xB3",
"kh": "\xB4",
"g": "\xB5",
"gh": "\xB6",
"ng-": "\xB7",
"ch": "\xB8",
"chh": "\xB9",
"j": "\xBA",
"jh": "\xBB",
"nj-": "\xBC",
"t'": "\xBD",
"t'h": "\xBE",
"d'": "\xBF",
"d'h": "\xC0",
"nd-": "\xC1",
"t": "\xC2",
"th": "\xC3",
"d": "\xC4",
"dh": "\xC5",
"n": "\xC6",
"p": "\xC8",
"ph": "\xC9",
"b": "\xCA",
"bh": "\xCB",
"m": "\xCC",
"y": "\xCD",
"r": "\xCF",
"l": "\xD1",
"v": "\xD4",
"sh": "\xD5",
"s": "\xD7",
"shh": "\xD6",
"h": "\xD8",
"_": "\xE8",
"Z": "\xE9",
".": "\xEA",
"Y": "\xFB",
"lY": "\xD2",
# Added for tamil/telugu
"r'": "\xD0",
"nY": "\xC7",
"l'": "\xD2",
"lYY": "\xD3",
}
# VOWELS
self.hashv_om2i = {
"a": "\xA4",
"aa": "\xA5",
"aA": "\xA5",
"i": "\xA6",
# "ai": "\xA6",
"ii": "\xA7",
"aI": "\xA7",
"u": "\xA8",
# "au": "\xA8",
"uu": "\xA9",
"aU": "\xA9",
"rx": "\xAA",
# "aq": "\xAA",
"e": "\xAB",
# "rx-": "\xAB",
"ei": "\xAC",
"ae": "\xAC",
"ee": "\xAD",
# "aE": "\xAD",
"ai": "\xAD",
"EY": "\xAE",
"aEY": "\xAE",
"o": "\xAF",
"aoV": "\xAF",
# "o": "\xB0",
"ao": "\xB0",
"oo": "\xB0",
"aO": "\xB1",
"OY": "\xB2",
# "aOY": "\xB2",
"au": "\xB1",
}
# MATRA
self.hashm_om2i = {
'a': "",
"aa": "\xDA",
"aA": "\xDA",
"i": "\xDB",
# "aI": "\xDB",
"ii": "\xDC",
# "aI": "\xDC",
"u": "\xDD",
# "au": "\xDD",
"uu": "\xDE",
"aU": "\xDE",
"rx": "\xDF",
# "rx-": "\xDF",
"e": "\xE0",
"aeV": "\xE0",
"ei": "\xE1",
"ae": "\xE1",
"E": "\xE2",
"ai": "\xE2",
"EY": "\xE3",
"aEY": "\xE3",
"o": "\xE4",
"aoV": "\xE4",
"oo": "\xE5",
"ao": "\xE5",
"O": "\xE6",
"au": "\xE6",
"OY": "\xE7",
"aOY": "\xE7",
}
# MODIFIERS
self.hashmd_om2i = {
"z": "\xA1",
"n'": "\xA2",
":": "\xA3",
}
self.digits_om2i = {
"0": "\xF1",
"1": "\xF2",
"2": "\xF3",
"3": "\xF4",
"4": "\xF5",
"5": "\xF6",
"6": "\xF7",
"7": "\xF8",
"8": "\xF9",
"9": "\xFA",
}
self.hashh_i2u = {
"\xA1": "\u0901", # Vowel-modifier CHANDRABINDU
"\xA2": "\u0902", # Vowel-modifier ANUSWAR
"\xA3": "\u0903", # Vowel-modifier VISARG
"\xA4": "\u0905", # Vowel A
"\xA5": "\u0906", # Vowel AA
"\xA6": "\u0907", # Vowel I
"\xA7": "\u0908", # Vowel II
"\xA8": "\u0909", # Vowel U
"\xA9": "\u090A", # Vowel UU
"\xAA": "\u090B", # Vowel RI
"\xAB": "\u090E", # Vowel E
"\xAC": "\u090F", # Vowel EY
"\xAD": "\u0910", # Vowel AI
"\xAE": "\u090D", # Vowel AI
# "\xB2": "\u090D", # Vowel AYE (Devanagari Script)
"\xAF": "\u0912", # Vowel O
"\xB0": "\u0913", # Vowel OW
"\xB1": "\u0914", # Vowel AU
"\xB2": "\u0911", # Vowel AWE
"\xB3": "\u0915", # Consonant KA
"\xB4": "\u0916", # Consonant KHA
"\xB5": "\u0917", # Consonant GA
"\xB6": "\u0918", # Consonant GHA
"\xB7": "\u0919", # Consonant NGA
"\xB8": "\u091A", # Consonant CHA
"\xB9": "\u091B", # Consonant CHHA
"\xBA": "\u091C", # Consonant JA
"\xBB": "\u091D", # Consonant JHA
"\xBC": "\u091E", # Consonant JNA
"\xBD": "\u091F", # Consonant Hard TA
"\xBE": "\u0920", # Consonant Hard THA
"\xBF": "\u0921", # Consonant Hard DA
"\xC0": "\u0922", # Consonant Hard DHA
"\xC1": "\u0923", # Consonant Hard NA
"\xC2": "\u0924", # Consonant Soft TA
"\xC3": "\u0925", # Consonant Soft THA
"\xC4": "\u0926", # Consonant Soft DA
"\xC5": "\u0927", # Consonant Soft DHA
"\xC6": "\u0928", # Consonant Soft NA
"\xC7": "\u0929", # Consonant NA (Tamil)
"\xC8": "\u092A", # Consonant PA
"\xC9": "\u092B", # Consonant PHA
"\xCA": "\u092C", # Consonant BA
"\xCB": "\u092D", # Consonant BHA
"\xCC": "\u092E", # Consonant MA
"\xCD": "\u092F", # Consonant YA
"\xCF": "\u0930", # Consonant RA
"\xD0": "\u0931", # Consonant Hard RA (Southern Script)
"\xD1": "\u0932", # Consonant LA
"\xD2": "\u0933", # Consonant Hard LA
"\xD3": "\u0934", # Consonant ZHA (Tamil & Malyalam)
"\xD4": "\u0935", # Consonant VA
"\xD5": "\u0936", # Consonant SHA
"\xD6": "\u0937", # Consonant Hard SHA
"\xD7": "\u0938", # Consonant SA
"\xD8": "\u0939", # Consonant HA
"\xDA": "\u093E", # Vowel Sign AA
"\xDB": "\u093F", # Vowel Sign I
"\xDC": "\u0940", # Vowel Sign II
"\xDD": "\u0941", # Vowel Sign U
"\xDE": "\u0942", # Vowel Sign UU
"\xDF": "\u0943", # Vowel Sign RI
"\xE0": "\u0946", # Vowel Sign E (Southern Scripts)
"\xE1": "\u0947", # Vowel Sign EY
"\xE2": "\u0948", # Vowel Sign AI
"\xE3": "\u0945", # Vowel Sign AYE (Devanagari Script)
"\xE4": "\u094A", # Vowel Sign O
"\xE5": "\u094B", # Vowel Sign OW
"\xE6": "\u094C", # Vowel Sign AU
"\xE7": "\u0949", # Vowel Sign AWE (Devanagari Script)
"\xE8": "\u094D", # Vowel Omission Sign (Halant)
"\xE9": "\u093C", # Diacritic Sign (Nukta)
"\xEA": ".", # Fullstop
"\xF1": "\u0966", # Digit 0
"\xF2": "\u0967", # Digit 1
"\xF3": "\u0968", # Digit 2
"\xF4": "\u0969", # Digit 3
"\xF5": "\u096A", # Digit 4
"\xF6": "\u096B", # Digit 5
"\xF7": "\u096C", # Digit 6
"\xF8": "\u096D", # Digit 7
"\xF9": "\u096E", # Digit 8
"\xFA": "\u096F", # Digit 9
}
self.hasht_i2u = {
"\xA1": "\u0C01", # Vowel-modifier CHANDRABINDU
"\xA2": "\u0C02", # Vowel-modifier ANUSWAR
"\xA3": "\u0C03", # Vowel-modifier VISARG
"\xA4": "\u0C05", # Vowel A
"\xA5": "\u0C06", # Vowel AA
"\xA6": "\u0C07", # Vowel I
"\xA7": "\u0C08", # Vowel II
"\xA8": "\u0C09", # Vowel U
"\xA9": "\u0C0A", # Vowel UU
"\xAA": "\u0C0B", # Vowel RI
"\xAB": "\u0C0E", # Vowel E
"\xAC": "\u0C0F", # Vowel EY
"\xAD": "\u0C10", # Vowel AI
"\xAF": "\u0C12", # Vowel O
"\xB0": "\u0C13", # Vowel OW
"\xB1": "\u0C14", # Vowel AU
"\xB3": "\u0C15", # Consonant KA
"\xB4": "\u0C16", # Consonant KHA
"\xB5": "\u0C17", # Consonant GA
"\xB6": "\u0C18", # Consonant GHA
"\xB7": "\u0C19", # Consonant NGA
"\xB8": "\u0C1A", # Consonant CHA
"\xB9": "\u0C1B", # Consonant CHHA
"\xBA": "\u0C1C", # Consonant JA
"\xBB": "\u0C1D", # Consonant JHA
"\xBC": "\u0C1E", # Consonant JNA
"\xBD": "\u0C1F", # Consonant Hard TA
"\xBE": "\u0C20", # Consonant Hard THA
"\xBF": "\u0C21", # Consonant Hard DA
"\xC0": "\u0C22", # Consonant Hard DHA
"\xC1": "\u0C23", # Consonant Hard NA
"\xC2": "\u0C24", # Consonant Soft TA
"\xC3": "\u0C25", # Consonant Soft THA
"\xC4": "\u0C26", # Consonant Soft DA
"\xC5": "\u0C27", # Consonant Soft DHA
"\xC6": "\u0C28", # Consonant Soft NA
"\xC8": "\u0C2A", # Consonant PA
"\xC9": "\u0C2B", # Consonant PHA
"\xCA": "\u0C2C", # Consonant BA
"\xCB": "\u0C2D", # Consonant BHA
"\xCC": "\u0C2E", # Consonant MA
"\xCD": "\u0C2F", # Consonant YA
"\xCF": "\u0C30", # Consonant RA
"\xD0": "\u0C31", # Consonant Hard RA (Southern Script)
"\xD1": "\u0C32", # Consonant LA
"\xD2": "\u0C33", # Consonant Hard LA
"\xD4": "\u0C35", # Consonant VA
"\xD5": "\u0C36", # Consonant SHA
"\xD6": "\u0C37", # Consonant Hard SHA
"\xD7": "\u0C38", # Consonant SA
"\xD8": "\u0C39", # Consonant HA
"\xDA": "\u0C3E", # Vowel Sign AA
"\xDB": "\u0C3F", # Vowel Sign I
"\xDC": "\u0C40", # Vowel Sign II
"\xDD": "\u0C41", # Vowel Sign U
"\xDE": "\u0C42", # Vowel Sign UU
"\xDF": "\u0C43", # Vowel Sign RI
"\xE0": "\u0C46", # Vowel Sign E (Southern Scripts)
"\xE1": "\u0C47", # Vowel Sign EY
"\xE2": "\u0C48", # Vowel Sign AI
"\xE4": "\u0C4A", # Vowel Sign O
"\xE5": "\u0C4B", # Vowel Sign OW
"\xE6": "\u0C4C", # Vowel Sign AU
"\xE8": "\u0C4D", # Vowel Omission Sign (Halant)
"\xEA": ".", # Fullstop
"\xF1": "\u0C66", # Digit 0
"\xF2": "\u0C67", # Digit 1
"\xF3": "\u0C68", # Digit 2
"\xF4": "\u0C69", # Digit 3
"\xF5": "\u0C6A", # Digit 4
"\xF6": "\u0C6B", # Digit 5
"\xF7": "\u0C6C", # Digit 6
"\xF8": "\u0C6D", # Digit 7
"\xF9": "\u0C6E", # Digit 8
"\xFA": "\u0C6F", # Digit 9
}
self.hashp_i2u = {
"\xA1": "\u0A70", # Vowel-modifier GURMUKHI TIPPI
"\xA2": "\u0A02", # Vowel-modifier ANUSWAR
"\xA3": "\u0A03", # Vowel-modifier VISARG
"\xA4": "\u0A05", # Vowel A
"\xA5": "\u0A06", # Vowel AA
"\xA6": "\u0A07", # Vowel I
"\xA7": "\u0A08", # Vowel II
"\xA8": "\u0A09", # Vowel U
"\xA9": "\u0A0A", # Vowel UU
"\xAA": "\u0A0B", # Vowel RI
"\xAB": "\u0A0E", # Vowel E
"\xAC": "\u0A0F", # Vowel EY
"\xAD": "\u0A10", # Vowel AI
# "\xB2": "\u0A0D", # Vowel AYE (Devanagari Script)
"\xAF": "\u0A12", # Vowel O
"\xB0": "\u0A13", # Vowel OW
"\xB1": "\u0A14", # Vowel AU
"\xB2": "\u0A11", # Vowel AWE
"\xB3": "\u0A15", # Consonant KA
"\xB4": "\u0A16", # Consonant KHA
"\xB5": "\u0A17", # Consonant GA
"\xB6": "\u0A18", # Consonant GHA
"\xB7": "\u0A19", # Consonant NGA
"\xB8": "\u0A1A", # Consonant CHA
"\xB9": "\u0A1B", # Consonant CHHA
"\xBA": "\u0A1C", # Consonant JA
"\xBB": "\u0A1D", # Consonant JHA
"\xBC": "\u0A1E", # Consonant JNA
"\xBD": "\u0A1F", # Consonant Hard TA
"\xBE": "\u0A20", # Consonant Hard THA
"\xBF": "\u0A21", # Consonant Hard DA
"\xC0": "\u0A22", # Consonant Hard DHA
"\xC1": "\u0A23", # Consonant Hard NA
"\xC2": "\u0A24", # Consonant Soft TA
"\xC3": "\u0A25", # Consonant Soft THA
"\xC4": "\u0A26", # Consonant Soft DA
"\xC5": "\u0A27", # Consonant Soft DHA
"\xC6": "\u0A28", # Consonant Soft NA
"\xC7": "\u0A29", # Consonant NA (Tamil)
"\xC8": "\u0A2A", # Consonant PA
"\xC9": "\u0A2B", # Consonant PHA
"\xCA": "\u0A2C", # Consonant BA
"\xCB": "\u0A2D", # Consonant BHA
"\xCC": "\u0A2E", # Consonant MA
"\xCD": "\u0A2F", # Consonant YA
"\xCF": "\u0A30", # Consonant RA
"\xD0": "\u0A31", # Consonant Hard RA (Southern Script)
"\xD1": "\u0A32", # Consonant LA
"\xD2": "\u0A33", # Consonant Hard LA
"\xD3": "\u0A34", # Consonant ZHA (Tamil & Malyalam)
"\xD4": "\u0A35", # Consonant VA
"\xD5": "\u0A36", # Consonant SHA
"\xD6": "\u0A37", # Consonant Hard SHA
"\xD7": "\u0A38", # Consonant SA
"\xD8": "\u0A39", # Consonant HA
"\xDA": "\u0A3E", # Vowel Sign AA
"\xDB": "\u0A3F", # Vowel Sign I
"\xDC": "\u0A40", # Vowel Sign II
"\xDD": "\u0A41", # Vowel Sign U
"\xDE": "\u0A42", # Vowel Sign UU
"\xDF": "\u0A43", # Vowel Sign RI
"\xE0": "\u0A46", # Vowel Sign E (Southern Scripts)
"\xE1": "\u0A47", # Vowel Sign EY
"\xE2": "\u0A48", # Vowel Sign AI
"\xE3": "\u0A45", # Vowel Sign AYE (Devanagari Script)
"\xE4": "\u0A4A", # Vowel Sign O
"\xE5": "\u0A4B", # Vowel Sign OW
"\xE6": "\u0A4C", # Vowel Sign AU
"\xE7": "\u0A49", # Vowel Sign AWE (Devanagari Script)
"\xE8": "\u0A4D", # Vowel Omission Sign (Halant)
"\xE9": "\u0A3C", # Diacritic Sign (Nukta)
"\xEA": ".", # Fullstop
"\xF1": "\u0A66", # Digit 0
"\xF2": "\u0A67", # Digit 1
"\xF3": "\u0A68", # Digit 2
"\xF4": "\u0A69", # Digit 3
"\xF5": "\u0A6A", # Digit 4
"\xF6": "\u0A6B", # Digit 5
"\xF7": "\u0A6C", # Digit 6
"\xF8": "\u0A6D", # Digit 7
"\xF9": "\u0A6E", # Digit 8
"\xFA": "\u0A6F", # Digit 9
"\xFB": "\u0A71" # GURMUKHI ADDAK
}
self.hashk_i2u = {
"\xA2": "\u0C82",
"\xA3": "\u0C83",
"\xA4": "\u0C85",
"\xA5": "\u0C86",
"\xA6": "\u0C87",
"\xA7": "\u0C88",
"\xA8": "\u0C89",
"\xA9": "\u0C8A",
"\xAA": "\u0C8B",
"\xAE": "\u0C8D",
"\xAB": "\u0C8E",
"\xAC": "\u0C8F",
"\xAD": "\u0C90",
"\xB2": "\u0C91",
"\xAF": "\u0C92",
"\xB0": "\u0C93",
"\xB1": "\u0C94",
"\xB3": "\u0C95",
"\xB4": "\u0C96",
"\xB5": "\u0C97",
"\xB6": "\u0C98",
"\xB7": "\u0C99",
"\xB8": "\u0C9A",
"\xB9": "\u0C9B",
"\xBA": "\u0C9C",
"\xBB": "\u0C9D",
"\xBC": "\u0C9E",
"\xBD": "\u0C9F",
"\xBE": "\u0CA0",
"\xBF": "\u0CA1",
"\xC0": "\u0CA2",
"\xC1": "\u0CA3",
"\xC2": "\u0CA4",
"\xC3": "\u0CA5",
"\xC4": "\u0CA6",
"\xC5": "\u0CA7",
"\xC6": "\u0CA8",
"\xC7": "\u0CA9",
"\xC8": "\u0CAA",
"\xC9": "\u0CAB",
"\xCA": "\u0CAC",
"\xCB": "\u0CAD",
"\xCC": "\u0CAE",
"\xCD": "\u0CAF",
"\xCF": "\u0CB0",
"\xD0": "\u0CB1",
"\xD1": "\u0CB2",
"\xD2": "\u0CB3",
"\xD3": "\u0CB4",
"\xD4": "\u0CB5",
"\xD5": "\u0CB6",
"\xD6": "\u0CB7",
"\xD7": "\u0CB8",
"\xD8": "\u0CB9",
"\xE9": "\u0CBC",
"\xDA": "\u0CBE",
"\xDB": "\u0CBF",
"\xDC": "\u0CC0",
"\xDD": "\u0CC1",
"\xDE": "\u0CC2",
"\xDF": "\u0CC3",
"\xE0": "\u0CC6",
"\xE1": "\u0CC7",
"\xE2": "\u0CC8",
"\xE7": "\u0CC9",
"\xE4": "\u0CCA",
"\xE5": "\u0CCB",
"\xE6": "\u0CCC",
"\xE8": "\u0CCD",
"\xEA": ".", # Fullstop
"\xF1": "\u0CE6",
"\xF2": "\u0CE7",
"\xF3": "\u0CE8",
"\xF4": "\u0CE9",
"\xF5": "\u0CEA",
"\xF6": "\u0CEB",
"\xF7": "\u0CEC",
"\xF8": "\u0CED",
"\xF9": "\u0CEE",
"\xFA": "\u0CEF"
}
self.hashm_i2u = {
"\xA2": "\u0D02", # Vowel-modifier ANUSWAR
"\xA3": "\u0D03", # Vowel-modifier VISARG
"\xA4": "\u0D05", # Vowel A
"\xA5": "\u0D06", # Vowel AA
"\xA6": "\u0D07", # Vowel I
"\xA7": "\u0D08", # Vowel II
"\xA8": "\u0D09", # Vowel U
"\xA9": "\u0D0A", # Vowel UU
"\xAA": "\u0D0B", # Vowel RI
"\xAB": "\u0D0E", # Vowel E
"\xAC": "\u0D0F", # Vowel EY
"\xAD": "\u0D10", # Vowel AI
"\xAF": "\u0D12", # Vowel O
"\xB0": "\u0D13", # Vowel OW
"\xB1": "\u0D14", # Vowel AU
"\xB2": "\u0D11", # Vowel AWE
"\xB3": "\u0D15", # Consonant KA
"\xB4": "\u0D16", # Consonant KHA
"\xB5": "\u0D17", # Consonant GA
"\xB6": "\u0D18", # Consonant GHA
"\xB7": "\u0D19", # Consonant NGA
"\xB8": "\u0D1A", # Consonant CHA
"\xB9": "\u0D1B", # Consonant CHHA
"\xBA": "\u0D1C", # Consonant JA
"\xBB": "\u0D1D", # Consonant JHA
"\xBC": "\u0D1E", # Consonant JNA
"\xBD": "\u0D1F", # Consonant Hard TA
"\xBE": "\u0D20", # Consonant Hard THA
"\xBF": "\u0D21", # Consonant Hard DA
"\xC0": "\u0D22", # Consonant Hard DHA
"\xC1": "\u0D23", # Consonant Hard NA
"\xC2": "\u0D24", # Consonant Soft TA
"\xC3": "\u0D25", # Consonant Soft THA
"\xC4": "\u0D26", # Consonant Soft DA
"\xC5": "\u0D27", # Consonant Soft DHA
"\xC6": "\u0D28", # Consonant Soft NA
"\xC7": "\u0D29", # Consonant NA (Tamil)
"\xC8": "\u0D2A", # Consonant PA
"\xC9": "\u0D2B", # Consonant PHA
"\xCA": "\u0D2C", # Consonant BA
"\xCB": "\u0D2D", # Consonant BHA
"\xCC": "\u0D2E", # Consonant MA
"\xCD": "\u0D2F", # Consonant YA
"\xCF": "\u0D30", # Consonant RA
"\xD0": "\u0D31", # Consonant Hard RA (Southern Script)
"\xD1": "\u0D32", # Consonant LA
"\xD2": "\u0D33", # Consonant Hard LA
"\xD3": "\u0D34", # Consonant ZHA (Tamil & Malyalam)
"\xD4": "\u0D35", # Consonant VA
"\xD5": "\u0D36", # Consonant SHA
"\xD6": "\u0D37", # Consonant Hard SHA
"\xD7": "\u0D38", # Consonant SA
"\xD8": "\u0D39", # Consonant HA
"\xDA": "\u0D3E", # Vowel Sign AA
"\xDB": "\u0D3F", # Vowel Sign I
"\xDC": "\u0D40", # Vowel Sign II
"\xDD": "\u0D41", # Vowel Sign U
"\xDE": "\u0D42", # Vowel Sign UU
"\xDF": "\u0D43", # Vowel Sign RI
"\xE0": "\u0D46", # Vowel Sign E (Southern Scripts)
"\xE1": "\u0D47", # Vowel Sign EY
"\xE2": "\u0D48", # Vowel Sign AI
"\xE4": "\u0D4A", # Vowel Sign O
"\xE5": "\u0D4B", # Vowel Sign OW
"\xE6": "\u0D4C", # Vowel Sign AU
"\xE8": "\u0D4D", # Vowel Omission Sign (Halant)
"\xEA": ".", # Fullstop
"\xF1": "\u0D66", # Digit 0
"\xF2": "\u0D67", # Digit 1
"\xF3": "\u0D68", # Digit 2
"\xF4": "\u0D69", # Digit 3
"\xF5": "\u0D6A", # Digit 4
"\xF6": "\u0D6B", # Digit 5
"\xF7": "\u0D6C", # Digit 6
"\xF8": "\u0D6D", # Digit 7
"\xF9": "\u0D6E", # Digit 8
"\xFA": "\u0D6F", # Digit 9
}
self.hashb_i2u = {
"\xA1": "\u0981",
"\xA2": "\u0982", # Vowel-modifier ANUSWAR
"\xA3": "\u0983", # Vowel-modifier VISARG
"\xA4": "\u0985", # Vowel A
"\xA5": "\u0986", # Vowel AA
"\xA6": "\u0987", # Vowel I
"\xA7": "\u0988", # Vowel II
"\xA8": "\u0989", # Vowel U
"\xA9": "\u098A", # Vowel UU
"\xAA": "\u098B", # Vowel RI
"\xAB": "\u098F", # Vowel
"\xAD": "\u0990", # Vowel AI
"\xAF": "\u0993", # Vowel O
"\xB1": "\u0994", # Vowel AU
"\xB3": "\u0995", # Consonant KA
"\xB4": "\u0996", # Consonant KHA
"\xB5": "\u0997", # Consonant GA
"\xB6": "\u0998", # Consonant GHA
"\xB7": "\u0999", # Consonant NGA
"\xB8": "\u099A", # Consonant CHA
"\xB9": "\u099B", # Consonant CHHA
"\xBA": "\u099C", # Consonant JA
"\xBB": "\u099D", # Consonant JHA
"\xBC": "\u099E", # Consonant JNA
"\xBD": "\u099F", # Consonant Hard TA
"\xBE": "\u09A0", # Consonant Hard THA
"\xBF": "\u09A1", # Consonant Hard DA
"\xC0": "\u09A2", # Consonant Hard DHA
"\xC1": "\u09A3", # Consonant Hard NA
"\xC2": "\u09A4", # Consonant Soft TA
"\xC3": "\u09A5", # Consonant Soft THA
"\xC4": "\u09A6", # Consonant Soft DA
"\xC5": "\u09A7", # Consonant Soft DHA
"\xC6": "\u09A8", # Consonant Soft NA
"\xC8": "\u09AA", # Consonant PA
"\xC9": "\u09AB", # Consonant PHA
"\xCA": "\u09AC", # Consonant BA
"\xCB": "\u09AD", # Consonant BHA
"\xCC": "\u09AE", # Consonant MA
"\xCD": "\u09AF", # Consonant YA
"\xCF": "\u09B0", # Consonant RA
"\xD1": "\u09B2", # Consonant LA
"\xD5": "\u09B6", # Consonant SHA
"\xD6": "\u09B7", # Consonant Hard SHA
"\xD7": "\u09B8", # Consonant SA
"\xD8": "\u09B9", # Consonant HA
"\xDA": "\u09BE", # Vowel Sign AA
"\xDB": "\u09BF", # Vowel Sign I
"\xDC": "\u09C0", # Vowel Sign II
"\xDD": "\u09C1", # Vowel Sign U
"\xDE": "\u09C2", # Vowel Sign UU
"\xDF": "\u09C3", # Vowel Sign RI
"\xE0": "\u09C7", # Vowel Sign E (Southern Scripts)
"\xE2": "\u09C8", # Vowel Sign AI
"\xE4": "\u09CB", # Vowel Sign O
"\xE6": "\u09CC", # Vowel Sign AU
"\xE8": "\u09CD", # Vowel Omission Sign (Halant)
"\xE9": "\u09BC",
"\xEA": ".", # Fullstop
"\xF1": "\u09E6", # Digit 0
"\xF2": "\u09E7", # Digit 1
"\xF3": "\u09E8", # Digit 2
"\xF4": "\u09E9", # Digit 3
"\xF5": "\u09EA", # Digit 4
"\xF6": "\u09EB", # Digit 5
"\xF7": "\u09EC", # Digit 6
"\xF8": "\u09ED", # Digit 7
"\xF9": "\u09EE", # Digit 8
"\xFA": "\u09EF", # Digit 9
}
self.hashcta_i2u = {
"\xA2": "\u0BAE\u0BCD", # Vowel-modifier ANUSWAR is m + halant
"\xA3": "\u0B83", # Vowel-modifier VISARG
"\xA4": "\u0B85", # Vowel A
"\xA5": "\u0B86", # Vowel AA
"\xA6": "\u0B87", # Vowel I
"\xA7": "\u0B88", # Vowel II
"\xA8": "\u0B89", # Vowel U
"\xA9": "\u0B8A", # Vowel UU
"\xAB": "\u0B8E", # Vowel
"\xAC": "\u0B8F",
"\xAD": "\u0B90", # Vowel AI
"\xAF": "\u0B92", # Vowel O
"\xB0": "\u0B93", # Vowel OW
"\xB1": "\u0B94", # Vowel AU
"\xB3": "\u0B95", # Consonant KA
"\xB7": "\u0B99", # Consonant NGA
"\xB8": "\u0B9A", # Consonant CHA
"\xBA": "\u0B9C", # Consonant JA
"\xBC": "\u0B9E", # Consonant JNA
"\xBD": "\u0B9F", # Consonant Hard TA
"\xC1": "\u0BA3", # Consonant Hard NA
"\xC2": "\u0BA4", # Consonant Soft TA
"\xC6": "\u0BA8", # Consonant Soft NA
"\xC7": "\u0BA9", # Consonant NA (Tamil)
"\xC8": "\u0BAA", # Consonant PA
"\xCC": "\u0BAE", # Consonant MA
"\xCD": "\u0BAF", # Consonant YA
"\xCF": "\u0BB0", # Consonant RA
"\xD0": "\u0BB1",
"\xD1": "\u0BB2", # Consonant LA
"\xD2": "\u0BB3", # Consonant Hard LA
"\xD3": "\u0BB4", # Consonant ZHA (Tamil & Malyalam)
"\xD4": "\u0BB5", # Consonant VA
"\xD5": "\u0BB7", # Consonant SHA is nomore use in tamil
"\xD6": "\u0BB7", # Consonant Hard SHA
"\xD7": "\u0BB8", # Consonant SA
"\xD8": "\u0BB9", # Consonant HA
"\xDA": "\u0BBE", # Vowel Sign AA
"\xDB": "\u0BBF", # Vowel Sign I
"\xDC": "\u0BC0", # Vowel Sign II
"\xDD": "\u0BC1", # Vowel Sign U
"\xDE": "\u0BC2", # Vowel Sign UU
"\xE0": "\u0BC6", # Vowel Sign E (Southern Scripts)
"\xE1": "\u0BC7", # Vowel Sign EY
"\xE2": "\u0BC8", # Vowel Sign AI
"\xE4": "\u0BCA", # Vowel Sign O
"\xE5": "\u0BCB", # Vowel Sign OW
"\xE6": "\u0BCC", # Vowel Sign AU
"\xE8": "\u0BCD", # Vowel Omission Sign (Halant)
"\xEA": ".", # Fullstop
"\xF1": "\u0BE6", # Digit 0
"\xF2": "\u0BE7", # Digit 1
"\xF3": "\u0BE8", # Digit 2
"\xF4": "\u0BE9", # Digit 3
"\xF5": "\u0BEA", # Digit 4
"\xF6": "\u0BEB", # Digit 5
"\xF7": "\u0BEC", # Digit 6
"\xF8": "\u0BED", # Digit 7
"\xF9": "\u0BEE", # Digit 8
"\xFA": "\u0BEF", # Digit 9
}
self.hasho_i2u = {
"\xA1": "\u0B01", # Vowel-modifier CHANDRABINDU
"\xA2": "\u0B02", # Vowel-modifier ANUSWAR
"\xA3": "\u0B03", # Vowel-modifier VISARG
"\xA4": "\u0B05", # Vowel A
"\xA5": "\u0B06", # Vowel AA
"\xA6": "\u0B07", # Vowel I
"\xA7": "\u0B08", # Vowel II
"\xA8": "\u0B09", # Vowel U
"\xA9": "\u0B0A", # Vowel UU
"\xAA": "\u0B0B", # Vowel RI
"\xAC": "\u0B0F", # Vowel EY
"\xAD": "\u0B10", # Vowel AI
"\xB0": "\u0B13", # Vowel OW
"\xB1": "\u0B14", # Vowel AU
"\xB3": "\u0B15", # Consonant KA
"\xB4": "\u0B16", # Consonant KHA
"\xB5": "\u0B17", # Consonant GA
"\xB6": "\u0B18", # Consonant GHA
"\xB7": "\u0B19", # Consonant NGA
"\xB8": "\u0B1A", # Consonant CHA
"\xB9": "\u0B1B", # Consonant CHHA
"\xBA": "\u0B1C", # Consonant JA
"\xBB": "\u0B1D", # Consonant JHA
"\xBC": "\u0B1E", # Consonant JNA
"\xBD": "\u0B1F", # Consonant Hard TA
"\xBE": "\u0B20", # Consonant Hard THA
"\xBF": "\u0B21", # Consonant Hard DA
"\xC0": "\u0B22", # Consonant Hard DHA
"\xC1": "\u0B23", # Consonant Hard NA
"\xC2": "\u0B24", # Consonant Soft TA
"\xC3": "\u0B25", # Consonant Soft THA
"\xC4": "\u0B26", # Consonant Soft DA
"\xC5": "\u0B27", # Consonant Soft DHA
"\xC6": "\u0B28", # Consonant Soft NA
"\xC8": "\u0B2A", # Consonant PA
"\xC9": "\u0B2B", # Consonant PHA
"\xCA": "\u0B2C", # Consonant BA
"\xCB": "\u0B2D", # Consonant BHA
"\xCC": "\u0B2E", # Consonant MA
"\xCD": "\u0B2F", # Consonant YA
"\xCF": "\u0B30", # Consonant RA
"\xD1": "\u0B32", # Consonant LA
"\xD2": "\u0B33", # Consonant Hard LA
"\xD4": "\u0B35", # Consonant VA
"\xD5": "\u0B36", # Consonant SHA
"\xD6": "\u0B37", # Consonant Hard SHA
"\xD7": "\u0B38", # Consonant SA
"\xD8": "\u0B39", # Consonant HA
"\xDA": "\u0B3E", # Vowel Sign AA
"\xDB": "\u0B3F", # Vowel Sign I
"\xDC": "\u0B40", # Vowel Sign II
"\xDD": "\u0B41", # Vowel Sign U
"\xDE": "\u0B42", # Vowel Sign UU
"\xDF": "\u0B43", # Vowel Sign RI
"\xE1": "\u0B47", # Vowel Sign EY
"\xE2": "\u0B48", # Vowel Sign AI
"\xE5": "\u0B4B", # Vowel Sign OW
"\xE6": "\u0B4C", # Vowel Sign AU
"\xE8": "\u0B4D", # Vowel Omission Sign (Halant)
"\xE9": "\u0B3C", # Diacritic Sign (Nukta)
"\xEA": ".", # Fullstop
"\xF1": "\u0B66", # Digit 0
"\xF2": "\u0B67", # Digit 1
"\xF3": "\u0B68", # Digit 2
"\xF4": "\u0B69", # Digit 3
"\xF5": "\u0B6A", # Digit 4
"\xF6": "\u0B6B", # Digit 5
"\xF7": "\u0B6C", # Digit 6
"\xF8": "\u0B6D", # Digit 7
"\xF9": "\u0B6E", # Digit 8
"\xFA": "\u0B6F", # Digit 9
}
self.hashg_i2u = {
"\xA1": "\u0A81", # Vowel-modifier CHANDRABINDU
"\xA2": "\u0A82", # Vowel-modifier ANUSWAR
"\xA3": "\u0A83", # Vowel-modifier VISARG
"\xA4": "\u0A85", # Vowel A
"\xA5": "\u0A86", # Vowel AA
"\xA6": "\u0A87", # Vowel I
"\xA7": "\u0A88", # Vowel II
"\xA8": "\u0A89", # Vowel U
"\xA9": "\u0A8A", # Vowel UU
"\xAA": "\u0A8B", # Vowel RI
"\xAE": "\u0A8D", # Vowel AI -Rashid added
# "\xB2": "\u0A8D", # Vowel AYE (Devanagari Script)
"\xAC": "\u0A8F", # Vowel EY
"\xAD": "\u0A90", # Vowel AI
"\xB0": "\u0A93", # Vowel OW
"\xB1": "\u0A94", # Vowel AU
"\xB2": "\u0A91", # Vowel AWE
"\xB3": "\u0A95", # Consonant KA
"\xB4": "\u0A96", # Consonant KHA
"\xB5": "\u0A97", # Consonant GA
"\xB6": "\u0A98", # Consonant GHA
"\xB7": "\u0A99", # Consonant NGA
"\xB8": "\u0A9A", # Consonant CHA
"\xB9": "\u0A9B", # Consonant CHHA
"\xBA": "\u0A9C", # Consonant JA
"\xBB": "\u0A9D", # Consonant JHA
"\xBC": "\u0A9E", # Consonant JNA
"\xBD": "\u0A9F", # Consonant Hard TA
"\xBE": "\u0AA0", # Consonant Hard THA
"\xBF": "\u0AA1", # Consonant Hard DA
"\xC0": "\u0AA2", # Consonant Hard DHA
"\xC1": "\u0AA3", # Consonant Hard NA
"\xC2": "\u0AA4", # Consonant Soft TA
"\xC3": "\u0AA5", # Consonant Soft THA
"\xC4": "\u0AA6", # Consonant Soft DA
"\xC5": "\u0AA7", # Consonant Soft DHA
"\xC6": "\u0AA8", # Consonant Soft NA
"\xC8": "\u0AAA", # Consonant PA
"\xC9": "\u0AAB", # Consonant PHA
"\xCA": "\u0AAC", # Consonant BA
"\xCB": "\u0AAD", # Consonant BHA
"\xCC": "\u0AAE", # Consonant MA
"\xCD": "\u0AAF", # Consonant YA
"\xCF": "\u0AB0", # Consonant RA
"\xD1": "\u0AB2", # Consonant LA
"\xD2": "\u0AB3", # Consonant Hard LA
"\xD4": "\u0AB5", # Consonant VA
"\xD5": "\u0AB6", # Consonant SHA
"\xD6": "\u0AB7", # Consonant Hard SHA
"\xD7": "\u0AB8", # Consonant SA
"\xD8": "\u0AB9", # Consonant HA
"\xE9": "\u0ABC", # Diacritic Sign (Nukta)
"\xDA": "\u0ABE", # Vowel Sign AA
"\xDB": "\u0ABF", # Vowel Sign I
"\xDC": "\u0AC0", # Vowel Sign II
"\xDD": "\u0AC1", # Vowel Sign U
"\xDE": "\u0AC2", # Vowel Sign UU
"\xDF": "\u0AC3", # Vowel Sign RI
"\xE1": "\u0AC7", # Vowel Sign EY
"\xE2": "\u0AC8", # Vowel Sign AI
"\xE3": "\u0AC5", # Vowel Sign AYE (Devanagari Script)
"\xE5": "\u0ACB", # Vowel Sign OW
"\xE6": "\u0ACC", # Vowel Sign AU
"\xE7": "\u0AC9", # Vowel Sign AWE (Devanagari Script)
"\xE8": "\u0ACD", # Vowel Omission Sign (Halant)
"\xEA": ".", # Fullstop
"\xF1": "\u0AE6", # Digit 0
"\xF2": "\u0AE7", # Digit 1
"\xF3": "\u0AE8", # Digit 2
"\xF4": "\u0AE9", # Digit 3
"\xF5": "\u0AEA", # Digit 4
"\xF6": "\u0AEB", # Digit 5
"\xF7": "\u0AEC", # Digit 6
"\xF8": "\u0AED", # Digit 7
"\xF9": "\u0AEE", # Digit 8
"\xFA": "\u0AEF", # Digit 9
}
# Change from WX to IT3 done in the following lines of code for Telugu
# compile regexes
const = 'kgfcjtdpbmylvshrn'
# special consonants which take two or more letters
constsp = 't:|d:|ng~|nj~|nd~|l:|r:|sh'
# new unified defintion where regex can follow match order
nconst = ("shh|chh|ng-|nj-|nd-|t\'h|d\'h|kh|gh|ch|jh|th|dh|ph|bh|sh|"
"t\'|l\'|r\'|d\'|k|g|j|t|d|n|p|b|m|y|r|l|v|s|h")
nvovel = 'rx-|rx|ei|ai|au|aa|ii|uu|oo|a|i|u|e|o'
nmd = 'n\'|:'
nq = 'rx'
self.ncvmd = re.compile("(%s)(%s)(%s)" % (nconst, nvovel, nmd))
self.ncamd = re.compile("(%s)a(%s)" % (nconst, nmd))
self.ncmd = re.compile("(%s)(%s)" % (nconst, nmd))
self.ncv = re.compile("(%s)(%s)" % (nconst, nvovel))
self.nca = re.compile("(%s)a" % nconst)
self.nc = re.compile("(%s)" % nconst)
self.nvmd = re.compile("(%s)(%s)" % (nvovel, nmd))
self.nv = re.compile("(%s)" % nvovel)
self.nmd = re.compile("(%s)" % nmd)
self.ncqmd = re.compile("(%s)(%s)(%s)" % (nconst, nq, nmd))
self.nqmd = re.compile("(%s)(%s)" % (nq, nmd))
self.ncq = re.compile("(%s)(%s)" % (nconst, nq))
self.nq = re.compile("(%s)" % nq)
# self.ceVmd = re.compile("([%s])eV([MHz])" % const)
self.cspe3md = re.compile("(%s)(ei|ai|au)(n?:)" % constsp)
self.cspe3 = re.compile("(%s)(ei|ai|au)" % constsp)
self.cspvmd = re.compile("(%s)([aeiou]{1,2})(n?:)" % constsp)
self.cspa = re.compile("((%s)h?)a" % constsp)
self.csp = re.compile("(%s)h?" % constsp)
self.cspamd = re.compile("(%s)a(n?:)" % constsp)
self.cspv = re.compile("(%s)([aeiou]{1,2})" % constsp)
self.ce3md = re.compile("([%s])(ei|ai|au)(n?:)" % const)
self.ce3 = re.compile("([%s])(ei|ai|au)" % const)
self.ca = re.compile("([%s]h?)a" % const)
self.c = re.compile("([%s])h?" % const)
self.cvmd = re.compile("([%s])([aeiou]{1,2})(n?:)" % const)
self.cv = re.compile("([%s])([aeiou]{1,2})" % const)
self.camd = re.compile("([%s])a(n?:)" % const)
self.cspqmd = re.compile("(%s)rx(n?:)" % constsp)
self.cspq = re.compile("(%s)rx" % constsp)
self.cqmd = re.compile("([%s])rx(n?:)" % const)
self.cq = re.compile("([%s])rx" % const)
self.qmd = re.compile("rx(n?:)")
self.dig = re.compile("([0-9])")
self.i2u = re.compile('([\xA1-\xFB])')
def initialize_utf2it3_hash(self):
self.hashc_i2w = {
"\xB3": "k",
"\xB4": "K",
"\xB5": "g",
"\xB6": "G",
"\xB7": "f",
"\xB8": "c",
"\xB9": "C",
"\xBA": "j",
"\xBB": "J",
"\xBC": "F",
"\xBD": "t",
"\xBE": "T",
"\xBF": "d",
"\xC0": "D",
"\xC1": "N",
"\xC2": "w",
"\xC3": "W",
"\xC4": "x",
"\xC5": "X",
"\xC6": "n",
"\xC7": "nY",
"\xC8": "p",
"\xC9": "P",
"\xCA": "b",
"\xCB": "B",
"\xCC": "m",
"\xCD": "y",
"\xCF": "r",
# Representation for Consonant HARD RA (Southern Script)
"\xD0": "rY",
"\xD1": "l",
"\xD2": "lY",
# Representation for Consonant ZHA (Tamil & Malyalam)
"\xD3": "lYY",
"\xD4": "v",
"\xD5": "S",
"\xD6": "R",
"\xD7": "s",
"\xD8": "h",
"\xE9": "Z", # NUKTA
}
self.hashv_i2w = {
"\xA4": "a",
"\xA5": "A",
"\xA6": "i",
"\xA7": "I",
"\xA8": "u",
"\xA9": "U",
"\xAA": "q",
"\xAB": "eV",
"\xAC": "e",
"\xAD": "E",
"\xAE": "EY",
"\xAF": "oV",
"\xB0": "o",
"\xB1": "O",
"\xB2": "OY",
}
self.hashm_i2w = {
"\xDA": "A",
"\xDB": "i",
"\xDC": "I",
"\xDD": "u",
"\xDE": "U",
"\xDF": "q",
"\xE0": "eV",
"\xE1": "e",
"\xE2": "E",
"\xE3": "EY",
"\xE4": "oV",
"\xE5": "o",
"\xE6": "O",
"\xE7": "OY",
}
self.hashmd_i2w = {
"\xA1": "z",
"\xA2": "M",
"\xA3": "H",
}
self.digits_i2w = {
"\xF1": "0",
"\xF2": "1",
"\xF3": "2",
"\xF4": "3",
"\xF5": "4",
"\xF6": "5",
"\xF7": "6",
"\xF8": "7",
"\xF9": "8",
"\xFA": "9",
}
self.hashh_u2i = {
"\u0901": "\xA1", # Vowel-modifier CHANDRABINDU
"\u0902": "\xA2", # Vowel-modifier ANUSWAR
"\u0903": "\xA3", # Vowel-modifier VISARG
"\u0905": "\xA4", # Vowel A
"\u0906": "\xA5", # Vowel AA
"\u0907": "\xA6", # Vowel I
"\u0908": "\xA7", # Vowel II
"\u0909": "\xA8", # Vowel U
"\u090A": "\xA9", # Vowel UU
"\u090B": "\xAA", # Vowel RI
"\u090D": "\xAE",
"\u090E": "\xAB",
"\u090F": "\xAC",
"\u0910": "\xAD",
"\u0911": "\xB2",
"\u0912": "\xAF",
"\u0913": "\xB0",
"\u0914": "\xB1",
"\u0915": "\xB3", # Consonant KA
"\u0916": "\xB4", # Consonant
"\u0917": "\xB5", # Consonant
"\u0918": "\xB6", # Consonant
"\u0919": "\xB7", # Consonant NGA
"\u091A": "\xB8", # Consonant
"\u091B": "\xB9", # Consonant
"\u091C": "\xBA", # Consonant
"\u091D": "\xBB", # Consonant
"\u091E": "\xBC", # Consonant JNA
"\u091F": "\xBD", # Consonant
"\u0920": "\xBE", # Consonant
"\u0921": "\xBF", # Consonant
"\u0922": "\xC0", # Consonant
"\u0923": "\xC1", # Consonant NA
"\u0924": "\xC2", # Consonant
"\u0925": "\xC3", # Consonant
"\u0926": "\xC4", # Consonant
"\u0927": "\xC5", # Consonant
"\u0928": "\xC6", # Consonant NA
"\u0929": "\xC7", # Consonant NNNA
"\u092A": "\xC8", # Consonant PA
"\u092B": "\xC9", # Consonant PHA
"\u092C": "\xCA", # Consonant BA
"\u092D": "\xCB", # Consonant BHA
"\u092E": "\xCC", # Consonant MA
"\u092F": "\xCD", # Consonant YA
"\u0930": "\xCF", # Consonant RA
"\u0931": "\xD0", # Consonant RRA
"\u0932": "\xD1", # Consonant LA
"\u0933": "\xD2", # Consonant LLA
"\u0934": "\xD3", # Consonant LLLA
"\u0935": "\xD4", # Consonant VA
"\u0936": "\xD5", # Consonant SHA
"\u0937": "\xD6", # Consonant SSA
"\u0938": "\xD7", # Consonant SA
"\u0939": "\xD8", # Consonant HA
"\u093C": "\xE9", # Consonant NUKTA
"\u093E": "\xDA", # Vowel Sign AA
"\u093F": "\xDB", # Vowel Sign I
"\u0940": "\xDC", # Vowel Sign II
"\u0941": "\xDD", # Vowel Sign U
"\u0942": "\xDE", # Vowel
"\u0943": "\xDF", # Vowel
"\u0946": "\xE0", # Vowel
"\u0947": "\xE1", # Vowel
"\u0948": "\xE2", # Vowel
"\u0949": "\xE7", # Vowel
"\u094A": "\xE4", # Vowel
"\u094B": "\xE5", # Vowel
"\u094C": "\xE6", # Vowel
"\u094D": "\xE8", # Halant
"\u0960": "\xAA", # Vowel Sanskrit
"\u0966": "\xF1", # Devanagari Digit 0
"\u0967": "\xF2", # Devanagari Digit 1
"\u0968": "\xF3", # Devanagari Digit 2
"\u0969": "\xF4", # Devanagari Digit 3
"\u096A": "\xF5", # Devanagari Digit 4
"\u096B": "\xF6", # Devanagari Digit 5
"\u096C": "\xF7", # Devanagari Digit 6
"\u096D": "\xF8", # Devanagari Digit 7
"\u096E": "\xF9", # Devanagari Digit 8
"\u096F": "\xFA", # Devanagari Digit 9
}
self.unicode_norm_hashh_u2i = {
"\u0958": "\u0915",
"\u0959": "\u0916",
"\u095A": "\u0917",
"\u095B": "\u091C",
"\u095C": "\u0921",
"\u095D": "\u0922",
"\u095E": "\u092B",
"\u095F": "\u092F",
}
self.hasht_u2i = {
"\u0C01": "\xA1",
"\u0C02": "\xA2",
"\u0C03": "\xA3",
"\u0C05": "\xA4",
"\u0C06": "\xA5",
"\u0C07": "\xA6",
"\u0C08": "\xA7",
"\u0C09": "\xA8",
"\u0C0A": "\xA9",
"\u0C0B": "\xAA",
"\u0C0D": "\xAE",
"\u0C0E": "\xAB",
"\u0C0F": "\xAC",
"\u0C10": "\xAD",
"\u0C11": "\xB2",
"\u0C12": "\xAF",
"\u0C13": "\xB0",
"\u0C14": "\xB1",
"\u0C15": "\xB3",
"\u0C16": "\xB4",
"\u0C17": "\xB5",
"\u0C18": "\xB6",
"\u0C19": "\xB7",
"\u0C1A": "\xB8",
"\u0C1B": "\xB9",
"\u0C1C": "\xBA",
"\u0C1D": "\xBB",
"\u0C1E": "\xBC",
"\u0C1F": "\xBD",
"\u0C20": "\xBE",
"\u0C21": "\xBF",
"\u0C22": "\xC0",
"\u0C23": "\xC1",
"\u0C24": "\xC2",
"\u0C25": "\xC3",
"\u0C26": "\xC4",
"\u0C27": "\xC5",
"\u0C28": "\xC6",
"\u0C29": "\xC7",
"\u0C2A": "\xC8",
"\u0C2B": "\xC9",
"\u0C2C": "\xCA",
"\u0C2D": "\xCB",
"\u0C2E": "\xCC",
"\u0C2F": "\xCD",
"\u0C30": "\xCF",
"\u0C31": "\xD0",
"\u0C32": "\xD1",
"\u0C33": "\xD2",
"\u0C34": "\xD3",
"\u0C35": "\xD4",
"\u0C36": "\xD5",
"\u0C37": "\xD6",
"\u0C38": "\xD7",
"\u0C39": "\xD8",
"\u0C3E": "\xDA",
"\u0C3F": "\xDB",
"\u0C40": "\xDC",
"\u0C41": "\xDD",
"\u0C42": "\xDE",
"\u0C43": "\xDF",
"\u0C46": "\xE0",
"\u0C47": "\xE1",
"\u0C48": "\xE2",
"\u0C4A": "\xE4",
"\u0C4B": "\xE5",
"\u0C4C": "\xE6",
"\u0C4D": "\xE8",
"\u0C64": "\xEA",
"\u0C65": "\xEA", # ADDED
"\u0C66": "\xF1",
"\u0C67": "\xF2",
"\u0C68": "\xF3",
"\u0C69": "\xF4",
"\u0C6A": "\xF5",
"\u0C6B": "\xF6",
"\u0C6C": "\xF7",
"\u0C6D": "\xF8",
"\u0C6E": "\xF9",
"\u0C6F": "\xFA",
}
self.hashp_u2i = {
"\u0A01": "\xA1", # Vowel-modifier CHANDRABINDU
"\u0A02": "\xA2", # Vowel-modifier ANUSWAR
"\u0A03": "\xA3", # Vowel-modifier VISARG
"\u0A05": "\xA4", # Vowel A
"\u0A06": "\xA5", # Vowel AA
"\u0A07": "\xA6", # Vowel I
"\u0A08": "\xA7", # Vowel II
"\u0A09": "\xA8", # Vowel U
"\u0A0A": "\xA9", # Vowel UU
"\u0A0B": "\xAA", # Vowel RI
"\u0A0D": "\xAE",
"\u0A0E": "\xAB",
"\u0A0F": "\xAC",
"\u0A10": "\xAD",
"\u0A11": "\xB2",
"\u0A12": "\xAF",
"\u0A13": "\xB0",
"\u0A14": "\xB1",
"\u0A15": "\xB3", # Consonant KA
"\u0A16": "\xB4", # Consonant
"\u0A17": "\xB5", # Consonant
"\u0A18": "\xB6", # Consonant
"\u0A19": "\xB7", # Consonant NGA
"\u0A1A": "\xB8", # Consonant
"\u0A1B": "\xB9", # Consonant
"\u0A1C": "\xBA", # Consonant
"\u0A1D": "\xBB", # Consonant
"\u0A1E": "\xBC", # Consonant JNA
"\u0A1F": "\xBD", # Consonant
"\u0A20": "\xBE", # Consonant
"\u0A21": "\xBF", # Consonant
"\u0A22": "\xC0", # Consonant
"\u0A23": "\xC1", # Consonant NA
"\u0A24": "\xC2", # Consonant
"\u0A25": "\xC3", # Consonant
"\u0A26": "\xC4", # Consonant
"\u0A27": "\xC5", # Consonant
"\u0A28": "\xC6", # Consonant NA
"\u0A29": "\xC7", # Consonant NNNA
"\u0A2A": "\xC8", # Consonant PA
"\u0A2B": "\xC9", # Consonant PHA
"\u0A2C": "\xCA", # Consonant BA
"\u0A2D": "\xCB", # Consonant BHA
"\u0A2E": "\xCC", # Consonant MA
"\u0A2F": "\xCD", # Consonant YA
"\u0A30": "\xCF", # Consonant RA
"\u0A31": "\xD0", # Consonant RRA
"\u0A32": "\xD1", # Consonant LA
"\u0A33": "\xD2", # Consonant LLA
"\u0A34": "\xD3", # Consonant LLLA
"\u0A35": "\xD4", # Consonant VA
"\u0A36": "\xD5", # Consonant SHA
"\u0A37": "\xD6", # Consonant SSA
"\u0A38": "\xD7", # Consonant SA
"\u0A39": "\xD8", # Consonant HA
"\u0A3C": "\xE9", # Consonant NUKTA
"\u0A3E": "\xDA", # Vowel Sign AA
"\u0A3F": "\xDB", # Vowel Sign I
"\u0A40": "\xDC", # Vowel Sign II
"\u0A41": "\xDD", # Vowel Sign U
"\u0A42": "\xDE", # Vowel
"\u0A43": "\xDF", # Vowel
"\u0A46": "\xE0", # Vowel
"\u0A47": "\xE1", # Vowel
"\u0A48": "\xE2", # Vowel
"\u0A49": "\xE7", # Vowel
"\u0A4A": "\xE4", # Vowel
"\u0A4B": "\xE5", # Vowel
"\u0A4C": "\xE6", # Vowel
"\u0A4D": "\xE8", # Vowel Omission Sign Halant
"\u0A5C": "\xE8", # Vowel Omission Sign Halant
"\u0A64": "\xEA", # PURNA VIRAM Reserved
"\u0A65": "\xEA", # DEERGH VIRAM
"\u0A66": "\xF1", # Consonant
"\u0A67": "\xF2", # Consonant
"\u0A68": "\xF3", # Consonant
"\u0A69": "\xF4", # Consonant
"\u0A6A": "\xF5", # Consonant
"\u0A6B": "\xF6",
"\u0A6C": "\xF7",
"\u0A6D": "\xF8",
"\u0A6E": "\xF9",
"\u0A6F": "\xFA",
"\u0A70": "\xA1", # Vowel-modifier GURMUKHI TIPPI
"\u0A71": "\xFB", # GURMUKHI ADDAK
}
self.unicode_norm_hashp_u2i = {
"\u0A59": "\u0A16",
"\u0A5A": "\u0A17",
"\u0A5B": "\u0A1C",
"\u0A5E": "\u0A2B",
}
self.hashk_u2i = {
"\u0C82": "\xA2", # Vowel-modifier ANUSWAR
"\u0C83": "\xA3", # Vowel-modifier VISARG
"\u0C85": "\xA4", # Vowel A
"\u0C86": "\xA5", # Vowel AA
"\u0C87": "\xA6", # Vowel I
"\u0C88": "\xA7", # Vowel II
"\u0C89": "\xA8", # Vowel U
"\u0C8A": "\xA9", # Vowel UU
"\u0C8B": "\xAA", # Vowel RI
"\u0C8D": "\xAE",
"\u0C8E": "\xAB",
"\u0C8F": "\xAC",
"\u0C90": "\xAD",
"\u0C91": "\xB2",
"\u0C92": "\xAF",
"\u0C93": "\xB0",
"\u0C94": "\xB1",
"\u0C95": "\xB3", # Consonant KA
"\u0C96": "\xB4", # Consonant
"\u0C97": "\xB5", # Consonant
"\u0C98": "\xB6", # Consonant
"\u0C99": "\xB7", # Consonant NGA
"\u0C9A": "\xB8", # Consonant
"\u0C9B": "\xB9", # Consonant
"\u0C9C": "\xBA", # Consonant
"\u0C9D": "\xBB", # Consonant
"\u0C9E": "\xBC", # Consonant JNA
"\u0C9F": "\xBD", # Consonant
"\u0CA0": "\xBE", # Consonant
"\u0CA1": "\xBF", # Consonant
"\u0CA2": "\xC0", # Consonant
"\u0CA3": "\xC1", # Consonant NA
"\u0CA4": "\xC2", # Consonant
"\u0CA5": "\xC3", # Consonant
"\u0CA6": "\xC4", # Consonant
"\u0CA7": "\xC5", # Consonant
"\u0CA8": "\xC6", # Consonant NA
"\u0CA9": "\xC7", # Consonant NNNA
"\u0CAA": "\xC8", # Consonant PA
"\u0CAB": "\xC9", # Consonant PHA
"\u0CAC": "\xCA", # Consonant BA
"\u0CAD": "\xCB", # Consonant BHA
"\u0CAE": "\xCC", # Consonant MA
"\u0CAF": "\xCD", # Consonant YA
"\u0CB0": "\xCF", # Consonant RA
"\u0CB1": "\xD0", # Consonant RRA
"\u0CB2": "\xD1", # Consonant LA
"\u0CB3": "\xD2", # Consonant LLA
"\u0CB4": "\xD3", # Consonant LLLA
"\u0CB5": "\xD4", # Consonant VA
"\u0CB6": "\xD5", # Consonant SHA
"\u0CB7": "\xD6", # Consonant SSA
"\u0CB8": "\xD7", # Consonant SA
"\u0CB9": "\xD8", # Consonant HA
"\u0CBC": "\xE9", # Consonant NUKTA
"\u0CBE": "\xDA", # Vowel Sign AA
"\u0CBF": "\xDB", # Vowel Sign I
"\u0CC0": "\xDC", # Vowel Sign II
"\u0CC1": "\xDD", # Vowel Sign U
"\u0CC2": "\xDE", # Vowel
"\u0CC3": "\xDF", # Vowel
"\u0CC6": "\xE0", # Vowel
"\u0CC7": "\xE1", # Vowel
"\u0CC8": "\xE2", # Vowel
"\u0CC9": "\xE7", # Vowel
"\u0CCA": "\xE4", # Vowel
"\u0CCB": "\xE5", # Vowel
"\u0CCC": "\xE6", # Vowel
"\u0CCD": "\xE8", # Consonant
"\u0CE4": "\xEA", # PURNA VIRAM Reserved
"\u0CE5": "\xEA", # DEERGH VIRAM
"\u0CE6": "\xF1", # Consonant
"\u0CE7": "\xF2", # Consonant
"\u0CE8": "\xF3", # Consonant
"\u0CE9": "\xF4", # Consonant
"\u0CEA": "\xF5", # Consonant
"\u0CEB": "\xF6",
"\u0CEC": "\xF7",
"\u0CED": "\xF8",
"\u0CEE": "\xF9",
"\u0CEF": "\xFA",
}
self.hashm_u2i = {
"\u0D02": "\xA2", # Vowel-modifier ANUSWAR
"\u0D03": "\xA3", # Vowel-modifier VISARG
"\u0D05": "\xA4", # Vowel A
"\u0D06": "\xA5", # Vowel AA
"\u0D07": "\xA6", # Vowel I
"\u0D08": "\xA7", # Vowel II
"\u0D09": "\xA8", # Vowel U
"\u0D0A": "\xA9", # Vowel UU
"\u0D0B": "\xAA", # Vowel RI
"\u0D0E": "\xAB",
"\u0D0F": "\xAC",
"\u0D10": "\xAD",
"\u0D11": "\xB2",
"\u0D12": "\xAF",
"\u0D13": "\xB0",
"\u0D14": "\xB1",
"\u0D15": "\xB3", # Consonant KA
"\u0D16": "\xB4", # Consonant
"\u0D17": "\xB5", # Consonant
"\u0D18": "\xB6", # Consonant
"\u0D19": "\xB7", # Consonant NGA
"\u0D1A": "\xB8", # Consonant
"\u0D1B": "\xB9", # Consonant
"\u0D1C": "\xBA", # Consonant
"\u0D1D": "\xBB", # Consonant
"\u0D1E": "\xBC", # Consonant JNA
"\u0D1F": "\xBD", # Consonant
"\u0D20": "\xBE", # Consonant
"\u0D21": "\xBF", # Consonant
"\u0D22": "\xC0", # Consonant
"\u0D23": "\xC1", # Consonant NNA
"\u0D24": "\xC2", # Consonant
"\u0D25": "\xC3", # Consonant
"\u0D26": "\xC4", # Consonant
"\u0D27": "\xC5", # Consonant
"\u0D28": "\xC6", # Consonant NA
"\u0D29": "\xC7", # Consonant NNNA
"\u0D2A": "\xC8", # Consonant PA
"\u0D2B": "\xC9", # Consonant PHA
"\u0D2C": "\xCA", # Consonant BA
"\u0D2D": "\xCB", # Consonant BHA
"\u0D2E": "\xCC", # Consonant MA
"\u0D2F": "\xCD", # Consonant YA
"\u0D30": "\xCF", # Consonant RA
"\u0D31": "\xD0", # Consonant RRA
"\u0D32": "\xD1", # Consonant LA
"\u0D33": "\xD2", # Consonant LLA
"\u0D34": "\xD3", # Consonant LLLA
"\u0D35": "\xD4", # Consonant VA
"\u0D36": "\xD5", # Consonant SHA
"\u0D37": "\xD6", # Consonant SSA
"\u0D38": "\xD7", # Consonant SA
"\u0D39": "\xD8", # Consonant HA
"\u0D3E": "\xDA", # Vowel Sign AA
"\u0D3F": "\xDB", # Vowel Sign I
"\u0D40": "\xDC", # Vowel Sign II
"\u0D41": "\xDD", # Vowel Sign U
"\u0D42": "\xDE", # Vowel
"\u0D43": "\xDF", # Vowel
"\u0D46": "\xE0", # Vowel
"\u0D47": "\xE1", # Vowel
"\u0D48": "\xE2", # Vowel
"\u0D4A": "\xE4", # Vowel
"\u0D4B": "\xE5", # Vowel
"\u0D4C": "\xE6", # Vowel
"\u0D4D": "\xE8", # Consonant
"\u0D64": "\xEA", # PURNA VIRAM Reserved
"\u0D65": "\xEA", # DEERGH VIRAM
"\u0D66": "\xF1", # Consonant
"\u0D67": "\xF2", # Consonant
"\u0D68": "\xF3", # Consonant
"\u0D69": "\xF4", # Consonant
"\u0D6A": "\xF5", # Consonant
"\u0D6B": "\xF6",
"\u0D6C": "\xF7",
"\u0D6D": "\xF8",
"\u0D6E": "\xF9",
"\u0D6F": "\xFA",
}
self.hashb_u2i = {
"\u0981": "\xA1", # vowel-modifier CHANDRABINDU
"\u0982": "\xA2", # Vowel-modifier ANUSWAR
"\u0983": "\xA3", # Vowel-modifier VISARG
"\u0985": "\xA4", # Vowel A
"\u0986": "\xA5", # Vowel AA
"\u0987": "\xA6", # Vowel I
"\u0988": "\xA7", # Vowel II
"\u0989": "\xA8", # Vowel U
"\u098A": "\xA9", # Vowel UU
"\u098B": "\xAA", # Vowel RI
"\u098F": "\xAB",
"\u0990": "\xAD",
"\u0993": "\xAF",
"\u0994": "\xB1",
"\u0995": "\xB3", # Consonant KA
"\u0996": "\xB4", # Consonant
"\u0997": "\xB5", # Consonant
"\u0998": "\xB6", # Consonant
"\u0999": "\xB7", # Consonant NGA
"\u099A": "\xB8", # Consonant
"\u099B": "\xB9", # Consonant
"\u099C": "\xBA", # Consonant
"\u099D": "\xBB", # Consonant
"\u099E": "\xBC", # Consonant JNA
"\u099F": "\xBD", # Consonant
"\u09A0": "\xBE", # Consonant
"\u09A1": "\xBF", # Consonant
"\u09A2": "\xC0", # Consonant
"\u09A3": "\xC1", # Consonant NA
"\u09A4": "\xC2", # Consonant
"\u09A5": "\xC3", # Consonant
"\u09A6": "\xC4", # Consonant
"\u09A7": "\xC5", # Consonant
"\u09A8": "\xC6", # Consonant NA
"\u09AA": "\xC8", # Consonant PA
"\u09AB": "\xC9", # Consonant PHA
"\u09AC": "\xCA", # Consonant BA
"\u09AD": "\xCB", # Consonant BHA
"\u09AE": "\xCC", # Consonant MA
"\u09AF": "\xCD", # Consonant YA
"\u09B0": "\xCF", # Consonant RA
"\u09B2": "\xD1", # Consonant LA
"\u09B6": "\xD5", # Consonant SHA
"\u09B7": "\xD6", # Consonant SSA
"\u09B8": "\xD7", # Consonant SA
"\u09B9": "\xD8", # Consonant HA
"\u09BC": "\xE9", # Consonant NUKTA
"\u09BE": "\xDA", # Vowel Sign AA
"\u09BF": "\xDB", # Vowel Sign I
"\u09C0": "\xDC", # Vowel Sign II
"\u09C1": "\xDD", # Vowel Sign U
"\u09C2": "\xDE", # Vowel
"\u09C3": "\xDF", # Vowel
"\u09C7": "\xE0", # Vowel
"\u09C8": "\xE2", # Vowel
"\u09CB": "\xE4", # Vowel
"\u09CC": "\xE6", # Vowel
"\u09CD": "\xE8", # Consonant
"\u09E4": "\xEA", # PURNA VIRAM Reserved
"\u09E5": "\xEA", # DEERGH VIRAM
"\u09E6": "\xF1", # Consonant
"\u09E7": "\xF2", # Consonant
"\u09E8": "\xF3", # Consonant
"\u09E9": "\xF4", # Consonant
"\u09EA": "\xF5", # Consonant
"\u09EB": "\xF6",
"\u09EC": "\xF7",
"\u09ED": "\xF8",
"\u09EE": "\xF9",
"\u09EF": "\xFA",
}
self.unicode_norm_hashb_u2i = {
"\u09DC": "\u09A1", # ADDED
"\u09DD": "\u09A2", # ADDED
"\u09DF": "\u09AF" # ADDED
}
self.hashta_u2i = {
"\u0B82": "\xA2", # Vowel-modifier ANUSWAR
"\u0B83": "\xA3", # Vowel-modifier VISARG
"\u0B85": "\xA4", # Vowel A
"\u0B86": "\xA5", # Vowel AA
"\u0B87": "\xA6", # Vowel I
"\u0B88": "\xA7", # Vowel II
"\u0B89": "\xA8", # Vowel U
"\u0B8A": "\xA9", # Vowel UU
"\u0B8E": "\xAB",
"\u0B8F": "\xAC",
"\u0B90": "\xAD",
"\u0B92": "\xAF", # check here
"\u0B93": "\xB0",
"\u0B94": "\xB1",
"\u0B95": "\xB3", # Consonant KA
"\u0B99": "\xB7", # Consonant NGA
"\u0B9A": "\xB8", # Consonant
"\u0B9C": "\xBA", # Consonant
"\u0B9E": "\xBC", # Consonant JNA
"\u0B9F": "\xBD", # Consonant
"\u0BA3": "\xC1", # Consonant NA
"\u0BA4": "\xC2", # Consonant
"\u0BA8": "\xC6", # Consonant NA
"\u0BA9": "\xC7", # Consonant NNNA
"\u0BAA": "\xC8", # Consonant PA
"\u0BAE": "\xCC", # Consonant MA
"\u0BAF": "\xCD", # Consonant YA
"\u0BB0": "\xCF", # Consonant RA
"\u0BB1": "\xD0", # Consonant RRA
"\u0BB2": "\xD1", # Consonant LA
"\u0BB3": "\xD2", # Consonant LLA
"\u0BB4": "\xD3", # Consonant LLLA
"\u0BB5": "\xD4", # Consonant VA
"\u0BB6": "\xD5", # Consonant SHA
"\u0BB7": "\xD6", # Consonant SSA
"\u0BB8": "\xD7", # Consonant SA
"\u0BB9": "\xD8", # Consonant HA
"\u0BBE": "\xDA", # Vowel Sign AA
"\u0BBF": "\xDB", # Vowel Sign I
"\u0BC0": "\xDC", # Vowel Sign II
"\u0BC1": "\xDD", # Vowel Sign U
"\u0BC2": "\xDE", # Vowel
"\u0BC6": "\xE0", # Vowel
"\u0BC7": "\xE1", # Vowel
"\u0BC8": "\xE2", # Vowel
"\u0BCA": "\xE4", # Vowel
"\u0BCB": "\xE5", # Vowel
"\u0BCC": "\xE6", # Vowel
"\u0BCD": "\xE8", # Halant
"\u0BE4": "\xEA", # PURNA VIRAM Reserved
"\u0BE5": "\xEA", # DEERGH VIRAM
"\u0BE6": "\xF1", # Consonant
"\u0BE7": "\xF2", # Consonant
"\u0BE8": "\xF3", # Consonant
"\u0BE9": "\xF4", # Consonant
"\u0BEA": "\xF5", # Consonant
"\u0BEB": "\xF6",
"\u0BEC": "\xF7",
"\u0BED": "\xF8",
"\u0BEE": "\xF9",
"\u0BEF": "\xFA",
}
self.hasho_u2i = {
"\u0B01": "\xA1", # Vowel-modifier CHANDRABINDU
"\u0B02": "\xA2", # Vowel-modifier ANUSWAR
"\u0B03": "\xA3", # Vowel-modifier VISARG
"\u0B05": "\xA4", # Vowel A
"\u0B06": "\xA5", # Vowel AA
"\u0B07": "\xA6", # Vowel I
"\u0B08": "\xA7", # Vowel II
"\u0B09": "\xA8", # Vowel U
"\u0B0A": "\xA9", # Vowel UU
"\u0B0B": "\xAA", # Vowel RI
"\u0B0F": "\xAC",
"\u0B10": "\xAD",
"\u0B13": "\xB0",
"\u0B14": "\xB1",
"\u0B15": "\xB3", # Consonant KA
"\u0B16": "\xB4", # Consonant
"\u0B17": "\xB5", # Consonant
"\u0B18": "\xB6", # Consonant
"\u0B19": "\xB7", # Consonant NGA
"\u0B1A": "\xB8", # Consonant
"\u0B1B": "\xB9", # Consonant
"\u0B1C": "\xBA", # Consonant
"\u0B1D": "\xBB", # Consonant
"\u0B1E": "\xBC", # Consonant JNA
"\u0B1F": "\xBD", # Consonant
"\u0B20": "\xBE", # Consonant
"\u0B21": "\xBF", # Consonant
"\u0B22": "\xC0", # Consonant
"\u0B23": "\xC1", # Consonant NA
"\u0B24": "\xC2", # Consonant
"\u0B25": "\xC3", # Consonant
"\u0B26": "\xC4", # Consonant
"\u0B27": "\xC5", # Consonant
"\u0B28": "\xC6", # Consonant NA
"\u0B2A": "\xC8", # Consonant PA
"\u0B2B": "\xC9", # Consonant PHA
"\u0B2C": "\xCA", # Consonant BA
"\u0B2D": "\xCB", # Consonant BHA
"\u0B2E": "\xCC", # Consonant MA
"\u0B2F": "\xCD", # Consonant YA
"\u0B30": "\xCF", # Consonant RA
"\u0B32": "\xD1", # Consonant LA
"\u0B33": "\xD2", # Consonant LLA
"\u0935": "\xD4", # Consonant VA
"\u0B36": "\xD5", # Consonant SHA
"\u0B37": "\xD6", # Consonant SSA
"\u0B38": "\xD7", # Consonant SA
"\u0B39": "\xD8", # Consonant HA
"\u0B3C": "\xE9", # Consonant NUKTA
"\u0B3E": "\xDA", # Vowel Sign AA
"\u0B3F": "\xDB", # Vowel Sign I
"\u0B40": "\xDC", # Vowel Sign II
"\u0B41": "\xDD", # Vowel Sign U
"\u0B42": "\xDE", # Vowel
"\u0B43": "\xDF", # Vowel
"\u0B47": "\xE1", # Vowel
"\u0B48": "\xE2", # Vowel
"\u0B4B": "\xE5", # Vowel O
"\u0B4C": "\xE6", # Vowel OU
"\u0B4D": "\xE8", # Halant
"\u0B64": "\xEA", # PURNA VIRAM Reserved
"\u0B65": "\xEA", # DEERGH VIRAM
"\u0B66": "\xF1", # Digit 0
"\u0B67": "\xF2", # Digit 1
"\u0B68": "\xF3", # Digit 2
"\u0B69": "\xF4", # Digit 3
"\u0B6A": "\xF5", # Digit 4
"\u0B6B": "\xF6", # Digit 5
"\u0B6C": "\xF7", # Digit 6
"\u0B6D": "\xF8", # Digit 7
"\u0B6E": "\xF9", # Digit 8
"\u0B6F": "\xFA", # Digit 9
}
self.unicode_norm_hasho_u2i = {
"\u0B5C": "\u0B21", # ADDED
"\u0B5D": "\u0B22", # ADDED
"\u0B5F": "\u0B2F" # ADDED FOR EASE
}
self.hashg_u2i = {
"\u0A81": "\xA1", # Vowel-modifier CHANDRABINDU
"\u0A82": "\xA2", # Vowel-modifier ANUSWAR
"\u0A83": "\xA3", # Vowel-modifier VISARG
"\u0A85": "\xA4", # Vowel A
"\u0A86": "\xA5", # Vowel AA
"\u0A87": "\xA6", # Vowel I
"\u0A88": "\xA7", # Vowel II
"\u0A89": "\xA8", # Vowel U
"\u0A8A": "\xA9", # Vowel UU
"\u0A8B": "\xAA", # Vowel RI
"\u0A8D": "\xAE",
"\u0A8F": "\xAC",
"\u0A90": "\xAD",
"\u0A91": "\xB2",
"\u0A93": "\xB0",
"\u0A94": "\xB1",
"\u0A95": "\xB3", # Consonant KA
"\u0A96": "\xB4", # Consonant
"\u0A97": "\xB5", # Consonant
"\u0A98": "\xB6", # Consonant
"\u0A99": "\xB7", # Consonant NGA
"\u0A9A": "\xB8", # Consonant
"\u0A9B": "\xB9", # Consonant
"\u0A9C": "\xBA", # Consonant
"\u0A9D": "\xBB", # Consonant
"\u0A9E": "\xBC", # Consonant JNA
"\u0A9F": "\xBD", # Consonant
"\u0AA0": "\xBE", # Consonant
"\u0AA1": "\xBF", # Consonant
"\u0AA2": "\xC0", # Consonant
"\u0AA3": "\xC1", # Consonant NA
"\u0AA4": "\xC2", # Consonant
"\u0AA5": "\xC3", # Consonant
"\u0AA6": "\xC4", # Consonant
"\u0AA7": "\xC5", # Consonant
"\u0AA8": "\xC6", # Consonant NA
"\u0AAA": "\xC8", # Consonant PA
"\u0AAB": "\xC9", # Consonant PHA
"\u0AAC": "\xCA", # Consonant BA
"\u0AAD": "\xCB", # Consonant BHA
"\u0AAE": "\xCC", # Consonant MA
"\u0AAF": "\xCD", # Consonant YA
"\u0AB0": "\xCF", # Consonant RA
"\u0AB2": "\xD1", # Consonant LA
"\u0AB3": "\xD2", # Consonant LLA
"\u0AB5": "\xD4", # Consonant VA
"\u0AB6": "\xD5", # Consonant SHA
"\u0AB7": "\xD6", # Consonant SSA
"\u0AB8": "\xD7", # Consonant SA
"\u0AB9": "\xD8", # Consonant HA
"\u0ABC": "\xE9", # Consonant NUKTA
"\u0ABE": "\xDA", # Vowel Sign AA
"\u0ABF": "\xDB", # Vowel Sign I
"\u0AC0": "\xDC", # Vowel Sign II
"\u0AC1": "\xDD", # Vowel Sign U
"\u0AC2": "\xDE", # Vowel
"\u0AC3": "\xDF", # Vowel
"\u0AC7": "\xE1", # Vowel
"\u0AC8": "\xE2", # Vowel
"\u0AC9": "\xE7", # Vowel
"\u0ACB": "\xE5", # Vowel
"\u0ACC": "\xE6", # Vowel
"\u0ACD": "\xE8", # Halant
"\u0AE0": "\xAA", # Vowel Sanskrit
"\u0AE4": "\xEA", # PURNA VIRAM Reserved
"\u0AE5": "\xEA", # DEERGH VIRAM
"\u0AE6": "\xF1", # Digit 0
"\u0AE7": "\xF2", # Digit 1
"\u0AE8": "\xF3", # Digit 2
"\u0AE9": "\xF4", # Digit 3
"\u0AEA": "\xF5", # Digit 4
"\u0AEB": "\xF6", # Digit 5
"\u0AEC": "\xF7", # Digit 6
"\u0AED": "\xF8", # Digit 7
"\u0AEE": "\xF9", # Digit 8
"\u0AEF": "\xFA", # Digit 9
}
# compile regexes
self.c = re.compile("([\xB3-\xD8])")
self.v = re.compile("([\xA5-\xB2])")
self.dig = re.compile("([\xF1-\xFA])")
self.ch = re.compile("([\xB3-\xD8])\xE8")
self.cn = re.compile("([\xB3-\xD8])\xE9")
self.amd = re.compile("[\xA4]([\xA1-\xA3])")
self.cm = re.compile("([\xB3-\xD8])([\xDA-\xE7])")
self.vmd = re.compile("([\xA5-\xB2])([\xA1-\xA3])")
self.cnh = re.compile("([\xB3-\xD8])\xE9\xE8")
self.cmd = re.compile("([\xB3-\xD8])([\xA1-\xA3])")
self.cnm = re.compile("([\xB3-\xD8])\xE9([\xDA-\xE7])")
self.cnmd = re.compile("([\xB3-\xD8])\xE9([\xA1-\xA3])")
self.cmmd = re.compile("([\xB3-\xD8])([\xDA-\xE7])([\xA1-\xA3])")
self.cnmmd = re.compile("([\xB3-\xD8])\xE9([\xDA-\xE7])([\xA1-\xA3])")
self.u2i_h = re.compile("([\u0900-\u097F])")
self.u2i_t = re.compile("([\u0C01-\u0C6F])")
self.u2i_k = re.compile("([\u0C80-\u0CFF])")
self.u2i_m = re.compile("([\u0D00-\u0D6F])")
self.u2i_b = re.compile("([\u0980-\u09EF])")
self.u2i_o = re.compile("([\u0B00-\u0B7F])")
self.u2i_p = re.compile("([\u0A01-\u0A75])")
self.u2i_g = re.compile("([\u0A80-\u0AFF])")
self.u2i_ta = re.compile("([\u0B82-\u0BEF])")
self.u2i_hn = re.compile("([\u0958-\u095F])")
self.u2i_on = re.compile("([\u0B5C\u0B5D\u0B5F])")
self.u2i_bn = re.compile("([\u09DC\u09DD\u09DF])")
self.u2i_pn = re.compile("([\u0A59-\u0A5B\u0A5E])")
def normalize(self, text):
"""Performs some common normalization, which includes:
- Byte order mark, word joiner, etc. removal
- ZERO_WIDTH_NON_JOINER and ZERO_WIDTH_JOINER removal
"""
text = text.replace('\uFEFF', '') # BYTE_ORDER_MARK
text = text.replace('\uFFFE', '') # BYTE_ORDER_MARK_2
text = text.replace('\u2060', '') # WORD JOINER
text = text.replace('\u00AD', '') # SOFT_HYPHEN
text = text.replace('\u200C', '') # ZERO_WIDTH_NON_JOINER
text = text.replace('\u200D', '') # ZERO_WIDTH_JOINER
# Convert Devanagari VIRAM and Deergh Viram to "fullstop"
text = text.replace('\u0964', '.')
text = text.replace('\u0965', '.')
return text
def map_rx(self, my_string):
if re.search("rx", my_string) is None:
return my_string
my_string = self.ncqmd.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashm_om2i["rx"] +
self.hashmd_om2i[
m.group(3)],
my_string)
my_string = self.ncq.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashm_om2i["rx"],
my_string)
my_string = self.nqmd.sub(
lambda m: self.hashv_om2i[m.group(1)] +
self.hashmd_om2i[
m.group(2)],
my_string)
my_string = self.nq.sub(
lambda m: self.hashv_om2i[
m.group(1)],
my_string)
return my_string
# map for vowels at the begining
def map_a(self, my_string):
if re.search("(a|e)", my_string) is None:
return my_string
my_string = re.sub('\baan:', self.hashv_om2i["aa"] +
self.hashmd_om2i["n'"], my_string)
my_string = re.sub('\ban:', self.hashv_om2i["a"] +
self.hashmd_om2i["n'"], my_string)
my_string = re.sub('\ba:', self.hashv_om2i["a"] +
self.hashmd_om2i[":"], my_string)
my_string = re.sub('\baa', self.hashv_om2i["aa"], my_string)
my_string = re.sub('\bai', self.hashv_om2i["ai"], my_string)
my_string = re.sub('\bei', self.hashv_om2i["ei"], my_string)
my_string = re.sub('\bau', self.hashv_om2i["au"], my_string)
return my_string
def nit32iscii(self, my_string):
# to handle vowels with modifiers
# to avoid conflict with consonants starting with n
my_string = self.map_a(my_string)
# for telugu rx processing
my_string = self.map_rx(my_string)
my_string = self.ncvmd.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashm_om2i[
m.group(2)] +
self.hashmd_om2i[
m.group(3)],
my_string)
my_string = self.ncamd.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashmd_om2i[
m.group(2)],
my_string)
my_string = self.ncmd.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashmd_om2i[
m.group(2)],
my_string)
my_string = self.ncv.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashm_om2i[
m.group(2)],
my_string)
my_string = self.nca.sub(
lambda m: self.hashc_om2i[
m.group(1)],
my_string)
# check if vowel n: is still present prefixed by vowel,
# in which case process them first
my_string = self.nvmd.sub(
lambda m: self.hashv_om2i[
m.group(1)] +
self.hashmd_om2i[m.group(2)],
my_string)
# string does not have consonants similar to n:
my_string = self.nc.sub(
lambda m: self.hashc_om2i[
m.group(1)] +
self.hashc_om2i["_"],
my_string)
my_string = self.nvmd.sub(
lambda m: self.hashv_om2i[
m.group(1)] +
self.hashmd_om2i[m.group(2)],
my_string)
my_string = self.nmd.sub(
lambda m: self.hashmd_om2i[
m.group(1)],
my_string)
my_string = self.nv.sub(
lambda m: self.hashv_om2i[
m.group(1)],
my_string)
my_string = my_string.replace('.', self.hashc_om2i["."])
return my_string
def iscii2unicode_hin(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashh_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_tel(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hasht_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_pan(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashp_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_kan(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashk_i2u.get(
m.group(1), ""), iscii)
unicode_ = unicode_.replace('\u0CAB\u0CBC', '\u0CDE')
return unicode_
def iscii2unicode_mal(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashm_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_ben(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashb_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_tam(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashcta_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2unicode_ori(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hasho_i2u.get(
m.group(1), ""), iscii)
unicode_ = unicode_.replace('\u0B2F\u0B3C', '\u0B5F')
return unicode_
def iscii2unicode_guj(self, iscii):
unicode_ = self.i2u.sub(
lambda m: self.hashg_i2u.get(
m.group(1), ""), iscii)
return unicode_
def iscii2it3(self, my_string):
"""Convert ISCII to it3"""
# CONSONANT+HALANT
my_string = self.ch.sub(
lambda m: self.hashc_i2w[
m.group(1)], my_string)
# CONSONANT+NUKTA+MATRA+MODIFIER
my_string = self.cnmmd.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashc_i2w["\xE9"] +
self.hashm_i2w[
m.group(2)] +
self.hashmd_i2w[
m.group(3)],
my_string)
# CONSONANT+NUKTA+MATRA
my_string = self.cnm.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashc_i2w["\xE9"] +
self.hashm_i2w[
m.group(2)],
my_string)
# CONSONANT+NUKTA+MODIFIER
my_string = self.cnmd.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashc_i2w["\xE9"] +
self.hashmd_i2w[
m.group(2)],
my_string)
# CONSONANT+NUKTA+HALANT
my_string = self.cnh.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashc_i2w["\xE9"],
my_string)
# CONSONANT+NUKTA
my_string = self.cn.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashc_i2w["\xE9"] +
"a",
my_string)
# CONSONANT+MATRA+MODIFIER
my_string = self.cmmd.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashm_i2w[
m.group(2)] +
self.hashmd_i2w[
m.group(3)],
my_string)
# CONSONANT+MATRA
my_string = self.cm.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
self.hashm_i2w[
m.group(2)],
my_string)
# CONSONANT+MODIFIER
my_string = self.cmd.sub(
lambda m: self.hashc_i2w[
m.group(1)] +
"a" +
self.hashmd_i2w[
m.group(2)],
my_string)
# CONSONANT
my_string = self.c.sub(
lambda m: self.hashc_i2w[
m.group(1)] + "a", my_string)
# VOWEL+MODIFIER, VOWEL, MATRA
my_string = self.vmd.sub(
lambda m: self.hashv_i2w[
m.group(1)] +
self.hashmd_i2w[
m.group(2)],
my_string)
my_string = self.amd.sub(
lambda m: "a" +
self.hashmd_i2w[
m.group(1)],
my_string)
my_string = self.v.sub(lambda m: self.hashv_i2w[m.group(1)], my_string)
# VOWEL A, FULL STOP or VIRAM Northern Scripts
my_string = my_string.replace("\xA4", "a")
my_string = my_string.replace("\xEA", ".")
# For PUNJABI ADDAK
my_string = my_string.replace("\xFB", "Y")
# Replace ISCII Digits with Roman
my_string = self.dig.sub(
lambda m: self.digits_i2w[
m.group(1)], my_string)
return my_string
def unicode2iscii_hin(self, unicode_):
# Normalize Unicode values (NUKTA variations)
unicode_ = self.u2i_hn.sub(
lambda m: self.unicode_norm_hashh_u2i.get(
m.group(1), "") + "\u093C", unicode_)
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_hin = self.u2i_h.sub(
lambda m: self.hashh_u2i.get(
m.group(1), ""), unicode_)
return iscii_hin
def unicode2iscii_tel(self, unicode_):
# dependent vowels
unicode_ = unicode_.replace('\u0c46\u0c56', '\u0c48')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_tel = self.u2i_t.sub(
lambda m: self.hasht_u2i.get(
m.group(1), ""), unicode_)
return iscii_tel
def unicode2iscii_pan(self, unicode_):
# Normalize Unicode values (NUKTA variations)
unicode_ = self.u2i_pn.sub(
lambda m: self.unicode_norm_hashp_u2i.get(
m.group(1), "") + "\u0A3C", unicode_)
# Convert Unicode values 0x0A5C to ISCII
unicode_ = unicode_.replace("\u0A5C", "\xBF\xE9")
if self.norm:
return unicode_
# Convert Unicode Punjabi values to ISCII values
iscii_pan = self.u2i_p.sub(
lambda m: self.hashp_u2i.get(
m.group(1), ""), unicode_)
return iscii_pan
def unicode2iscii_kan(self, unicode_):
# Normalize Unicode values (NUKTA variations)
unicode_ = unicode_.replace('\u0CDE', '\u0CAB\u0CBC')
# Normalize two-part dependent vowels
unicode_ = unicode_.replace('\u0cbf\u0cd5', '\u0cc0')
unicode_ = unicode_.replace('\u0cc6\u0cd5', '\u0cc7')
unicode_ = unicode_.replace('\u0cc6\u0cd6', '\u0cc8')
unicode_ = unicode_.replace('\u0cc6\u0cc2', '\u0cca')
unicode_ = unicode_.replace('\u0cca\u0cd5', '\u0ccb')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_kan = self.u2i_k.sub(
lambda m: self.hashk_u2i.get(
m.group(1), ""), unicode_)
return iscii_kan
def unicode2iscii_mal(self, unicode_):
# Normalize two-part dependent vowels
unicode_ = unicode_.replace('\u0d46\u0d3e', '\u0d4a')
unicode_ = unicode_.replace('\u0d47\u0d3e', '\u0d4b')
unicode_ = unicode_.replace('\u0d46\u0d57', '\u0d57')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_mal = self.u2i_m.sub(
lambda m: self.hashm_u2i.get(
m.group(1), ""), unicode_)
return iscii_mal
def unicode2iscii_ben(self, unicode_):
# Normalize Unicode values (NUKTA variations)
unicode_ = self.u2i_bn.sub(
lambda m: self.unicode_norm_hashb_u2i.get(
m.group(1), "") + "\u09BC", unicode_)
# Normalize two part dependent vowels
unicode_ = unicode_.replace('\u09c7\u09be', '\u09cb')
unicode_ = unicode_.replace('\u09c7\u0bd7', '\u09cc')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_ben = self.u2i_b.sub(
lambda m: self.hashb_u2i.get(
m.group(1), ""), unicode_)
return iscii_ben
def unicode2iscii_tam(self, unicode_):
# Normalizetwo part dependent vowels
unicode_ = unicode_.replace('\u0b92\u0bd7', '\u0b94')
unicode_ = unicode_.replace('\u0bc6\u0bbe', '\u0bca')
unicode_ = unicode_.replace('\u0bc7\u0bbe', '\u0bcb')
unicode_ = unicode_.replace('\u0bc6\u0bd7', '\u0bcc')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_tam = self.u2i_ta.sub(
lambda m: self.hashta_u2i.get(
m.group(1), ""), unicode_)
return iscii_tam
def unicode2iscii_ori(self, unicode_):
# Normalize Unicode values (NUKTA variations)
unicode_ = self.u2i_on.sub(
lambda m: self.unicode_norm_hasho_u2i.get(
m.group(1), "") + "\u0B3C", unicode_)
# Normalize two part dependent vowels
unicode_ = unicode_.replace('\u0b47\u0b3e', '\u0b4b')
unicode_ = unicode_.replace('\u0b47\u0b57', '\u0b4c')
if self.norm:
return unicode_
# Convert Unicode values to ISCII values
iscii_ori = self.u2i_o.sub(
lambda m: self.hasho_u2i.get(
m.group(1), ""), unicode_)
return iscii_ori
def unicode2iscii_guj(self, unicode_):
# Convert Gujurati Unicode values to ISCII values
if self.norm:
return unicode_
iscii_guj = self.u2i_g.sub(
lambda m: self.hashg_u2i.get(
m.group(1), ""), unicode_)
return iscii_guj
def utf2it3_urd(self, text):
# hamza and mada normalizations
text = text.replace('\u0627\u0653', '\u0622')
text = text.replace('\u0648\u0654', '\u0624')
text = text.replace('\u06cc\u0654', '\u0626')
text = text.replace('\u06d2\u0654', '\u06d3')
text = text.replace('\u0627\u0654', '\u0623')
text = text.replace('\u06c1\u0654', '\u06c0')
text = text.replace('\u06d5\u0654', '\u06c0')
# vowel removal
text = text.replace('\u0650', '')
text = text.replace('\u064e', '')
text = text.replace('\u064f', '')
# unicode_equivalence normalization
text = text.translate(self.norm_tbl)
if self.norm:
return text
# utf to it3 mapping
text = text.replace('\u06A9\u06BE', 'K')
text = text.replace('\u06AF\u06BE', 'G')
text = text.replace('\u0686\u06BE', 'C')
text = text.replace('\u062c\u06BE', 'J')
text = text.replace('\u0679\u06BE', 'T')
text = text.replace('\u0688\u06BE', 'D')
text = text.replace('\u062A\u06BE', 'W')
text = text.replace('\u062F\u06BE', 'X')
text = text.replace('\u067E\u06BE', 'P')
text = text.replace('\u0628\u06BE', 'B')
text = text.replace('\u0645\u06BE', 'M')
text = text.replace('\u0646\u06BE', 'N')
text = text.replace('\u0644\u06BE', 'L')
text = text.replace('\u0691\u06BE', 'DY')
text = text.translate(self.trans_tbl)
return text
def it32utf_urd(self, text):
# it3 to utf mapping
text = text.replace('jyy', '\u0636')
text = text.replace('jVY', '\u0698')
text = text.replace('QYY', '\u0655')
text = text.replace('jYY', '\u0632')
text = text.replace('sYY', '\u0635')
text = text.replace('EYY', '\u06D3')
text = text.replace('jy', '\u0638')
text = text.replace('vY', '\u0624')
text = text.replace('IY', '\u0626')
text = text.replace('aY', '\u0623')
text = text.replace('HY', '\u06C0')
text = text.replace('QY', '\u0621')
text = text.replace('hY', '\u06BE')
text = text.replace('qV', '\u0670')
text = text.replace('GV', '\u0656')
text = text.replace('qf', '\u064B')
text = text.replace('qF', '\u064D')
text = text.replace('wY', '\u0637')
text = text.replace('EY', '\u0639')
text = text.replace('gY', '\u063A')
text = text.replace('PY', '\u0641')
text = text.replace('KY', '\u062E')
text = text.replace('jY', '\u0630')
text = text.replace('sY', '\u062B')
text = text.replace('dY', '\u0691')
text = text.replace('DY', '\u0691\u06BE')
text = text.translate(self.trans_tbl)
return text
def iscii2unicode(self, iscii):
"""Convert ISCII to Unicode"""
if self.lang in ["hin", "mar", "nep", "bod", "kok"]:
unicode_ = self.iscii2unicode_hin(iscii)
elif self.lang == "tel":
unicode_ = self.iscii2unicode_tel(iscii)
elif self.lang in ["ben", "asm"]:
unicode_ = self.iscii2unicode_ben(iscii)
elif self.lang == "kan":
unicode_ = self.iscii2unicode_kan(iscii)
elif self.lang == "pan":
unicode_ = self.iscii2unicode_pan(iscii)
elif self.lang == "mal":
unicode_ = self.iscii2unicode_mal(iscii)
elif self.lang == "tam":
unicode_ = self.iscii2unicode_tam(iscii)
elif self.lang == "ori":
unicode_ = self.iscii2unicode_ori(iscii)
elif self.lang == "guj":
unicode_ = self.iscii2unicode_guj(iscii)
else:
raise NotImplementedError(
'Language `%s` is not implemented.' %
self.lang)
return unicode_
def unicode2iscii(self, unicode_):
"""Convert Unicode to ISCII"""
if self.lang in ["hin", "mar", "nep", "bod", "kok"]:
iscii = self.unicode2iscii_hin(unicode_)
elif self.lang == "tel":
iscii = self.unicode2iscii_tel(unicode_)
elif self.lang in ["ben", "asm"]:
iscii = self.unicode2iscii_ben(unicode_)
elif self.lang == "kan":
iscii = self.unicode2iscii_kan(unicode_)
elif self.lang == "pan":
iscii = self.unicode2iscii_pan(unicode_)
elif self.lang == "mal":
iscii = self.unicode2iscii_mal(unicode_)
elif self.lang == "tam":
iscii = self.unicode2iscii_tam(unicode_)
elif self.lang == "ori":
iscii = self.unicode2iscii_ori(unicode_)
elif self.lang == "guj":
iscii = self.unicode2iscii_guj(unicode_)
else:
raise NotImplementedError(
'Language `%s` is not implemented.' %
self.lang)
return iscii
def utf2it3(self, unicode_):
"""Convert UTF string to it3-Roman"""
unicode_ = self.normalize(unicode_)
# Mask iscii characters (if any)
if not self.norm:
unicode_ = self.mask_isc.sub(lambda m: self.iscii_num[m.group(1)],
unicode_)
# Mask Roman characters
if self.rmask:
unicode_ = self.mask_rom.sub(r'_\1_', unicode_)
if self.lang == 'urd':
it3 = self.utf2it3_urd(unicode_)
return it3
# Convert Unicode values to ISCII values
iscii = self.unicode2iscii(unicode_)
if self.norm:
return iscii
# Convert ISCII to it3-Roman
it3 = self.iscii2it3(iscii)
# Consecutive Vowel Normalization
it3 = re.sub('[\xA0-\xFA]+', '', it3)
# Unmask iscii characters
it3 = self.unmask_isc.sub(lambda m: self.num_iscii[m.group(1)], it3)
return it3
def it32utf(self, it3):
"""Convert it3-Roman to UTF"""
unicode_ = ''
# it3 uses only lower case letters
it3 = it3.lower()
# replace ~ if found with dash
it3 = it3.replace("~", "-")
it3_list = self.unmask_rom.split(it3)
for it3 in it3_list:
if not it3:
continue
elif self.rmask and it3[0] == '_' and it3[-1] == '_':
unicode_ += it3[1:-1]
else:
# Mask iscii characters (if any)
it3 = self.mask_isc.sub(
lambda m: self.iscii_num[
m.group(1)], it3)
if self.lang == 'urd':
unicode_t = self.it32utf_urd(it3)
else:
iscii = self.nit32iscii(it3)
# Convert ISCII to Unicode
unicode_t = self.iscii2unicode(iscii)
# Unmask iscii characters
unicode_ += self.unmask_isc.sub(
lambda m: self.num_iscii[
m.group(1)], unicode_t)
# Convert Unicode to utf-8
return unicode_
|
"""Django rest framework serializers for the brewery app.
"""
from rest_framework import serializers
from brewery import models
class JouliaControllerReleaseSerializers(serializers.ModelSerializer):
"""Standard serializer for JouliaControllerRelease model."""
class Meta:
model = models.JouliaControllerRelease
fields = '__all__'
class BrewingStateSerializer(serializers.ModelSerializer):
"""Standard serializer for BrewingState model."""
class Meta:
model = models.BrewingState
fields = '__all__'
class BrewingCompanySerializer(serializers.ModelSerializer):
"""Standard serializer for BrewingCompany model."""
class Meta:
model = models.BrewingCompany
fields = ('id', 'group', 'name',)
class BrewerySerializer(serializers.ModelSerializer):
"""Standard serializer for Brewery."""
class Meta:
model = models.Brewery
fields = '__all__'
class ResistanceTemperatureDeviceSerializer(serializers.ModelSerializer):
"""Standard serializer for ResistanceTemperatureDevice."""
class Meta:
model = models.ResistanceTemperatureDevice
fields = '__all__'
class ResistanceTemperatureDeviceAmplifierSerializer(serializers.ModelSerializer):
"""Standard serializer for ResistanceTemperatureDeviceAmplifier."""
class Meta:
model = models.ResistanceTemperatureDeviceAmplifier
fields = '__all__'
class ResistanceTemperatureDeviceMeasurementSerializer(
serializers.ModelSerializer):
"""Standard serializer for ResistanceTemperatureDeviceMeasurement."""
rtd = ResistanceTemperatureDeviceSerializer()
amplifier = ResistanceTemperatureDeviceAmplifierSerializer()
class Meta:
model = models.ResistanceTemperatureDeviceMeasurement
fields = '__all__'
def create(self, validated_data):
validated_data['rtd'] = ResistanceTemperatureDeviceSerializer()\
.create(validated_data.get('rtd', {}))
validated_data['amplifier']\
= ResistanceTemperatureDeviceAmplifierSerializer().create(
validated_data.get('amplifier', {}))
return models.ResistanceTemperatureDeviceMeasurement\
.objects.create(**validated_data)
def update(self, instance, validated_data):
ResistanceTemperatureDeviceSerializer()\
.update(instance.rtd, validated_data.pop('rtd', {}))
ResistanceTemperatureDeviceAmplifierSerializer()\
.update(instance.amplifier, validated_data.pop('amplifier', {}))
return super(ResistanceTemperatureDeviceMeasurementSerializer, self)\
.update(instance, validated_data)
class MashTunSerializer(serializers.ModelSerializer):
"""Standard serializer for MashTun."""
temperature_sensor = ResistanceTemperatureDeviceMeasurementSerializer()
class Meta:
model = models.MashTun
fields = '__all__'
def create(self, validated_data):
validated_data['temperature_sensor']\
= ResistanceTemperatureDeviceMeasurementSerializer().create(
validated_data.get('temperature_sensor', {}))
return models.MashTun.objects.create(**validated_data)
def update(self, instance, validated_data):
ResistanceTemperatureDeviceMeasurementSerializer().update(
instance.temperature_sensor,
validated_data.pop('temperature_sensor', {}))
return super(MashTunSerializer, self).update(
instance, validated_data)
class HeatingElementSerializer(serializers.ModelSerializer):
"""Standard serializer for HeatingElement."""
class Meta:
model = models.HeatingElement
fields = '__all__'
class HotLiquorTunSerializer(serializers.ModelSerializer):
"""Standard serializer for HotLiquorTun."""
temperature_sensor = ResistanceTemperatureDeviceMeasurementSerializer()
heating_element = HeatingElementSerializer()
class Meta:
model = models.HotLiquorTun
fields = '__all__'
def create(self, validated_data):
validated_data['temperature_sensor']\
= ResistanceTemperatureDeviceMeasurementSerializer().create(
validated_data.get('temperature_sensor', {}))
validated_data['heating_element'] = HeatingElementSerializer().create(
validated_data.get('heating_element', {}))
return models.HotLiquorTun.objects.create(**validated_data)
def update(self, instance, validated_data):
ResistanceTemperatureDeviceMeasurementSerializer().update(
instance.temperature_sensor,
validated_data.pop('temperature_sensor', {}))
HeatingElementSerializer().update(
instance.heating_element,
validated_data.pop('heating_element', {}))
return super(HotLiquorTunSerializer, self).update(
instance, validated_data)
class PumpSerializer(serializers.ModelSerializer):
"""Standard serializer for Pump."""
class Meta:
model = models.Pump
fields = '__all__'
class BrewhouseSerializer(serializers.ModelSerializer):
"""Standard serializer for Brewhouse. Makes use of writable nested
serializers for equipment configuration."""
active = serializers.ReadOnlyField()
boil_kettle = HotLiquorTunSerializer()
mash_tun = MashTunSerializer()
main_pump = PumpSerializer()
class Meta:
model = models.Brewhouse
fields = '__all__'
def create(self, validated_data):
validated_data['boil_kettle'] = HotLiquorTunSerializer().create(
validated_data.get('boil_kettle', {}))
validated_data['mash_tun'] = MashTunSerializer().create(
validated_data.get('mash_tun', {}))
validated_data['main_pump'] = PumpSerializer().create(
validated_data.get('main_pump', {}))
return models.Brewhouse.objects.create(**validated_data)
def update(self, instance, validated_data):
HotLiquorTunSerializer().update(
instance.boil_kettle, validated_data.pop('boil_kettle', {}))
MashTunSerializer().update(
instance.mash_tun, validated_data.pop('mash_tun', {}))
PumpSerializer().update(
instance.main_pump, validated_data.pop('main_pump', {}))
return super(BrewhouseSerializer, self).update(instance, validated_data)
class BeerStyleSerializer(serializers.ModelSerializer):
"""Standard serializer for BeerStyle."""
class Meta:
model = models.BeerStyle
fields = '__all__'
class YeastIngredientSerializer(serializers.ModelSerializer):
"""Standard serializer for YeastIngredient."""
class Meta:
model = models.YeastIngredient
fields = '__all__'
class MaltIngredientSerializer(serializers.ModelSerializer):
"""Standard serializer for MaltIngredient."""
class Meta:
model = models.MaltIngredient
fields = '__all__'
class BitteringIngredientSerializer(serializers.ModelSerializer):
"""Standard serializer for BitteringIngredient."""
class Meta:
model = models.BitteringIngredient
fields = '__all__'
class MaltIngredientAdditionSerializer(serializers.ModelSerializer):
"""Standard serializer for MaltIngredientAddition."""
class Meta:
model = models.MaltIngredientAddition
fields = '__all__'
class BitteringIngredientAdditionSerializer(serializers.ModelSerializer):
"""Standard serializer for BitteringIngredientAddition."""
class Meta:
model = models.BitteringIngredientAddition
fields = '__all__'
class RecipeSerializer(serializers.ModelSerializer):
"""Standard serializer for Recipe."""
last_brewed = serializers.SerializerMethodField()
number_of_batches = serializers.SerializerMethodField()
class Meta:
model = models.Recipe
fields = ('id', 'name', 'style', 'last_brewed', 'number_of_batches',
'company', 'strike_temperature', 'mashout_temperature',
'mashout_time', 'boil_time', 'cool_temperature',
'original_gravity', 'final_gravity', 'abv', 'ibu', 'srm',
'volume', 'pre_boil_volume_gallons',
'post_boil_volume_gallons', 'yeast', 'brewhouse_efficiency',)
@staticmethod
def get_last_brewed(recipe):
recipe_instances = recipe.recipeinstance_set
if recipe_instances.count() != 0:
return recipe_instances.latest('date').date
else:
return None
@staticmethod
def get_number_of_batches(recipe):
return recipe.recipeinstance_set.count()
class MashPointSerializer(serializers.ModelSerializer):
"""Standard serializer for MashPoint."""
index = serializers.IntegerField(required=False)
class Meta:
model = models.MashPoint
fields = '__all__'
class RecipeInstanceSerializer(serializers.ModelSerializer):
"""Standard serializer for RecipeInstance."""
class Meta:
model = models.RecipeInstance
fields = '__all__'
class TimeSeriesDataPointSerializer(serializers.ModelSerializer):
"""Standard serializer for TimeSeriesDataPoint."""
class Meta:
model = models.TimeSeriesDataPoint
fields = '__all__'
|
""" Simple FTP client module. """
import subprocess
from collections import namedtuple
from datetime import datetime
from enum import IntEnum
from ftplib import all_errors
from pathlib import Path
from shutil import rmtree
from urllib.parse import urlparse, unquote
from gi.repository import GLib
from app.commons import log, run_task, run_idle
from app.connections import UtfFTP
from app.ui.dialogs import show_dialog, DialogType, get_builder
from app.ui.main_helper import on_popup_menu
from .uicommons import Gtk, Gdk, UI_RESOURCES_PATH, KeyboardKey, MOD_MASK
File = namedtuple("File", ["icon", "name", "size", "date", "attr", "extra"])
class FtpClientBox(Gtk.HBox):
""" Simple FTP client base class. """
ROOT = ".."
FOLDER = "<Folder>"
LINK = "<Link>"
MAX_SIZE = 10485760 # 10 MB file limit
URI_SEP = "::::"
class Column(IntEnum):
ICON = 0
NAME = 1
SIZE = 2
DATE = 3
ATTR = 4
EXTRA = 5
def __init__(self, app, settings, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_spacing(2)
self.set_orientation(Gtk.Orientation.VERTICAL)
self._app = app
self._settings = settings
self._ftp = None
self._select_enabled = True
handlers = {"on_connect": self.on_connect,
"on_disconnect": self.on_disconnect,
"on_ftp_row_activated": self.on_ftp_row_activated,
"on_file_row_activated": self.on_file_row_activated,
"on_ftp_edit": self.on_ftp_edit,
"on_ftp_edited": self.on_ftp_edited,
"on_file_edit": self.on_file_edit,
"on_file_edited": self.on_file_edited,
"on_file_remove": self.on_file_remove,
"on_ftp_remove": self.on_ftp_file_remove,
"on_file_create_folder": self.on_file_create_folder,
"on_ftp_create_folder": self.on_ftp_create_folder,
"on_view_drag_begin": self.on_view_drag_begin,
"on_ftp_drag_data_get": self.on_ftp_drag_data_get,
"on_ftp_drag_data_received": self.on_ftp_drag_data_received,
"on_file_drag_data_get": self.on_file_drag_data_get,
"on_file_drag_data_received": self.on_file_drag_data_received,
"on_view_drag_end": self.on_view_drag_end,
"on_view_popup_menu": on_popup_menu,
"on_view_key_press": self.on_view_key_press,
"on_view_press": self.on_view_press,
"on_view_release": self.on_view_release}
builder = get_builder(UI_RESOURCES_PATH + "ftp.glade", handlers)
self.add(builder.get_object("main_frame"))
self._ftp_info_label = builder.get_object("ftp_info_label")
self._ftp_view = builder.get_object("ftp_view")
self._ftp_model = builder.get_object("ftp_list_store")
self._ftp_name_renderer = builder.get_object("ftp_name_column_renderer")
self._file_view = builder.get_object("file_view")
self._file_model = builder.get_object("file_list_store")
self._file_name_renderer = builder.get_object("file_name_column_renderer")
# Buttons
self._connect_button = builder.get_object("connect_button")
disconnect_button = builder.get_object("disconnect_button")
disconnect_button.bind_property("visible", builder.get_object("ftp_create_folder_menu_item"), "sensitive")
disconnect_button.bind_property("visible", builder.get_object("ftp_edit_menu_item"), "sensitive")
disconnect_button.bind_property("visible", builder.get_object("ftp_remove_menu_item"), "sensitive")
self._connect_button.bind_property("visible", builder.get_object("disconnect_button"), "visible", 4)
# Force Ctrl
self._ftp_view.connect("key-press-event", self._app.force_ctrl)
self._file_view.connect("key-press-event", self._app.force_ctrl)
# Icons
theme = Gtk.IconTheme.get_default()
folder_icon = "folder-symbolic" if settings.is_darwin else "folder"
self._folder_icon = theme.load_icon(folder_icon, 16, 0) if theme.lookup_icon(folder_icon, 16, 0) else None
self._link_icon = theme.load_icon("emblem-symbolic-link", 16, 0) if theme.lookup_icon("emblem-symbolic-link",
16, 0) else None
# Initialization
self.init_drag_and_drop()
self.init_ftp()
self.init_file_data()
self.show()
@run_task
def init_ftp(self):
GLib.idle_add(self._ftp_model.clear)
try:
if self._ftp:
self._ftp.close()
self._ftp = UtfFTP(host=self._settings.host, user=self._settings.user, passwd=self._settings.password)
self._ftp.encoding = "utf-8"
self.update_ftp_info(self._ftp.getwelcome())
except all_errors as e:
self.update_ftp_info(str(e))
self.on_disconnect()
else:
self.init_ftp_data()
@run_task
def init_ftp_data(self, path=None):
if not self._ftp:
return
if path:
try:
self._ftp.cwd(path)
except all_errors as e:
self.update_ftp_info(str(e))
files = []
try:
self._ftp.dir(files.append)
except all_errors as e:
log(e)
self.update_ftp_info(str(e))
self.on_disconnect()
else:
self.append_ftp_data(files)
GLib.idle_add(self._connect_button.set_visible, False)
@run_task
def init_file_data(self, path=None):
self.append_file_data(Path(path if path else self._settings.data_local_path))
@run_idle
def append_file_data(self, path: Path):
self._file_model.clear()
self._file_model.append(File(None, self.ROOT, None, None, str(path), "0"))
try:
dirs = [p for p in path.iterdir()]
except OSError as e:
log(e)
else:
for p in dirs:
is_dir = p.is_dir()
st = p.stat()
size = str(st.st_size)
date = datetime.fromtimestamp(st.st_mtime).strftime("%d-%m-%y %H:%M")
icon = None
if is_dir:
r_size = self.FOLDER
icon = self._folder_icon
elif p.is_symlink():
r_size = self.LINK
icon = self._link_icon
else:
r_size = self.get_size_from_bytes(size)
self._file_model.append(File(icon, p.name, r_size, date, str(p.resolve()), size))
@run_idle
def append_ftp_data(self, files):
self._ftp_model.clear()
self._ftp_model.append(File(None, self.ROOT, None, None, self._ftp.pwd(), "0"))
for f in files:
f_data = f.split()
f_type = f_data[0][0]
is_dir = f_type == "d"
is_link = f_type == "l"
size = f_data[4]
icon = None
if is_dir:
r_size = self.FOLDER
icon = self._folder_icon
elif is_link:
r_size = self.LINK
icon = self._link_icon
else:
r_size = self.get_size_from_bytes(size)
date = "{}, {} {}".format(f_data[5], f_data[6], f_data[7])
self._ftp_model.append(File(icon, " ".join(f_data[8:]), r_size, date, f_data[0], size))
def on_connect(self, item=None):
self.init_ftp()
def on_disconnect(self, item=None):
if self._ftp:
self._ftp.close()
self._connect_button.set_visible(True)
GLib.idle_add(self._ftp_model.clear)
def on_ftp_row_activated(self, view, path, column):
row = self._ftp_model[path][:]
f_path = row[self.Column.NAME]
size = row[self.Column.SIZE]
if size == self.FOLDER or f_path == self.ROOT:
self.init_ftp_data(f_path)
else:
b_size = row[self.Column.EXTRA]
if b_size.isdigit() and int(b_size) > self.MAX_SIZE:
self._app.show_error_dialog("The file size is too large!")
else:
self.open_ftp_file(f_path)
def on_file_row_activated(self, view, path, column):
row = self._file_model[path][:]
path = Path(row[self.Column.ATTR])
if row[self.Column.SIZE] == self.FOLDER:
self.init_file_data(path)
elif row[self.Column.NAME] == self.ROOT:
self.init_file_data(path.parent)
else:
self.open_file(row[self.Column.ATTR])
@run_task
def open_file(self, path):
GLib.idle_add(self._file_view.set_sensitive, False)
try:
cmd = ["open" if self._settings.is_darwin else "xdg-open", path]
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
finally:
GLib.idle_add(self._file_view.set_sensitive, True)
@run_task
def open_ftp_file(self, f_path):
is_darwin = self._settings.is_darwin
GLib.idle_add(self._ftp_view.set_sensitive, False)
try:
import tempfile
import os
path = os.path.expanduser("~/Desktop") if is_darwin else None
with tempfile.NamedTemporaryFile(mode="wb", dir=path, delete=not is_darwin) as tf:
msg = "Downloading file: {}. Status: {}"
try:
status = self._ftp.retrbinary("RETR " + f_path, tf.write)
self.update_ftp_info(msg.format(f_path, status))
except all_errors as e:
self.update_ftp_info(msg.format(f_path, e))
tf.flush()
cmd = ["open" if is_darwin else "xdg-open", tf.name]
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
finally:
GLib.idle_add(self._ftp_view.set_sensitive, True)
def on_ftp_edit(self, renderer):
model, paths = self._ftp_view.get_selection().get_selected_rows()
if not paths:
return
if len(paths) > 1:
self._app.show_error_dialog("Please, select only one item!")
return
renderer.set_property("editable", True)
self._ftp_view.set_cursor(paths, self._ftp_view.get_column(0), True)
def on_ftp_edited(self, renderer, path, new_value):
renderer.set_property("editable", False)
row = self._ftp_model[path]
old_name = row[self.Column.NAME]
if old_name == new_value:
return
resp = self._ftp.rename_file(old_name, new_value)
self.update_ftp_info("{} Status: {}".format(old_name, resp))
if resp[0] == "2":
row[self.Column.NAME] = new_value
def on_file_edit(self, renderer):
model, paths = self._file_view.get_selection().get_selected_rows()
if len(paths) > 1:
self._app.show_error_dialog("Please, select only one item!")
return
renderer.set_property("editable", True)
self._file_view.set_cursor(paths, self._file_view.get_column(0), True)
def on_file_edited(self, renderer, path, new_value):
renderer.set_property("editable", False)
row = self._file_model[path]
old_name = row[self.Column.NAME]
if old_name == new_value:
return
path = Path(row[self.Column.ATTR])
if path.exists():
try:
new_path = path.rename("{}/{}".format(path.parent, new_value))
except ValueError as e:
log(e)
self._app.show_error_dialog(str(e))
else:
if new_path.name == new_value:
row[self.Column.NAME] = new_value
row[self.Column.ATTR] = str(new_path.resolve())
def on_file_remove(self, item=None):
if show_dialog(DialogType.QUESTION, self._app._main_window) != Gtk.ResponseType.OK:
return
model, paths = self._file_view.get_selection().get_selected_rows()
to_delete = []
for path in filter(lambda p: model[p][self.Column.NAME] != self.ROOT, paths):
f_path = Path(model[path][self.Column.ATTR])
try:
rmtree(f_path, ignore_errors=True) if f_path.is_dir() else f_path.unlink()
except OSError as e:
log(e)
else:
to_delete.append(model.get_iter(path))
list(map(model.remove, to_delete))
def on_ftp_file_remove(self, item=None):
if show_dialog(DialogType.QUESTION, self._app._main_window) != Gtk.ResponseType.OK:
return
model, paths = self._ftp_view.get_selection().get_selected_rows()
to_delete = []
for path in filter(lambda p: model[p][self.Column.NAME] != self.ROOT, paths):
row = model[path][:]
name = row[self.Column.NAME]
if row[self.Column.SIZE] == self.FOLDER:
resp = self._ftp.delete_dir(name, self.update_ftp_info)
else:
resp = self._ftp.delete_file(name, self.update_ftp_info)
if resp[0] == "2":
to_delete.append(model.get_iter(path))
list(map(model.remove, to_delete))
def on_file_create_folder(self, renderer):
itr = self._file_model.get_iter_first()
if not itr:
return
name = self.get_new_folder_name(self._file_model)
cur_path = self._file_model.get_value(itr, self.Column.ATTR)
path = Path("{}/{}".format(cur_path, name))
try:
path.mkdir()
except OSError as e:
log(e)
self._app.show_error_dialog(str(e))
else:
itr = self._file_model.append(File(self._folder_icon, path.name, self.FOLDER, "", str(path.resolve()), "0"))
renderer.set_property("editable", True)
self._file_view.set_cursor(self._file_model.get_path(itr), self._file_view.get_column(0), True)
def on_ftp_create_folder(self, renderer):
itr = self._ftp_model.get_iter_first()
if not itr:
return
cur_path = self._ftp_model.get_value(itr, self.Column.ATTR)
name = self.get_new_folder_name(self._ftp_model)
try:
folder = "{}/{}".format(cur_path, name)
resp = self._ftp.mkd(folder)
except all_errors as e:
self.update_ftp_info(str(e))
log(e)
else:
if resp == "{}/{}".format(cur_path, name):
itr = self._ftp_model.append(File(self._folder_icon, name, self.FOLDER, "", "drwxr-xr-x", "0"))
renderer.set_property("editable", True)
self._ftp_view.set_cursor(self._ftp_model.get_path(itr), self._ftp_view.get_column(0), True)
def get_new_folder_name(self, model):
""" Returns the default name for the newly created folder. """
name = "new folder"
names = {r[self.Column.NAME] for r in model}
count = 0
while name in names:
count += 1
name = "{}{}".format(name, count)
return name
# ***************** Drag-and-drop ********************* #
def init_drag_and_drop(self):
self._ftp_view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY)
self._ftp_view.enable_model_drag_dest([], Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
self._ftp_view.drag_source_add_uri_targets()
self._ftp_view.drag_dest_add_uri_targets()
self._file_view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY)
self._file_view.enable_model_drag_dest([], Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
self._file_view.drag_source_add_uri_targets()
self._file_view.drag_dest_add_uri_targets()
self._ftp_view.get_selection().set_select_function(lambda *args: self._select_enabled)
self._file_view.get_selection().set_select_function(lambda *args: self._select_enabled)
def on_view_drag_begin(self, view, context):
model, paths = view.get_selection().get_selected_rows()
if len(paths) < 1:
return
pix = self._app.get_drag_icon_pixbuf(model, paths, self.Column.NAME, self.Column.SIZE)
Gtk.drag_set_icon_pixbuf(context, pix, 0, 0)
return True
def on_ftp_drag_data_get(self, view, context, data, info, time):
model, paths = view.get_selection().get_selected_rows()
if len(paths) > 0:
sep = self.URI_SEP if self._settings.is_darwin else "\n"
uris = []
for r in [model[p][:] for p in paths]:
if r[self.Column.SIZE] != self.LINK and r[self.Column.NAME] != self.ROOT:
uris.append(Path("/{}:{}".format(r[self.Column.NAME], r[self.Column.ATTR])).as_uri())
data.set_uris([sep.join(uris)])
@run_task
def on_ftp_drag_data_received(self, view, context, x, y, data: Gtk.SelectionData, info, time):
if not self._ftp:
return
resp = "2"
try:
GLib.idle_add(self._app._wait_dialog.show)
uris = data.get_uris()
if self._settings.is_darwin and len(uris) == 1:
uris = uris[0].split(self.URI_SEP)
for uri in uris:
uri = urlparse(unquote(uri)).path
path = Path(uri)
if path.is_dir():
try:
self._ftp.mkd(path.name)
except all_errors as e:
pass # NOP
self._ftp.cwd(path.name)
resp = self._ftp.upload_dir(str(path.resolve()) + "/", self.update_ftp_info)
else:
resp = self._ftp.send_file(path.name, str(path.parent) + "/", callback=self.update_ftp_info)
finally:
GLib.idle_add(self._app._wait_dialog.hide)
if resp and resp[0] == "2":
itr = self._ftp_model.get_iter_first()
if itr:
self.init_ftp_data(self._ftp_model.get_value(itr, self.Column.ATTR))
Gtk.drag_finish(context, True, False, time)
return True
def on_file_drag_data_get(self, view, context, data: Gtk.SelectionData, info, time):
model, paths = view.get_selection().get_selected_rows()
if len(paths) > 0:
sep = self.URI_SEP if self._settings.is_darwin else "\n"
uris = [sep.join([Path(model[p][self.Column.ATTR]).as_uri() for p in paths])]
data.set_uris(uris)
@run_task
def on_file_drag_data_received(self, view, context, x, y, data, info, time):
cur_path = self._file_model.get_value(self._file_model.get_iter_first(), self.Column.ATTR) + "/"
try:
GLib.idle_add(self._app._wait_dialog.show)
uris = data.get_uris()
if self._settings.is_darwin and len(uris) == 1:
uris = uris[0].split(self.URI_SEP)
for uri in uris:
name, sep, attr = unquote(Path(uri).name).partition(":")
if not attr:
return True
if attr[0] == "d":
self._ftp.download_dir(name, cur_path, self.update_ftp_info)
else:
self._ftp.download_file(name, cur_path, self.update_ftp_info)
except OSError as e:
log(e)
finally:
GLib.idle_add(self._app._wait_dialog.hide)
self.init_file_data(cur_path)
Gtk.drag_finish(context, True, False, time)
return True
def on_view_drag_end(self, view, context):
self._select_enabled = True
view.get_selection().unselect_all()
@run_idle
def update_ftp_info(self, message):
message = message.strip()
self._ftp_info_label.set_text(message)
self._ftp_info_label.set_tooltip_text(message)
def on_view_key_press(self, view, event):
key_code = event.hardware_keycode
if not KeyboardKey.value_exist(key_code):
return
key = KeyboardKey(key_code)
ctrl = event.state & MOD_MASK
if key is KeyboardKey.F7:
if self._ftp_view.is_focus():
self.on_ftp_create_folder(self._ftp_name_renderer)
elif self._file_view.is_focus():
self.on_file_create_folder(self._file_name_renderer)
elif key is KeyboardKey.F2 or ctrl and KeyboardKey.R:
if self._ftp_view.is_focus():
self.on_ftp_edit(self._ftp_name_renderer)
elif self._file_view.is_focus():
self.on_file_edit(self._file_name_renderer)
elif key is KeyboardKey.DELETE:
if self._ftp_view.is_focus():
self.on_ftp_file_remove()
elif self._file_view.is_focus():
self.on_file_remove()
def on_view_press(self, view, event):
if event.get_event_type() == Gdk.EventType.BUTTON_PRESS and event.button == Gdk.BUTTON_PRIMARY:
target = view.get_path_at_pos(event.x, event.y)
mask = not (event.state & (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK))
if target and mask and view.get_selection().path_is_selected(target[0]):
self._select_enabled = False
def on_view_release(self, view, event):
""" Handles a mouse click (release) to view. """
# Enable selection.
self._select_enabled = True
def get_size_from_bytes(self, size):
""" Simple convert function from bytes to other units like K, M or G. """
try:
b = float(size)
except ValueError:
return size
else:
kb, mb, gb = 1024.0, 1048576.0, 1073741824.0
if b < kb:
return str(b)
elif kb <= b < mb:
return "{0:.1f} K".format(b / kb)
elif mb <= b < gb:
return "{0:.1f} M".format(b / mb)
elif gb <= b:
return "{0:.1f} G".format(b / gb)
if __name__ == '__main__':
pass
|
"""Tests for bllb logging module."""
# pylint: disable=unused-wildcard-import, undefined-variable
import re
from hypothesis import given
from hypothesis.strategies import text
from hypothesis_auto import auto_pytest, auto_pytest_magic
import pytest
from bripy.bllb.str import *
DEFAULT_RUNS = 50
FUNCTIONS = {
hash_utf8: DEFAULT_RUNS,
get_slug: DEFAULT_RUNS,
date_slug: DEFAULT_RUNS,
get_nums: DEFAULT_RUNS,
get_ints: DEFAULT_RUNS,
is_number: DEFAULT_RUNS,
is_number_like: DEFAULT_RUNS,
get_acronyms: DEFAULT_RUNS,
split_camel_case: DEFAULT_RUNS,
get_symbols: DEFAULT_RUNS,
comp: DEFAULT_RUNS,
comp_quick: DEFAULT_RUNS,
comp_real_quick: DEFAULT_RUNS,
symbol_counts_dist: DEFAULT_RUNS,
check_case: DEFAULT_RUNS,
keep_word: DEFAULT_RUNS,
check_case_list: DEFAULT_RUNS,
remove_chars: DEFAULT_RUNS,
text_only: DEFAULT_RUNS,
split_num_words: DEFAULT_RUNS,
make_token_pattern: DEFAULT_RUNS,
make_exp: DEFAULT_RUNS,
pre: DEFAULT_RUNS,
tok: DEFAULT_RUNS,
rejoin: DEFAULT_RUNS,
tok1: DEFAULT_RUNS,
tok3: DEFAULT_RUNS,
make_trans_table: DEFAULT_RUNS,
get_whiteout: DEFAULT_RUNS,
clean_text: DEFAULT_RUNS,
pad_punctuation_w_space: DEFAULT_RUNS,
Entropy.h: DEFAULT_RUNS,
Entropy.h_printable: DEFAULT_RUNS,
Entropy.h_alphanum_lower: DEFAULT_RUNS,
}
for func, runs in FUNCTIONS.items():
auto_pytest_magic(func, auto_runs_=runs)
@given(text())
def test_split_words(text: str):
"""Test split_words function by performing identical steps."""
new_s = " ".join(split_words(text, True))
words = []
for word in re.findall(r"[\w']+", text):
for _ in word.split("_"):
words.append(check_case(_, True))
old_s = " ".join(words)
assert new_s == old_s
@auto_pytest(test_split_words, auto_runs_=DEFAULT_RUNS)
def test_split_words_auto(test_case):
"""Auto generate tests for test_split_words."""
test_case()
test_nums = ['0', '-1', '0.123', '.123', '-.123', '1.23']
@pytest.mark.parametrize("text", test_nums)
def test_is_number(text):
"""Test is_number."""
assert is_number(text)
test_num_like = ['0', '-1,100', '1,23', '1/1/1', '1_100', '1.23.45.67']
@pytest.mark.parametrize("text", test_num_like)
def test_is_number_like(text):
"""Test is_number_like."""
assert is_number_like(text)
def test_check_case():
"""Test check_case with non-default options."""
assert check_case('TEST', lower=False) == 'TEST'
def test_token_num():
"""Test make_token_pattern with non-default options."""
assert make_token_pattern(inc_num=True)
def test_pre():
"""Test pre with non-default options."""
assert pre('TEST', casefold=False) == 'TEST'
def test_trans():
"""Test make_trans_table with non-default options."""
assert make_trans_table(tolower=False, toupper=True, repl_num=True)
def test_hash():
"""Test that hash of a known value works properly."""
assert hash_utf8("") == "d41d8cd98f00b204e9800998ecf8427e"
|
# coding: utf-8# File content is auto-generated. Do not modify.
# pylint: skip-file
from ._internal import SymbolBase
from ..base import _Null
def Activation(data=None, act_type=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies an activation function element-wise to the input.
The following activation functions are supported:
- `relu`: Rectified Linear Unit, :math:`y = max(x, 0)`
- `sigmoid`: :math:`y = \frac{1}{1 + exp(-x)}`
- `tanh`: Hyperbolic tangent, :math:`y = \frac{exp(x) - exp(-x)}{exp(x) + exp(-x)}`
- `softrelu`: Soft ReLU, or SoftPlus, :math:`y = log(1 + exp(x))`
- `softsign`: :math:`y = \frac{x}{1 + abs(x)}`
Defined in ../src/operator/nn/activation.cc:L165
Parameters
----------
data : Symbol
The input array.
act_type : {'relu', 'sigmoid', 'softrelu', 'softsign', 'tanh'}, required
Activation function to be applied.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
A one-hidden-layer MLP with ReLU activation:
>>> data = Variable('data')
>>> mlp = FullyConnected(data=data, num_hidden=128, name='proj')
>>> mlp = Activation(data=mlp, act_type='relu', name='activation')
>>> mlp = FullyConnected(data=mlp, num_hidden=10, name='mlp')
>>> mlp
<Symbol mlp>
ReLU activation
>>> test_suites = [
... ('relu', lambda x: np.maximum(x, 0)),
... ('sigmoid', lambda x: 1 / (1 + np.exp(-x))),
... ('tanh', lambda x: np.tanh(x)),
... ('softrelu', lambda x: np.log(1 + np.exp(x)))
... ]
>>> x = test_utils.random_arrays((2, 3, 4))
>>> for act_type, numpy_impl in test_suites:
... op = Activation(act_type=act_type, name='act')
... y = test_utils.simple_forward(op, act_data=x)
... y_np = numpy_impl(x)
... print('%s: %s' % (act_type, test_utils.almost_equal(y, y_np)))
relu: True
sigmoid: True
tanh: True
softrelu: True
"""
return (0,)
def BNStatsFinalize(sum=None, sum_squares=None, gamma=None, beta=None, moving_mean=None, moving_var=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, elem_count=_Null, name=None, attr=None, out=None, **kwargs):
r"""Batch normalization stats finalize.
This is an experimental operator designed to work in concert with the NormalizedConvolution op.
Think of batchnorm as split into:
1) input data statistics generation (but now sum and sum_squares, not mean and variance)
2) statistics finalize (maps sum, sum_squares, beta and gamma to an equiv_scale and equiv_bias)
3) apply equiv_scale and equiv_bias to data
With this picture, the NormalizedConvolution includes parts 1) and 3) from above:
NormalizedConvolution == StatsApply -> Relu -> Convolution -> StatsGen
What's left over from this NormalizedConvolution is BNStatsFinalize, which performs the mapping
of part 2) above, plus the running mean, running variance state machine update of Batchnorm.
Legacy description of Batchnorm:
Normalizes a data batch by mean and variance, and applies a scale ``gamma`` as
well as offset ``beta``.
Assume the input has more than one dimension and we normalize along axis 1.
We first compute the mean and variance along this axis:
.. math::
data\_mean[i] = mean(data[:,i,:,...]) \\
data\_var[i] = var(data[:,i,:,...])
Then compute the normalized output, which has the same shape as input, as following:
.. math::
out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i]
Both *mean* and *var* returns a scalar by treating the input as a vector.
Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``
have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and
the inverse of ``data_var``, which are needed for the backward pass. Note that gradient of these
two outputs are blocked.
Besides the inputs and the outputs, this operator accepts two auxiliary
states, ``moving_mean`` and ``moving_var``, which are *k*-length
vectors. They are global statistics for the whole dataset, which are updated
by::
moving_mean = moving_mean * momentum + data_mean * (1 - momentum)
moving_var = moving_var * momentum + data_var * (1 - momentum)
If ``use_global_stats`` is set to be true, then ``moving_mean`` and
``moving_var`` are used instead of ``data_mean`` and ``data_var`` to compute
the output. It is often used during inference.
The parameter ``axis`` specifies which axis of the input shape denotes
the 'channel' (separately normalized groups). The default is 1. Specifying -1 sets the channel
axis to be the last item in the input shape.
Both ``gamma`` and ``beta`` are learnable parameters. But if ``fix_gamma`` is true,
then set ``gamma`` to 1 and its gradient to 0.
.. Note::
When ``fix_gamma`` is set to True, no sparse support is provided. If ``fix_gamma is`` set to False,
the sparse tensors will fallback.
Defined in ../src/operator/nn/bn_stats_finalize.cc:L226
Parameters
----------
sum : Symbol
sum of input data to be normalized
sum_squares : Symbol
sum of squares of input data to be normalized
gamma : Symbol
gamma array
beta : Symbol
beta array
moving_mean : Symbol
running mean of input
moving_var : Symbol
running variance of input
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output the mean and inverse std
elem_count : long (non-negative), required
Number of elements accumulated in 'sum' and 'sum_squares'.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def BatchNorm(data=None, gamma=None, beta=None, moving_mean=None, moving_var=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, axis=_Null, cudnn_off=_Null, min_calib_range=_Null, max_calib_range=_Null, act_type=_Null, bn_group=_Null, xbuf_ptr=_Null, name=None, attr=None, out=None, **kwargs):
r"""Batch normalization.
Normalizes a data batch by mean and variance, and applies a scale ``gamma`` as
well as offset ``beta``.
Assume the input has more than one dimension and we normalize along axis 1.
We first compute the mean and variance along this axis:
.. math::
data\_mean[i] = mean(data[:,i,:,...]) \\
data\_var[i] = var(data[:,i,:,...])
Then compute the normalized output, which has the same shape as input, as following:
.. math::
out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i]
Both *mean* and *var* returns a scalar by treating the input as a vector.
Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``
have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and
the inverse of ``data_var``, which are needed for the backward pass. Note that gradient of these
two outputs are blocked.
Besides the inputs and the outputs, this operator accepts two auxiliary
states, ``moving_mean`` and ``moving_var``, which are *k*-length
vectors. They are global statistics for the whole dataset, which are updated
by::
moving_mean = moving_mean * momentum + data_mean * (1 - momentum)
moving_var = moving_var * momentum + data_var * (1 - momentum)
If ``use_global_stats`` is set to be true, then ``moving_mean`` and
``moving_var`` are used instead of ``data_mean`` and ``data_var`` to compute
the output. It is often used during inference.
The parameter ``axis`` specifies which axis of the input shape denotes
the 'channel' (separately normalized groups). The default is 1. Specifying -1 sets the channel
axis to be the last item in the input shape.
Both ``gamma`` and ``beta`` are learnable parameters. But if ``fix_gamma`` is true,
then set ``gamma`` to 1 and its gradient to 0.
.. Note::
When ``fix_gamma`` is set to True, no sparse support is provided. If ``fix_gamma is`` set to False,
the sparse tensors will fallback.
Defined in ../src/operator/nn/batch_norm.cc:L620
Parameters
----------
data : Symbol
Input data to batch normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
moving_mean : Symbol
running mean of input
moving_var : Symbol
running variance of input
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output the mean and inverse std
axis : int, optional, default='1'
Specify which shape axis the channel is specified
cudnn_off : boolean, optional, default=0
Do not select CUDNN operator, if available
min_calib_range : float or None, optional, default=None
The minimum scalar value in the form of float32 obtained through calibration. If present, it will be used to by quantized batch norm op to calculate primitive scale.Note: this calib_range is to calib bn output.
max_calib_range : float or None, optional, default=None
The maximum scalar value in the form of float32 obtained through calibration. If present, it will be used to by quantized batch norm op to calculate primitive scale.Note: this calib_range is to calib bn output.
act_type : {None, 'relu', 'sigmoid', 'softrelu', 'tanh'},optional, default='None'
Fused activation function to be applied.
bn_group : int, optional, default='1'
BN group
xbuf_ptr : long (non-negative), optional, default=0
xbuf ptr
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def BatchNormAddRelu(data=None, gamma=None, beta=None, moving_mean=None, moving_var=None, addend=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, axis=_Null, cudnn_off=_Null, bn_group=_Null, xbuf_ptr=_Null, name=None, attr=None, out=None, **kwargs):
r"""Batch normalization with built-in addition and ReLU Activation.
Normalizes a data batch by mean and variance, and applies a scale ``gamma`` as
well as offset ``beta``. This version is somewhat special purpose in that the
usual normalized data output is then added to an additional data input, followed
by ReLU activation.
Assume the input has more than one dimension and we normalize along axis 1.
We first compute the mean and variance along this axis:
.. math::
data\_mean[i] = mean(data[:,i,:,...]) \\
data\_var[i] = var(data[:,i,:,...])
Then compute the normalized output, which has the same shape as input, as following:
.. math::
out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i]
Both *mean* and *var* returns a scalar by treating the input as a vector.
Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``
have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and
the inverse of ``data_var``, which are needed for the backward pass. Note that gradient of these
two outputs are blocked.
Besides the inputs and the outputs, this operator accepts two auxiliary
states, ``moving_mean`` and ``moving_var``, which are *k*-length
vectors. They are global statistics for the whole dataset, which are updated
by::
moving_mean = moving_mean * momentum + data_mean * (1 - momentum)
moving_var = moving_var * momentum + data_var * (1 - momentum)
If ``use_global_stats`` is set to be true, then ``moving_mean`` and
``moving_var`` are used instead of ``data_mean`` and ``data_var`` to compute
the output. It is often used during inference.
The parameter ``axis`` specifies which axis of the input shape denotes
the 'channel' (separately normalized groups). The default is 1. Specifying -1 sets the channel
axis to be the last item in the input shape.
Both ``gamma`` and ``beta`` are learnable parameters. But if ``fix_gamma`` is true,
then set ``gamma`` to 1 and its gradient to 0.
Note::
When fix_gamma is set to True, no sparse support is provided. If fix_gamma is set to False,
the sparse tensors will fallback.
Defined in ../src/operator/nn/batch_norm_add_relu.cc:L518
Parameters
----------
data : Symbol
Input data to batch normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
moving_mean : Symbol
running mean of input
moving_var : Symbol
running variance of input
addend : Symbol
input summed with BN output before relu
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output the mean and inverse std
axis : int, optional, default='1'
Specify which shape axis the channel is specified
cudnn_off : boolean, optional, default=0
Do not select CUDNN operator, if available
bn_group : int, optional, default='1'
BN group
xbuf_ptr : long (non-negative), optional, default=0
xbuf ptr
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def BatchNorm_v1(data=None, gamma=None, beta=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, name=None, attr=None, out=None, **kwargs):
r"""Batch normalization.
This operator is DEPRECATED. Perform BatchNorm on the input.
Normalizes a data batch by mean and variance, and applies a scale ``gamma`` as
well as offset ``beta``.
Assume the input has more than one dimension and we normalize along axis 1.
We first compute the mean and variance along this axis:
.. math::
data\_mean[i] = mean(data[:,i,:,...]) \\
data\_var[i] = var(data[:,i,:,...])
Then compute the normalized output, which has the same shape as input, as following:
.. math::
out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i]
Both *mean* and *var* returns a scalar by treating the input as a vector.
Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``
have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and
``data_var`` as well, which are needed for the backward pass.
Besides the inputs and the outputs, this operator accepts two auxiliary
states, ``moving_mean`` and ``moving_var``, which are *k*-length
vectors. They are global statistics for the whole dataset, which are updated
by::
moving_mean = moving_mean * momentum + data_mean * (1 - momentum)
moving_var = moving_var * momentum + data_var * (1 - momentum)
If ``use_global_stats`` is set to be true, then ``moving_mean`` and
``moving_var`` are used instead of ``data_mean`` and ``data_var`` to compute
the output. It is often used during inference.
Both ``gamma`` and ``beta`` are learnable parameters. But if ``fix_gamma`` is true,
then set ``gamma`` to 1 and its gradient to 0.
There's no sparse support for this operator, and it will exhibit problematic behavior if used with
sparse tensors.
Defined in ../src/operator/batch_norm_v1.cc:L95
Parameters
----------
data : Symbol
Input data to batch normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
eps : float, optional, default=0.00100000005
Epsilon to prevent div 0
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output All,normal mean and var
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def BilinearSampler(data=None, grid=None, cudnn_off=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies bilinear sampling to input feature map.
Bilinear Sampling is the key of [NIPS2015] \"Spatial Transformer Networks\". The usage of the operator is very similar to remap function in OpenCV,
except that the operator has the backward pass.
Given :math:`data` and :math:`grid`, then the output is computed by
.. math::
x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\
y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\
output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src})
:math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and :math:`G()` denotes the bilinear interpolation kernel.
The out-boundary points will be padded with zeros.The shape of the output will be (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]).
The operator assumes that :math:`data` has 'NCHW' layout and :math:`grid` has been normalized to [-1, 1].
BilinearSampler often cooperates with GridGenerator which generates sampling grids for BilinearSampler.
GridGenerator supports two kinds of transformation: ``affine`` and ``warp``.
If users want to design a CustomOp to manipulate :math:`grid`, please firstly refer to the code of GridGenerator.
Example 1::
## Zoom out data two times
data = array([[[[1, 4, 3, 6],
[1, 8, 8, 9],
[0, 4, 1, 5],
[1, 0, 1, 3]]]])
affine_matrix = array([[2, 0, 0],
[0, 2, 0]])
affine_matrix = reshape(affine_matrix, shape=(1, 6))
grid = GridGenerator(data=affine_matrix, transform_type='affine', target_shape=(4, 4))
out = BilinearSampler(data, grid)
out
[[[[ 0, 0, 0, 0],
[ 0, 3.5, 6.5, 0],
[ 0, 1.25, 2.5, 0],
[ 0, 0, 0, 0]]]
Example 2::
## shift data horizontally by -1 pixel
data = array([[[[1, 4, 3, 6],
[1, 8, 8, 9],
[0, 4, 1, 5],
[1, 0, 1, 3]]]])
warp_maxtrix = array([[[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]]])
grid = GridGenerator(data=warp_matrix, transform_type='warp')
out = BilinearSampler(data, grid)
out
[[[[ 4, 3, 6, 0],
[ 8, 8, 9, 0],
[ 4, 1, 5, 0],
[ 0, 1, 3, 0]]]
Defined in ../src/operator/bilinear_sampler.cc:L256
Parameters
----------
data : Symbol
Input data to the BilinearsamplerOp.
grid : Symbol
Input grid to the BilinearsamplerOp.grid has two channels: x_src, y_src
cudnn_off : boolean or None, optional, default=None
whether to turn cudnn off
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def BlockGrad(data=None, name=None, attr=None, out=None, **kwargs):
r"""Stops gradient computation.
Stops the accumulated gradient of the inputs from flowing through this operator
in the backward direction. In other words, this operator prevents the contribution
of its inputs to be taken into account for computing gradients.
Example::
v1 = [1, 2]
v2 = [0, 1]
a = Variable('a')
b = Variable('b')
b_stop_grad = stop_gradient(3 * b)
loss = MakeLoss(b_stop_grad + a)
executor = loss.simple_bind(ctx=cpu(), a=(1,2), b=(1,2))
executor.forward(is_train=True, a=v1, b=v2)
executor.outputs
[ 1. 5.]
executor.backward()
executor.grad_arrays
[ 0. 0.]
[ 1. 1.]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L325
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def CTCLoss(data=None, label=None, data_lengths=None, label_lengths=None, use_data_lengths=_Null, use_label_lengths=_Null, blank_label=_Null, name=None, attr=None, out=None, **kwargs):
r"""Connectionist Temporal Classification Loss.
.. note:: The existing alias ``contrib_CTCLoss`` is deprecated.
The shapes of the inputs and outputs:
- **data**: `(sequence_length, batch_size, alphabet_size)`
- **label**: `(batch_size, label_sequence_length)`
- **out**: `(batch_size)`
The `data` tensor consists of sequences of activation vectors (without applying softmax),
with i-th channel in the last dimension corresponding to i-th label
for i between 0 and alphabet_size-1 (i.e always 0-indexed).
Alphabet size should include one additional value reserved for blank label.
When `blank_label` is ``"first"``, the ``0``-th channel is be reserved for
activation of blank label, or otherwise if it is "last", ``(alphabet_size-1)``-th channel should be
reserved for blank label.
``label`` is an index matrix of integers. When `blank_label` is ``"first"``,
the value 0 is then reserved for blank label, and should not be passed in this matrix. Otherwise,
when `blank_label` is ``"last"``, the value `(alphabet_size-1)` is reserved for blank label.
If a sequence of labels is shorter than *label_sequence_length*, use the special
padding value at the end of the sequence to conform it to the correct
length. The padding value is `0` when `blank_label` is ``"first"``, and `-1` otherwise.
For example, suppose the vocabulary is `[a, b, c]`, and in one batch we have three sequences
'ba', 'cbb', and 'abac'. When `blank_label` is ``"first"``, we can index the labels as
`{'a': 1, 'b': 2, 'c': 3}`, and we reserve the 0-th channel for blank label in data tensor.
The resulting `label` tensor should be padded to be::
[[2, 1, 0, 0], [3, 2, 2, 0], [1, 2, 1, 3]]
When `blank_label` is ``"last"``, we can index the labels as
`{'a': 0, 'b': 1, 'c': 2}`, and we reserve the channel index 3 for blank label in data tensor.
The resulting `label` tensor should be padded to be::
[[1, 0, -1, -1], [2, 1, 1, -1], [0, 1, 0, 2]]
``out`` is a list of CTC loss values, one per example in the batch.
See *Connectionist Temporal Classification: Labelling Unsegmented
Sequence Data with Recurrent Neural Networks*, A. Graves *et al*. for more
information on the definition and the algorithm.
Defined in ../src/operator/nn/ctc_loss.cc:L100
Parameters
----------
data : Symbol
Input ndarray
label : Symbol
Ground-truth labels for the loss.
data_lengths : Symbol
Lengths of data for each of the samples. Only required when use_data_lengths is true.
label_lengths : Symbol
Lengths of labels for each of the samples. Only required when use_label_lengths is true.
use_data_lengths : boolean, optional, default=0
Whether the data lenghts are decided by `data_lengths`. If false, the lengths are equal to the max sequence length.
use_label_lengths : boolean, optional, default=0
Whether the label lenghts are decided by `label_lengths`, or derived from `padding_mask`. If false, the lengths are derived from the first occurrence of the value of `padding_mask`. The value of `padding_mask` is ``0`` when first CTC label is reserved for blank, and ``-1`` when last label is reserved for blank. See `blank_label`.
blank_label : {'first', 'last'},optional, default='first'
Set the label that is reserved for blank label.If "first", 0-th label is reserved, and label values for tokens in the vocabulary are between ``1`` and ``alphabet_size-1``, and the padding mask is ``-1``. If "last", last label value ``alphabet_size-1`` is reserved for blank label instead, and label values for tokens in the vocabulary are between ``0`` and ``alphabet_size-2``, and the padding mask is ``0``.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Cast(data=None, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Casts all elements of the input to a new type.
.. note:: ``Cast`` is deprecated. Use ``cast`` instead.
Example::
cast([0.9, 1.3], dtype='int32') = [0, 1]
cast([1e20, 11.1], dtype='float16') = [inf, 11.09375]
cast([300, 11.1, 10.9, -1, -3], dtype='uint8') = [44, 11, 10, 255, 253]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L664
Parameters
----------
data : Symbol
The input.
dtype : {'bfloat16', 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'}, required
Output data type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Concat(*data, **kwargs):
r"""Joins input arrays along a given axis.
.. note:: `Concat` is deprecated. Use `concat` instead.
The dimensions of the input arrays should be the same except the axis along
which they will be concatenated.
The dimension of the output array along the concatenated axis will be equal
to the sum of the corresponding dimensions of the input arrays.
The storage type of ``concat`` output depends on storage types of inputs
- concat(csr, csr, ..., csr, dim=0) = csr
- otherwise, ``concat`` generates output with default storage
Example::
x = [[1,1],[2,2]]
y = [[3,3],[4,4],[5,5]]
z = [[6,6], [7,7],[8,8]]
concat(x,y,z,dim=0) = [[ 1., 1.],
[ 2., 2.],
[ 3., 3.],
[ 4., 4.],
[ 5., 5.],
[ 6., 6.],
[ 7., 7.],
[ 8., 8.]]
Note that you cannot concat x,y,z along dimension 1 since dimension
0 is not the same for all the input arrays.
concat(y,z,dim=1) = [[ 3., 3., 6., 6.],
[ 4., 4., 7., 7.],
[ 5., 5., 8., 8.]]
Defined in ../src/operator/nn/concat.cc:L385
This function support variable length of positional input.
Parameters
----------
data : Symbol[]
List of arrays to concatenate
dim : int, optional, default='1'
the dimension to be concated.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
Concat two (or more) inputs along a specific dimension:
>>> a = Variable('a')
>>> b = Variable('b')
>>> c = Concat(a, b, dim=1, name='my-concat')
>>> c
<Symbol my-concat>
>>> SymbolDoc.get_output_shape(c, a=(128, 10, 3, 3), b=(128, 15, 3, 3))
{'my-concat_output': (128L, 25L, 3L, 3L)}
Note the shape should be the same except on the dimension that is being
concatenated.
"""
return (0,)
def Convolution(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, cudnn_tensor_core=_Null, cudnn_tensor_core_only=_Null, layout=_Null, cudnn_algo_verbose=_Null, cudnn_algo_fwd=_Null, cudnn_algo_bwd_data=_Null, cudnn_algo_bwd_filter=_Null, cudnn_algo_fwd_prec=_Null, cudnn_algo_bwd_prec=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute *N*-D convolution on *(N+2)*-D input.
In the 2-D convolution, given input data with shape *(batch_size,
channel, height, width)*, the output is computed by
.. math::
out[n,i,:,:] = bias[i] + \sum_{j=0}^{channel} data[n,j,:,:] \star
weight[i,j,:,:]
where :math:`\star` is the 2-D cross-correlation operator.
For general 2-D convolution, the shapes are
- **data**: *(batch_size, channel, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_height, out_width)*.
Define::
f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1
then we have::
out_height=f(height, kernel[0], pad[0], stride[0], dilate[0])
out_width=f(width, kernel[1], pad[1], stride[1], dilate[1])
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
The default data ``layout`` is *NCHW*, namely *(batch_size, channel, height,
width)*. We can choose other layouts such as *NWC*.
If ``num_group`` is larger than 1, denoted by *g*, then split the input ``data``
evenly into *g* parts along the channel axis, and also evenly split ``weight``
along the first dimension. Next compute the convolution on the *i*-th part of
the data with the *i*-th weight part. The output is obtained by concatenating all
the *g* results.
1-D convolution does not have *height* dimension but only *width* in space.
- **data**: *(batch_size, channel, width)*
- **weight**: *(num_filter, channel, kernel[0])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_width)*.
3-D convolution adds an additional *depth* dimension besides *height* and
*width*. The shapes are
- **data**: *(batch_size, channel, depth, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1], kernel[2])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_depth, out_height, out_width)*.
Both ``weight`` and ``bias`` are learnable parameters.
There are other options to tune the performance.
- **cudnn_tune**: enable this option leads to higher startup time but may give
faster speed. Options are
- **off**: no tuning
- **limited_workspace**:run test and pick the fastest algorithm that doesn't
exceed workspace limit.
- **fastest**: pick the fastest algorithm and ignore workspace limit.
- **None** (default): the behavior is determined by environment variable
``MXNET_CUDNN_AUTOTUNE_DEFAULT``. 0 for off, 1 for limited workspace
(default), 2 for fastest.
- **workspace**: A large number leads to more (GPU) memory usage but may improve
the performance.
Defined in ../src/operator/nn/convolution.cc:L498
Parameters
----------
data : Symbol
Input data to the ConvolutionOp.
weight : Symbol
Weight matrix.
bias : Symbol
Bias parameter.
kernel : Shape(tuple), required
Convolution kernel size: (w,), (h, w) or (d, h, w)
stride : Shape(tuple), optional, default=[]
Convolution stride: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
dilate : Shape(tuple), optional, default=[]
Convolution dilate: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
Zero pad for convolution: (w,), (h, w) or (d, h, w). Defaults to no padding.
num_filter : int (non-negative), required
Convolution filter(channel) number
num_group : int (non-negative), optional, default=1
Number of group partitions.
workspace : long (non-negative), optional, default=1024
Maximum temporary workspace allowed (MB) in convolution.This parameter has two usages. When CUDNN is not used, it determines the effective batch size of the convolution kernel. When CUDNN is used, it controls the maximum temporary storage used for tuning the best CUDNN kernel when `limited_workspace` strategy is used.
no_bias : boolean, optional, default=0
Whether to disable bias parameter.
cudnn_tune : {None, 'fastest', 'limited_workspace', 'off'},optional, default='None'
Whether to pick convolution algo by running performance test.
cudnn_off : boolean, optional, default=0
Turn off cudnn for this layer.
cudnn_tensor_core : boolean or None, optional, default=None
Allow Tensor Core math within the algos.
cudnn_tensor_core_only : boolean, optional, default=0
Require Tensor Core math within the algos.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC', 'NWC'},optional, default='None'
Set layout for input, output and weight. Empty for
default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.NHWC and NDHWC are only supported on GPU.
cudnn_algo_verbose : boolean, optional, default=0
Verboseness of algo selection. 1 = output selection, 0 = no output
cudnn_algo_fwd : int, optional, default='-1'
Specified Forward Algorithm.
cudnn_algo_bwd_data : int, optional, default='-1'
Specified Backprop-to-Data Algorithm.
cudnn_algo_bwd_filter : int, optional, default='-1'
Specified Backprop-to-Filter Algorithm.
cudnn_algo_fwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the forward convolution kernel.
Default is the tensor data type, or float32 if the tensor data
type is float16.
cudnn_algo_bwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the back-prop kernels.
Default is the tensor data type, or float32 if the tensor data
type is float16.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Convolution_v1(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, layout=_Null, name=None, attr=None, out=None, **kwargs):
r"""This operator is DEPRECATED. Apply convolution to input then add a bias.
Parameters
----------
data : Symbol
Input data to the ConvolutionV1Op.
weight : Symbol
Weight matrix.
bias : Symbol
Bias parameter.
kernel : Shape(tuple), required
convolution kernel size: (h, w) or (d, h, w)
stride : Shape(tuple), optional, default=[]
convolution stride: (h, w) or (d, h, w)
dilate : Shape(tuple), optional, default=[]
convolution dilate: (h, w) or (d, h, w)
pad : Shape(tuple), optional, default=[]
pad for convolution: (h, w) or (d, h, w)
num_filter : int (non-negative), required
convolution filter(channel) number
num_group : int (non-negative), optional, default=1
Number of group partitions. Equivalent to slicing input into num_group
partitions, apply convolution on each, then concatenate the results
workspace : long (non-negative), optional, default=1024
Maximum temporary workspace allowed for convolution (MB).This parameter determines the effective batch size of the convolution kernel, which may be smaller than the given batch size. Also, the workspace will be automatically enlarged to make sure that we can run the kernel with batch_size=1
no_bias : boolean, optional, default=0
Whether to disable bias parameter.
cudnn_tune : {None, 'fastest', 'limited_workspace', 'off'},optional, default='None'
Whether to pick convolution algo by running performance test.
Leads to higher startup time but may give faster speed. Options are:
'off': no tuning
'limited_workspace': run test and pick the fastest algorithm that doesn't exceed workspace limit.
'fastest': pick the fastest algorithm and ignore workspace limit.
If set to None (default), behavior is determined by environment
variable MXNET_CUDNN_AUTOTUNE_DEFAULT: 0 for off,
1 for limited workspace (default), 2 for fastest.
cudnn_off : boolean, optional, default=0
Turn off cudnn for this layer.
layout : {None, 'NCDHW', 'NCHW', 'NDHWC', 'NHWC'},optional, default='None'
Set layout for input, output and weight. Empty for
default layout: NCHW for 2d and NCDHW for 3d.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Correlation(data1=None, data2=None, kernel_size=_Null, max_displacement=_Null, stride1=_Null, stride2=_Null, pad_size=_Null, is_multiply=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies correlation to inputs.
The correlation layer performs multiplicative patch comparisons between two feature maps.
Given two multi-channel feature maps :math:`f_{1}, f_{2}`, with :math:`w`, :math:`h`, and :math:`c` being their width, height, and number of channels,
the correlation layer lets the network compare each patch from :math:`f_{1}` with each patch from :math:`f_{2}`.
For now we consider only a single comparison of two patches. The 'correlation' of two patches centered at :math:`x_{1}` in the first map and
:math:`x_{2}` in the second map is then defined as:
.. math::
c(x_{1}, x_{2}) = \sum_{o \in [-k,k] \times [-k,k]} <f_{1}(x_{1} + o), f_{2}(x_{2} + o)>
for a square patch of size :math:`K:=2k+1`.
Note that the equation above is identical to one step of a convolution in neural networks, but instead of convolving data with a filter, it convolves data with other
data. For this reason, it has no training weights.
Computing :math:`c(x_{1}, x_{2})` involves :math:`c * K^{2}` multiplications. Comparing all patch combinations involves :math:`w^{2}*h^{2}` such computations.
Given a maximum displacement :math:`d`, for each location :math:`x_{1}` it computes correlations :math:`c(x_{1}, x_{2})` only in a neighborhood of size :math:`D:=2d+1`,
by limiting the range of :math:`x_{2}`. We use strides :math:`s_{1}, s_{2}`, to quantize :math:`x_{1}` globally and to quantize :math:`x_{2}` within the neighborhood
centered around :math:`x_{1}`.
The final output is defined by the following expression:
.. math::
out[n, q, i, j] = c(x_{i, j}, x_{q})
where :math:`i` and :math:`j` enumerate spatial locations in :math:`f_{1}`, and :math:`q` denotes the :math:`q^{th}` neighborhood of :math:`x_{i,j}`.
Defined in ../src/operator/correlation.cc:L198
Parameters
----------
data1 : Symbol
Input data1 to the correlation.
data2 : Symbol
Input data2 to the correlation.
kernel_size : int (non-negative), optional, default=1
kernel size for Correlation must be an odd number
max_displacement : int (non-negative), optional, default=1
Max displacement of Correlation
stride1 : int (non-negative), optional, default=1
stride1 quantize data1 globally
stride2 : int (non-negative), optional, default=1
stride2 quantize data2 within the neighborhood centered around data1
pad_size : int (non-negative), optional, default=0
pad for Correlation
is_multiply : boolean, optional, default=1
operation type is either multiplication or subduction
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Crop(*data, **kwargs):
r"""
.. note:: `Crop` is deprecated. Use `slice` instead.
Crop the 2nd and 3rd dim of input data, with the corresponding size of h_w or
with width and height of the second input symbol, i.e., with one input, we need h_w to
specify the crop height and width, otherwise the second input symbol's size will be used
Defined in ../src/operator/crop.cc:L50
This function support variable length of positional input.
Parameters
----------
data : Symbol or Symbol[]
Tensor or List of Tensors, the second input will be used as crop_like shape reference
offset : Shape(tuple), optional, default=[0,0]
crop offset coordinate: (y, x)
h_w : Shape(tuple), optional, default=[0,0]
crop height and width: (h, w)
center_crop : boolean, optional, default=0
If set to true, then it will use be the center_crop,or it will crop using the shape of crop_like
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def CuDNNBatchNorm(data=None, gamma=None, beta=None, moving_mean=None, moving_var=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, axis=_Null, cudnn_off=_Null, min_calib_range=_Null, max_calib_range=_Null, act_type=_Null, bn_group=_Null, xbuf_ptr=_Null, name=None, attr=None, out=None, **kwargs):
r"""Apply batch normalization to input.
Parameters
----------
data : Symbol
Input data to batch normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
moving_mean : Symbol
running mean of input
moving_var : Symbol
running variance of input
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output the mean and inverse std
axis : int, optional, default='1'
Specify which shape axis the channel is specified
cudnn_off : boolean, optional, default=0
Do not select CUDNN operator, if available
min_calib_range : float or None, optional, default=None
The minimum scalar value in the form of float32 obtained through calibration. If present, it will be used to by quantized batch norm op to calculate primitive scale.Note: this calib_range is to calib bn output.
max_calib_range : float or None, optional, default=None
The maximum scalar value in the form of float32 obtained through calibration. If present, it will be used to by quantized batch norm op to calculate primitive scale.Note: this calib_range is to calib bn output.
act_type : {None, 'relu', 'sigmoid', 'softrelu', 'tanh'},optional, default='None'
Fused activation function to be applied.
bn_group : int, optional, default='1'
BN group
xbuf_ptr : long (non-negative), optional, default=0
xbuf ptr
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Custom(*data, **kwargs):
r"""Apply a custom operator implemented in a frontend language (like Python).
Custom operators should override required methods like `forward` and `backward`.
The custom operator must be registered before it can be used.
Please check the tutorial here: https://mxnet.incubator.apache.org/api/faq/new_op
Defined in ../src/operator/custom/custom.cc:L534
Parameters
----------
data : Symbol[]
Input data for the custom operator.
op_type : string
Name of the custom operator. This is the name that is passed to `mx.operator.register` to register the operator.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Deconvolution(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, adj=_Null, target_shape=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, cudnn_tensor_core=_Null, cudnn_tensor_core_only=_Null, layout=_Null, cudnn_algo_verbose=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes 1D or 2D transposed convolution (aka fractionally strided convolution) of the input tensor. This operation can be seen as the gradient of Convolution operation with respect to its input. Convolution usually reduces the size of the input. Transposed convolution works the other way, going from a smaller input to a larger output while preserving the connectivity pattern.
Parameters
----------
data : Symbol
Input tensor to the deconvolution operation.
weight : Symbol
Weights representing the kernel.
bias : Symbol
Bias added to the result after the deconvolution operation.
kernel : Shape(tuple), required
Deconvolution kernel size: (w,), (h, w) or (d, h, w). This is same as the kernel size used for the corresponding convolution
stride : Shape(tuple), optional, default=[]
The stride used for the corresponding convolution: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
dilate : Shape(tuple), optional, default=[]
Dilation factor for each dimension of the input: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
The amount of implicit zero padding added during convolution for each dimension of the input: (w,), (h, w) or (d, h, w). ``(kernel-1)/2`` is usually a good choice. If `target_shape` is set, `pad` will be ignored and a padding that will generate the target shape will be used. Defaults to no padding.
adj : Shape(tuple), optional, default=[]
Adjustment for output shape: (w,), (h, w) or (d, h, w). If `target_shape` is set, `adj` will be ignored and computed accordingly.
target_shape : Shape(tuple), optional, default=[]
Shape of the output tensor: (w,), (h, w) or (d, h, w).
num_filter : int (non-negative), required
Number of output filters.
num_group : int (non-negative), optional, default=1
Number of groups partition.
workspace : long (non-negative), optional, default=512
Maximum temporary workspace allowed (MB) in deconvolution.This parameter has two usages. When CUDNN is not used, it determines the effective batch size of the deconvolution kernel. When CUDNN is used, it controls the maximum temporary storage used for tuning the best CUDNN kernel when `limited_workspace` strategy is used.
no_bias : boolean, optional, default=1
Whether to disable bias parameter.
cudnn_tune : {None, 'fastest', 'limited_workspace', 'off'},optional, default='None'
Whether to pick convolution algorithm by running performance test.
cudnn_off : boolean, optional, default=0
Turn off cudnn for this layer.
cudnn_tensor_core : boolean or None, optional, default=None
Allow Tensor Core math within the algos.
cudnn_tensor_core_only : boolean, optional, default=0
Require Tensor Core math within the algos.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC', 'NWC'},optional, default='None'
Set layout for input, output and weight. Empty for default layout, NCW for 1d, NCHW for 2d and NCDHW for 3d.HWC, NHWC and NDHWC are only supported on GPU.
cudnn_algo_verbose : boolean, optional, default=0
Verboseness of algo selection. 1 = output selection, 0 = no output
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Dropout(data=None, p=_Null, mode=_Null, axes=_Null, cudnn_off=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies dropout operation to input array.
- During training, each element of the input is set to zero with probability p.
The whole array is rescaled by :math:`1/(1-p)` to keep the expected
sum of the input unchanged.
- During testing, this operator does not change the input if mode is 'training'.
If mode is 'always', the same computaion as during training will be applied.
Example::
random.seed(998)
input_array = array([[3., 0.5, -0.5, 2., 7.],
[2., -0.4, 7., 3., 0.2]])
a = symbol.Variable('a')
dropout = symbol.Dropout(a, p = 0.2)
executor = dropout.simple_bind(a = input_array.shape)
## If training
executor.forward(is_train = True, a = input_array)
executor.outputs
[[ 3.75 0.625 -0. 2.5 8.75 ]
[ 2.5 -0.5 8.75 3.75 0. ]]
## If testing
executor.forward(is_train = False, a = input_array)
executor.outputs
[[ 3. 0.5 -0.5 2. 7. ]
[ 2. -0.4 7. 3. 0.2 ]]
Defined in ../src/operator/nn/dropout.cc:L96
Parameters
----------
data : Symbol
Input array to which dropout will be applied.
p : float, optional, default=0.5
Fraction of the input that gets dropped out during training time.
mode : {'always', 'training'},optional, default='training'
Whether to only turn on dropout during training or to also turn on for inference.
axes : Shape(tuple), optional, default=[]
Axes for variational dropout kernel.
cudnn_off : boolean or None, optional, default=0
Whether to turn off cudnn in dropout operator. This option is ignored if axes is specified.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
Apply dropout to corrupt input as zero with probability 0.2:
>>> data = Variable('data')
>>> data_dp = Dropout(data=data, p=0.2)
>>> shape = (100, 100) # take larger shapes to be more statistical stable
>>> x = np.ones(shape)
>>> op = Dropout(p=0.5, name='dp')
>>> # dropout is identity during testing
>>> y = test_utils.simple_forward(op, dp_data=x, is_train=False)
>>> test_utils.almost_equal(x, y)
True
>>> y = test_utils.simple_forward(op, dp_data=x, is_train=True)
>>> # expectation is (approximately) unchanged
>>> np.abs(x.mean() - y.mean()) < 0.1
True
>>> set(np.unique(y)) == set([0, 2])
True
"""
return (0,)
def ElementWiseSum(*args, **kwargs):
r"""Adds all input arguments element-wise.
.. math::
add\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n
``add_n`` is potentially more efficient than calling ``add`` by `n` times.
The storage type of ``add_n`` output depends on storage types of inputs
- add_n(row_sparse, row_sparse, ..) = row_sparse
- add_n(default, csr, default) = default
- add_n(any input combinations longer than 4 (>4) with at least one default type) = default
- otherwise, ``add_n`` falls all inputs back to default storage and generates default storage
Defined in ../src/operator/tensor/elemwise_sum.cc:L156
This function support variable length of positional input.
Parameters
----------
args : Symbol[]
Positional input arguments
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Embedding(data=None, weight=None, input_dim=_Null, output_dim=_Null, dtype=_Null, sparse_grad=_Null, name=None, attr=None, out=None, **kwargs):
r"""Maps integer indices to vector representations (embeddings).
This operator maps words to real-valued vectors in a high-dimensional space,
called word embeddings. These embeddings can capture semantic and syntactic properties of the words.
For example, it has been noted that in the learned embedding spaces, similar words tend
to be close to each other and dissimilar words far apart.
For an input array of shape (d1, ..., dK),
the shape of an output array is (d1, ..., dK, output_dim).
All the input values should be integers in the range [0, input_dim).
If the input_dim is ip0 and output_dim is op0, then shape of the embedding weight matrix must be
(ip0, op0).
When "sparse_grad" is False, if any index mentioned is too large, it is replaced by the index that
addresses the last vector in an embedding matrix.
When "sparse_grad" is True, an error will be raised if invalid indices are found.
Examples::
input_dim = 4
output_dim = 5
// Each row in weight matrix y represents a word. So, y = (w0,w1,w2,w3)
y = [[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.],
[ 10., 11., 12., 13., 14.],
[ 15., 16., 17., 18., 19.]]
// Input array x represents n-grams(2-gram). So, x = [(w1,w3), (w0,w2)]
x = [[ 1., 3.],
[ 0., 2.]]
// Mapped input x to its vector representation y.
Embedding(x, y, 4, 5) = [[[ 5., 6., 7., 8., 9.],
[ 15., 16., 17., 18., 19.]],
[[ 0., 1., 2., 3., 4.],
[ 10., 11., 12., 13., 14.]]]
The storage type of weight can be either row_sparse or default.
.. Note::
If "sparse_grad" is set to True, the storage type of gradient w.r.t weights will be
"row_sparse". Only a subset of optimizers support sparse gradients, including SGD, AdaGrad
and Adam. Note that by default lazy updates is turned on, which may perform differently
from standard updates. For more details, please check the Optimization API at:
https://mxnet.incubator.apache.org/api/python/optimization/optimization.html
Defined in ../src/operator/tensor/indexing_op.cc:L598
Parameters
----------
data : Symbol
The input array to the embedding operator.
weight : Symbol
The embedding weight matrix.
input_dim : int, required
Vocabulary size of the input indices.
output_dim : int, required
Dimension of the embedding vectors.
dtype : {'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32'
Data type of weight.
sparse_grad : boolean, optional, default=0
Compute row sparse gradient in the backward calculation. If set to True, the grad's storage type is row_sparse.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
Assume we want to map the 26 English alphabet letters to 16-dimensional
vectorial representations.
>>> vocabulary_size = 26
>>> embed_dim = 16
>>> seq_len, batch_size = (10, 64)
>>> input = Variable('letters')
>>> op = Embedding(data=input, input_dim=vocabulary_size, output_dim=embed_dim,
...name='embed')
>>> SymbolDoc.get_output_shape(op, letters=(seq_len, batch_size))
{'embed_output': (10L, 64L, 16L)}
>>> vocab_size, embed_dim = (26, 16)
>>> batch_size = 12
>>> word_vecs = test_utils.random_arrays((vocab_size, embed_dim))
>>> op = Embedding(name='embed', input_dim=vocab_size, output_dim=embed_dim)
>>> x = np.random.choice(vocab_size, batch_size)
>>> y = test_utils.simple_forward(op, embed_data=x, embed_weight=word_vecs)
>>> y_np = word_vecs[x]
>>> test_utils.almost_equal(y, y_np)
True
"""
return (0,)
def Flatten(data=None, name=None, attr=None, out=None, **kwargs):
r"""Flattens the input array into a 2-D array by collapsing the higher dimensions.
.. note:: `Flatten` is deprecated. Use `flatten` instead.
For an input array with shape ``(d1, d2, ..., dk)``, `flatten` operation reshapes
the input array into an output array of shape ``(d1, d2*...*dk)``.
Note that the behavior of this function is different from numpy.ndarray.flatten,
which behaves similar to mxnet.ndarray.reshape((-1,)).
Example::
x = [[
[1,2,3],
[4,5,6],
[7,8,9]
],
[ [1,2,3],
[4,5,6],
[7,8,9]
]],
flatten(x) = [[ 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[ 1., 2., 3., 4., 5., 6., 7., 8., 9.]]
Defined in ../src/operator/tensor/matrix_op.cc:L250
Parameters
----------
data : Symbol
Input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
Flatten is usually applied before `FullyConnected`, to reshape the 4D tensor
produced by convolutional layers to 2D matrix:
>>> data = Variable('data') # say this is 4D from some conv/pool
>>> flatten = Flatten(data=data, name='flat') # now this is 2D
>>> SymbolDoc.get_output_shape(flatten, data=(2, 3, 4, 5))
{'flat_output': (2L, 60L)}
>>> test_dims = [(2, 3, 4, 5), (2, 3), (2,)]
>>> op = Flatten(name='flat')
>>> for dims in test_dims:
... x = test_utils.random_arrays(dims)
... y = test_utils.simple_forward(op, flat_data=x)
... y_np = x.reshape((dims[0], np.prod(dims[1:]).astype('int32')))
... print('%s: %s' % (dims, test_utils.almost_equal(y, y_np)))
(2, 3, 4, 5): True
(2, 3): True
(2,): True
"""
return (0,)
def FullyConnected(data=None, weight=None, bias=None, num_hidden=_Null, no_bias=_Null, cublas_algo_verbose=_Null, cublas_off=_Null, cublas_tensor_core=_Null, cublas_algo_fwd=_Null, cublas_algo_bwd_data=_Null, cublas_algo_bwd_weights=_Null, cublas_algo_fwd_prec=_Null, cublas_algo_bwd_prec=_Null, flatten=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies a linear transformation: :math:`Y = XW^T + b`.
If ``flatten`` is set to be true, then the shapes are:
- **data**: `(batch_size, x1, x2, ..., xn)`
- **weight**: `(num_hidden, x1 * x2 * ... * xn)`
- **bias**: `(num_hidden,)`
- **out**: `(batch_size, num_hidden)`
If ``flatten`` is set to be false, then the shapes are:
- **data**: `(x1, x2, ..., xn, input_dim)`
- **weight**: `(num_hidden, input_dim)`
- **bias**: `(num_hidden,)`
- **out**: `(x1, x2, ..., xn, num_hidden)`
The learnable parameters include both ``weight`` and ``bias``.
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
.. Note::
The sparse support for FullyConnected is limited to forward evaluation with `row_sparse`
weight and bias, where the length of `weight.indices` and `bias.indices` must be equal
to `num_hidden`. This could be useful for model inference with `row_sparse` weights
trained with importance sampling or noise contrastive estimation.
To compute linear transformation with 'csr' sparse data, sparse.dot is recommended instead
of sparse.FullyConnected.
Defined in ../src/operator/nn/fully_connected.cc:L287
Parameters
----------
data : Symbol
Input data.
weight : Symbol
Weight matrix.
bias : Symbol
Bias parameter.
num_hidden : int, required
Number of hidden nodes of the output.
no_bias : boolean, optional, default=0
Whether to disable bias parameter.
cublas_algo_verbose : boolean, optional, default=0
Verboseness of algo selection. true = output selection, false = no output
cublas_off : boolean, optional, default=0
Turn off full-control cublas for this layer.
cublas_tensor_core : boolean or None, optional, default=None
Allow Tensor Core math for default-chosen algos.
cublas_algo_fwd : int or None, optional, default='None'
Specified Forward GEMM Algorithm.
cublas_algo_bwd_data : int or None, optional, default='None'
Specified Backprop-to-Data GEMM Algorithm.
cublas_algo_bwd_weights : int or None, optional, default='None'
Specified Backprop-to-Weights GEMM Algorithm.
cublas_algo_fwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the forward GEMM kernel.
Default is the tensor data type, or float32 if the tensor data
type is float16.
cublas_algo_bwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the back-prop kernels.
Default is the tensor data type, or float32 if the tensor data
type is float16.
flatten : boolean, optional, default=1
Whether to collapse all but the first axis of the input data tensor.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
Examples
--------
Construct a fully connected operator with target dimension 512.
>>> data = Variable('data') # or some constructed NN
>>> op = FullyConnected(data=data,
... num_hidden=512,
... name='FC1')
>>> op
<Symbol FC1>
>>> SymbolDoc.get_output_shape(op, data=(128, 100))
{'FC1_output': (128L, 512L)}
A simple 3-layer MLP with ReLU activation:
>>> net = Variable('data')
>>> for i, dim in enumerate([128, 64]):
... net = FullyConnected(data=net, num_hidden=dim, name='FC%d' % i)
... net = Activation(data=net, act_type='relu', name='ReLU%d' % i)
>>> # 10-class predictor (e.g. MNIST)
>>> net = FullyConnected(data=net, num_hidden=10, name='pred')
>>> net
<Symbol pred>
>>> dim_in, dim_out = (3, 4)
>>> x, w, b = test_utils.random_arrays((10, dim_in), (dim_out, dim_in), (dim_out,))
>>> op = FullyConnected(num_hidden=dim_out, name='FC')
>>> out = test_utils.simple_forward(op, FC_data=x, FC_weight=w, FC_bias=b)
>>> # numpy implementation of FullyConnected
>>> out_np = np.dot(x, w.T) + b
>>> test_utils.almost_equal(out, out_np)
True
"""
return (0,)
def GridGenerator(data=None, transform_type=_Null, target_shape=_Null, name=None, attr=None, out=None, **kwargs):
r"""Generates 2D sampling grid for bilinear sampling.
Parameters
----------
data : Symbol
Input data to the function.
transform_type : {'affine', 'warp'}, required
The type of transformation. For `affine`, input data should be an affine matrix of size (batch, 6). For `warp`, input data should be an optical flow of size (batch, 2, h, w).
target_shape : Shape(tuple), optional, default=[0,0]
Specifies the output shape (H, W). This is required if transformation type is `affine`. If transformation type is `warp`, this parameter is ignored.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def GroupNorm(data=None, gamma=None, beta=None, num_groups=_Null, eps=_Null, output_mean_var=_Null, name=None, attr=None, out=None, **kwargs):
r"""Group normalization.
The input channels are separated into ``num_groups`` groups, each containing ``num_channels / num_groups`` channels.
The mean and standard-deviation are calculated separately over the each group.
.. math::
data = data.reshape((N, num_groups, C // num_groups, ...))
out = \frac{data - mean(data, axis)}{\sqrt{var(data, axis) + \epsilon}} * gamma + beta
Both ``gamma`` and ``beta`` are learnable parameters.
Defined in ../src/operator/nn/group_norm.cc:L77
Parameters
----------
data : Symbol
Input data
gamma : Symbol
gamma array
beta : Symbol
beta array
num_groups : int, optional, default='1'
Total number of groups.
eps : float, optional, default=9.99999975e-06
An `epsilon` parameter to prevent division by 0.
output_mean_var : boolean, optional, default=0
Output the mean and std calculated along the given axis.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def IdentityAttachKLSparseReg(data=None, sparseness_target=_Null, penalty=_Null, momentum=_Null, name=None, attr=None, out=None, **kwargs):
r"""Apply a sparse regularization to the output a sigmoid activation function.
Parameters
----------
data : Symbol
Input data.
sparseness_target : float, optional, default=0.100000001
The sparseness target
penalty : float, optional, default=0.00100000005
The tradeoff parameter for the sparseness penalty
momentum : float, optional, default=0.899999976
The momentum for running average
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def InstanceNorm(data=None, gamma=None, beta=None, eps=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies instance normalization to the n-dimensional input array.
This operator takes an n-dimensional input array where (n>2) and normalizes
the input using the following formula:
.. math::
out = \frac{x - mean[data]}{ \sqrt{Var[data]} + \epsilon} * gamma + beta
This layer is similar to batch normalization layer (`BatchNorm`)
with two differences: first, the normalization is
carried out per example (instance), not over a batch. Second, the
same normalization is applied both at test and train time. This
operation is also known as `contrast normalization`.
If the input data is of shape [batch, channel, spacial_dim1, spacial_dim2, ...],
`gamma` and `beta` parameters must be vectors of shape [channel].
This implementation is based on this paper [1]_
.. [1] Instance Normalization: The Missing Ingredient for Fast Stylization,
D. Ulyanov, A. Vedaldi, V. Lempitsky, 2016 (arXiv:1607.08022v2).
Examples::
// Input of shape (2,1,2)
x = [[[ 1.1, 2.2]],
[[ 3.3, 4.4]]]
// gamma parameter of length 1
gamma = [1.5]
// beta parameter of length 1
beta = [0.5]
// Instance normalization is calculated with the above formula
InstanceNorm(x,gamma,beta) = [[[-0.997527 , 1.99752665]],
[[-0.99752653, 1.99752724]]]
Defined in ../src/operator/instance_norm.cc:L103
Parameters
----------
data : Symbol
An n-dimensional input array (n > 2) of the form [batch, channel, spatial_dim1, spatial_dim2, ...].
gamma : Symbol
A vector of length 'channel', which multiplies the normalized input.
beta : Symbol
A vector of length 'channel', which is added to the product of the normalized input and the weight.
eps : float, optional, default=0.00100000005
An `epsilon` parameter to prevent division by 0.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def InstanceNormV2(data=None, gamma=None, beta=None, axis=_Null, eps=_Null, output_mean_var=_Null, act_type=_Null, xbuf_group=_Null, xbuf_ptr=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies instance normalization to the n-dimensional input array.
This operator takes an n-dimensional input array where (n>2) and normalizes
the input using the following formula:
.. math::
out = \frac{x - mean[data]}{ \sqrt{Var[data] + \epsilon}} * gamma + beta
This layer is similar to batch normalization layer (`BatchNorm`)
with two differences: first, the normalization is
carried out per example (instance), not over a batch. Second, the
same normalization is applied both at test and train time. This
operation is also known as `contrast normalization`.
If the input data is of shape [batch, channel, spacial_dim1, spacial_dim2, ...],
`gamma` and `beta` parameters must be vectors of shape [channel].
This implementation is based on this paper [1]_
.. [1] Instance Normalization: The Missing Ingredient for Fast Stylization,
D. Ulyanov, A. Vedaldi, V. Lempitsky, 2016 (arXiv:1607.08022v2).
Examples::
// Input of shape (2,1,2)
x = [[[ 1.1, 2.2]],
[[ 3.3, 4.4]]]
// gamma parameter of length 1
gamma = [1.5]
// beta parameter of length 1
beta = [0.5]
// Instance normalization is calculated with the above formula
InstanceNorm(x,gamma,beta) = [[[-0.997527 , 1.99752665]],
[[-0.99752653, 1.99752724]]]
Defined in ../src/operator/nn/instance_norm_v2.cc:L172
Parameters
----------
data : Symbol
Input data to instance normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
axis : int, optional, default='1'
The axis to perform instance normalization. Usually, this should be be axis of the channel dimension. Negative values means indexing from right to left.
eps : float, optional, default=0.00100000005
An `epsilon` parameter to prevent division by 0.
output_mean_var : boolean, optional, default=0
Output the mean and std calculated along the given axis.
act_type : {None, 'relu', 'sigmoid', 'softrelu', 'tanh'},optional, default='None'
Fused activation function to be applied.
xbuf_group : int, optional, default='1'
exchange buffer group size
xbuf_ptr : long (non-negative), optional, default=0
exchange buffer pointer
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def L2Normalization(data=None, eps=_Null, mode=_Null, name=None, attr=None, out=None, **kwargs):
r"""Normalize the input array using the L2 norm.
For 1-D NDArray, it computes::
out = data / sqrt(sum(data ** 2) + eps)
For N-D NDArray, if the input array has shape (N, N, ..., N),
with ``mode`` = ``instance``, it normalizes each instance in the multidimensional
array by its L2 norm.::
for i in 0...N
out[i,:,:,...,:] = data[i,:,:,...,:] / sqrt(sum(data[i,:,:,...,:] ** 2) + eps)
with ``mode`` = ``channel``, it normalizes each channel in the array by its L2 norm.::
for i in 0...N
out[:,i,:,...,:] = data[:,i,:,...,:] / sqrt(sum(data[:,i,:,...,:] ** 2) + eps)
with ``mode`` = ``spatial``, it normalizes the cross channel norm for each position
in the array by its L2 norm.::
for dim in 2...N
for i in 0...N
out[.....,i,...] = take(out, indices=i, axis=dim) / sqrt(sum(take(out, indices=i, axis=dim) ** 2) + eps)
-dim-
Example::
x = [[[1,2],
[3,4]],
[[2,2],
[5,6]]]
L2Normalization(x, mode='instance')
=[[[ 0.18257418 0.36514837]
[ 0.54772252 0.73029673]]
[[ 0.24077171 0.24077171]
[ 0.60192931 0.72231513]]]
L2Normalization(x, mode='channel')
=[[[ 0.31622776 0.44721359]
[ 0.94868326 0.89442718]]
[[ 0.37139067 0.31622776]
[ 0.92847669 0.94868326]]]
L2Normalization(x, mode='spatial')
=[[[ 0.44721359 0.89442718]
[ 0.60000002 0.80000001]]
[[ 0.70710677 0.70710677]
[ 0.6401844 0.76822126]]]
Defined in ../src/operator/l2_normalization.cc:L196
Parameters
----------
data : Symbol
Input array to normalize.
eps : float, optional, default=1.00000001e-10
A small constant for numerical stability.
mode : {'channel', 'instance', 'spatial'},optional, default='instance'
Specify the dimension along which to compute L2 norm.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def LRN(data=None, alpha=_Null, beta=_Null, knorm=_Null, nsize=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies local response normalization to the input.
The local response normalization layer performs "lateral inhibition" by normalizing
over local input regions.
If :math:`a_{x,y}^{i}` is the activity of a neuron computed by applying kernel :math:`i` at position
:math:`(x, y)` and then applying the ReLU nonlinearity, the response-normalized
activity :math:`b_{x,y}^{i}` is given by the expression:
.. math::
b_{x,y}^{i} = \frac{a_{x,y}^{i}}{\Bigg({k + \frac{\alpha}{n} \sum_{j=max(0, i-\frac{n}{2})}^{min(N-1, i+\frac{n}{2})} (a_{x,y}^{j})^{2}}\Bigg)^{\beta}}
where the sum runs over :math:`n` "adjacent" kernel maps at the same spatial position, and :math:`N` is the total
number of kernels in the layer.
Defined in ../src/operator/nn/lrn.cc:L158
Parameters
----------
data : Symbol
Input data to LRN
alpha : float, optional, default=9.99999975e-05
The variance scaling parameter :math:`lpha` in the LRN expression.
beta : float, optional, default=0.75
The power parameter :math:`eta` in the LRN expression.
knorm : float, optional, default=2
The parameter :math:`k` in the LRN expression.
nsize : int (non-negative), required
normalization window width in elements.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def LayerNorm(data=None, gamma=None, beta=None, axis=_Null, eps=_Null, output_mean_var=_Null, name=None, attr=None, out=None, **kwargs):
r"""Layer normalization.
Normalizes the channels of the input tensor by mean and variance, and applies a scale ``gamma`` as
well as offset ``beta``.
Assume the input has more than one dimension and we normalize along axis 1.
We first compute the mean and variance along this axis and then
compute the normalized output, which has the same shape as input, as following:
.. math::
out = \frac{data - mean(data, axis)}{\sqrt{var(data, axis) + \epsilon}} * gamma + beta
Both ``gamma`` and ``beta`` are learnable parameters.
Unlike BatchNorm and InstanceNorm, the *mean* and *var* are computed along the channel dimension.
Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta``
have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and
``data_std``. Note that no gradient will be passed through these two outputs.
The parameter ``axis`` specifies which axis of the input shape denotes
the 'channel' (separately normalized groups). The default is -1, which sets the channel
axis to be the last item in the input shape.
Defined in ../src/operator/nn/layer_norm.cc:L159
Parameters
----------
data : Symbol
Input data to layer normalization
gamma : Symbol
gamma array
beta : Symbol
beta array
axis : int, optional, default='-1'
The axis to perform layer normalization. Usually, this should be be axis of the channel dimension. Negative values means indexing from right to left.
eps : float, optional, default=9.99999975e-06
An `epsilon` parameter to prevent division by 0.
output_mean_var : boolean, optional, default=0
Output the mean and std calculated along the given axis.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def LeakyReLU(data=None, gamma=None, act_type=_Null, slope=_Null, lower_bound=_Null, upper_bound=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies Leaky rectified linear unit activation element-wise to the input.
Leaky ReLUs attempt to fix the "dying ReLU" problem by allowing a small `slope`
when the input is negative and has a slope of one when input is positive.
The following modified ReLU Activation functions are supported:
- *elu*: Exponential Linear Unit. `y = x > 0 ? x : slope * (exp(x)-1)`
- *selu*: Scaled Exponential Linear Unit. `y = lambda * (x > 0 ? x : alpha * (exp(x) - 1))` where
*lambda = 1.0507009873554804934193349852946* and *alpha = 1.6732632423543772848170429916717*.
- *leaky*: Leaky ReLU. `y = x > 0 ? x : slope * x`
- *prelu*: Parametric ReLU. This is same as *leaky* except that `slope` is learnt during training.
- *rrelu*: Randomized ReLU. same as *leaky* but the `slope` is uniformly and randomly chosen from
*[lower_bound, upper_bound)* for training, while fixed to be
*(lower_bound+upper_bound)/2* for inference.
Defined in ../src/operator/leaky_relu.cc:L172
Parameters
----------
data : Symbol
Input data to activation function.
gamma : Symbol
Input data to activation function.
act_type : {'elu', 'gelu', 'leaky', 'prelu', 'rrelu', 'selu'},optional, default='leaky'
Activation function to be applied.
slope : float, optional, default=0.25
Init slope for the activation. (For leaky and elu only)
lower_bound : float, optional, default=0.125
Lower bound of random slope. (For rrelu only)
upper_bound : float, optional, default=0.333999991
Upper bound of random slope. (For rrelu only)
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def LinearRegressionOutput(data=None, label=None, grad_scale=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes and optimizes for squared loss during backward propagation.
Just outputs ``data`` during forward propagation.
If :math:`\hat{y}_i` is the predicted value of the i-th sample, and :math:`y_i` is the corresponding target value,
then the squared loss estimated over :math:`n` samples is defined as
:math:`\text{SquaredLoss}(\textbf{Y}, \hat{\textbf{Y}} ) = \frac{1}{n} \sum_{i=0}^{n-1} \lVert \textbf{y}_i - \hat{\textbf{y}}_i \rVert_2`
.. note::
Use the LinearRegressionOutput as the final output layer of a net.
The storage type of ``label`` can be ``default`` or ``csr``
- LinearRegressionOutput(default, default) = default
- LinearRegressionOutput(default, csr) = default
By default, gradients of this loss function are scaled by factor `1/m`, where m is the number of regression outputs of a training example.
The parameter `grad_scale` can be used to change this scale to `grad_scale/m`.
Defined in ../src/operator/regression_output.cc:L92
Parameters
----------
data : Symbol
Input data to the function.
label : Symbol
Input label to the function.
grad_scale : float, optional, default=1
Scale the gradient by a float factor
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def LogisticRegressionOutput(data=None, label=None, grad_scale=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies a logistic function to the input.
The logistic function, also known as the sigmoid function, is computed as
:math:`\frac{1}{1+exp(-\textbf{x})}`.
Commonly, the sigmoid is used to squash the real-valued output of a linear model
:math:`wTx+b` into the [0,1] range so that it can be interpreted as a probability.
It is suitable for binary classification or probability prediction tasks.
.. note::
Use the LogisticRegressionOutput as the final output layer of a net.
The storage type of ``label`` can be ``default`` or ``csr``
- LogisticRegressionOutput(default, default) = default
- LogisticRegressionOutput(default, csr) = default
The loss function used is the Binary Cross Entropy Loss:
:math:`-{(y\log(p) + (1 - y)\log(1 - p))}`
Where `y` is the ground truth probability of positive outcome for a given example, and `p` the probability predicted by the model. By default, gradients of this loss function are scaled by factor `1/m`, where m is the number of regression outputs of a training example.
The parameter `grad_scale` can be used to change this scale to `grad_scale/m`.
Defined in ../src/operator/regression_output.cc:L152
Parameters
----------
data : Symbol
Input data to the function.
label : Symbol
Input label to the function.
grad_scale : float, optional, default=1
Scale the gradient by a float factor
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def MAERegressionOutput(data=None, label=None, grad_scale=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes mean absolute error of the input.
MAE is a risk metric corresponding to the expected value of the absolute error.
If :math:`\hat{y}_i` is the predicted value of the i-th sample, and :math:`y_i` is the corresponding target value,
then the mean absolute error (MAE) estimated over :math:`n` samples is defined as
:math:`\text{MAE}(\textbf{Y}, \hat{\textbf{Y}} ) = \frac{1}{n} \sum_{i=0}^{n-1} \lVert \textbf{y}_i - \hat{\textbf{y}}_i \rVert_1`
.. note::
Use the MAERegressionOutput as the final output layer of a net.
The storage type of ``label`` can be ``default`` or ``csr``
- MAERegressionOutput(default, default) = default
- MAERegressionOutput(default, csr) = default
By default, gradients of this loss function are scaled by factor `1/m`, where m is the number of regression outputs of a training example.
The parameter `grad_scale` can be used to change this scale to `grad_scale/m`.
Defined in ../src/operator/regression_output.cc:L120
Parameters
----------
data : Symbol
Input data to the function.
label : Symbol
Input label to the function.
grad_scale : float, optional, default=1
Scale the gradient by a float factor
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def MakeLoss(data=None, grad_scale=_Null, valid_thresh=_Null, normalization=_Null, name=None, attr=None, out=None, **kwargs):
r"""Make your own loss function in network construction.
This operator accepts a customized loss function symbol as a terminal loss and
the symbol should be an operator with no backward dependency.
The output of this function is the gradient of loss with respect to the input data.
For example, if you are a making a cross entropy loss function. Assume ``out`` is the
predicted output and ``label`` is the true label, then the cross entropy can be defined as::
cross_entropy = label * log(out) + (1 - label) * log(1 - out)
loss = MakeLoss(cross_entropy)
We will need to use ``MakeLoss`` when we are creating our own loss function or we want to
combine multiple loss functions. Also we may want to stop some variables' gradients
from backpropagation. See more detail in ``BlockGrad`` or ``stop_gradient``.
In addition, we can give a scale to the loss by setting ``grad_scale``,
so that the gradient of the loss will be rescaled in the backpropagation.
.. note:: This operator should be used as a Symbol instead of NDArray.
Defined in ../src/operator/make_loss.cc:L71
Parameters
----------
data : Symbol
Input array.
grad_scale : float, optional, default=1
Gradient scale as a supplement to unary and binary operators
valid_thresh : float, optional, default=0
clip each element in the array to 0 when it is less than ``valid_thresh``. This is used when ``normalization`` is set to ``'valid'``.
normalization : {'batch', 'null', 'valid'},optional, default='null'
If this is set to null, the output gradient will not be normalized. If this is set to batch, the output gradient will be divided by the batch size. If this is set to valid, the output gradient will be divided by the number of valid input elements.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def NormConvolution(data=None, sum=None, sum_squares=None, gamma=None, beta=None, moving_mean=None, moving_var=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, no_norm=_Null, layout=_Null, act_type=_Null, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, output_equiv_scale_bias=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute *N*-D normConvolution on *(N+2)*-D input.
******** Documentation not yet correct for this fused normalized convolution!! *************
In the 2-D normConvolution, given input data with shape *(batch_size,
channel, height, width)*, the output is computed by
.. math::
out[n,i,:,:] = bias[i] + \sum_{j=0}^{channel} data[n,j,:,:] \star
weight[i,j,:,:]
where :math:`\star` is the 2-D cross-correlation operator.
For general 2-D normConvolution, the shapes are
- **data**: *(batch_size, channel, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_height, out_width)*.
Define::
f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1
then we have::
out_height=f(height, kernel[0], pad[0], stride[0], dilate[0])
out_width=f(width, kernel[1], pad[1], stride[1], dilate[1])
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
The default data ``layout`` is *NCHW*, namely *(batch_size, channel, height,
width)*. We can choose other layouts such as *NWC*.
If ``num_group`` is larger than 1, denoted by *g*, then split the input ``data``
evenly into *g* parts along the channel axis, and also evenly split ``weight``
along the first dimension. Next compute the normConvolution on the *i*-th part of
the data with the *i*-th weight part. The output is obtained by concatenating all
the *g* results.
1-D normConvolution does not have *height* dimension but only *width* in space.
- **data**: *(batch_size, channel, width)*
- **weight**: *(num_filter, channel, kernel[0])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_width)*.
3-D normConvolution adds an additional *depth* dimension besides *height* and
*width*. The shapes are
- **data**: *(batch_size, channel, depth, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1], kernel[2])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_depth, out_height, out_width)*.
Both ``weight`` and ``bias`` are learnable parameters.
Defined in ../src/operator/nn/norm_convolution.cc:L423
Parameters
----------
data : Symbol
Input data to the NormConvolutionOp.
sum : Symbol
sum of input data to be normalized
sum_squares : Symbol
sum of squares of input data to be normalized
gamma : Symbol
gamma array
beta : Symbol
beta array
moving_mean : Symbol
running mean of input
moving_var : Symbol
running variance of input
kernel : Shape(tuple), required
NormConvolution kernel size: (w,), (h, w) or (d, h, w)
stride : Shape(tuple), optional, default=[]
NormConvolution stride: (w,), (h, w) or (d, h, w). Default 1 for each dim.
dilate : Shape(tuple), optional, default=[]
NormConvolution dilate: (w,), (h, w) or (d, h, w). Default 1 for each dim.
pad : Shape(tuple), optional, default=[]
Zero pad for NormConvolution: (w,), (h, w) or (d, h, w). Default no padding.
num_filter : int (non-negative), required
NormConvolution filter(channel) number
num_group : int (non-negative), optional, default=1
Number of group partitions.
no_norm : boolean, optional, default=0
Whether to disable input normalization prior to the convolution.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC'},optional, default='None'
Set layout for input, output and weight. Empty for
default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.NHWC and NDHWC are only supported on GPU.
act_type : {None, 'relu', 'sigmoid', 'softrelu', 'tanh'},optional, default='None'
Fused activation function to be applied.
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
momentum : float, optional, default=0.899999976
Momentum for moving average
fix_gamma : boolean, optional, default=1
Fix gamma while training
use_global_stats : boolean, optional, default=0
Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
output_mean_var : boolean, optional, default=0
Output the mean and inverse std.
output_equiv_scale_bias : boolean, optional, default=0
Output the equiv_scale and equiv_bias (generally for testing).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def NormalizedConvolution(data=None, equiv_scale=None, equiv_bias=None, mean=None, var=None, gamma=None, beta=None, weight=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, no_equiv_scale_bias=_Null, layout=_Null, act_type=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute *N*-D normalizedConvolution on *(N+2)*-D input.
******** Documentation not yet correct for this fused normalized convolution!! *************
In the 2-D normalizedConvolution, given input data with shape *(batch_size,
channel, height, width)*, the output is computed by
.. math::
out[n,i,:,:] = bias[i] + \sum_{j=0}^{channel} data[n,j,:,:] \star
weight[i,j,:,:]
where :math:`\star` is the 2-D cross-correlation operator.
For general 2-D normalizedConvolution, the shapes are
- **data**: *(batch_size, channel, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_height, out_width)*.
Define::
f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1
then we have::
out_height=f(height, kernel[0], pad[0], stride[0], dilate[0])
out_width=f(width, kernel[1], pad[1], stride[1], dilate[1])
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
The default data ``layout`` is *NCHW*, namely *(batch_size, channel, height,
width)*. We can choose other layouts such as *NWC*.
If ``num_group`` is larger than 1, denoted by *g*, then split the input ``data``
evenly into *g* parts along the channel axis, and also evenly split ``weight``
along the first dimension. Next compute the normalizedConvolution on the *i*-th part of
the data with the *i*-th weight part. The output is obtained by concatenating all
the *g* results.
1-D normalizedConvolution does not have *height* dimension but only *width* in space.
- **data**: *(batch_size, channel, width)*
- **weight**: *(num_filter, channel, kernel[0])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_width)*.
3-D normalizedConvolution adds an additional *depth* dimension besides *height* and
*width*. The shapes are
- **data**: *(batch_size, channel, depth, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1], kernel[2])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_depth, out_height, out_width)*.
Both ``weight`` and ``bias`` are learnable parameters.
Defined in ../src/operator/nn/normalized_convolution.cc:L397
Parameters
----------
data : Symbol
Input data to the NormalizedConvolutionOp.
equiv_scale : Symbol
equivalent scale array
equiv_bias : Symbol
equivalent bias array
mean : Symbol
mean array
var : Symbol
array describing variance (actually an inverse std dev)
gamma : Symbol
gamma array (also known as 'scale')
beta : Symbol
beta array (also known as 'bias')
weight : Symbol
Weight matrix.
kernel : Shape(tuple), required
NormalizedConvolution kernel size: (w,), (h, w) or (d, h, w)
stride : Shape(tuple), optional, default=[]
NormalizedConvolution stride: (w,), (h, w) or (d, h, w). Default 1 for each dim.
dilate : Shape(tuple), optional, default=[]
NormalizedConvolution dilate: (w,), (h, w) or (d, h, w). Default 1 for each dim.
pad : Shape(tuple), optional, default=[]
Zero pad for NormalizedConvolution: (w,), (h, w) or (d, h, w). Default no padding.
num_filter : int (non-negative), required
NormalizedConvolution filter(channel) number
num_group : int (non-negative), optional, default=1
Number of group partitions.
no_equiv_scale_bias : boolean, optional, default=0
Whether to disable normalization equivalent-scale and equivalent-bias adjustments.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC'},optional, default='None'
Set layout for input, output and weight. Empty for
default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.NHWC and NDHWC are only supported on GPU.
act_type : {None, 'relu', 'sigmoid', 'softrelu', 'tanh'},optional, default='None'
Fused activation function to be applied.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Pad(data=None, mode=_Null, pad_width=_Null, constant_value=_Null, name=None, attr=None, out=None, **kwargs):
r"""Pads an input array with a constant or edge values of the array.
.. note:: `Pad` is deprecated. Use `pad` instead.
.. note:: Current implementation only supports 4D and 5D input arrays with padding applied
only on axes 1, 2 and 3. Expects axes 4 and 5 in `pad_width` to be zero.
This operation pads an input array with either a `constant_value` or edge values
along each axis of the input array. The amount of padding is specified by `pad_width`.
`pad_width` is a tuple of integer padding widths for each axis of the format
``(before_1, after_1, ... , before_N, after_N)``. The `pad_width` should be of length ``2*N``
where ``N`` is the number of dimensions of the array.
For dimension ``N`` of the input array, ``before_N`` and ``after_N`` indicates how many values
to add before and after the elements of the array along dimension ``N``.
The widths of the higher two dimensions ``before_1``, ``after_1``, ``before_2``,
``after_2`` must be 0.
Example::
x = [[[[ 1. 2. 3.]
[ 4. 5. 6.]]
[[ 7. 8. 9.]
[ 10. 11. 12.]]]
[[[ 11. 12. 13.]
[ 14. 15. 16.]]
[[ 17. 18. 19.]
[ 20. 21. 22.]]]]
pad(x,mode="edge", pad_width=(0,0,0,0,1,1,1,1)) =
[[[[ 1. 1. 2. 3. 3.]
[ 1. 1. 2. 3. 3.]
[ 4. 4. 5. 6. 6.]
[ 4. 4. 5. 6. 6.]]
[[ 7. 7. 8. 9. 9.]
[ 7. 7. 8. 9. 9.]
[ 10. 10. 11. 12. 12.]
[ 10. 10. 11. 12. 12.]]]
[[[ 11. 11. 12. 13. 13.]
[ 11. 11. 12. 13. 13.]
[ 14. 14. 15. 16. 16.]
[ 14. 14. 15. 16. 16.]]
[[ 17. 17. 18. 19. 19.]
[ 17. 17. 18. 19. 19.]
[ 20. 20. 21. 22. 22.]
[ 20. 20. 21. 22. 22.]]]]
pad(x, mode="constant", constant_value=0, pad_width=(0,0,0,0,1,1,1,1)) =
[[[[ 0. 0. 0. 0. 0.]
[ 0. 1. 2. 3. 0.]
[ 0. 4. 5. 6. 0.]
[ 0. 0. 0. 0. 0.]]
[[ 0. 0. 0. 0. 0.]
[ 0. 7. 8. 9. 0.]
[ 0. 10. 11. 12. 0.]
[ 0. 0. 0. 0. 0.]]]
[[[ 0. 0. 0. 0. 0.]
[ 0. 11. 12. 13. 0.]
[ 0. 14. 15. 16. 0.]
[ 0. 0. 0. 0. 0.]]
[[ 0. 0. 0. 0. 0.]
[ 0. 17. 18. 19. 0.]
[ 0. 20. 21. 22. 0.]
[ 0. 0. 0. 0. 0.]]]]
Defined in ../src/operator/pad.cc:L766
Parameters
----------
data : Symbol
An n-dimensional input array.
mode : {'constant', 'edge', 'reflect'}, required
Padding type to use. "constant" pads with `constant_value` "edge" pads using the edge values of the input array "reflect" pads by reflecting values with respect to the edges.
pad_width : Shape(tuple), required
Widths of the padding regions applied to the edges of each axis. It is a tuple of integer padding widths for each axis of the format ``(before_1, after_1, ... , before_N, after_N)``. It should be of length ``2*N`` where ``N`` is the number of dimensions of the array.This is equivalent to pad_width in numpy.pad, but flattened.
constant_value : double, optional, default=0
The value used for padding when `mode` is "constant".
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Pooling(data=None, kernel=_Null, pool_type=_Null, global_pool=_Null, cudnn_off=_Null, pooling_convention=_Null, stride=_Null, pad=_Null, p_value=_Null, count_include_pad=_Null, layout=_Null, name=None, attr=None, out=None, **kwargs):
r"""Performs pooling on the input.
The shapes for 1-D pooling are
- **data** and **out**: *(batch_size, channel, width)* (NCW layout) or
*(batch_size, width, channel)* (NWC layout),
The shapes for 2-D pooling are
- **data** and **out**: *(batch_size, channel, height, width)* (NCHW layout) or
*(batch_size, height, width, channel)* (NHWC layout),
out_height = f(height, kernel[0], pad[0], stride[0])
out_width = f(width, kernel[1], pad[1], stride[1])
The definition of *f* depends on ``pooling_convention``, which has two options:
- **valid** (default)::
f(x, k, p, s) = floor((x+2*p-k)/s)+1
- **full**, which is compatible with Caffe::
f(x, k, p, s) = ceil((x+2*p-k)/s)+1
When ``global_pool`` is set to be true, then global pooling is performed. It will reset
``kernel=(height, width)`` and set the appropiate padding to 0.
Three pooling options are supported by ``pool_type``:
- **avg**: average pooling
- **max**: max pooling
- **sum**: sum pooling
- **lp**: Lp pooling
For 3-D pooling, an additional *depth* dimension is added before
*height*. Namely the input data and output will have shape *(batch_size, channel, depth,
height, width)* (NCDHW layout) or *(batch_size, depth, height, width, channel)* (NDHWC layout).
Notes on Lp pooling:
Lp pooling was first introduced by this paper: https://arxiv.org/pdf/1204.3968.pdf.
L-1 pooling is simply sum pooling, while L-inf pooling is simply max pooling.
We can see that Lp pooling stands between those two, in practice the most common value for p is 2.
For each window ``X``, the mathematical expression for Lp pooling is:
:math:`f(X) = \sqrt[p]{\sum_{x}^{X} x^p}`
Defined in ../src/operator/nn/pooling.cc:L431
Parameters
----------
data : Symbol
Input data to the pooling operator.
kernel : Shape(tuple), optional, default=[]
Pooling kernel size: (y, x) or (d, y, x)
pool_type : {'avg', 'lp', 'max', 'sum'},optional, default='max'
Pooling type to be applied.
global_pool : boolean, optional, default=0
Ignore kernel size, do global pooling based on current input feature map.
cudnn_off : boolean, optional, default=0
Turn off cudnn pooling and use MXNet pooling operator.
pooling_convention : {'full', 'same', 'valid'},optional, default='valid'
Pooling convention to be applied.
stride : Shape(tuple), optional, default=[]
Stride: for pooling (y, x) or (d, y, x). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
Pad for pooling: (y, x) or (d, y, x). Defaults to no padding.
p_value : int or None, optional, default='None'
Value of p for Lp pooling, can be 1 or 2, required for Lp Pooling.
count_include_pad : boolean or None, optional, default=None
Only used for AvgPool, specify whether to count padding elements for averagecalculation. For example, with a 5*5 kernel on a 3*3 corner of a image,the sum of the 9 valid elements will be divided by 25 if this is set to true,or it will be divided by 9 if this is set to false. Defaults to true.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC', 'NWC'},optional, default='None'
Set layout for input and output. Empty for
default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Pooling_v1(data=None, kernel=_Null, pool_type=_Null, global_pool=_Null, pooling_convention=_Null, stride=_Null, pad=_Null, name=None, attr=None, out=None, **kwargs):
r"""This operator is DEPRECATED.
Perform pooling on the input.
The shapes for 2-D pooling is
- **data**: *(batch_size, channel, height, width)*
- **out**: *(batch_size, num_filter, out_height, out_width)*, with::
out_height = f(height, kernel[0], pad[0], stride[0])
out_width = f(width, kernel[1], pad[1], stride[1])
The definition of *f* depends on ``pooling_convention``, which has two options:
- **valid** (default)::
f(x, k, p, s) = floor((x+2*p-k)/s)+1
- **full**, which is compatible with Caffe::
f(x, k, p, s) = ceil((x+2*p-k)/s)+1
But ``global_pool`` is set to be true, then do a global pooling, namely reset
``kernel=(height, width)``.
Three pooling options are supported by ``pool_type``:
- **avg**: average pooling
- **max**: max pooling
- **sum**: sum pooling
1-D pooling is special case of 2-D pooling with *weight=1* and
*kernel[1]=1*.
For 3-D pooling, an additional *depth* dimension is added before
*height*. Namely the input data will have shape *(batch_size, channel, depth,
height, width)*.
Defined in ../src/operator/pooling_v1.cc:L104
Parameters
----------
data : Symbol
Input data to the pooling operator.
kernel : Shape(tuple), optional, default=[]
pooling kernel size: (y, x) or (d, y, x)
pool_type : {'avg', 'max', 'sum'},optional, default='max'
Pooling type to be applied.
global_pool : boolean, optional, default=0
Ignore kernel size, do global pooling based on current input feature map.
pooling_convention : {'full', 'valid'},optional, default='valid'
Pooling convention to be applied.
stride : Shape(tuple), optional, default=[]
stride: for pooling (y, x) or (d, y, x)
pad : Shape(tuple), optional, default=[]
pad for pooling: (y, x) or (d, y, x)
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def RNN(data=None, parameters=None, state=None, state_cell=None, sequence_length=None, state_size=_Null, num_layers=_Null, bidirectional=_Null, mode=_Null, p=_Null, state_outputs=_Null, projection_size=_Null, lstm_state_clip_min=_Null, lstm_state_clip_max=_Null, lstm_state_clip_nan=_Null, use_sequence_length=_Null, cudnn_algo_verbose=_Null, cudnn_algo=_Null, cudnn_tensor_core=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies recurrent layers to input data. Currently, vanilla RNN, LSTM and GRU are
implemented, with both multi-layer and bidirectional support.
When the input data is of type float32 and the environment variables MXNET_CUDA_ALLOW_TENSOR_CORE
and MXNET_CUDA_TENSOR_OP_MATH_ALLOW_CONVERSION are set to 1, this operator will try to use
pseudo-float16 precision (float32 math with float16 I/O) precision in order to use
Tensor Cores on suitable NVIDIA GPUs. This can sometimes give significant speedups.
**Vanilla RNN**
Applies a single-gate recurrent layer to input X. Two kinds of activation function are supported:
ReLU and Tanh.
With ReLU activation function:
.. math::
h_t = relu(W_{ih} * x_t + b_{ih} + W_{hh} * h_{(t-1)} + b_{hh})
With Tanh activtion function:
.. math::
h_t = \tanh(W_{ih} * x_t + b_{ih} + W_{hh} * h_{(t-1)} + b_{hh})
Reference paper: Finding structure in time - Elman, 1988.
https://crl.ucsd.edu/~elman/Papers/fsit.pdf
**LSTM**
Long Short-Term Memory - Hochreiter, 1997. http://www.bioinf.jku.at/publications/older/2604.pdf
.. math::
\begin{array}{ll}
i_t = \mathrm{sigmoid}(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\
f_t = \mathrm{sigmoid}(W_{if} x_t + b_{if} + W_{hf} h_{(t-1)} + b_{hf}) \\
g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hc} h_{(t-1)} + b_{hg}) \\
o_t = \mathrm{sigmoid}(W_{io} x_t + b_{io} + W_{ho} h_{(t-1)} + b_{ho}) \\
c_t = f_t * c_{(t-1)} + i_t * g_t \\
h_t = o_t * \tanh(c_t)
\end{array}
With the projection size being set, LSTM could use the projection feature to reduce the parameters
size and give some speedups without significant damage to the accuracy.
Long Short-Term Memory Based Recurrent Neural Network Architectures for Large Vocabulary Speech
Recognition - Sak et al. 2014. https://arxiv.org/abs/1402.1128
.. math::
\begin{array}{ll}
i_t = \mathrm{sigmoid}(W_{ii} x_t + b_{ii} + W_{ri} r_{(t-1)} + b_{ri}) \\
f_t = \mathrm{sigmoid}(W_{if} x_t + b_{if} + W_{rf} r_{(t-1)} + b_{rf}) \\
g_t = \tanh(W_{ig} x_t + b_{ig} + W_{rc} r_{(t-1)} + b_{rg}) \\
o_t = \mathrm{sigmoid}(W_{io} x_t + b_{o} + W_{ro} r_{(t-1)} + b_{ro}) \\
c_t = f_t * c_{(t-1)} + i_t * g_t \\
h_t = o_t * \tanh(c_t)
r_t = W_{hr} h_t
\end{array}
**GRU**
Gated Recurrent Unit - Cho et al. 2014. http://arxiv.org/abs/1406.1078
The definition of GRU here is slightly different from paper but compatible with CUDNN.
.. math::
\begin{array}{ll}
r_t = \mathrm{sigmoid}(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
z_t = \mathrm{sigmoid}(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
h_t = (1 - z_t) * n_t + z_t * h_{(t-1)} \\
\end{array}
Defined in ../src/operator/rnn.cc:L369
Parameters
----------
data : Symbol
Input data to RNN
parameters : Symbol
Vector of all RNN trainable parameters concatenated
state : Symbol
initial hidden state of the RNN
state_cell : Symbol
initial cell state for LSTM networks (only for LSTM)
sequence_length : Symbol
Vector of valid sequence lengths for each element in batch. (Only used if use_sequence_length kwarg is True)
state_size : int (non-negative), required
size of the state for each layer
num_layers : int (non-negative), required
number of stacked layers
bidirectional : boolean, optional, default=0
whether to use bidirectional recurrent layers
mode : {'gru', 'lstm', 'rnn_relu', 'rnn_tanh'}, required
the type of RNN to compute
p : float, optional, default=0
drop rate of the dropout on the outputs of each RNN layer, except the last layer.
state_outputs : boolean, optional, default=0
Whether to have the states as symbol outputs.
projection_size : int or None, optional, default='None'
size of project size
lstm_state_clip_min : double or None, optional, default=None
Minimum clip value of LSTM states. This option must be used together with lstm_state_clip_max.
lstm_state_clip_max : double or None, optional, default=None
Maximum clip value of LSTM states. This option must be used together with lstm_state_clip_min.
lstm_state_clip_nan : boolean, optional, default=0
Whether to stop NaN from propagating in state by clipping it to min/max. If clipping range is not specified, this option is ignored.
use_sequence_length : boolean, optional, default=0
If set to true, this layer takes in an extra input parameter `sequence_length` to specify variable length sequence
cudnn_algo_verbose : boolean, optional, default=0
Verboseness of algo selection. true = output selection, false = no output
cudnn_algo : int, optional, default='-1'
Specified RNN Algorithm.
cudnn_tensor_core : boolean or None, optional, default=None
Allow Tensor Core math for the algos.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ROIPooling(data=None, rois=None, pooled_size=_Null, spatial_scale=_Null, name=None, attr=None, out=None, **kwargs):
r"""Performs region of interest(ROI) pooling on the input array.
ROI pooling is a variant of a max pooling layer, in which the output size is fixed and
region of interest is a parameter. Its purpose is to perform max pooling on the inputs
of non-uniform sizes to obtain fixed-size feature maps. ROI pooling is a neural-net
layer mostly used in training a `Fast R-CNN` network for object detection.
This operator takes a 4D feature map as an input array and region proposals as `rois`,
then it pools over sub-regions of input and produces a fixed-sized output array
regardless of the ROI size.
To crop the feature map accordingly, you can resize the bounding box coordinates
by changing the parameters `rois` and `spatial_scale`.
The cropped feature maps are pooled by standard max pooling operation to a fixed size output
indicated by a `pooled_size` parameter. batch_size will change to the number of region
bounding boxes after `ROIPooling`.
The size of each region of interest doesn't have to be perfectly divisible by
the number of pooling sections(`pooled_size`).
Example::
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.],
[ 36., 37., 38., 39., 40., 41.],
[ 42., 43., 44., 45., 46., 47.]]]]
// region of interest i.e. bounding box coordinates.
y = [[0,0,0,4,4]]
// returns array of shape (2,2) according to the given roi with max pooling.
ROIPooling(x, y, (2,2), 1.0) = [[[[ 14., 16.],
[ 26., 28.]]]]
// region of interest is changed due to the change in `spacial_scale` parameter.
ROIPooling(x, y, (2,2), 0.7) = [[[[ 7., 9.],
[ 19., 21.]]]]
Defined in ../src/operator/roi_pooling.cc:L225
Parameters
----------
data : Symbol
The input array to the pooling operator, a 4D Feature maps
rois : Symbol
Bounding box coordinates, a 2D array of [[batch_index, x1, y1, x2, y2]], where (x1, y1) and (x2, y2) are top left and bottom right corners of designated region of interest. `batch_index` indicates the index of corresponding image in the input array
pooled_size : Shape(tuple), required
ROI pooling output shape (h,w)
spatial_scale : float, required
Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal of total stride in convolutional layers
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Reshape(data=None, shape=_Null, reverse=_Null, target_shape=_Null, keep_highest=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reshapes the input array.
.. note:: ``Reshape`` is deprecated, use ``reshape``
Given an array and a shape, this function returns a copy of the array in the new shape.
The shape is a tuple of integers such as (2,3,4). The size of the new shape should be same as the size of the input array.
Example::
reshape([1,2,3,4], shape=(2,2)) = [[1,2], [3,4]]
Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}. The significance of each is explained below:
- ``0`` copy this dimension from the input to the output shape.
Example::
- input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)
- input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)
- ``-1`` infers the dimension of the output shape by using the remainder of the input dimensions
keeping the size of the new array same as that of the input array.
At most one dimension of shape can be -1.
Example::
- input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)
- input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)
- input shape = (2,3,4), shape=(-1,), output shape = (24,)
- ``-2`` copy all/remainder of the input dimensions to the output shape.
Example::
- input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)
- input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)
- input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)
- ``-3`` use the product of two consecutive dimensions of the input shape as the output dimension.
Example::
- input shape = (2,3,4), shape = (-3,4), output shape = (6,4)
- input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)
- input shape = (2,3,4), shape = (0,-3), output shape = (2,12)
- input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)
- ``-4`` split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).
Example::
- input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)
- input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)
If the argument `reverse` is set to 1, then the special values are inferred from right to left.
Example::
- without reverse=1, for input shape = (10,5,4), shape = (-1,0), output shape would be (40,5)
- with reverse=1, output shape will be (50,4).
Defined in ../src/operator/tensor/matrix_op.cc:L175
Parameters
----------
data : Symbol
Input data to reshape.
shape : Shape(tuple), optional, default=[]
The target shape
reverse : boolean, optional, default=0
If true then the special values are inferred from right to left
target_shape : Shape(tuple), optional, default=[]
(Deprecated! Use ``shape`` instead.) Target new shape. One and only one dim can be 0, in which case it will be inferred from the rest of dims
keep_highest : boolean, optional, default=0
(Deprecated! Use ``shape`` instead.) Whether keep the highest dim unchanged.If set to true, then the first dim in target_shape is ignored,and always fixed as input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SVMOutput(data=None, label=None, margin=_Null, regularization_coefficient=_Null, use_linear=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes support vector machine based transformation of the input.
This tutorial demonstrates using SVM as output layer for classification instead of softmax:
https://github.com/dmlc/mxnet/tree/master/example/svm_mnist.
Parameters
----------
data : Symbol
Input data for SVM transformation.
label : Symbol
Class label for the input data.
margin : float, optional, default=1
The loss function penalizes outputs that lie outside this margin. Default margin is 1.
regularization_coefficient : float, optional, default=1
Regularization parameter for the SVM. This balances the tradeoff between coefficient size and error.
use_linear : boolean, optional, default=0
Whether to use L1-SVM objective. L2-SVM objective is used by default.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ScaleBiasAddRelu(dataX=None, dataZ=None, x_equiv_scale=None, x_equiv_bias=None, z_equiv_scale=None, z_equiv_bias=None, x_gamma=None, x_beta=None, x_mean=None, x_invvar=None, z_gamma=None, z_beta=None, z_mean=None, z_invvar=None, eps=_Null, dual_scale_bias=_Null, fused_add=_Null, fused_relu=_Null, layout=_Null, act_type=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute ScaleBiasAddRelu.
Defined in ../src/operator/nn/scale_bias_add_relu.cc:L272
Parameters
----------
dataX : Symbol
Input data to the ScaleBiasAddReluOp.
dataZ : Symbol
Input data to the ScaleBiasAddReluOp.
x_equiv_scale : Symbol
equivalent scale array
x_equiv_bias : Symbol
equivalent bias array
z_equiv_scale : Symbol
equivalent scale array
z_equiv_bias : Symbol
equivalent bias array
x_gamma : Symbol
x_beta : Symbol
x_mean : Symbol
x_invvar : Symbol
z_gamma : Symbol
z_beta : Symbol
z_mean : Symbol
z_invvar : Symbol
eps : double, optional, default=0.0010000000474974513
Epsilon to prevent div 0. Must be no less than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
dual_scale_bias : boolean, optional, default=1
dual scale bias
fused_add : boolean, optional, default=1
dual scale bias
fused_relu : boolean, optional, default=1
dual scale bias
layout : {None, 'NHWC'},optional, default='None'
Set layout for input and outputNHWC is only supported on GPU.
act_type : {None, 'relu'},optional, default='None'
Fused activation function to be applied.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SequenceLast(data=None, sequence_length=None, use_sequence_length=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Takes the last element of a sequence.
This function takes an n-dimensional input array of the form
[max_sequence_length, batch_size, other_feature_dims] and returns a (n-1)-dimensional array
of the form [batch_size, other_feature_dims].
Parameter `sequence_length` is used to handle variable-length sequences. `sequence_length` should be
an input array of positive ints of dimension [batch_size]. To use this parameter,
set `use_sequence_length` to `True`, otherwise each example in the batch is assumed
to have the max sequence length.
.. note:: Alternatively, you can also use `take` operator.
Example::
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.],
[ 25., 26., 27.]]]
// returns last sequence when sequence_length parameter is not used
SequenceLast(x) = [[ 19., 20., 21.],
[ 22., 23., 24.],
[ 25., 26., 27.]]
// sequence_length is used
SequenceLast(x, sequence_length=[1,1,1], use_sequence_length=True) =
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]]
// sequence_length is used
SequenceLast(x, sequence_length=[1,2,3], use_sequence_length=True) =
[[ 1., 2., 3.],
[ 13., 14., 15.],
[ 25., 26., 27.]]
Defined in ../src/operator/sequence_last.cc:L106
Parameters
----------
data : Symbol
n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] where n>2
sequence_length : Symbol
vector of sequence lengths of the form [batch_size]
use_sequence_length : boolean, optional, default=0
If set to true, this layer takes in an extra input parameter `sequence_length` to specify variable length sequence
axis : int, optional, default='0'
The sequence axis. Only values of 0 and 1 are currently supported.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SequenceMask(data=None, sequence_length=None, use_sequence_length=_Null, value=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Sets all elements outside the sequence to a constant value.
This function takes an n-dimensional input array of the form
[max_sequence_length, batch_size, other_feature_dims] and returns an array of the same shape.
Parameter `sequence_length` is used to handle variable-length sequences. `sequence_length`
should be an input array of positive ints of dimension [batch_size].
To use this parameter, set `use_sequence_length` to `True`,
otherwise each example in the batch is assumed to have the max sequence length and
this operator works as the `identity` operator.
Example::
x = [[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 13., 14., 15.],
[ 16., 17., 18.]]]
// Batch 1
B1 = [[ 1., 2., 3.],
[ 7., 8., 9.],
[ 13., 14., 15.]]
// Batch 2
B2 = [[ 4., 5., 6.],
[ 10., 11., 12.],
[ 16., 17., 18.]]
// works as identity operator when sequence_length parameter is not used
SequenceMask(x) = [[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 13., 14., 15.],
[ 16., 17., 18.]]]
// sequence_length [1,1] means 1 of each batch will be kept
// and other rows are masked with default mask value = 0
SequenceMask(x, sequence_length=[1,1], use_sequence_length=True) =
[[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.]]]
// sequence_length [2,3] means 2 of batch B1 and 3 of batch B2 will be kept
// and other rows are masked with value = 1
SequenceMask(x, sequence_length=[2,3], use_sequence_length=True, value=1) =
[[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 1., 1., 1.],
[ 16., 17., 18.]]]
Defined in ../src/operator/sequence_mask.cc:L186
Parameters
----------
data : Symbol
n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] where n>2
sequence_length : Symbol
vector of sequence lengths of the form [batch_size]
use_sequence_length : boolean, optional, default=0
If set to true, this layer takes in an extra input parameter `sequence_length` to specify variable length sequence
value : float, optional, default=0
The value to be used as a mask.
axis : int, optional, default='0'
The sequence axis. Only values of 0 and 1 are currently supported.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SequenceReverse(data=None, sequence_length=None, use_sequence_length=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reverses the elements of each sequence.
This function takes an n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims]
and returns an array of the same shape.
Parameter `sequence_length` is used to handle variable-length sequences.
`sequence_length` should be an input array of positive ints of dimension [batch_size].
To use this parameter, set `use_sequence_length` to `True`,
otherwise each example in the batch is assumed to have the max sequence length.
Example::
x = [[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 13., 14., 15.],
[ 16., 17., 18.]]]
// Batch 1
B1 = [[ 1., 2., 3.],
[ 7., 8., 9.],
[ 13., 14., 15.]]
// Batch 2
B2 = [[ 4., 5., 6.],
[ 10., 11., 12.],
[ 16., 17., 18.]]
// returns reverse sequence when sequence_length parameter is not used
SequenceReverse(x) = [[[ 13., 14., 15.],
[ 16., 17., 18.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 1., 2., 3.],
[ 4., 5., 6.]]]
// sequence_length [2,2] means 2 rows of
// both batch B1 and B2 will be reversed.
SequenceReverse(x, sequence_length=[2,2], use_sequence_length=True) =
[[[ 7., 8., 9.],
[ 10., 11., 12.]],
[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 13., 14., 15.],
[ 16., 17., 18.]]]
// sequence_length [2,3] means 2 of batch B2 and 3 of batch B3
// will be reversed.
SequenceReverse(x, sequence_length=[2,3], use_sequence_length=True) =
[[[ 7., 8., 9.],
[ 16., 17., 18.]],
[[ 1., 2., 3.],
[ 10., 11., 12.]],
[[ 13., 14, 15.],
[ 4., 5., 6.]]]
Defined in ../src/operator/sequence_reverse.cc:L122
Parameters
----------
data : Symbol
n-dimensional input array of the form [max_sequence_length, batch_size, other dims] where n>2
sequence_length : Symbol
vector of sequence lengths of the form [batch_size]
use_sequence_length : boolean, optional, default=0
If set to true, this layer takes in an extra input parameter `sequence_length` to specify variable length sequence
axis : int, optional, default='0'
The sequence axis. Only 0 is currently supported.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SliceChannel(data=None, num_outputs=_Null, axis=_Null, squeeze_axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Splits an array along a particular axis into multiple sub-arrays.
.. note:: ``SliceChannel`` is deprecated. Use ``split`` instead.
**Note** that `num_outputs` should evenly divide the length of the axis
along which to split the array.
Example::
x = [[[ 1.]
[ 2.]]
[[ 3.]
[ 4.]]
[[ 5.]
[ 6.]]]
x.shape = (3, 2, 1)
y = split(x, axis=1, num_outputs=2) // a list of 2 arrays with shape (3, 1, 1)
y = [[[ 1.]]
[[ 3.]]
[[ 5.]]]
[[[ 2.]]
[[ 4.]]
[[ 6.]]]
y[0].shape = (3, 1, 1)
z = split(x, axis=0, num_outputs=3) // a list of 3 arrays with shape (1, 2, 1)
z = [[[ 1.]
[ 2.]]]
[[[ 3.]
[ 4.]]]
[[[ 5.]
[ 6.]]]
z[0].shape = (1, 2, 1)
`squeeze_axis=1` removes the axis with length 1 from the shapes of the output arrays.
**Note** that setting `squeeze_axis` to ``1`` removes axis with length 1 only
along the `axis` which it is split.
Also `squeeze_axis` can be set to true only if ``input.shape[axis] == num_outputs``.
Example::
z = split(x, axis=0, num_outputs=3, squeeze_axis=1) // a list of 3 arrays with shape (2, 1)
z = [[ 1.]
[ 2.]]
[[ 3.]
[ 4.]]
[[ 5.]
[ 6.]]
z[0].shape = (2 ,1 )
Defined in ../src/operator/slice_channel.cc:L107
Parameters
----------
data : Symbol
The input
num_outputs : int, required
Number of splits. Note that this should evenly divide the length of the `axis`.
axis : int, optional, default='1'
Axis along which to split.
squeeze_axis : boolean, optional, default=0
If true, Removes the axis with length 1 from the shapes of the output arrays. **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1 only along the `axis` which it is split. Also `squeeze_axis` can be set to ``true`` only if ``input.shape[axis] == num_outputs``.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def Softmax(data=None, label=None, grad_scale=_Null, ignore_label=_Null, multi_output=_Null, use_ignore=_Null, preserve_shape=_Null, normalization=_Null, out_grad=_Null, smooth_alpha=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the gradient of cross entropy loss with respect to softmax output.
- This operator computes the gradient in two steps.
The cross entropy loss does not actually need to be computed.
- Applies softmax function on the input array.
- Computes and returns the gradient of cross entropy loss w.r.t. the softmax output.
- The softmax function, cross entropy loss and gradient is given by:
- Softmax Function:
.. math:: \text{softmax}(x)_i = \frac{exp(x_i)}{\sum_j exp(x_j)}
- Cross Entropy Function:
.. math:: \text{CE(label, output)} = - \sum_i \text{label}_i \log(\text{output}_i)
- The gradient of cross entropy loss w.r.t softmax output:
.. math:: \text{gradient} = \text{output} - \text{label}
- During forward propagation, the softmax function is computed for each instance in the input array.
For general *N*-D input arrays with shape :math:`(d_1, d_2, ..., d_n)`. The size is
:math:`s=d_1 \cdot d_2 \cdot \cdot \cdot d_n`. We can use the parameters `preserve_shape`
and `multi_output` to specify the way to compute softmax:
- By default, `preserve_shape` is ``false``. This operator will reshape the input array
into a 2-D array with shape :math:`(d_1, \frac{s}{d_1})` and then compute the softmax function for
each row in the reshaped array, and afterwards reshape it back to the original shape
:math:`(d_1, d_2, ..., d_n)`.
- If `preserve_shape` is ``true``, the softmax function will be computed along
the last axis (`axis` = ``-1``).
- If `multi_output` is ``true``, the softmax function will be computed along
the second axis (`axis` = ``1``).
- During backward propagation, the gradient of cross-entropy loss w.r.t softmax output array is computed.
The provided label can be a one-hot label array or a probability label array.
- If the parameter `use_ignore` is ``true``, `ignore_label` can specify input instances
with a particular label to be ignored during backward propagation. **This has no effect when
softmax `output` has same shape as `label`**.
Example::
data = [[1,2,3,4],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
label = [1,0,2,3]
ignore_label = 1
SoftmaxOutput(data=data, label = label,\
multi_output=true, use_ignore=true,\
ignore_label=ignore_label)
## forward softmax output
[[ 0.0320586 0.08714432 0.23688284 0.64391428]
[ 0.25 0.25 0.25 0.25 ]
[ 0.25 0.25 0.25 0.25 ]
[ 0.25 0.25 0.25 0.25 ]]
## backward gradient output
[[ 0. 0. 0. 0. ]
[-0.75 0.25 0.25 0.25]
[ 0.25 0.25 -0.75 0.25]
[ 0.25 0.25 0.25 -0.75]]
## notice that the first row is all 0 because label[0] is 1, which is equal to ignore_label.
- The parameter `grad_scale` can be used to rescale the gradient, which is often used to
give each loss function different weights.
- This operator also supports various ways to normalize the gradient by `normalization`,
The `normalization` is applied if softmax output has different shape than the labels.
The `normalization` mode can be set to the followings:
- ``'null'``: do nothing.
- ``'batch'``: divide the gradient by the batch size.
- ``'valid'``: divide the gradient by the number of instances which are not ignored.
Defined in ../src/operator/softmax_output.cc:L243
Parameters
----------
data : Symbol
Input array.
label : Symbol
Ground truth label.
grad_scale : float, optional, default=1
Scales the gradient by a float factor.
ignore_label : float, optional, default=-1
The instances whose `labels` == `ignore_label` will be ignored during backward, if `use_ignore` is set to ``true``).
multi_output : boolean, optional, default=0
If set to ``true``, the softmax function will be computed along axis ``1``. This is applied when the shape of input array differs from the shape of label array.
use_ignore : boolean, optional, default=0
If set to ``true``, the `ignore_label` value will not contribute to the backward gradient.
preserve_shape : boolean, optional, default=0
If set to ``true``, the softmax function will be computed along the last axis (``-1``).
normalization : {'batch', 'null', 'valid'},optional, default='null'
Normalizes the gradient.
out_grad : boolean, optional, default=0
Multiplies gradient with output gradient element-wise.
smooth_alpha : float, optional, default=0
Constant for computing a label smoothed version of cross-entropyfor the backwards pass. This constant gets subtracted from theone-hot encoding of the gold label and distributed uniformly toall other labels.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SoftmaxActivation(data=None, mode=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies softmax activation to input. This is intended for internal layers.
.. note::
This operator has been deprecated, please use `softmax`.
If `mode` = ``instance``, this operator will compute a softmax for each instance in the batch.
This is the default mode.
If `mode` = ``channel``, this operator will compute a k-class softmax at each position
of each instance, where `k` = ``num_channel``. This mode can only be used when the input array
has at least 3 dimensions.
This can be used for `fully convolutional network`, `image segmentation`, etc.
Example::
>>> input_array = mx.nd.array([[3., 0.5, -0.5, 2., 7.],
>>> [2., -.4, 7., 3., 0.2]])
>>> softmax_act = mx.nd.SoftmaxActivation(input_array)
>>> print softmax_act.asnumpy()
[[ 1.78322066e-02 1.46375655e-03 5.38485940e-04 6.56010211e-03 9.73605454e-01]
[ 6.56221947e-03 5.95310994e-04 9.73919690e-01 1.78379621e-02 1.08472735e-03]]
Defined in ../src/operator/nn/softmax_activation.cc:L59
Parameters
----------
data : Symbol
The input array.
mode : {'channel', 'instance'},optional, default='instance'
Specifies how to compute the softmax. If set to ``instance``, it computes softmax for each instance. If set to ``channel``, It computes cross channel softmax for each position of each instance.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SoftmaxOutput(data=None, label=None, grad_scale=_Null, ignore_label=_Null, multi_output=_Null, use_ignore=_Null, preserve_shape=_Null, normalization=_Null, out_grad=_Null, smooth_alpha=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the gradient of cross entropy loss with respect to softmax output.
- This operator computes the gradient in two steps.
The cross entropy loss does not actually need to be computed.
- Applies softmax function on the input array.
- Computes and returns the gradient of cross entropy loss w.r.t. the softmax output.
- The softmax function, cross entropy loss and gradient is given by:
- Softmax Function:
.. math:: \text{softmax}(x)_i = \frac{exp(x_i)}{\sum_j exp(x_j)}
- Cross Entropy Function:
.. math:: \text{CE(label, output)} = - \sum_i \text{label}_i \log(\text{output}_i)
- The gradient of cross entropy loss w.r.t softmax output:
.. math:: \text{gradient} = \text{output} - \text{label}
- During forward propagation, the softmax function is computed for each instance in the input array.
For general *N*-D input arrays with shape :math:`(d_1, d_2, ..., d_n)`. The size is
:math:`s=d_1 \cdot d_2 \cdot \cdot \cdot d_n`. We can use the parameters `preserve_shape`
and `multi_output` to specify the way to compute softmax:
- By default, `preserve_shape` is ``false``. This operator will reshape the input array
into a 2-D array with shape :math:`(d_1, \frac{s}{d_1})` and then compute the softmax function for
each row in the reshaped array, and afterwards reshape it back to the original shape
:math:`(d_1, d_2, ..., d_n)`.
- If `preserve_shape` is ``true``, the softmax function will be computed along
the last axis (`axis` = ``-1``).
- If `multi_output` is ``true``, the softmax function will be computed along
the second axis (`axis` = ``1``).
- During backward propagation, the gradient of cross-entropy loss w.r.t softmax output array is computed.
The provided label can be a one-hot label array or a probability label array.
- If the parameter `use_ignore` is ``true``, `ignore_label` can specify input instances
with a particular label to be ignored during backward propagation. **This has no effect when
softmax `output` has same shape as `label`**.
Example::
data = [[1,2,3,4],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
label = [1,0,2,3]
ignore_label = 1
SoftmaxOutput(data=data, label = label,\
multi_output=true, use_ignore=true,\
ignore_label=ignore_label)
## forward softmax output
[[ 0.0320586 0.08714432 0.23688284 0.64391428]
[ 0.25 0.25 0.25 0.25 ]
[ 0.25 0.25 0.25 0.25 ]
[ 0.25 0.25 0.25 0.25 ]]
## backward gradient output
[[ 0. 0. 0. 0. ]
[-0.75 0.25 0.25 0.25]
[ 0.25 0.25 -0.75 0.25]
[ 0.25 0.25 0.25 -0.75]]
## notice that the first row is all 0 because label[0] is 1, which is equal to ignore_label.
- The parameter `grad_scale` can be used to rescale the gradient, which is often used to
give each loss function different weights.
- This operator also supports various ways to normalize the gradient by `normalization`,
The `normalization` is applied if softmax output has different shape than the labels.
The `normalization` mode can be set to the followings:
- ``'null'``: do nothing.
- ``'batch'``: divide the gradient by the batch size.
- ``'valid'``: divide the gradient by the number of instances which are not ignored.
Defined in ../src/operator/softmax_output.cc:L243
Parameters
----------
data : Symbol
Input array.
label : Symbol
Ground truth label.
grad_scale : float, optional, default=1
Scales the gradient by a float factor.
ignore_label : float, optional, default=-1
The instances whose `labels` == `ignore_label` will be ignored during backward, if `use_ignore` is set to ``true``).
multi_output : boolean, optional, default=0
If set to ``true``, the softmax function will be computed along axis ``1``. This is applied when the shape of input array differs from the shape of label array.
use_ignore : boolean, optional, default=0
If set to ``true``, the `ignore_label` value will not contribute to the backward gradient.
preserve_shape : boolean, optional, default=0
If set to ``true``, the softmax function will be computed along the last axis (``-1``).
normalization : {'batch', 'null', 'valid'},optional, default='null'
Normalizes the gradient.
out_grad : boolean, optional, default=0
Multiplies gradient with output gradient element-wise.
smooth_alpha : float, optional, default=0
Constant for computing a label smoothed version of cross-entropyfor the backwards pass. This constant gets subtracted from theone-hot encoding of the gold label and distributed uniformly toall other labels.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SpatialParallelConvolution(data=None, weight=None, dummy=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, cudnn_tensor_core=_Null, cudnn_tensor_core_only=_Null, layout=_Null, cudnn_algo_verbose=_Null, cudnn_algo_fwd=_Null, cudnn_algo_bwd_data=_Null, cudnn_algo_bwd_filter=_Null, cudnn_algo_fwd_prec=_Null, cudnn_algo_bwd_prec=_Null, num_gpus=_Null, rank=_Null, nccl_unique_id=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute *N*-D convolution on *(N+2)*-D input,
using data stored on multiple GPUs, spatially divided in the
outermost dimension.
In the 2-D convolution, given input data with shape *(batch_size,
channel, height, width)*, the output is computed by
.. math::
out[n,i,:,:] = bias[i] + \sum_{j=0}^{channel} data[n,j,:,:] \star
weight[i,j,:,:]
where :math:`\star` is the 2-D cross-correlation operator.
For general 2-D convolution, the shapes are
- **data**: *(batch_size, channel, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_height, out_width)*.
Define::
f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1
then we have::
out_height=f(height, kernel[0], pad[0], stride[0], dilate[0])
out_width=f(width, kernel[1], pad[1], stride[1], dilate[1])
If ``no_bias`` is set to be true, then the ``bias`` term is ignored.
The default data ``layout`` is *NCHW*, namely *(batch_size, channel, height,
width)*. We can choose other layouts such as *NWC*.
If ``num_group`` is larger than 1, denoted by *g*, then split the input ``data``
evenly into *g* parts along the channel axis, and also evenly split ``weight``
along the first dimension. Next compute the convolution on the *i*-th part of
the data with the *i*-th weight part. The output is obtained by concatenating all
the *g* results.
1-D convolution does not have *height* dimension but only *width* in space.
- **data**: *(batch_size, channel, width)*
- **weight**: *(num_filter, channel, kernel[0])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_width)*.
3-D convolution adds an additional *depth* dimension besides *height* and
*width*. The shapes are
- **data**: *(batch_size, channel, depth, height, width)*
- **weight**: *(num_filter, channel, kernel[0], kernel[1], kernel[2])*
- **bias**: *(num_filter,)*
- **out**: *(batch_size, num_filter, out_depth, out_height, out_width)*.
Both ``weight`` and ``bias`` are learnable parameters.
There are other options to tune the performance.
- **cudnn_tune**: enable this option leads to higher startup time but may give
faster speed. Options are
- **off**: no tuning
- **limited_workspace**:run test and pick the fastest algorithm that doesn't
exceed workspace limit.
- **fastest**: pick the fastest algorithm and ignore workspace limit.
- **None** (default): the behavior is determined by environment variable
``MXNET_CUDNN_AUTOTUNE_DEFAULT``. 0 for off, 1 for limited workspace
(default), 2 for fastest.
- **workspace**: A large number leads to more (GPU) memory usage but may improve
the performance.
Defined in ../src/operator/nn/spatial_parallel_convolution.cc:L436
Parameters
----------
data : Symbol
Input data to the ConvolutionOp.
weight : Symbol
Weight matrix.
dummy : Symbol
Dummy parameter needed to make sure no 2 spatial parallel convolutions are performed at the same time.
bias : Symbol
Bias parameter.
kernel : Shape(tuple), required
Convolution kernel size: (w,), (h, w) or (d, h, w)
stride : Shape(tuple), optional, default=[]
Convolution stride: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
dilate : Shape(tuple), optional, default=[]
Convolution dilate: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
Zero pad for convolution: (w,), (h, w) or (d, h, w). Defaults to no padding.
num_filter : int (non-negative), required
Convolution filter(channel) number
num_group : int (non-negative), optional, default=1
Number of group partitions.
workspace : long (non-negative), optional, default=1024
Maximum temporary workspace allowed (MB) in convolution.This parameter has two usages. When CUDNN is not used, it determines the effective batch size of the convolution kernel. When CUDNN is used, it controls the maximum temporary storage used for tuning the best CUDNN kernel when `limited_workspace` strategy is used.
no_bias : boolean, optional, default=0
Whether to disable bias parameter.
cudnn_tune : {None, 'fastest', 'limited_workspace', 'off'},optional, default='None'
Whether to pick convolution algo by running performance test.
cudnn_off : boolean, optional, default=0
Turn off cudnn for this layer.
cudnn_tensor_core : boolean or None, optional, default=None
Allow Tensor Core math within the algos.
cudnn_tensor_core_only : boolean, optional, default=0
Require Tensor Core math within the algos.
layout : {None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC', 'NWC'},optional, default='None'
Set layout for input, output and weight. Empty for
default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.NHWC and NDHWC are only supported on GPU.
cudnn_algo_verbose : boolean, optional, default=0
Verboseness of algo selection. 1 = output selection, 0 = no output
cudnn_algo_fwd : int, optional, default='-1'
Specified Forward Algorithm.
cudnn_algo_bwd_data : int, optional, default='-1'
Specified Backprop-to-Data Algorithm.
cudnn_algo_bwd_filter : int, optional, default='-1'
Specified Backprop-to-Filter Algorithm.
cudnn_algo_fwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the forward convolution kernel.
Default is the tensor data type, or float32 if the tensor data
type is float16.
cudnn_algo_bwd_prec : {'None', 'float16', 'float32', 'float64'},optional, default='None'
Precision of the computation of the back-prop kernels.
Default is the tensor data type, or float32 if the tensor data
type is float16.
num_gpus : int, required
Number of GPUs per sample.
rank : int, required
Rank inside a group
nccl_unique_id : long (non-negative), required
NCCL unique ID
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SpatialTransformer(data=None, loc=None, target_shape=_Null, transform_type=_Null, sampler_type=_Null, cudnn_off=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies a spatial transformer to input feature map.
Parameters
----------
data : Symbol
Input data to the SpatialTransformerOp.
loc : Symbol
localisation net, the output dim should be 6 when transform_type is affine. You shold initialize the weight and bias with identity tranform.
target_shape : Shape(tuple), optional, default=[0,0]
output shape(h, w) of spatial transformer: (y, x)
transform_type : {'affine'}, required
transformation type
sampler_type : {'bilinear'}, required
sampling type
cudnn_off : boolean or None, optional, default=None
whether to turn cudnn off
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def SwapAxis(data=None, dim1=_Null, dim2=_Null, name=None, attr=None, out=None, **kwargs):
r"""Interchanges two axes of an array.
Examples::
x = [[1, 2, 3]])
swapaxes(x, 0, 1) = [[ 1],
[ 2],
[ 3]]
x = [[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]] // (2,2,2) array
swapaxes(x, 0, 2) = [[[ 0, 4],
[ 2, 6]],
[[ 1, 5],
[ 3, 7]]]
Defined in ../src/operator/swapaxis.cc:L70
Parameters
----------
data : Symbol
Input array.
dim1 : int, optional, default='0'
the first axis to be swapped.
dim2 : int, optional, default='0'
the second axis to be swapped.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def UpSampling(*data, **kwargs):
r"""Upsamples the given input data.
Two algorithms (``sample_type``) are available for upsampling:
- Nearest Neighbor
- Bilinear
**Nearest Neighbor Upsampling**
Input data is expected to be NCHW.
Example::
x = [[[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]]]
UpSampling(x, scale=2, sample_type='nearest') = [[[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]]]
**Bilinear Upsampling**
Uses `deconvolution` algorithm under the hood. You need provide both input data and the kernel.
Input data is expected to be NCHW.
`num_filter` is expected to be same as the number of channels.
Example::
x = [[[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]]]
w = [[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]]
UpSampling(x, w, scale=2, sample_type='bilinear', num_filter=1) = [[[[1. 2. 2. 2. 2. 1.]
[2. 4. 4. 4. 4. 2.]
[2. 4. 4. 4. 4. 2.]
[2. 4. 4. 4. 4. 2.]
[2. 4. 4. 4. 4. 2.]
[1. 2. 2. 2. 2. 1.]]]]
Defined in ../src/operator/nn/upsampling.cc:L173
This function support variable length of positional input.
Parameters
----------
data : Symbol[]
Array of tensors to upsample. For bilinear upsampling, there should be 2 inputs - 1 data and 1 weight.
scale : int, required
Up sampling scale
num_filter : int, optional, default='0'
Input filter. Only used by bilinear sample_type.Since bilinear upsampling uses deconvolution, num_filters is set to the number of channels.
sample_type : {'bilinear', 'nearest'}, required
upsampling method
multi_input_mode : {'concat', 'sum'},optional, default='concat'
How to handle multiple input. concat means concatenate upsampled images along the channel dimension. sum means add all images together, only available for nearest neighbor upsampling.
workspace : long (non-negative), optional, default=512
Tmp workspace for deconvolution (MB)
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def abs(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise absolute value of the input.
Example::
abs([-2, 0, 3]) = [2, 0, 3]
The storage type of ``abs`` output depends upon the input storage type:
- abs(default) = default
- abs(row_sparse) = row_sparse
- abs(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L720
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def adam_update(weight=None, grad=None, mean=None, var=None, lr=_Null, beta1=_Null, beta2=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, lazy_update=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for Adam optimizer. Adam is seen as a generalization
of AdaGrad.
Adam update consists of the following steps, where g represents gradient and m, v
are 1st and 2nd order moment estimates (mean and variance).
.. math::
g_t = \nabla J(W_{t-1})\\
m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t\\
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
W_t = W_{t-1} - \alpha \frac{ m_t }{ \sqrt{ v_t } + \epsilon }
It updates the weights using::
m = beta1*m + (1-beta1)*grad
v = beta2*v + (1-beta2)*(grad**2)
w += - learning_rate * m / (sqrt(v) + epsilon)
However, if grad's storage type is ``row_sparse``, ``lazy_update`` is True and the storage
type of weight is the same as those of m and v,
only the row slices whose indices appear in grad.indices are updated (for w, m and v)::
for row in grad.indices:
m[row] = beta1*m[row] + (1-beta1)*grad[row]
v[row] = beta2*v[row] + (1-beta2)*(grad[row]**2)
w[row] += - learning_rate * m[row] / (sqrt(v[row]) + epsilon)
Defined in ../src/operator/optimizer_op.cc:L686
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mean : Symbol
Moving mean
var : Symbol
Moving variance
lr : float, required
Learning rate
beta1 : float, optional, default=0.899999976
The decay rate for the 1st moment estimates.
beta2 : float, optional, default=0.999000013
The decay rate for the 2nd moment estimates.
epsilon : float, optional, default=9.99999994e-09
A small constant for numerical stability.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
lazy_update : boolean, optional, default=1
If true, lazy updates are applied if gradient's stype is row_sparse and all of w, m and v have the same stype
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def add_n(*args, **kwargs):
r"""Adds all input arguments element-wise.
.. math::
add\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n
``add_n`` is potentially more efficient than calling ``add`` by `n` times.
The storage type of ``add_n`` output depends on storage types of inputs
- add_n(row_sparse, row_sparse, ..) = row_sparse
- add_n(default, csr, default) = default
- add_n(any input combinations longer than 4 (>4) with at least one default type) = default
- otherwise, ``add_n`` falls all inputs back to default storage and generates default storage
Defined in ../src/operator/tensor/elemwise_sum.cc:L156
This function support variable length of positional input.
Parameters
----------
args : Symbol[]
Positional input arguments
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def all_finite(data=None, init_output=_Null, name=None, attr=None, out=None, **kwargs):
r"""Check if all the float numbers in the array are finite (used for AMP)
Defined in ../src/operator/contrib/all_finite.cc:L101
Parameters
----------
data : NDArray
Array
init_output : boolean, optional, default=1
Initialize output to 1.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def amp_cast(data=None, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Cast function between low precision float/FP32 used by AMP.
It casts only between low precision float/FP32 and does not do anything for other types.
Defined in ../src/operator/tensor/amp_cast.cc:L135
Parameters
----------
data : Symbol
The input.
dtype : {'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'}, required
Output data type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def amp_multicast(*data, **kwargs):
r"""Cast function used by AMP, that casts its inputs to the common widest type.
It casts only between low precision float/FP32 and does not do anything for other types.
Defined in ../src/operator/tensor/amp_cast.cc:L180
Parameters
----------
data : Symbol[]
Weights
num_outputs : int, required
Number of input/output pairs to be casted to the widest type.
cast_narrow : boolean, optional, default=0
Whether to cast to the narrowest type
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arccos(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse cosine of the input array.
The input should be in range `[-1, 1]`.
The output is in the closed interval :math:`[0, \pi]`
.. math::
arccos([-1, -.707, 0, .707, 1]) = [\pi, 3\pi/4, \pi/2, \pi/4, 0]
The storage type of ``arccos`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L233
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arccosh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the element-wise inverse hyperbolic cosine of the input array, \
computed element-wise.
The storage type of ``arccosh`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L535
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arcsin(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse sine of the input array.
The input should be in the range `[-1, 1]`.
The output is in the closed interval of [:math:`-\pi/2`, :math:`\pi/2`].
.. math::
arcsin([-1, -.707, 0, .707, 1]) = [-\pi/2, -\pi/4, 0, \pi/4, \pi/2]
The storage type of ``arcsin`` output depends upon the input storage type:
- arcsin(default) = default
- arcsin(row_sparse) = row_sparse
- arcsin(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L187
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arcsinh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the element-wise inverse hyperbolic sine of the input array, \
computed element-wise.
The storage type of ``arcsinh`` output depends upon the input storage type:
- arcsinh(default) = default
- arcsinh(row_sparse) = row_sparse
- arcsinh(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L494
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arctan(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse tangent of the input array.
The output is in the closed interval :math:`[-\pi/2, \pi/2]`
.. math::
arctan([-1, 0, 1]) = [-\pi/4, 0, \pi/4]
The storage type of ``arctan`` output depends upon the input storage type:
- arctan(default) = default
- arctan(row_sparse) = row_sparse
- arctan(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L282
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def arctanh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the element-wise inverse hyperbolic tangent of the input array, \
computed element-wise.
The storage type of ``arctanh`` output depends upon the input storage type:
- arctanh(default) = default
- arctanh(row_sparse) = row_sparse
- arctanh(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L579
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def argmax(data=None, axis=_Null, keepdims=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns indices of the maximum values along an axis.
In the case of multiple occurrences of maximum values, the indices corresponding to the first occurrence
are returned.
Examples::
x = [[ 0., 1., 2.],
[ 3., 4., 5.]]
// argmax along axis 0
argmax(x, axis=0) = [ 1., 1., 1.]
// argmax along axis 1
argmax(x, axis=1) = [ 2., 2.]
// argmax along axis 1 keeping same dims as an input array
argmax(x, axis=1, keepdims=True) = [[ 2.],
[ 2.]]
Defined in ../src/operator/tensor/broadcast_reduce_op_index.cc:L52
Parameters
----------
data : Symbol
The input
axis : int or None, optional, default='None'
The axis along which to perform the reduction. Negative values means indexing from right to left. ``Requires axis to be set as int, because global reduction is not supported yet.``
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axis is left in the result as dimension with size one.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def argmax_channel(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns argmax indices of each channel from the input array.
The result will be an NDArray of shape (num_channel,).
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence
are returned.
Examples::
x = [[ 0., 1., 2.],
[ 3., 4., 5.]]
argmax_channel(x) = [ 2., 2.]
Defined in ../src/operator/tensor/broadcast_reduce_op_index.cc:L97
Parameters
----------
data : Symbol
The input array
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def argmin(data=None, axis=_Null, keepdims=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns indices of the minimum values along an axis.
In the case of multiple occurrences of minimum values, the indices corresponding to the first occurrence
are returned.
Examples::
x = [[ 0., 1., 2.],
[ 3., 4., 5.]]
// argmin along axis 0
argmin(x, axis=0) = [ 0., 0., 0.]
// argmin along axis 1
argmin(x, axis=1) = [ 0., 0.]
// argmin along axis 1 keeping same dims as an input array
argmin(x, axis=1, keepdims=True) = [[ 0.],
[ 0.]]
Defined in ../src/operator/tensor/broadcast_reduce_op_index.cc:L77
Parameters
----------
data : Symbol
The input
axis : int or None, optional, default='None'
The axis along which to perform the reduction. Negative values means indexing from right to left. ``Requires axis to be set as int, because global reduction is not supported yet.``
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axis is left in the result as dimension with size one.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def argsort(data=None, axis=_Null, is_ascend=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns the indices that would sort an input array along the given axis.
This function performs sorting along the given axis and returns an array of indices having same shape
as an input array that index data in sorted order.
Examples::
x = [[ 0.3, 0.2, 0.4],
[ 0.1, 0.3, 0.2]]
// sort along axis -1
argsort(x) = [[ 1., 0., 2.],
[ 0., 2., 1.]]
// sort along axis 0
argsort(x, axis=0) = [[ 1., 0., 1.]
[ 0., 1., 0.]]
// flatten and then sort
argsort(x, axis=None) = [ 3., 1., 5., 0., 4., 2.]
Defined in ../src/operator/tensor/ordering_op.cc:L185
Parameters
----------
data : Symbol
The input array
axis : int or None, optional, default='-1'
Axis along which to sort the input tensor. If not given, the flattened array is used. Default is -1.
is_ascend : boolean, optional, default=1
Whether to sort in ascending or descending order.
dtype : {'float16', 'float32', 'float64', 'int32', 'int64', 'uint8'},optional, default='float32'
DType of the output indices. It is only valid when ret_typ is "indices" or "both". An error will be raised if the selected data type cannot precisely represent the indices.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def batch_dot(lhs=None, rhs=None, transpose_a=_Null, transpose_b=_Null, forward_stype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Batchwise dot product.
``batch_dot`` is used to compute dot product of ``x`` and ``y`` when ``x`` and
``y`` are data in batch, namely N-D (N >= 3) arrays in shape of `(B0, ..., B_i, :, :)`.
For example, given ``x`` with shape `(B_0, ..., B_i, N, M)` and ``y`` with shape
`(B_0, ..., B_i, M, K)`, the result array will have shape `(B_0, ..., B_i, N, K)`,
which is computed by::
batch_dot(x,y)[b_0, ..., b_i, :, :] = dot(x[b_0, ..., b_i, :, :], y[b_0, ..., b_i, :, :])
Defined in ../src/operator/tensor/dot.cc:L127
Parameters
----------
lhs : Symbol
The first input
rhs : Symbol
The second input
transpose_a : boolean, optional, default=0
If true then transpose the first input before dot.
transpose_b : boolean, optional, default=0
If true then transpose the second input before dot.
forward_stype : {None, 'csr', 'default', 'row_sparse'},optional, default='None'
The desired storage type of the forward output given by user, if thecombination of input storage types and this hint does not matchany implemented ones, the dot operator will perform fallback operationand still produce an output of the desired storage type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def batch_take(a=None, indices=None, name=None, attr=None, out=None, **kwargs):
r"""Takes elements from a data batch.
.. note::
`batch_take` is deprecated. Use `pick` instead.
Given an input array of shape ``(d0, d1)`` and indices of shape ``(i0,)``, the result will be
an output array of shape ``(i0,)`` with::
output[i] = input[i, indices[i]]
Examples::
x = [[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]
// takes elements with specified indices
batch_take(x, [0,1,0]) = [ 1. 4. 5.]
Defined in ../src/operator/tensor/indexing_op.cc:L836
Parameters
----------
a : Symbol
The input array
indices : Symbol
The index array
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_add(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise sum of the input arrays with broadcasting.
`broadcast_plus` is an alias to the function `broadcast_add`.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_add(x, y) = [[ 1., 1., 1.],
[ 2., 2., 2.]]
broadcast_plus(x, y) = [[ 1., 1., 1.],
[ 2., 2., 2.]]
Supported sparse operations:
broadcast_add(csr, dense(1D)) = dense
broadcast_add(dense(1D), csr) = dense
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L58
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_axes(data=None, axis=_Null, size=_Null, name=None, attr=None, out=None, **kwargs):
r"""Broadcasts the input array over particular axes.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
`broadcast_axes` is an alias to the function `broadcast_axis`.
Example::
// given x of shape (1,2,1)
x = [[[ 1.],
[ 2.]]]
// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1., 1., 1.],
[ 2., 2., 2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1., 1., 1.],
[ 2., 2., 2.]],
[[ 1., 1., 1.],
[ 2., 2., 2.]]]
Defined in ../src/operator/tensor/broadcast_reduce_op_value.cc:L93
Parameters
----------
data : Symbol
The input
axis : Shape(tuple), optional, default=[]
The axes to perform the broadcasting.
size : Shape(tuple), optional, default=[]
Target sizes of the broadcasting axes.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_axis(data=None, axis=_Null, size=_Null, name=None, attr=None, out=None, **kwargs):
r"""Broadcasts the input array over particular axes.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
`broadcast_axes` is an alias to the function `broadcast_axis`.
Example::
// given x of shape (1,2,1)
x = [[[ 1.],
[ 2.]]]
// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1., 1., 1.],
[ 2., 2., 2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1., 1., 1.],
[ 2., 2., 2.]],
[[ 1., 1., 1.],
[ 2., 2., 2.]]]
Defined in ../src/operator/tensor/broadcast_reduce_op_value.cc:L93
Parameters
----------
data : Symbol
The input
axis : Shape(tuple), optional, default=[]
The axes to perform the broadcasting.
size : Shape(tuple), optional, default=[]
Target sizes of the broadcasting axes.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_div(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise division of the input arrays with broadcasting.
Example::
x = [[ 6., 6., 6.],
[ 6., 6., 6.]]
y = [[ 2.],
[ 3.]]
broadcast_div(x, y) = [[ 3., 3., 3.],
[ 2., 2., 2.]]
Supported sparse operations:
broadcast_div(csr, dense(1D)) = csr
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L187
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_equal(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **equal to** (==) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_equal(x, y) = [[ 0., 0., 0.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L46
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_greater(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **greater than** (>) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_greater(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L82
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_greater_equal(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **greater than or equal to** (>=) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_greater_equal(x, y) = [[ 1., 1., 1.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L100
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_hypot(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r""" Returns the hypotenuse of a right angled triangle, given its "legs"
with broadcasting.
It is equivalent to doing :math:`sqrt(x_1^2 + x_2^2)`.
Example::
x = [[ 3., 3., 3.]]
y = [[ 4.],
[ 4.]]
broadcast_hypot(x, y) = [[ 5., 5., 5.],
[ 5., 5., 5.]]
z = [[ 0.],
[ 4.]]
broadcast_hypot(x, z) = [[ 3., 3., 3.],
[ 5., 5., 5.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L158
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_lesser(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **lesser than** (<) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_lesser(x, y) = [[ 0., 0., 0.],
[ 0., 0., 0.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L118
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_lesser_equal(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **lesser than or equal to** (<=) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_lesser_equal(x, y) = [[ 0., 0., 0.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L136
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_like(lhs=None, rhs=None, lhs_axes=_Null, rhs_axes=_Null, name=None, attr=None, out=None, **kwargs):
r"""Broadcasts lhs to have the same shape as rhs.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_like([[1,2,3]], [[5,6,7],[7,8,9]]) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
broadcast_like([9], [1,2,3,4,5], lhs_axes=(0,), rhs_axes=(-1,)) = [9,9,9,9,9]
Defined in ../src/operator/tensor/broadcast_reduce_op_value.cc:L179
Parameters
----------
lhs : Symbol
First input.
rhs : Symbol
Second input.
lhs_axes : Shape or None, optional, default=None
Axes to perform broadcast on in the first input array
rhs_axes : Shape or None, optional, default=None
Axes to copy from the second input array
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_logical_and(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **logical and** with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_logical_and(x, y) = [[ 0., 0., 0.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L154
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_logical_or(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **logical or** with broadcasting.
Example::
x = [[ 1., 1., 0.],
[ 1., 1., 0.]]
y = [[ 1.],
[ 0.]]
broadcast_logical_or(x, y) = [[ 1., 1., 1.],
[ 1., 1., 0.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L172
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_logical_xor(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **logical xor** with broadcasting.
Example::
x = [[ 1., 1., 0.],
[ 1., 1., 0.]]
y = [[ 1.],
[ 0.]]
broadcast_logical_xor(x, y) = [[ 0., 0., 1.],
[ 1., 1., 0.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L190
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_maximum(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise maximum of the input arrays with broadcasting.
This function compares two input arrays and returns a new array having the element-wise maxima.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_maximum(x, y) = [[ 1., 1., 1.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L81
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_minimum(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise minimum of the input arrays with broadcasting.
This function compares two input arrays and returns a new array having the element-wise minima.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_maximum(x, y) = [[ 0., 0., 0.],
[ 1., 1., 1.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L117
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_minus(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise difference of the input arrays with broadcasting.
`broadcast_minus` is an alias to the function `broadcast_sub`.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_sub(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
broadcast_minus(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
Supported sparse operations:
broadcast_sub/minus(csr, dense(1D)) = dense
broadcast_sub/minus(dense(1D), csr) = dense
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L106
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_mod(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise modulo of the input arrays with broadcasting.
Example::
x = [[ 8., 8., 8.],
[ 8., 8., 8.]]
y = [[ 2.],
[ 3.]]
broadcast_mod(x, y) = [[ 0., 0., 0.],
[ 2., 2., 2.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L222
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_mul(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise product of the input arrays with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_mul(x, y) = [[ 0., 0., 0.],
[ 1., 1., 1.]]
Supported sparse operations:
broadcast_mul(csr, dense(1D)) = csr
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L146
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_not_equal(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of element-wise **not equal to** (!=) comparison operation with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_not_equal(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L64
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_plus(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise sum of the input arrays with broadcasting.
`broadcast_plus` is an alias to the function `broadcast_add`.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_add(x, y) = [[ 1., 1., 1.],
[ 2., 2., 2.]]
broadcast_plus(x, y) = [[ 1., 1., 1.],
[ 2., 2., 2.]]
Supported sparse operations:
broadcast_add(csr, dense(1D)) = dense
broadcast_add(dense(1D), csr) = dense
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L58
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_power(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns result of first array elements raised to powers from second array, element-wise with broadcasting.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_power(x, y) = [[ 2., 2., 2.],
[ 4., 4., 4.]]
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L45
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_sub(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise difference of the input arrays with broadcasting.
`broadcast_minus` is an alias to the function `broadcast_sub`.
Example::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
y = [[ 0.],
[ 1.]]
broadcast_sub(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
broadcast_minus(x, y) = [[ 1., 1., 1.],
[ 0., 0., 0.]]
Supported sparse operations:
broadcast_sub/minus(csr, dense(1D)) = dense
broadcast_sub/minus(dense(1D), csr) = dense
Defined in ../src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L106
Parameters
----------
lhs : Symbol
First input to the function
rhs : Symbol
Second input to the function
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def broadcast_to(data=None, shape=_Null, name=None, attr=None, out=None, **kwargs):
r"""Broadcasts the input array to a new shape.
Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations
with arrays of different shapes efficiently without creating multiple copies of arrays.
Also see, `Broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_ for more explanation.
Broadcasting is allowed on axes with size 1, such as from `(2,1,3,1)` to
`(2,8,3,9)`. Elements will be duplicated on the broadcasted axes.
For example::
broadcast_to([[1,2,3]], shape=(2,3)) = [[ 1., 2., 3.],
[ 1., 2., 3.]])
The dimension which you do not want to change can also be kept as `0` which means copy the original value.
So with `shape=(2,0)`, we will obtain the same result as in the above example.
Defined in ../src/operator/tensor/broadcast_reduce_op_value.cc:L117
Parameters
----------
data : Symbol
The input
shape : Shape(tuple), optional, default=[]
The shape of the desired array. We can set the dim to zero if it's same as the original. E.g `A = broadcast_to(B, shape=(10, 0, 0))` has the same meaning as `A = broadcast_axis(B, axis=0, size=10)`.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cast(data=None, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Casts all elements of the input to a new type.
.. note:: ``Cast`` is deprecated. Use ``cast`` instead.
Example::
cast([0.9, 1.3], dtype='int32') = [0, 1]
cast([1e20, 11.1], dtype='float16') = [inf, 11.09375]
cast([300, 11.1, 10.9, -1, -3], dtype='uint8') = [44, 11, 10, 255, 253]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L664
Parameters
----------
data : Symbol
The input.
dtype : {'bfloat16', 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'}, required
Output data type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cast_storage(data=None, stype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Casts tensor storage type to the new type.
When an NDArray with default storage type is cast to csr or row_sparse storage,
the result is compact, which means:
- for csr, zero values will not be retained
- for row_sparse, row slices of all zeros will not be retained
The storage type of ``cast_storage`` output depends on stype parameter:
- cast_storage(csr, 'default') = default
- cast_storage(row_sparse, 'default') = default
- cast_storage(default, 'csr') = csr
- cast_storage(default, 'row_sparse') = row_sparse
- cast_storage(csr, 'csr') = csr
- cast_storage(row_sparse, 'row_sparse') = row_sparse
Example::
dense = [[ 0., 1., 0.],
[ 2., 0., 3.],
[ 0., 0., 0.],
[ 0., 0., 0.]]
# cast to row_sparse storage type
rsp = cast_storage(dense, 'row_sparse')
rsp.indices = [0, 1]
rsp.values = [[ 0., 1., 0.],
[ 2., 0., 3.]]
# cast to csr storage type
csr = cast_storage(dense, 'csr')
csr.indices = [1, 0, 2]
csr.values = [ 1., 2., 3.]
csr.indptr = [0, 1, 3, 3, 3]
Defined in ../src/operator/tensor/cast_storage.cc:L71
Parameters
----------
data : Symbol
The input.
stype : {'csr', 'default', 'row_sparse'}, required
Output storage type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cbrt(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise cube-root value of the input.
.. math::
cbrt(x) = \sqrt[3]{x}
Example::
cbrt([1, 8, -125]) = [1, 2, -5]
The storage type of ``cbrt`` output depends upon the input storage type:
- cbrt(default) = default
- cbrt(row_sparse) = row_sparse
- cbrt(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L270
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ceil(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise ceiling of the input.
The ceil of the scalar x is the smallest integer i, such that i >= x.
Example::
ceil([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1., 2., 2., 3.]
The storage type of ``ceil`` output depends upon the input storage type:
- ceil(default) = default
- ceil(row_sparse) = row_sparse
- ceil(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L815
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def choose_element_0index(data=None, index=None, axis=_Null, keepdims=_Null, mode=_Null, name=None, attr=None, out=None, **kwargs):
r"""Picks elements from an input array according to the input indices along the given axis.
Given an input array of shape ``(d0, d1)`` and indices of shape ``(i0,)``, the result will be
an output array of shape ``(i0,)`` with::
output[i] = input[i, indices[i]]
By default, if any index mentioned is too large, it is replaced by the index that addresses
the last element along an axis (the `clip` mode).
This function supports n-dimensional input and (n-1)-dimensional indices arrays.
Examples::
x = [[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]
// picks elements with specified indices along axis 0
pick(x, y=[0,1], 0) = [ 1., 4.]
// picks elements with specified indices along axis 1
pick(x, y=[0,1,0], 1) = [ 1., 4., 5.]
// picks elements with specified indices along axis 1 using 'wrap' mode
// to place indicies that would normally be out of bounds
pick(x, y=[2,-1,-2], 1, mode='wrap') = [ 1., 4., 5.]
y = [[ 1.],
[ 0.],
[ 2.]]
// picks elements with specified indices along axis 1 and dims are maintained
pick(x, y, 1, keepdims=True) = [[ 2.],
[ 3.],
[ 6.]]
Defined in ../src/operator/tensor/broadcast_reduce_op_index.cc:L151
Parameters
----------
data : Symbol
The input array
index : Symbol
The index array
axis : int or None, optional, default='-1'
int or None. The axis to picking the elements. Negative values means indexing from right to left. If is `None`, the elements in the index w.r.t the flattened input will be picked.
keepdims : boolean, optional, default=0
If true, the axis where we pick the elements is left in the result as dimension with size one.
mode : {'clip', 'wrap'},optional, default='clip'
Specify how out-of-bound indices behave. Default is "clip". "clip" means clip to the range. So, if all indices mentioned are too large, they are replaced by the index that addresses the last element along an axis. "wrap" means to wrap around.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def clip(data=None, a_min=_Null, a_max=_Null, name=None, attr=None, out=None, **kwargs):
r"""Clips (limits) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges.
Clipping ``x`` between `a_min` and `a_max` would be::
.. math::
clip(x, a_min, a_max) = \max(\min(x, a_max), a_min))
Example::
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
clip(x,1,8) = [ 1., 1., 2., 3., 4., 5., 6., 7., 8., 8.]
The storage type of ``clip`` output depends on storage types of inputs and the a_min, a_max \
parameter values:
- clip(default) = default
- clip(row_sparse, a_min <= 0, a_max >= 0) = row_sparse
- clip(csr, a_min <= 0, a_max >= 0) = csr
- clip(row_sparse, a_min < 0, a_max < 0) = default
- clip(row_sparse, a_min > 0, a_max > 0) = default
- clip(csr, a_min < 0, a_max < 0) = csr
- clip(csr, a_min > 0, a_max > 0) = csr
Defined in ../src/operator/tensor/matrix_op.cc:L693
Parameters
----------
data : Symbol
Input array.
a_min : float, required
Minimum value
a_max : float, required
Maximum value
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def col2im(data=None, output_size=_Null, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, name=None, attr=None, out=None, **kwargs):
r"""Combining the output column matrix of im2col back to image array.
Like :class:`~mxnet.ndarray.im2col`, this operator is also used in the vanilla convolution
implementation. Despite the name, col2im is not the reverse operation of im2col. Since there
may be overlaps between neighbouring sliding blocks, the column elements cannot be directly
put back into image. Instead, they are accumulated (i.e., summed) in the input image
just like the gradient computation, so col2im is the gradient of im2col and vice versa.
Using the notation in im2col, given an input column array of shape
:math:`(N, C \times \prod(\text{kernel}), W)`, this operator accumulates the column elements
into output array of shape :math:`(N, C, \text{output_size}[0], \text{output_size}[1], \dots)`.
Only 1-D, 2-D and 3-D of spatial dimension is supported in this operator.
Defined in ../src/operator/nn/im2col.cc:L182
Parameters
----------
data : Symbol
Input array to combine sliding blocks.
output_size : Shape(tuple), required
The spatial dimension of image array: (w,), (h, w) or (d, h, w).
kernel : Shape(tuple), required
Sliding kernel size: (w,), (h, w) or (d, h, w).
stride : Shape(tuple), optional, default=[]
The stride between adjacent sliding blocks in spatial dimension: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
dilate : Shape(tuple), optional, default=[]
The spacing between adjacent kernel points: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
The zero-value padding size on both sides of spatial dimension: (w,), (h, w) or (d, h, w). Defaults to no padding.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def concat(*data, **kwargs):
r"""Joins input arrays along a given axis.
.. note:: `Concat` is deprecated. Use `concat` instead.
The dimensions of the input arrays should be the same except the axis along
which they will be concatenated.
The dimension of the output array along the concatenated axis will be equal
to the sum of the corresponding dimensions of the input arrays.
The storage type of ``concat`` output depends on storage types of inputs
- concat(csr, csr, ..., csr, dim=0) = csr
- otherwise, ``concat`` generates output with default storage
Example::
x = [[1,1],[2,2]]
y = [[3,3],[4,4],[5,5]]
z = [[6,6], [7,7],[8,8]]
concat(x,y,z,dim=0) = [[ 1., 1.],
[ 2., 2.],
[ 3., 3.],
[ 4., 4.],
[ 5., 5.],
[ 6., 6.],
[ 7., 7.],
[ 8., 8.]]
Note that you cannot concat x,y,z along dimension 1 since dimension
0 is not the same for all the input arrays.
concat(y,z,dim=1) = [[ 3., 3., 6., 6.],
[ 4., 4., 7., 7.],
[ 5., 5., 8., 8.]]
Defined in ../src/operator/nn/concat.cc:L385
This function support variable length of positional input.
Parameters
----------
data : Symbol[]
List of arrays to concatenate
dim : int, optional, default='1'
the dimension to be concated.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cos(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes the element-wise cosine of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
cos([0, \pi/4, \pi/2]) = [1, 0.707, 0]
The storage type of ``cos`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L90
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cosh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the hyperbolic cosine of the input array, computed element-wise.
.. math::
cosh(x) = 0.5\times(exp(x) + exp(-x))
The storage type of ``cosh`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L409
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def crop(data=None, begin=_Null, end=_Null, step=_Null, name=None, attr=None, out=None, **kwargs):
r"""Slices a region of the array.
.. note:: ``crop`` is deprecated. Use ``slice`` instead.
This function returns a sliced array between the indices given
by `begin` and `end` with the corresponding `step`.
For an input array of ``shape=(d_0, d_1, ..., d_n-1)``,
slice operation with ``begin=(b_0, b_1...b_m-1)``,
``end=(e_0, e_1, ..., e_m-1)``, and ``step=(s_0, s_1, ..., s_m-1)``,
where m <= n, results in an array with the shape
``(|e_0-b_0|/|s_0|, ..., |e_m-1-b_m-1|/|s_m-1|, d_m, ..., d_n-1)``.
The resulting array's *k*-th dimension contains elements
from the *k*-th dimension of the input array starting
from index ``b_k`` (inclusive) with step ``s_k``
until reaching ``e_k`` (exclusive).
If the *k*-th elements are `None` in the sequence of `begin`, `end`,
and `step`, the following rule will be used to set default values.
If `s_k` is `None`, set `s_k=1`. If `s_k > 0`, set `b_k=0`, `e_k=d_k`;
else, set `b_k=d_k-1`, `e_k=-1`.
The storage type of ``slice`` output depends on storage types of inputs
- slice(csr) = csr
- otherwise, ``slice`` generates output with default storage
.. note:: When input data storage type is csr, it only supports
step=(), or step=(None,), or step=(1,) to generate a csr output.
For other step parameter values, it falls back to slicing
a dense tensor.
Example::
x = [[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]
slice(x, begin=(0,1), end=(2,4)) = [[ 2., 3., 4.],
[ 6., 7., 8.]]
slice(x, begin=(None, 0), end=(None, 3), step=(-1, 2)) = [[9., 11.],
[5., 7.],
[1., 3.]]
Defined in ../src/operator/tensor/matrix_op.cc:L498
Parameters
----------
data : Symbol
Source input
begin : Shape(tuple), required
starting indices for the slice operation, supports negative indices.
end : Shape(tuple), required
ending indices for the slice operation, supports negative indices.
step : Shape(tuple), optional, default=[]
step for the slice operation, supports negative values.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ctc_loss(data=None, label=None, data_lengths=None, label_lengths=None, use_data_lengths=_Null, use_label_lengths=_Null, blank_label=_Null, name=None, attr=None, out=None, **kwargs):
r"""Connectionist Temporal Classification Loss.
.. note:: The existing alias ``contrib_CTCLoss`` is deprecated.
The shapes of the inputs and outputs:
- **data**: `(sequence_length, batch_size, alphabet_size)`
- **label**: `(batch_size, label_sequence_length)`
- **out**: `(batch_size)`
The `data` tensor consists of sequences of activation vectors (without applying softmax),
with i-th channel in the last dimension corresponding to i-th label
for i between 0 and alphabet_size-1 (i.e always 0-indexed).
Alphabet size should include one additional value reserved for blank label.
When `blank_label` is ``"first"``, the ``0``-th channel is be reserved for
activation of blank label, or otherwise if it is "last", ``(alphabet_size-1)``-th channel should be
reserved for blank label.
``label`` is an index matrix of integers. When `blank_label` is ``"first"``,
the value 0 is then reserved for blank label, and should not be passed in this matrix. Otherwise,
when `blank_label` is ``"last"``, the value `(alphabet_size-1)` is reserved for blank label.
If a sequence of labels is shorter than *label_sequence_length*, use the special
padding value at the end of the sequence to conform it to the correct
length. The padding value is `0` when `blank_label` is ``"first"``, and `-1` otherwise.
For example, suppose the vocabulary is `[a, b, c]`, and in one batch we have three sequences
'ba', 'cbb', and 'abac'. When `blank_label` is ``"first"``, we can index the labels as
`{'a': 1, 'b': 2, 'c': 3}`, and we reserve the 0-th channel for blank label in data tensor.
The resulting `label` tensor should be padded to be::
[[2, 1, 0, 0], [3, 2, 2, 0], [1, 2, 1, 3]]
When `blank_label` is ``"last"``, we can index the labels as
`{'a': 0, 'b': 1, 'c': 2}`, and we reserve the channel index 3 for blank label in data tensor.
The resulting `label` tensor should be padded to be::
[[1, 0, -1, -1], [2, 1, 1, -1], [0, 1, 0, 2]]
``out`` is a list of CTC loss values, one per example in the batch.
See *Connectionist Temporal Classification: Labelling Unsegmented
Sequence Data with Recurrent Neural Networks*, A. Graves *et al*. for more
information on the definition and the algorithm.
Defined in ../src/operator/nn/ctc_loss.cc:L100
Parameters
----------
data : Symbol
Input ndarray
label : Symbol
Ground-truth labels for the loss.
data_lengths : Symbol
Lengths of data for each of the samples. Only required when use_data_lengths is true.
label_lengths : Symbol
Lengths of labels for each of the samples. Only required when use_label_lengths is true.
use_data_lengths : boolean, optional, default=0
Whether the data lenghts are decided by `data_lengths`. If false, the lengths are equal to the max sequence length.
use_label_lengths : boolean, optional, default=0
Whether the label lenghts are decided by `label_lengths`, or derived from `padding_mask`. If false, the lengths are derived from the first occurrence of the value of `padding_mask`. The value of `padding_mask` is ``0`` when first CTC label is reserved for blank, and ``-1`` when last label is reserved for blank. See `blank_label`.
blank_label : {'first', 'last'},optional, default='first'
Set the label that is reserved for blank label.If "first", 0-th label is reserved, and label values for tokens in the vocabulary are between ``1`` and ``alphabet_size-1``, and the padding mask is ``-1``. If "last", last label value ``alphabet_size-1`` is reserved for blank label instead, and label values for tokens in the vocabulary are between ``0`` and ``alphabet_size-2``, and the padding mask is ``0``.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def cumsum(a=None, axis=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Return the cumulative sum of the elements along a given axis.
Defined in ../src/operator/numpy/np_cumsum.cc:L70
Parameters
----------
a : Symbol
Input ndarray
axis : int or None, optional, default='None'
Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtype : {None, 'float16', 'float32', 'float64', 'int32', 'int64', 'int8'},optional, default='None'
Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def degrees(data=None, name=None, attr=None, out=None, **kwargs):
r"""Converts each element of the input array from radians to degrees.
.. math::
degrees([0, \pi/2, \pi, 3\pi/2, 2\pi]) = [0, 90, 180, 270, 360]
The storage type of ``degrees`` output depends upon the input storage type:
- degrees(default) = default
- degrees(row_sparse) = row_sparse
- degrees(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L332
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def depth_to_space(data=None, block_size=_Null, name=None, attr=None, out=None, **kwargs):
r"""Rearranges(permutes) data from depth into blocks of spatial data.
Similar to ONNX DepthToSpace operator:
https://github.com/onnx/onnx/blob/master/docs/Operators.md#DepthToSpace.
The output is a new tensor where the values from depth dimension are moved in spatial blocks
to height and width dimension. The reverse of this operation is ``space_to_depth``.
.. math::
\begin{gather*}
x \prime = reshape(x, [N, block\_size, block\_size, C / (block\_size ^ 2), H * block\_size, W * block\_size]) \\
x \prime \prime = transpose(x \prime, [0, 3, 4, 1, 5, 2]) \\
y = reshape(x \prime \prime, [N, C / (block\_size ^ 2), H * block\_size, W * block\_size])
\end{gather*}
where :math:`x` is an input tensor with default layout as :math:`[N, C, H, W]`: [batch, channels, height, width]
and :math:`y` is the output tensor of layout :math:`[N, C / (block\_size ^ 2), H * block\_size, W * block\_size]`
Example::
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]]]]
depth_to_space(x, 2) = [[[[0, 6, 1, 7, 2, 8],
[12, 18, 13, 19, 14, 20],
[3, 9, 4, 10, 5, 11],
[15, 21, 16, 22, 17, 23]]]]
Defined in ../src/operator/tensor/matrix_op.cc:L988
Parameters
----------
data : Symbol
Input ndarray
block_size : int, required
Blocks of [block_size. block_size] are moved
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def diag(data=None, k=_Null, axis1=_Null, axis2=_Null, name=None, attr=None, out=None, **kwargs):
r"""Extracts a diagonal or constructs a diagonal array.
``diag``'s behavior depends on the input array dimensions:
- 1-D arrays: constructs a 2-D array with the input as its diagonal, all other elements are zero.
- N-D arrays: extracts the diagonals of the sub-arrays with axes specified by ``axis1`` and ``axis2``.
The output shape would be decided by removing the axes numbered ``axis1`` and ``axis2`` from the
input shape and appending to the result a new axis with the size of the diagonals in question.
For example, when the input shape is `(2, 3, 4, 5)`, ``axis1`` and ``axis2`` are 0 and 2
respectively and ``k`` is 0, the resulting shape would be `(3, 5, 2)`.
Examples::
x = [[1, 2, 3],
[4, 5, 6]]
diag(x) = [1, 5]
diag(x, k=1) = [2, 6]
diag(x, k=-1) = [4]
x = [1, 2, 3]
diag(x) = [[1, 0, 0],
[0, 2, 0],
[0, 0, 3]]
diag(x, k=1) = [[0, 1, 0],
[0, 0, 2],
[0, 0, 0]]
diag(x, k=-1) = [[0, 0, 0],
[1, 0, 0],
[0, 2, 0]]
x = [[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]]
diag(x) = [[1, 7],
[2, 8]]
diag(x, k=1) = [[3],
[4]]
diag(x, axis1=-2, axis2=-1) = [[1, 4],
[5, 8]]
Defined in ../src/operator/tensor/diag_op.cc:L87
Parameters
----------
data : Symbol
Input ndarray
k : int, optional, default='0'
Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal. If input has shape (S0 S1) k must be between -S0 and S1
axis1 : int, optional, default='0'
The first axis of the sub-arrays of interest. Ignored when the input is a 1-D array.
axis2 : int, optional, default='1'
The second axis of the sub-arrays of interest. Ignored when the input is a 1-D array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def dot(lhs=None, rhs=None, transpose_a=_Null, transpose_b=_Null, forward_stype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Dot product of two arrays.
``dot``'s behavior depends on the input array dimensions:
- 1-D arrays: inner product of vectors
- 2-D arrays: matrix multiplication
- N-D arrays: a sum product over the last axis of the first input and the first
axis of the second input
For example, given 3-D ``x`` with shape `(n,m,k)` and ``y`` with shape `(k,r,s)`, the
result array will have shape `(n,m,r,s)`. It is computed by::
dot(x,y)[i,j,a,b] = sum(x[i,j,:]*y[:,a,b])
Example::
x = reshape([0,1,2,3,4,5,6,7], shape=(2,2,2))
y = reshape([7,6,5,4,3,2,1,0], shape=(2,2,2))
dot(x,y)[0,0,1,1] = 0
sum(x[0,0,:]*y[:,1,1]) = 0
The storage type of ``dot`` output depends on storage types of inputs, transpose option and
forward_stype option for output storage type. Implemented sparse operations include:
- dot(default, default, transpose_a=True/False, transpose_b=True/False) = default
- dot(csr, default, transpose_a=True) = default
- dot(csr, default, transpose_a=True) = row_sparse
- dot(csr, default) = default
- dot(csr, row_sparse) = default
- dot(default, csr) = csr (CPU only)
- dot(default, csr, forward_stype='default') = default
- dot(default, csr, transpose_b=True, forward_stype='default') = default
If the combination of input storage types and forward_stype does not match any of the
above patterns, ``dot`` will fallback and generate output with default storage.
.. Note::
If the storage type of the lhs is "csr", the storage type of gradient w.r.t rhs will be
"row_sparse". Only a subset of optimizers support sparse gradients, including SGD, AdaGrad
and Adam. Note that by default lazy updates is turned on, which may perform differently
from standard updates. For more details, please check the Optimization API at:
https://mxnet.incubator.apache.org/api/python/optimization/optimization.html
Defined in ../src/operator/tensor/dot.cc:L77
Parameters
----------
lhs : Symbol
The first input
rhs : Symbol
The second input
transpose_a : boolean, optional, default=0
If true then transpose the first input before dot.
transpose_b : boolean, optional, default=0
If true then transpose the second input before dot.
forward_stype : {None, 'csr', 'default', 'row_sparse'},optional, default='None'
The desired storage type of the forward output given by user, if thecombination of input storage types and this hint does not matchany implemented ones, the dot operator will perform fallback operationand still produce an output of the desired storage type.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def elemwise_add(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Adds arguments element-wise.
The storage type of ``elemwise_add`` output depends on storage types of inputs
- elemwise_add(row_sparse, row_sparse) = row_sparse
- elemwise_add(csr, csr) = csr
- elemwise_add(default, csr) = default
- elemwise_add(csr, default) = default
- elemwise_add(default, rsp) = default
- elemwise_add(rsp, default) = default
- otherwise, ``elemwise_add`` generates output with default storage
Parameters
----------
lhs : Symbol
first input
rhs : Symbol
second input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def elemwise_div(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Divides arguments element-wise.
The storage type of ``elemwise_div`` output is always dense
Parameters
----------
lhs : Symbol
first input
rhs : Symbol
second input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def elemwise_mul(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Multiplies arguments element-wise.
The storage type of ``elemwise_mul`` output depends on storage types of inputs
- elemwise_mul(default, default) = default
- elemwise_mul(row_sparse, row_sparse) = row_sparse
- elemwise_mul(default, row_sparse) = row_sparse
- elemwise_mul(row_sparse, default) = row_sparse
- elemwise_mul(csr, csr) = csr
- otherwise, ``elemwise_mul`` generates output with default storage
Parameters
----------
lhs : Symbol
first input
rhs : Symbol
second input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def elemwise_sub(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Subtracts arguments element-wise.
The storage type of ``elemwise_sub`` output depends on storage types of inputs
- elemwise_sub(row_sparse, row_sparse) = row_sparse
- elemwise_sub(csr, csr) = csr
- elemwise_sub(default, csr) = default
- elemwise_sub(csr, default) = default
- elemwise_sub(default, rsp) = default
- elemwise_sub(rsp, default) = default
- otherwise, ``elemwise_sub`` generates output with default storage
Parameters
----------
lhs : Symbol
first input
rhs : Symbol
second input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def erf(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise gauss error function of the input.
Example::
erf([0, -1., 10.]) = [0., -0.8427, 1.]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L884
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def erfinv(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse gauss error function of the input.
Example::
erfinv([0, 0.5., -1.]) = [0., 0.4769, -inf]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L906
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def exp(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise exponential value of the input.
.. math::
exp(x) = e^x \approx 2.718^x
Example::
exp([0, 1, 2]) = [1., 2.71828175, 7.38905621]
The storage type of ``exp`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L64
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def expand_dims(data=None, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Inserts a new axis of size 1 into the array shape
For example, given ``x`` with shape ``(2,3,4)``, then ``expand_dims(x, axis=1)``
will return a new array with shape ``(2,1,3,4)``.
Defined in ../src/operator/tensor/matrix_op.cc:L411
Parameters
----------
data : Symbol
Source input
axis : int, required
Position where new axis is to be inserted. Suppose that the input `NDArray`'s dimension is `ndim`, the range of the inserted axis is `[-ndim, ndim]`
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def expm1(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns ``exp(x) - 1`` computed element-wise on the input.
This function provides greater precision than ``exp(x) - 1`` for small values of ``x``.
The storage type of ``expm1`` output depends upon the input storage type:
- expm1(default) = default
- expm1(row_sparse) = row_sparse
- expm1(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L244
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def fill_element_0index(lhs=None, mhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
r"""Fill one element of each line(row for python, column for R/Julia) in lhs according to index indicated by rhs and values indicated by mhs. This function assume rhs uses 0-based index.
Parameters
----------
lhs : NDArray
Left operand to the function.
mhs : NDArray
Middle operand to the function.
rhs : NDArray
Right operand to the function.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def fix(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise rounded value to the nearest \
integer towards zero of the input.
Example::
fix([-2.1, -1.9, 1.9, 2.1]) = [-2., -1., 1., 2.]
The storage type of ``fix`` output depends upon the input storage type:
- fix(default) = default
- fix(row_sparse) = row_sparse
- fix(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L872
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def flatten(data=None, name=None, attr=None, out=None, **kwargs):
r"""Flattens the input array into a 2-D array by collapsing the higher dimensions.
.. note:: `Flatten` is deprecated. Use `flatten` instead.
For an input array with shape ``(d1, d2, ..., dk)``, `flatten` operation reshapes
the input array into an output array of shape ``(d1, d2*...*dk)``.
Note that the behavior of this function is different from numpy.ndarray.flatten,
which behaves similar to mxnet.ndarray.reshape((-1,)).
Example::
x = [[
[1,2,3],
[4,5,6],
[7,8,9]
],
[ [1,2,3],
[4,5,6],
[7,8,9]
]],
flatten(x) = [[ 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[ 1., 2., 3., 4., 5., 6., 7., 8., 9.]]
Defined in ../src/operator/tensor/matrix_op.cc:L250
Parameters
----------
data : Symbol
Input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def flip(data=None, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reverses the order of elements along given axis while preserving array shape.
Note: reverse and flip are equivalent. We use reverse in the following examples.
Examples::
x = [[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]]
reverse(x, axis=0) = [[ 5., 6., 7., 8., 9.],
[ 0., 1., 2., 3., 4.]]
reverse(x, axis=1) = [[ 4., 3., 2., 1., 0.],
[ 9., 8., 7., 6., 5.]]
Defined in ../src/operator/tensor/matrix_op.cc:L848
Parameters
----------
data : Symbol
Input data array
axis : Shape(tuple), required
The axis which to reverse elements.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def floor(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise floor of the input.
The floor of the scalar x is the largest integer i, such that i <= x.
Example::
floor([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-3., -2., 1., 1., 2.]
The storage type of ``floor`` output depends upon the input storage type:
- floor(default) = default
- floor(row_sparse) = row_sparse
- floor(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L834
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ftml_update(weight=None, grad=None, d=None, v=None, z=None, lr=_Null, beta1=_Null, beta2=_Null, epsilon=_Null, t=_Null, wd=_Null, rescale_grad=_Null, clip_grad=_Null, name=None, attr=None, out=None, **kwargs):
r"""The FTML optimizer described in
*FTML - Follow the Moving Leader in Deep Learning*,
available at http://proceedings.mlr.press/v70/zheng17a/zheng17a.pdf.
.. math::
g_t = \nabla J(W_{t-1})\\
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
d_t = \frac{ 1 - \beta_1^t }{ \eta_t } (\sqrt{ \frac{ v_t }{ 1 - \beta_2^t } } + \epsilon)
\sigma_t = d_t - \beta_1 d_{t-1}
z_t = \beta_1 z_{ t-1 } + (1 - \beta_1^t) g_t - \sigma_t W_{t-1}
W_t = - \frac{ z_t }{ d_t }
Defined in ../src/operator/optimizer_op.cc:L638
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
d : Symbol
Internal state ``d_t``
v : Symbol
Internal state ``v_t``
z : Symbol
Internal state ``z_t``
lr : float, required
Learning rate.
beta1 : float, optional, default=0.600000024
Generally close to 0.5.
beta2 : float, optional, default=0.999000013
Generally close to 1.
epsilon : double, optional, default=9.9999999392252903e-09
Epsilon to prevent div 0.
t : int, required
Number of update.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_grad : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ftrl_update(weight=None, grad=None, z=None, n=None, lr=_Null, lamda1=_Null, beta=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for Ftrl optimizer.
Referenced from *Ad Click Prediction: a View from the Trenches*, available at
http://dl.acm.org/citation.cfm?id=2488200.
It updates the weights using::
rescaled_grad = clip(grad * rescale_grad, clip_gradient)
z += rescaled_grad - (sqrt(n + rescaled_grad**2) - sqrt(n)) * weight / learning_rate
n += rescaled_grad**2
w = (sign(z) * lamda1 - z) / ((beta + sqrt(n)) / learning_rate + wd) * (abs(z) > lamda1)
If w, z and n are all of ``row_sparse`` storage type,
only the row slices whose indices appear in grad.indices are updated (for w, z and n)::
for row in grad.indices:
rescaled_grad[row] = clip(grad[row] * rescale_grad, clip_gradient)
z[row] += rescaled_grad[row] - (sqrt(n[row] + rescaled_grad[row]**2) - sqrt(n[row])) * weight[row] / learning_rate
n[row] += rescaled_grad[row]**2
w[row] = (sign(z[row]) * lamda1 - z[row]) / ((beta + sqrt(n[row])) / learning_rate + wd) * (abs(z[row]) > lamda1)
Defined in ../src/operator/optimizer_op.cc:L945
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
z : Symbol
z
n : Symbol
Square of grad
lr : float, required
Learning rate
lamda1 : float, optional, default=0.00999999978
The L1 regularization coefficient.
beta : float, optional, default=1
Per-Coordinate Learning Rate beta.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def gamma(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the gamma function (extension of the factorial function \
to the reals), computed element-wise on the input array.
The storage type of ``gamma`` output is always dense
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def gammaln(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise log of the absolute value of the gamma function \
of the input.
The storage type of ``gammaln`` output is always dense
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def gather_nd(data=None, indices=None, name=None, attr=None, out=None, **kwargs):
r"""Gather elements or slices from `data` and store to a tensor whose
shape is defined by `indices`.
Given `data` with shape `(X_0, X_1, ..., X_{N-1})` and indices with shape
`(M, Y_0, ..., Y_{K-1})`, the output will have shape `(Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1})`,
where `M <= N`. If `M == N`, output shape will simply be `(Y_0, ..., Y_{K-1})`.
The elements in output is defined as follows::
output[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}] = data[indices[0, y_0, ..., y_{K-1}],
...,
indices[M-1, y_0, ..., y_{K-1}],
x_M, ..., x_{N-1}]
Examples::
data = [[0, 1], [2, 3]]
indices = [[1, 1, 0], [0, 1, 0]]
gather_nd(data, indices) = [2, 3, 0]
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
indices = [[0, 1], [1, 0]]
gather_nd(data, indices) = [[3, 4], [5, 6]]
Parameters
----------
data : Symbol
data
indices : Symbol
indices
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def hard_sigmoid(data=None, alpha=_Null, beta=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes hard sigmoid of x element-wise.
.. math::
y = max(0, min(1, alpha * x + beta))
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L161
Parameters
----------
data : Symbol
The input array.
alpha : float, optional, default=0.200000003
Slope of hard sigmoid
beta : float, optional, default=0.5
Bias of hard sigmoid.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def identity(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns a copy of the input.
From:../src/operator/tensor/elemwise_unary_op_basic.cc:244
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def im2col(data=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, name=None, attr=None, out=None, **kwargs):
r"""Extract sliding blocks from input array.
This operator is used in vanilla convolution implementation to transform the sliding
blocks on image to column matrix, then the convolution operation can be computed
by matrix multiplication between column and convolution weight. Due to the close
relation between im2col and convolution, the concept of **kernel**, **stride**,
**dilate** and **pad** in this operator are inherited from convolution operation.
Given the input data of shape :math:`(N, C, *)`, where :math:`N` is the batch size,
:math:`C` is the channel size, and :math:`*` is the arbitrary spatial dimension,
the output column array is always with shape :math:`(N, C \times \prod(\text{kernel}), W)`,
where :math:`C \times \prod(\text{kernel})` is the block size, and :math:`W` is the
block number which is the spatial size of the convolution output with same input parameters.
Only 1-D, 2-D and 3-D of spatial dimension is supported in this operator.
Defined in ../src/operator/nn/im2col.cc:L100
Parameters
----------
data : Symbol
Input array to extract sliding blocks.
kernel : Shape(tuple), required
Sliding kernel size: (w,), (h, w) or (d, h, w).
stride : Shape(tuple), optional, default=[]
The stride between adjacent sliding blocks in spatial dimension: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
dilate : Shape(tuple), optional, default=[]
The spacing between adjacent kernel points: (w,), (h, w) or (d, h, w). Defaults to 1 for each dimension.
pad : Shape(tuple), optional, default=[]
The zero-value padding size on both sides of spatial dimension: (w,), (h, w) or (d, h, w). Defaults to no padding.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def khatri_rao(*args, **kwargs):
r"""Computes the Khatri-Rao product of the input matrices.
Given a collection of :math:`n` input matrices,
.. math::
A_1 \in \mathbb{R}^{M_1 \times M}, \ldots, A_n \in \mathbb{R}^{M_n \times N},
the (column-wise) Khatri-Rao product is defined as the matrix,
.. math::
X = A_1 \otimes \cdots \otimes A_n \in \mathbb{R}^{(M_1 \cdots M_n) \times N},
where the :math:`k` th column is equal to the column-wise outer product
:math:`{A_1}_k \otimes \cdots \otimes {A_n}_k` where :math:`{A_i}_k` is the kth
column of the ith matrix.
Example::
>>> A = mx.nd.array([[1, -1],
>>> [2, -3]])
>>> B = mx.nd.array([[1, 4],
>>> [2, 5],
>>> [3, 6]])
>>> C = mx.nd.khatri_rao(A, B)
>>> print(C.asnumpy())
[[ 1. -4.]
[ 2. -5.]
[ 3. -6.]
[ 2. -12.]
[ 4. -15.]
[ 6. -18.]]
Defined in ../src/operator/contrib/krprod.cc:L108
This function support variable length of positional input.
Parameters
----------
args : Symbol[]
Positional input matrices
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lamb_update_phase1(weight=None, grad=None, mean=None, var=None, beta1=_Null, beta2=_Null, epsilon=_Null, t=_Null, bias_correction=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, name=None, attr=None, out=None, **kwargs):
r"""Phase I of lamb update it performs the following operations and returns g:.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
grad = grad * rescale_grad
if (grad < -clip_gradient)
then
grad = -clip_gradient
if (grad > clip_gradient)
then
grad = clip_gradient
mean = beta1 * mean + (1 - beta1) * grad;
variance = beta2 * variance + (1. - beta2) * grad ^ 2;
if (bias_correction)
then
mean_hat = mean / (1. - beta1^t);
var_hat = var / (1 - beta2^t);
g = mean_hat / (var_hat^(1/2) + epsilon) + wd * weight;
else
g = mean / (var_data^(1/2) + epsilon) + wd * weight;
\end{gather*}
Defined in ../src/operator/optimizer_op.cc:L1022
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mean : Symbol
Moving mean
var : Symbol
Moving variance
beta1 : float, optional, default=0.899999976
The decay rate for the 1st moment estimates.
beta2 : float, optional, default=0.999000013
The decay rate for the 2nd moment estimates.
epsilon : float, optional, default=9.99999997e-07
A small constant for numerical stability.
t : int, required
Index update count.
bias_correction : boolean, optional, default=1
Whether to use bias correction.
wd : float, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lamb_update_phase2(weight=None, g=None, r1=None, r2=None, lr=_Null, lower_bound=_Null, upper_bound=_Null, name=None, attr=None, out=None, **kwargs):
r"""Phase II of lamb update it performs the following operations and updates grad.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
if (lower_bound >= 0)
then
r1 = max(r1, lower_bound)
if (upper_bound >= 0)
then
r1 = max(r1, upper_bound)
if (r1 == 0 or r2 == 0)
then
lr = lr
else
lr = lr * (r1/r2)
weight = weight - lr * g
\end{gather*}
Defined in ../src/operator/optimizer_op.cc:L1061
Parameters
----------
weight : Symbol
Weight
g : Symbol
Output of lamb_update_phase 1
r1 : Symbol
r1
r2 : Symbol
r2
lr : float, required
Learning rate
lower_bound : float, optional, default=-1
Lower limit of norm of weight. If lower_bound <= 0, Lower limit is not set
upper_bound : float, optional, default=-1
Upper limit of norm of weight. If upper_bound <= 0, Upper limit is not set
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lars_multi_mp_sgd_mom_update(*data, **kwargs):
r"""Momentum update function for multi-precision Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \alpha * \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\
W_t = W_{t-1} + v_t
It updates the weights using::
v = momentum * v - learning_rate * gradient
weight += v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
Defined in ../src/operator/lars_multi_sgd.cc:L203
Parameters
----------
data : Symbol[]
Weights, gradients, momentums, learning rates and weight decays
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lars_multi_mp_sgd_update(*data, **kwargs):
r"""Update function for multi-precision Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
Defined in ../src/operator/lars_multi_sgd.cc:L143
Parameters
----------
data : Symbol[]
Weights, gradients, learning rates and weight decays
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lars_multi_sgd_mom_update(*data, **kwargs):
r"""Momentum update function for Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \alpha * \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\
W_t = W_{t-1} + v_t
It updates the weights using::
v = momentum * v - learning_rate * gradient
weight += v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
Defined in ../src/operator/lars_multi_sgd.cc:L94
Parameters
----------
data : Symbol[]
Weights, gradients, momentum, learning rates and weight decays
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def lars_multi_sgd_update(*data, **kwargs):
r"""Update function for Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
Defined in ../src/operator/lars_multi_sgd.cc:L45
Parameters
----------
data : Symbol[]
Weights, gradients, learning rates and weight decays
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_det(A=None, name=None, attr=None, out=None, **kwargs):
r"""Compute the determinant of a matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, *A* is a square matrix. We compute:
*out* = *det(A)*
If *n>2*, *det* is performed separately on the trailing two dimensions
for all inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
.. note:: There is no gradient backwarded when A is non-invertible (which is
equivalent to det(A) = 0) because zero is rarely hit upon in float
point computation and the Jacobi's formula on determinant gradient
is not computationally efficient when A is non-invertible.
Examples::
Single matrix determinant
A = [[1., 4.], [2., 3.]]
det(A) = [-5.]
Batch matrix determinant
A = [[[1., 4.], [2., 3.]],
[[2., 3.], [1., 4.]]]
det(A) = [-5., 5.]
Defined in ../src/operator/tensor/la_op.cc:L975
Parameters
----------
A : Symbol
Tensor of square matrix
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_extractdiag(A=None, offset=_Null, name=None, attr=None, out=None, **kwargs):
r"""Extracts the diagonal entries of a square matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, then *A* represents a single square matrix which diagonal elements get extracted as a 1-dimensional tensor.
If *n>2*, then *A* represents a batch of square matrices on the trailing two dimensions. The extracted diagonals are returned as an *n-1*-dimensional tensor.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix diagonal extraction
A = [[1.0, 2.0],
[3.0, 4.0]]
extractdiag(A) = [1.0, 4.0]
extractdiag(A, 1) = [2.0]
Batch matrix diagonal extraction
A = [[[1.0, 2.0],
[3.0, 4.0]],
[[5.0, 6.0],
[7.0, 8.0]]]
extractdiag(A) = [[1.0, 4.0],
[5.0, 8.0]]
Defined in ../src/operator/tensor/la_op.cc:L495
Parameters
----------
A : Symbol
Tensor of square matrices
offset : int, optional, default='0'
Offset of the diagonal versus the main diagonal. 0 corresponds to the main diagonal, a negative/positive value to diagonals below/above the main diagonal.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_extracttrian(A=None, offset=_Null, lower=_Null, name=None, attr=None, out=None, **kwargs):
r"""Extracts a triangular sub-matrix from a square matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, then *A* represents a single square matrix from which a triangular sub-matrix is extracted as a 1-dimensional tensor.
If *n>2*, then *A* represents a batch of square matrices on the trailing two dimensions. The extracted triangular sub-matrices are returned as an *n-1*-dimensional tensor.
The *offset* and *lower* parameters determine the triangle to be extracted:
- When *offset = 0* either the lower or upper triangle with respect to the main diagonal is extracted depending on the value of parameter *lower*.
- When *offset = k > 0* the upper triangle with respect to the k-th diagonal above the main diagonal is extracted.
- When *offset = k < 0* the lower triangle with respect to the k-th diagonal below the main diagonal is extracted.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single triagonal extraction
A = [[1.0, 2.0],
[3.0, 4.0]]
extracttrian(A) = [1.0, 3.0, 4.0]
extracttrian(A, lower=False) = [1.0, 2.0, 4.0]
extracttrian(A, 1) = [2.0]
extracttrian(A, -1) = [3.0]
Batch triagonal extraction
A = [[[1.0, 2.0],
[3.0, 4.0]],
[[5.0, 6.0],
[7.0, 8.0]]]
extracttrian(A) = [[1.0, 3.0, 4.0],
[5.0, 7.0, 8.0]]
Defined in ../src/operator/tensor/la_op.cc:L605
Parameters
----------
A : Symbol
Tensor of square matrices
offset : int, optional, default='0'
Offset of the diagonal versus the main diagonal. 0 corresponds to the main diagonal, a negative/positive value to diagonals below/above the main diagonal.
lower : boolean, optional, default=1
Refer to the lower triangular matrix if lower=true, refer to the upper otherwise. Only relevant when offset=0
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_gelqf(A=None, name=None, attr=None, out=None, **kwargs):
r"""LQ factorization for general matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, we compute the LQ factorization (LAPACK *gelqf*, followed by *orglq*). *A*
must have shape *(x, y)* with *x <= y*, and must have full rank *=x*. The LQ
factorization consists of *L* with shape *(x, x)* and *Q* with shape *(x, y)*, so
that:
*A* = *L* \* *Q*
Here, *L* is lower triangular (upper triangle equal to zero) with nonzero diagonal,
and *Q* is row-orthonormal, meaning that
*Q* \* *Q*\ :sup:`T`
is equal to the identity matrix of shape *(x, x)*.
If *n>2*, *gelqf* is performed separately on the trailing two dimensions for all
inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single LQ factorization
A = [[1., 2., 3.], [4., 5., 6.]]
Q, L = gelqf(A)
Q = [[-0.26726124, -0.53452248, -0.80178373],
[0.87287156, 0.21821789, -0.43643578]]
L = [[-3.74165739, 0.],
[-8.55235974, 1.96396101]]
Batch LQ factorization
A = [[[1., 2., 3.], [4., 5., 6.]],
[[7., 8., 9.], [10., 11., 12.]]]
Q, L = gelqf(A)
Q = [[[-0.26726124, -0.53452248, -0.80178373],
[0.87287156, 0.21821789, -0.43643578]],
[[-0.50257071, -0.57436653, -0.64616234],
[0.7620735, 0.05862104, -0.64483142]]]
L = [[[-3.74165739, 0.],
[-8.55235974, 1.96396101]],
[[-13.92838828, 0.],
[-19.09768702, 0.52758934]]]
Defined in ../src/operator/tensor/la_op.cc:L798
Parameters
----------
A : Symbol
Tensor of input matrices to be factorized
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_gemm(A=None, B=None, C=None, transpose_a=_Null, transpose_b=_Null, alpha=_Null, beta=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Performs general matrix multiplication and accumulation.
Input are tensors *A*, *B*, *C*, each of dimension *n >= 2* and having the same shape
on the leading *n-2* dimensions.
If *n=2*, the BLAS3 function *gemm* is performed:
*out* = *alpha* \* *op*\ (*A*) \* *op*\ (*B*) + *beta* \* *C*
Here, *alpha* and *beta* are scalar parameters, and *op()* is either the identity or
matrix transposition (depending on *transpose_a*, *transpose_b*).
If *n>2*, *gemm* is performed separately for a batch of matrices. The column indices of the matrices
are given by the last dimensions of the tensors, the row indices by the axis specified with the *axis*
parameter. By default, the trailing two dimensions will be used for matrix encoding.
For a non-default axis parameter, the operation performed is equivalent to a series of swapaxes/gemm/swapaxes
calls. For example let *A*, *B*, *C* be 5 dimensional tensors. Then gemm(*A*, *B*, *C*, axis=1) is equivalent
to the following without the overhead of the additional swapaxis operations::
A1 = swapaxes(A, dim1=1, dim2=3)
B1 = swapaxes(B, dim1=1, dim2=3)
C = swapaxes(C, dim1=1, dim2=3)
C = gemm(A1, B1, C)
C = swapaxis(C, dim1=1, dim2=3)
When the input data is of type float32 and the environment variables MXNET_CUDA_ALLOW_TENSOR_CORE
and MXNET_CUDA_TENSOR_OP_MATH_ALLOW_CONVERSION are set to 1, this operator will try to use
pseudo-float16 precision (float32 math with float16 I/O) precision in order to use
Tensor Cores on suitable NVIDIA GPUs. This can sometimes give significant speedups.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix multiply-add
A = [[1.0, 1.0], [1.0, 1.0]]
B = [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]
C = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
gemm(A, B, C, transpose_b=True, alpha=2.0, beta=10.0)
= [[14.0, 14.0, 14.0], [14.0, 14.0, 14.0]]
Batch matrix multiply-add
A = [[[1.0, 1.0]], [[0.1, 0.1]]]
B = [[[1.0, 1.0]], [[0.1, 0.1]]]
C = [[[10.0]], [[0.01]]]
gemm(A, B, C, transpose_b=True, alpha=2.0 , beta=10.0)
= [[[104.0]], [[0.14]]]
Defined in ../src/operator/tensor/la_op.cc:L89
Parameters
----------
A : Symbol
Tensor of input matrices
B : Symbol
Tensor of input matrices
C : Symbol
Tensor of input matrices
transpose_a : boolean, optional, default=0
Multiply with transposed of first input (A).
transpose_b : boolean, optional, default=0
Multiply with transposed of second input (B).
alpha : double, optional, default=1
Scalar factor multiplied with A*B.
beta : double, optional, default=1
Scalar factor multiplied with C.
axis : int, optional, default='-2'
Axis corresponding to the matrix rows.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_gemm2(A=None, B=None, transpose_a=_Null, transpose_b=_Null, alpha=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Performs general matrix multiplication.
Input are tensors *A*, *B*, each of dimension *n >= 2* and having the same shape
on the leading *n-2* dimensions.
If *n=2*, the BLAS3 function *gemm* is performed:
*out* = *alpha* \* *op*\ (*A*) \* *op*\ (*B*)
Here *alpha* is a scalar parameter and *op()* is either the identity or the matrix
transposition (depending on *transpose_a*, *transpose_b*).
If *n>2*, *gemm* is performed separately for a batch of matrices. The column indices of the matrices
are given by the last dimensions of the tensors, the row indices by the axis specified with the *axis*
parameter. By default, the trailing two dimensions will be used for matrix encoding.
For a non-default axis parameter, the operation performed is equivalent to a series of swapaxes/gemm/swapaxes
calls. For example let *A*, *B* be 5 dimensional tensors. Then gemm(*A*, *B*, axis=1) is equivalent to
the following without the overhead of the additional swapaxis operations::
A1 = swapaxes(A, dim1=1, dim2=3)
B1 = swapaxes(B, dim1=1, dim2=3)
C = gemm2(A1, B1)
C = swapaxis(C, dim1=1, dim2=3)
When the input data is of type float32 and the environment variables MXNET_CUDA_ALLOW_TENSOR_CORE
and MXNET_CUDA_TENSOR_OP_MATH_ALLOW_CONVERSION are set to 1, this operator will try to use
pseudo-float16 precision (float32 math with float16 I/O) precision in order to use
Tensor Cores on suitable NVIDIA GPUs. This can sometimes give significant speedups.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix multiply
A = [[1.0, 1.0], [1.0, 1.0]]
B = [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]
gemm2(A, B, transpose_b=True, alpha=2.0)
= [[4.0, 4.0, 4.0], [4.0, 4.0, 4.0]]
Batch matrix multiply
A = [[[1.0, 1.0]], [[0.1, 0.1]]]
B = [[[1.0, 1.0]], [[0.1, 0.1]]]
gemm2(A, B, transpose_b=True, alpha=2.0)
= [[[4.0]], [[0.04 ]]]
Defined in ../src/operator/tensor/la_op.cc:L163
Parameters
----------
A : Symbol
Tensor of input matrices
B : Symbol
Tensor of input matrices
transpose_a : boolean, optional, default=0
Multiply with transposed of first input (A).
transpose_b : boolean, optional, default=0
Multiply with transposed of second input (B).
alpha : double, optional, default=1
Scalar factor multiplied with A*B.
axis : int, optional, default='-2'
Axis corresponding to the matrix row indices.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_inverse(A=None, name=None, attr=None, out=None, **kwargs):
r"""Compute the inverse of a matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, *A* is a square matrix. We compute:
*out* = *A*\ :sup:`-1`
If *n>2*, *inverse* is performed separately on the trailing two dimensions
for all inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix inverse
A = [[1., 4.], [2., 3.]]
inverse(A) = [[-0.6, 0.8], [0.4, -0.2]]
Batch matrix inverse
A = [[[1., 4.], [2., 3.]],
[[1., 3.], [2., 4.]]]
inverse(A) = [[[-0.6, 0.8], [0.4, -0.2]],
[[-2., 1.5], [1., -0.5]]]
Defined in ../src/operator/tensor/la_op.cc:L920
Parameters
----------
A : Symbol
Tensor of square matrix
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_makediag(A=None, offset=_Null, name=None, attr=None, out=None, **kwargs):
r"""Constructs a square matrix with the input as diagonal.
Input is a tensor *A* of dimension *n >= 1*.
If *n=1*, then *A* represents the diagonal entries of a single square matrix. This matrix will be returned as a 2-dimensional tensor.
If *n>1*, then *A* represents a batch of diagonals of square matrices. The batch of diagonal matrices will be returned as an *n+1*-dimensional tensor.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single diagonal matrix construction
A = [1.0, 2.0]
makediag(A) = [[1.0, 0.0],
[0.0, 2.0]]
makediag(A, 1) = [[0.0, 1.0, 0.0],
[0.0, 0.0, 2.0],
[0.0, 0.0, 0.0]]
Batch diagonal matrix construction
A = [[1.0, 2.0],
[3.0, 4.0]]
makediag(A) = [[[1.0, 0.0],
[0.0, 2.0]],
[[3.0, 0.0],
[0.0, 4.0]]]
Defined in ../src/operator/tensor/la_op.cc:L547
Parameters
----------
A : Symbol
Tensor of diagonal entries
offset : int, optional, default='0'
Offset of the diagonal versus the main diagonal. 0 corresponds to the main diagonal, a negative/positive value to diagonals below/above the main diagonal.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_maketrian(A=None, offset=_Null, lower=_Null, name=None, attr=None, out=None, **kwargs):
r"""Constructs a square matrix with the input representing a specific triangular sub-matrix.
This is basically the inverse of *linalg.extracttrian*. Input is a tensor *A* of dimension *n >= 1*.
If *n=1*, then *A* represents the entries of a triangular matrix which is lower triangular if *offset<0* or *offset=0*, *lower=true*. The resulting matrix is derived by first constructing the square
matrix with the entries outside the triangle set to zero and then adding *offset*-times an additional
diagonal with zero entries to the square matrix.
If *n>1*, then *A* represents a batch of triangular sub-matrices. The batch of corresponding square matrices is returned as an *n+1*-dimensional tensor.
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix construction
A = [1.0, 2.0, 3.0]
maketrian(A) = [[1.0, 0.0],
[2.0, 3.0]]
maketrian(A, lower=false) = [[1.0, 2.0],
[0.0, 3.0]]
maketrian(A, offset=1) = [[0.0, 1.0, 2.0],
[0.0, 0.0, 3.0],
[0.0, 0.0, 0.0]]
maketrian(A, offset=-1) = [[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[2.0, 3.0, 0.0]]
Batch matrix construction
A = [[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]]
maketrian(A) = [[[1.0, 0.0],
[2.0, 3.0]],
[[4.0, 0.0],
[5.0, 6.0]]]
maketrian(A, offset=1) = [[[0.0, 1.0, 2.0],
[0.0, 0.0, 3.0],
[0.0, 0.0, 0.0]],
[[0.0, 4.0, 5.0],
[0.0, 0.0, 6.0],
[0.0, 0.0, 0.0]]]
Defined in ../src/operator/tensor/la_op.cc:L673
Parameters
----------
A : Symbol
Tensor of triangular matrices stored as vectors
offset : int, optional, default='0'
Offset of the diagonal versus the main diagonal. 0 corresponds to the main diagonal, a negative/positive value to diagonals below/above the main diagonal.
lower : boolean, optional, default=1
Refer to the lower triangular matrix if lower=true, refer to the upper otherwise. Only relevant when offset=0
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_potrf(A=None, name=None, attr=None, out=None, **kwargs):
r"""Performs Cholesky factorization of a symmetric positive-definite matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, the Cholesky factor *B* of the symmetric, positive definite matrix *A* is
computed. *B* is triangular (entries of upper or lower triangle are all zero), has
positive diagonal entries, and:
*A* = *B* \* *B*\ :sup:`T` if *lower* = *true*
*A* = *B*\ :sup:`T` \* *B* if *lower* = *false*
If *n>2*, *potrf* is performed separately on the trailing two dimensions for all inputs
(batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix factorization
A = [[4.0, 1.0], [1.0, 4.25]]
potrf(A) = [[2.0, 0], [0.5, 2.0]]
Batch matrix factorization
A = [[[4.0, 1.0], [1.0, 4.25]], [[16.0, 4.0], [4.0, 17.0]]]
potrf(A) = [[[2.0, 0], [0.5, 2.0]], [[4.0, 0], [1.0, 4.0]]]
Defined in ../src/operator/tensor/la_op.cc:L214
Parameters
----------
A : Symbol
Tensor of input matrices to be decomposed
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_potri(A=None, name=None, attr=None, out=None, **kwargs):
r"""Performs matrix inversion from a Cholesky factorization.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, *A* is a triangular matrix (entries of upper or lower triangle are all zero)
with positive diagonal. We compute:
*out* = *A*\ :sup:`-T` \* *A*\ :sup:`-1` if *lower* = *true*
*out* = *A*\ :sup:`-1` \* *A*\ :sup:`-T` if *lower* = *false*
In other words, if *A* is the Cholesky factor of a symmetric positive definite matrix
*B* (obtained by *potrf*), then
*out* = *B*\ :sup:`-1`
If *n>2*, *potri* is performed separately on the trailing two dimensions for all inputs
(batch mode).
.. note:: The operator supports float32 and float64 data types only.
.. note:: Use this operator only if you are certain you need the inverse of *B*, and
cannot use the Cholesky factor *A* (*potrf*), together with backsubstitution
(*trsm*). The latter is numerically much safer, and also cheaper.
Examples::
Single matrix inverse
A = [[2.0, 0], [0.5, 2.0]]
potri(A) = [[0.26563, -0.0625], [-0.0625, 0.25]]
Batch matrix inverse
A = [[[2.0, 0], [0.5, 2.0]], [[4.0, 0], [1.0, 4.0]]]
potri(A) = [[[0.26563, -0.0625], [-0.0625, 0.25]],
[[0.06641, -0.01562], [-0.01562, 0,0625]]]
Defined in ../src/operator/tensor/la_op.cc:L275
Parameters
----------
A : Symbol
Tensor of lower triangular matrices
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_slogdet(A=None, name=None, attr=None, out=None, **kwargs):
r"""Compute the sign and log of the determinant of a matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, *A* is a square matrix. We compute:
*sign* = *sign(det(A))*
*logabsdet* = *log(abs(det(A)))*
If *n>2*, *slogdet* is performed separately on the trailing two dimensions
for all inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
.. note:: The gradient is not properly defined on sign, so the gradient of
it is not backwarded.
.. note:: No gradient is backwarded when A is non-invertible. Please see
the docs of operator det for detail.
Examples::
Single matrix signed log determinant
A = [[2., 3.], [1., 4.]]
sign, logabsdet = slogdet(A)
sign = [1.]
logabsdet = [1.609438]
Batch matrix signed log determinant
A = [[[2., 3.], [1., 4.]],
[[1., 2.], [2., 4.]],
[[1., 2.], [4., 3.]]]
sign, logabsdet = slogdet(A)
sign = [1., 0., -1.]
logabsdet = [1.609438, -inf, 1.609438]
Defined in ../src/operator/tensor/la_op.cc:L1034
Parameters
----------
A : Symbol
Tensor of square matrix
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_sumlogdiag(A=None, name=None, attr=None, out=None, **kwargs):
r"""Computes the sum of the logarithms of the diagonal elements of a square matrix.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, *A* must be square with positive diagonal entries. We sum the natural
logarithms of the diagonal elements, the result has shape (1,).
If *n>2*, *sumlogdiag* is performed separately on the trailing two dimensions for all
inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix reduction
A = [[1.0, 1.0], [1.0, 7.0]]
sumlogdiag(A) = [1.9459]
Batch matrix reduction
A = [[[1.0, 1.0], [1.0, 7.0]], [[3.0, 0], [0, 17.0]]]
sumlogdiag(A) = [1.9459, 3.9318]
Defined in ../src/operator/tensor/la_op.cc:L445
Parameters
----------
A : Symbol
Tensor of square matrices
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_syrk(A=None, transpose=_Null, alpha=_Null, name=None, attr=None, out=None, **kwargs):
r"""Multiplication of matrix with its transpose.
Input is a tensor *A* of dimension *n >= 2*.
If *n=2*, the operator performs the BLAS3 function *syrk*:
*out* = *alpha* \* *A* \* *A*\ :sup:`T`
if *transpose=False*, or
*out* = *alpha* \* *A*\ :sup:`T` \ \* *A*
if *transpose=True*.
If *n>2*, *syrk* is performed separately on the trailing two dimensions for all
inputs (batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix multiply
A = [[1., 2., 3.], [4., 5., 6.]]
syrk(A, alpha=1., transpose=False)
= [[14., 32.],
[32., 77.]]
syrk(A, alpha=1., transpose=True)
= [[17., 22., 27.],
[22., 29., 36.],
[27., 36., 45.]]
Batch matrix multiply
A = [[[1., 1.]], [[0.1, 0.1]]]
syrk(A, alpha=2., transpose=False) = [[[4.]], [[0.04]]]
Defined in ../src/operator/tensor/la_op.cc:L730
Parameters
----------
A : Symbol
Tensor of input matrices
transpose : boolean, optional, default=0
Use transpose of input matrix.
alpha : double, optional, default=1
Scalar factor to be applied to the result.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_trmm(A=None, B=None, transpose=_Null, rightside=_Null, lower=_Null, alpha=_Null, name=None, attr=None, out=None, **kwargs):
r"""Performs multiplication with a lower triangular matrix.
Input are tensors *A*, *B*, each of dimension *n >= 2* and having the same shape
on the leading *n-2* dimensions.
If *n=2*, *A* must be triangular. The operator performs the BLAS3 function
*trmm*:
*out* = *alpha* \* *op*\ (*A*) \* *B*
if *rightside=False*, or
*out* = *alpha* \* *B* \* *op*\ (*A*)
if *rightside=True*. Here, *alpha* is a scalar parameter, and *op()* is either the
identity or the matrix transposition (depending on *transpose*).
If *n>2*, *trmm* is performed separately on the trailing two dimensions for all inputs
(batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single triangular matrix multiply
A = [[1.0, 0], [1.0, 1.0]]
B = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
trmm(A, B, alpha=2.0) = [[2.0, 2.0, 2.0], [4.0, 4.0, 4.0]]
Batch triangular matrix multiply
A = [[[1.0, 0], [1.0, 1.0]], [[1.0, 0], [1.0, 1.0]]]
B = [[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]]]
trmm(A, B, alpha=2.0) = [[[2.0, 2.0, 2.0], [4.0, 4.0, 4.0]],
[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]]
Defined in ../src/operator/tensor/la_op.cc:L333
Parameters
----------
A : Symbol
Tensor of lower triangular matrices
B : Symbol
Tensor of matrices
transpose : boolean, optional, default=0
Use transposed of the triangular matrix
rightside : boolean, optional, default=0
Multiply triangular matrix from the right to non-triangular one.
lower : boolean, optional, default=1
True if the triangular matrix is lower triangular, false if it is upper triangular.
alpha : double, optional, default=1
Scalar factor to be applied to the result.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def linalg_trsm(A=None, B=None, transpose=_Null, rightside=_Null, lower=_Null, alpha=_Null, name=None, attr=None, out=None, **kwargs):
r"""Solves matrix equation involving a lower triangular matrix.
Input are tensors *A*, *B*, each of dimension *n >= 2* and having the same shape
on the leading *n-2* dimensions.
If *n=2*, *A* must be triangular. The operator performs the BLAS3 function
*trsm*, solving for *out* in:
*op*\ (*A*) \* *out* = *alpha* \* *B*
if *rightside=False*, or
*out* \* *op*\ (*A*) = *alpha* \* *B*
if *rightside=True*. Here, *alpha* is a scalar parameter, and *op()* is either the
identity or the matrix transposition (depending on *transpose*).
If *n>2*, *trsm* is performed separately on the trailing two dimensions for all inputs
(batch mode).
.. note:: The operator supports float32 and float64 data types only.
Examples::
Single matrix solve
A = [[1.0, 0], [1.0, 1.0]]
B = [[2.0, 2.0, 2.0], [4.0, 4.0, 4.0]]
trsm(A, B, alpha=0.5) = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
Batch matrix solve
A = [[[1.0, 0], [1.0, 1.0]], [[1.0, 0], [1.0, 1.0]]]
B = [[[2.0, 2.0, 2.0], [4.0, 4.0, 4.0]],
[[4.0, 4.0, 4.0], [8.0, 8.0, 8.0]]]
trsm(A, B, alpha=0.5) = [[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
[[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]]
Defined in ../src/operator/tensor/la_op.cc:L396
Parameters
----------
A : Symbol
Tensor of lower triangular matrices
B : Symbol
Tensor of matrices
transpose : boolean, optional, default=0
Use transposed of the triangular matrix
rightside : boolean, optional, default=0
Multiply triangular matrix from the right to non-triangular one.
lower : boolean, optional, default=1
True if the triangular matrix is lower triangular, false if it is upper triangular.
alpha : double, optional, default=1
Scalar factor to be applied to the result.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def log(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise Natural logarithmic value of the input.
The natural logarithm is logarithm in base *e*, so that ``log(exp(x)) = x``
The storage type of ``log`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L77
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def log10(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise Base-10 logarithmic value of the input.
``10**log10(x) = x``
The storage type of ``log10`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L94
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def log1p(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise ``log(1 + x)`` value of the input.
This function is more accurate than ``log(1 + x)`` for small ``x`` so that
:math:`1+x\approx 1`
The storage type of ``log1p`` output depends upon the input storage type:
- log1p(default) = default
- log1p(row_sparse) = row_sparse
- log1p(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L199
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def log2(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise Base-2 logarithmic value of the input.
``2**log2(x) = x``
The storage type of ``log2`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_logexp.cc:L106
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def log_softmax(data=None, axis=_Null, temperature=_Null, dtype=_Null, use_length=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the log softmax of the input.
This is equivalent to computing softmax followed by log.
Examples::
>>> x = mx.nd.array([1, 2, .1])
>>> mx.nd.log_softmax(x).asnumpy()
array([-1.41702998, -0.41702995, -2.31702995], dtype=float32)
>>> x = mx.nd.array( [[1, 2, .1],[.1, 2, 1]] )
>>> mx.nd.log_softmax(x, axis=0).asnumpy()
array([[-0.34115392, -0.69314718, -1.24115396],
[-1.24115396, -0.69314718, -0.34115392]], dtype=float32)
Parameters
----------
data : Symbol
The input array.
axis : int, optional, default='-1'
The axis along which to compute softmax.
temperature : double or None, optional, default=None
Temperature parameter in softmax
dtype : {None, 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None).
use_length : boolean or None, optional, default=0
Whether to use the length input as a mask over the data input.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def logical_not(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the result of logical NOT (!) function
Example:
logical_not([-2., 0., 1.]) = [0., 1., 0.]
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def make_loss(data=None, name=None, attr=None, out=None, **kwargs):
r"""Make your own loss function in network construction.
This operator accepts a customized loss function symbol as a terminal loss and
the symbol should be an operator with no backward dependency.
The output of this function is the gradient of loss with respect to the input data.
For example, if you are a making a cross entropy loss function. Assume ``out`` is the
predicted output and ``label`` is the true label, then the cross entropy can be defined as::
cross_entropy = label * log(out) + (1 - label) * log(1 - out)
loss = make_loss(cross_entropy)
We will need to use ``make_loss`` when we are creating our own loss function or we want to
combine multiple loss functions. Also we may want to stop some variables' gradients
from backpropagation. See more detail in ``BlockGrad`` or ``stop_gradient``.
The storage type of ``make_loss`` output depends upon the input storage type:
- make_loss(default) = default
- make_loss(row_sparse) = row_sparse
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L358
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def max(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the max of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L32
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def max_axis(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the max of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L32
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mean(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the mean of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L84
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def min(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the min of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L47
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def min_axis(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the min of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L47
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def moments(data=None, axes=_Null, keepdims=_Null, name=None, attr=None, out=None, **kwargs):
r"""
Calculate the mean and variance of `data`.
The mean and variance are calculated by aggregating the contents of data across axes.
If x is 1-D and axes = [0] this is just the mean and variance of a vector.
Example:
x = [[1, 2, 3], [4, 5, 6]]
mean, var = moments(data=x, axes=[0])
mean = [2.5, 3.5, 4.5]
var = [2.25, 2.25, 2.25]
mean, var = moments(data=x, axes=[1])
mean = [2.0, 5.0]
var = [0.66666667, 0.66666667]
mean, var = moments(data=x, axis=[0, 1])
mean = [3.5]
var = [2.9166667]
Defined in ../src/operator/nn/moments.cc:L54
Parameters
----------
data : Symbol
Input ndarray
axes : Shape or None, optional, default=None
Array of ints. Axes along which to compute mean and variance.
keepdims : boolean, optional, default=0
produce moments with the same dimensionality as the input.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mp_lamb_update_phase1(weight=None, grad=None, mean=None, var=None, weight32=None, beta1=_Null, beta2=_Null, epsilon=_Null, t=_Null, bias_correction=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, name=None, attr=None, out=None, **kwargs):
r"""Mixed Precision version of Phase I of lamb update
it performs the following operations and returns g:.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
grad32 = grad(float16) * rescale_grad
if (grad < -clip_gradient)
then
grad = -clip_gradient
if (grad > clip_gradient)
then
grad = clip_gradient
mean = beta1 * mean + (1 - beta1) * grad;
variance = beta2 * variance + (1. - beta2) * grad ^ 2;
if (bias_correction)
then
mean_hat = mean / (1. - beta1^t);
var_hat = var / (1 - beta2^t);
g = mean_hat / (var_hat^(1/2) + epsilon) + wd * weight32;
else
g = mean / (var_data^(1/2) + epsilon) + wd * weight32;
\end{gather*}
Defined in ../src/operator/optimizer_op.cc:L1102
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mean : Symbol
Moving mean
var : Symbol
Moving variance
weight32 : Symbol
Weight32
beta1 : float, optional, default=0.899999976
The decay rate for the 1st moment estimates.
beta2 : float, optional, default=0.999000013
The decay rate for the 2nd moment estimates.
epsilon : float, optional, default=9.99999997e-07
A small constant for numerical stability.
t : int, required
Index update count.
bias_correction : boolean, optional, default=1
Whether to use bias correction.
wd : float, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mp_lamb_update_phase2(weight=None, g=None, r1=None, r2=None, weight32=None, lr=_Null, lower_bound=_Null, upper_bound=_Null, name=None, attr=None, out=None, **kwargs):
r"""Mixed Precision version Phase II of lamb update
it performs the following operations and updates grad.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
if (lower_bound >= 0)
then
r1 = max(r1, lower_bound)
if (upper_bound >= 0)
then
r1 = max(r1, upper_bound)
if (r1 == 0 or r2 == 0)
then
lr = lr
else
lr = lr * (r1/r2)
weight32 = weight32 - lr * g
weight(float16) = weight32
\end{gather*}
Defined in ../src/operator/optimizer_op.cc:L1144
Parameters
----------
weight : Symbol
Weight
g : Symbol
Output of mp_lamb_update_phase 1
r1 : Symbol
r1
r2 : Symbol
r2
weight32 : Symbol
Weight32
lr : float, required
Learning rate
lower_bound : float, optional, default=-1
Lower limit of norm of weight. If lower_bound <= 0, Lower limit is not set
upper_bound : float, optional, default=-1
Upper limit of norm of weight. If upper_bound <= 0, Upper limit is not set
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mp_nag_mom_update(name=None, attr=None, out=None, **kwargs):
r"""
Parameters
----------
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mp_sgd_mom_update(weight=None, grad=None, mom=None, weight32=None, lr=_Null, momentum=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, lazy_update=_Null, name=None, attr=None, out=None, **kwargs):
r"""Updater function for multi-precision sgd optimizer
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mom : Symbol
Momentum
weight32 : Symbol
Weight32
lr : float, required
Learning rate
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
lazy_update : boolean, optional, default=1
If true, lazy updates are applied if gradient's stype is row_sparse and both weight and momentum have the same stype
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def mp_sgd_update(weight=None, grad=None, weight32=None, lr=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, lazy_update=_Null, name=None, attr=None, out=None, **kwargs):
r"""Updater function for multi-precision sgd optimizer
Parameters
----------
weight : Symbol
Weight
grad : Symbol
gradient
weight32 : Symbol
Weight32
lr : float, required
Learning rate
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
lazy_update : boolean, optional, default=1
If true, lazy updates are applied if gradient's stype is row_sparse.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_all_finite(*data, **kwargs):
r"""Check if all the float numbers in all the arrays are finite (used for AMP)
Defined in ../src/operator/contrib/all_finite.cc:L133
Parameters
----------
data : Symbol[]
Arrays
num_arrays : int, optional, default='1'
Number of arrays.
init_output : boolean, optional, default=1
Initialize output to 1.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_lars(lrs=None, weights_sum_sq=None, grads_sum_sq=None, wds=None, eta=_Null, eps=_Null, rescale_grad=_Null, name=None, attr=None, out=None, **kwargs):
r"""Compute the LARS coefficients of multiple weights and grads from their sums of square"
Defined in ../src/operator/contrib/multi_lars.cc:L37
Parameters
----------
lrs : Symbol
Learning rates to scale by LARS coefficient
weights_sum_sq : Symbol
sum of square of weights arrays
grads_sum_sq : Symbol
sum of square of gradients arrays
wds : Symbol
weight decays
eta : float, required
LARS eta
eps : float, required
LARS eps
rescale_grad : float, optional, default=1
Gradient rescaling factor
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_mp_nag_mom_update(*data, **kwargs):
r"""Update function for multi-precision Nesterov Accelerated Gradient( NAG) optimizer.
Defined in ../src/operator/optimizer_op.cc:L793
Parameters
----------
data : Symbol[]
Weights
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_mp_sgd_mom_update(*data, **kwargs):
r"""Momentum update function for multi-precision Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \nabla J(W_{t-1})\\
W_t = W_{t-1} + \alpha * v_t
It updates the weights using::
v = momentum * v - gradient
weight += learning_rate * v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
Defined in ../src/operator/optimizer_op.cc:L470
Parameters
----------
data : Symbol[]
Weights
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_mp_sgd_update(*data, **kwargs):
r"""Update function for multi-precision Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
Defined in ../src/operator/optimizer_op.cc:L415
Parameters
----------
data : Symbol[]
Weights
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_nag_mom_update(*data, **kwargs):
r"""Update function for Nesterov Accelerated Gradient( NAG) optimizer.
It updates the weights using the following formula,
.. math::
v_t = \gamma v_{t-1} + \eta * \nabla J(W_{t-1} - \gamma v_{t-1})\\
W_t = W_{t-1} - v_t
Where
:math:`\eta` is the learning rate of the optimizer
:math:`\gamma` is the decay rate of the momentum estimate
:math:`\v_t` is the update vector at time step `t`
:math:`\W_t` is the weight vector at time step `t`
Defined in ../src/operator/optimizer_op.cc:L754
Parameters
----------
data : Symbol[]
Weights, gradients and momentum
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_sgd_mom_update(*data, **kwargs):
r"""Momentum update function for Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \nabla J(W_{t-1})\\
W_t = W_{t-1} + \alpha * v_t
It updates the weights using::
v = momentum * v - gradient
weight += learning_rate * v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
Defined in ../src/operator/optimizer_op.cc:L372
Parameters
----------
data : Symbol[]
Weights, gradients and momentum
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_sgd_update(*data, **kwargs):
r"""Update function for Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
Defined in ../src/operator/optimizer_op.cc:L327
Parameters
----------
data : Symbol[]
Weights
lrs : tuple of <float>, required
Learning rates.
wds : tuple of <float>, required
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
num_weights : int, optional, default='1'
Number of updated weights.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def multi_sum_sq(*data, **kwargs):
r"""Compute the sums of squares of multiple arrays
Defined in ../src/operator/contrib/multi_sum_sq.cc:L36
Parameters
----------
data : Symbol[]
Arrays
num_arrays : int, required
number of input arrays.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def nag_mom_update(weight=None, grad=None, mom=None, lr=_Null, momentum=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for Nesterov Accelerated Gradient( NAG) optimizer.
It updates the weights using the following formula,
.. math::
v_t = \gamma v_{t-1} + \eta * \nabla J(W_{t-1} - \gamma v_{t-1})\\
W_t = W_{t-1} - v_t
Where
:math:`\eta` is the learning rate of the optimizer
:math:`\gamma` is the decay rate of the momentum estimate
:math:`\v_t` is the update vector at time step `t`
:math:`\W_t` is the weight vector at time step `t`
Defined in ../src/operator/optimizer_op.cc:L724
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mom : Symbol
Momentum
lr : float, required
Learning rate
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def nanprod(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the product of array elements over given axes treating Not a Numbers (``NaN``) as one.
Defined in ../src/operator/tensor/broadcast_reduce_prod_value.cc:L47
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def nansum(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the sum of array elements over given axes treating Not a Numbers (``NaN``) as zero.
Defined in ../src/operator/tensor/broadcast_reduce_sum_value.cc:L102
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def negative(data=None, name=None, attr=None, out=None, **kwargs):
r"""Numerical negative of the argument, element-wise.
The storage type of ``negative`` output depends upon the input storage type:
- negative(default) = default
- negative(row_sparse) = row_sparse
- negative(csr) = csr
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def norm(data=None, ord=_Null, axis=_Null, out_dtype=_Null, keepdims=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the norm on an NDArray.
This operator computes the norm on an NDArray with the specified axis, depending
on the value of the ord parameter. By default, it computes the L2 norm on the entire
array. Currently only ord=2 supports sparse ndarrays.
Examples::
x = [[[1, 2],
[3, 4]],
[[2, 2],
[5, 6]]]
norm(x, ord=2, axis=1) = [[3.1622777 4.472136 ]
[5.3851647 6.3245554]]
norm(x, ord=1, axis=1) = [[4., 6.],
[7., 8.]]
rsp = x.cast_storage('row_sparse')
norm(rsp) = [5.47722578]
csr = x.cast_storage('csr')
norm(csr) = [5.47722578]
Defined in ../src/operator/tensor/broadcast_reduce_norm_value.cc:L89
Parameters
----------
data : Symbol
The input
ord : int, optional, default='2'
Order of the norm. Currently ord=1 and ord=2 is supported.
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices,
and the matrix norms of these matrices are computed.
out_dtype : {None, 'float16', 'float32', 'float64', 'int32', 'int64', 'int8'},optional, default='None'
The data type of the output.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axis is left in the result as dimension with size one.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def normal(loc=_Null, scale=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a normal (Gaussian) distribution.
.. note:: The existing alias ``normal`` is deprecated.
Samples are distributed according to a normal distribution parametrized by *loc* (mean) and *scale*
(standard deviation).
Example::
normal(loc=0, scale=1, shape=(2,2)) = [[ 1.89171135, -1.16881478],
[-1.23474145, 1.55807114]]
Defined in ../src/operator/random/sample_op.cc:L113
Parameters
----------
loc : float, optional, default=0
Mean of the distribution.
scale : float, optional, default=1
Standard deviation of the distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def one_hot(indices=None, depth=_Null, on_value=_Null, off_value=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns a one-hot array.
The locations represented by `indices` take value `on_value`, while all
other locations take value `off_value`.
`one_hot` operation with `indices` of shape ``(i0, i1)`` and `depth` of ``d`` would result
in an output array of shape ``(i0, i1, d)`` with::
output[i,j,:] = off_value
output[i,j,indices[i,j]] = on_value
Examples::
one_hot([1,0,2,0], 3) = [[ 0. 1. 0.]
[ 1. 0. 0.]
[ 0. 0. 1.]
[ 1. 0. 0.]]
one_hot([1,0,2,0], 3, on_value=8, off_value=1,
dtype='int32') = [[1 8 1]
[8 1 1]
[1 1 8]
[8 1 1]]
one_hot([[1,0],[1,0],[2,0]], 3) = [[[ 0. 1. 0.]
[ 1. 0. 0.]]
[[ 0. 1. 0.]
[ 1. 0. 0.]]
[[ 0. 0. 1.]
[ 1. 0. 0.]]]
Defined in ../src/operator/tensor/indexing_op.cc:L883
Parameters
----------
indices : Symbol
array of locations where to set on_value
depth : int, required
Depth of the one hot dimension.
on_value : double, optional, default=1
The value assigned to the locations represented by indices.
off_value : double, optional, default=0
The value assigned to the locations not represented by indices.
dtype : {'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32'
DType of the output
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ones_like(data=None, name=None, attr=None, out=None, **kwargs):
r"""Return an array of ones with the same shape and type
as the input array.
Examples::
x = [[ 0., 0., 0.],
[ 0., 0., 0.]]
ones_like(x) = [[ 1., 1., 1.],
[ 1., 1., 1.]]
Parameters
----------
data : Symbol
The input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def pad(data=None, mode=_Null, pad_width=_Null, constant_value=_Null, name=None, attr=None, out=None, **kwargs):
r"""Pads an input array with a constant or edge values of the array.
.. note:: `Pad` is deprecated. Use `pad` instead.
.. note:: Current implementation only supports 4D and 5D input arrays with padding applied
only on axes 1, 2 and 3. Expects axes 4 and 5 in `pad_width` to be zero.
This operation pads an input array with either a `constant_value` or edge values
along each axis of the input array. The amount of padding is specified by `pad_width`.
`pad_width` is a tuple of integer padding widths for each axis of the format
``(before_1, after_1, ... , before_N, after_N)``. The `pad_width` should be of length ``2*N``
where ``N`` is the number of dimensions of the array.
For dimension ``N`` of the input array, ``before_N`` and ``after_N`` indicates how many values
to add before and after the elements of the array along dimension ``N``.
The widths of the higher two dimensions ``before_1``, ``after_1``, ``before_2``,
``after_2`` must be 0.
Example::
x = [[[[ 1. 2. 3.]
[ 4. 5. 6.]]
[[ 7. 8. 9.]
[ 10. 11. 12.]]]
[[[ 11. 12. 13.]
[ 14. 15. 16.]]
[[ 17. 18. 19.]
[ 20. 21. 22.]]]]
pad(x,mode="edge", pad_width=(0,0,0,0,1,1,1,1)) =
[[[[ 1. 1. 2. 3. 3.]
[ 1. 1. 2. 3. 3.]
[ 4. 4. 5. 6. 6.]
[ 4. 4. 5. 6. 6.]]
[[ 7. 7. 8. 9. 9.]
[ 7. 7. 8. 9. 9.]
[ 10. 10. 11. 12. 12.]
[ 10. 10. 11. 12. 12.]]]
[[[ 11. 11. 12. 13. 13.]
[ 11. 11. 12. 13. 13.]
[ 14. 14. 15. 16. 16.]
[ 14. 14. 15. 16. 16.]]
[[ 17. 17. 18. 19. 19.]
[ 17. 17. 18. 19. 19.]
[ 20. 20. 21. 22. 22.]
[ 20. 20. 21. 22. 22.]]]]
pad(x, mode="constant", constant_value=0, pad_width=(0,0,0,0,1,1,1,1)) =
[[[[ 0. 0. 0. 0. 0.]
[ 0. 1. 2. 3. 0.]
[ 0. 4. 5. 6. 0.]
[ 0. 0. 0. 0. 0.]]
[[ 0. 0. 0. 0. 0.]
[ 0. 7. 8. 9. 0.]
[ 0. 10. 11. 12. 0.]
[ 0. 0. 0. 0. 0.]]]
[[[ 0. 0. 0. 0. 0.]
[ 0. 11. 12. 13. 0.]
[ 0. 14. 15. 16. 0.]
[ 0. 0. 0. 0. 0.]]
[[ 0. 0. 0. 0. 0.]
[ 0. 17. 18. 19. 0.]
[ 0. 20. 21. 22. 0.]
[ 0. 0. 0. 0. 0.]]]]
Defined in ../src/operator/pad.cc:L766
Parameters
----------
data : Symbol
An n-dimensional input array.
mode : {'constant', 'edge', 'reflect'}, required
Padding type to use. "constant" pads with `constant_value` "edge" pads using the edge values of the input array "reflect" pads by reflecting values with respect to the edges.
pad_width : Shape(tuple), required
Widths of the padding regions applied to the edges of each axis. It is a tuple of integer padding widths for each axis of the format ``(before_1, after_1, ... , before_N, after_N)``. It should be of length ``2*N`` where ``N`` is the number of dimensions of the array.This is equivalent to pad_width in numpy.pad, but flattened.
constant_value : double, optional, default=0
The value used for padding when `mode` is "constant".
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def pick(data=None, index=None, axis=_Null, keepdims=_Null, mode=_Null, name=None, attr=None, out=None, **kwargs):
r"""Picks elements from an input array according to the input indices along the given axis.
Given an input array of shape ``(d0, d1)`` and indices of shape ``(i0,)``, the result will be
an output array of shape ``(i0,)`` with::
output[i] = input[i, indices[i]]
By default, if any index mentioned is too large, it is replaced by the index that addresses
the last element along an axis (the `clip` mode).
This function supports n-dimensional input and (n-1)-dimensional indices arrays.
Examples::
x = [[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]
// picks elements with specified indices along axis 0
pick(x, y=[0,1], 0) = [ 1., 4.]
// picks elements with specified indices along axis 1
pick(x, y=[0,1,0], 1) = [ 1., 4., 5.]
// picks elements with specified indices along axis 1 using 'wrap' mode
// to place indicies that would normally be out of bounds
pick(x, y=[2,-1,-2], 1, mode='wrap') = [ 1., 4., 5.]
y = [[ 1.],
[ 0.],
[ 2.]]
// picks elements with specified indices along axis 1 and dims are maintained
pick(x, y, 1, keepdims=True) = [[ 2.],
[ 3.],
[ 6.]]
Defined in ../src/operator/tensor/broadcast_reduce_op_index.cc:L151
Parameters
----------
data : Symbol
The input array
index : Symbol
The index array
axis : int or None, optional, default='-1'
int or None. The axis to picking the elements. Negative values means indexing from right to left. If is `None`, the elements in the index w.r.t the flattened input will be picked.
keepdims : boolean, optional, default=0
If true, the axis where we pick the elements is left in the result as dimension with size one.
mode : {'clip', 'wrap'},optional, default='clip'
Specify how out-of-bound indices behave. Default is "clip". "clip" means clip to the range. So, if all indices mentioned are too large, they are replaced by the index that addresses the last element along an axis. "wrap" means to wrap around.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def prod(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the product of array elements over given axes.
Defined in ../src/operator/tensor/./broadcast_reduce_op.h:L31
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def radians(data=None, name=None, attr=None, out=None, **kwargs):
r"""Converts each element of the input array from degrees to radians.
.. math::
radians([0, 90, 180, 270, 360]) = [0, \pi/2, \pi, 3\pi/2, 2\pi]
The storage type of ``radians`` output depends upon the input storage type:
- radians(default) = default
- radians(row_sparse) = row_sparse
- radians(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L351
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_exponential(lam=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from an exponential distribution.
Samples are distributed according to an exponential distribution parametrized by *lambda* (rate).
Example::
exponential(lam=4, shape=(2,2)) = [[ 0.0097189 , 0.08999364],
[ 0.04146638, 0.31715935]]
Defined in ../src/operator/random/sample_op.cc:L137
Parameters
----------
lam : float, optional, default=1
Lambda parameter (rate) of the exponential distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_gamma(alpha=_Null, beta=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a gamma distribution.
Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) and *beta* (scale).
Example::
gamma(alpha=9, beta=0.5, shape=(2,2)) = [[ 7.10486984, 3.37695289],
[ 3.91697288, 3.65933681]]
Defined in ../src/operator/random/sample_op.cc:L125
Parameters
----------
alpha : float, optional, default=1
Alpha parameter (shape) of the gamma distribution.
beta : float, optional, default=1
Beta parameter (scale) of the gamma distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_generalized_negative_binomial(mu=_Null, alpha=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a generalized negative binomial distribution.
Samples are distributed according to a generalized negative binomial distribution parametrized by
*mu* (mean) and *alpha* (dispersion). *alpha* is defined as *1/k* where *k* is the failure limit of the
number of unsuccessful experiments (generalized to real numbers).
Samples will always be returned as a floating point data type.
Example::
generalized_negative_binomial(mu=2.0, alpha=0.3, shape=(2,2)) = [[ 2., 1.],
[ 6., 4.]]
Defined in ../src/operator/random/sample_op.cc:L179
Parameters
----------
mu : float, optional, default=1
Mean of the negative binomial distribution.
alpha : float, optional, default=1
Alpha (dispersion) parameter of the negative binomial distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_negative_binomial(k=_Null, p=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a negative binomial distribution.
Samples are distributed according to a negative binomial distribution parametrized by
*k* (limit of unsuccessful experiments) and *p* (failure probability in each experiment).
Samples will always be returned as a floating point data type.
Example::
negative_binomial(k=3, p=0.4, shape=(2,2)) = [[ 4., 7.],
[ 2., 5.]]
Defined in ../src/operator/random/sample_op.cc:L164
Parameters
----------
k : int, optional, default='1'
Limit of unsuccessful experiments.
p : float, optional, default=1
Failure probability in each experiment.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_normal(loc=_Null, scale=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a normal (Gaussian) distribution.
.. note:: The existing alias ``normal`` is deprecated.
Samples are distributed according to a normal distribution parametrized by *loc* (mean) and *scale*
(standard deviation).
Example::
normal(loc=0, scale=1, shape=(2,2)) = [[ 1.89171135, -1.16881478],
[-1.23474145, 1.55807114]]
Defined in ../src/operator/random/sample_op.cc:L113
Parameters
----------
loc : float, optional, default=0
Mean of the distribution.
scale : float, optional, default=1
Standard deviation of the distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_dirichlet(sample=None, alpha=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
Dirichlet distributions with parameter *alpha*.
The shape of *alpha* must match the leftmost subshape of *sample*. That is, *sample*
can have the same shape as *alpha*, in which case the output contains one density per
distribution, or *sample* can be a tensor of tensors with that shape, in which case
the output is a tensor of densities such that the densities at index *i* in the output
are given by the samples at index *i* in *sample* parameterized by the value of *alpha*
at index *i*.
Examples::
random_pdf_dirichlet(sample=[[1,2],[2,3],[3,4]], alpha=[2.5, 2.5]) =
[38.413498, 199.60245, 564.56085]
sample = [[[1, 2, 3], [10, 20, 30], [100, 200, 300]],
[[0.1, 0.2, 0.3], [0.01, 0.02, 0.03], [0.001, 0.002, 0.003]]]
random_pdf_dirichlet(sample=sample, alpha=[0.1, 0.4, 0.9]) =
[[2.3257459e-02, 5.8420084e-04, 1.4674458e-05],
[9.2589635e-01, 3.6860607e+01, 1.4674468e+03]]
Defined in ../src/operator/random/pdf_op.cc:L315
Parameters
----------
sample : Symbol
Samples from the distributions.
alpha : Symbol
Concentration parameters of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_exponential(sample=None, lam=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
exponential distributions with parameters *lam* (rate).
The shape of *lam* must match the leftmost subshape of *sample*. That is, *sample*
can have the same shape as *lam*, in which case the output contains one density per
distribution, or *sample* can be a tensor of tensors with that shape, in which case
the output is a tensor of densities such that the densities at index *i* in the output
are given by the samples at index *i* in *sample* parameterized by the value of *lam*
at index *i*.
Examples::
random_pdf_exponential(sample=[[1, 2, 3]], lam=[1]) =
[[0.36787945, 0.13533528, 0.04978707]]
sample = [[1,2,3],
[1,2,3],
[1,2,3]]
random_pdf_exponential(sample=sample, lam=[1,0.5,0.25]) =
[[0.36787945, 0.13533528, 0.04978707],
[0.30326533, 0.18393973, 0.11156508],
[0.1947002, 0.15163267, 0.11809164]]
Defined in ../src/operator/random/pdf_op.cc:L304
Parameters
----------
sample : Symbol
Samples from the distributions.
lam : Symbol
Lambda (rate) parameters of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_gamma(sample=None, alpha=None, beta=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
gamma distributions with parameters *alpha* (shape) and *beta* (rate).
*alpha* and *beta* must have the same shape, which must match the leftmost subshape
of *sample*. That is, *sample* can have the same shape as *alpha* and *beta*, in which
case the output contains one density per distribution, or *sample* can be a tensor
of tensors with that shape, in which case the output is a tensor of densities such that
the densities at index *i* in the output are given by the samples at index *i* in *sample*
parameterized by the values of *alpha* and *beta* at index *i*.
Examples::
random_pdf_gamma(sample=[[1,2,3,4,5]], alpha=[5], beta=[1]) =
[[0.01532831, 0.09022352, 0.16803136, 0.19536681, 0.17546739]]
sample = [[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7]]
random_pdf_gamma(sample=sample, alpha=[5,6,7], beta=[1,1,1]) =
[[0.01532831, 0.09022352, 0.16803136, 0.19536681, 0.17546739],
[0.03608941, 0.10081882, 0.15629345, 0.17546739, 0.16062315],
[0.05040941, 0.10419563, 0.14622283, 0.16062315, 0.14900276]]
Defined in ../src/operator/random/pdf_op.cc:L301
Parameters
----------
sample : Symbol
Samples from the distributions.
alpha : Symbol
Alpha (shape) parameters of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
beta : Symbol
Beta (scale) parameters of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_generalized_negative_binomial(sample=None, mu=None, alpha=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
generalized negative binomial distributions with parameters *mu* (mean)
and *alpha* (dispersion). This can be understood as a reparameterization of
the negative binomial, where *k* = *1 / alpha* and *p* = *1 / (mu \* alpha + 1)*.
*mu* and *alpha* must have the same shape, which must match the leftmost subshape
of *sample*. That is, *sample* can have the same shape as *mu* and *alpha*, in which
case the output contains one density per distribution, or *sample* can be a tensor
of tensors with that shape, in which case the output is a tensor of densities such that
the densities at index *i* in the output are given by the samples at index *i* in *sample*
parameterized by the values of *mu* and *alpha* at index *i*.
Examples::
random_pdf_generalized_negative_binomial(sample=[[1, 2, 3, 4]], alpha=[1], mu=[1]) =
[[0.25, 0.125, 0.0625, 0.03125]]
sample = [[1,2,3,4],
[1,2,3,4]]
random_pdf_generalized_negative_binomial(sample=sample, alpha=[1, 0.6666], mu=[1, 1.5]) =
[[0.25, 0.125, 0.0625, 0.03125 ],
[0.26517063, 0.16573331, 0.09667706, 0.05437994]]
Defined in ../src/operator/random/pdf_op.cc:L311
Parameters
----------
sample : Symbol
Samples from the distributions.
mu : Symbol
Means of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
alpha : Symbol
Alpha (dispersion) parameters of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_negative_binomial(sample=None, k=None, p=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of samples of
negative binomial distributions with parameters *k* (failure limit) and *p* (failure probability).
*k* and *p* must have the same shape, which must match the leftmost subshape
of *sample*. That is, *sample* can have the same shape as *k* and *p*, in which
case the output contains one density per distribution, or *sample* can be a tensor
of tensors with that shape, in which case the output is a tensor of densities such that
the densities at index *i* in the output are given by the samples at index *i* in *sample*
parameterized by the values of *k* and *p* at index *i*.
Examples::
random_pdf_negative_binomial(sample=[[1,2,3,4]], k=[1], p=a[0.5]) =
[[0.25, 0.125, 0.0625, 0.03125]]
# Note that k may be real-valued
sample = [[1,2,3,4],
[1,2,3,4]]
random_pdf_negative_binomial(sample=sample, k=[1, 1.5], p=[0.5, 0.5]) =
[[0.25, 0.125, 0.0625, 0.03125 ],
[0.26516506, 0.16572815, 0.09667476, 0.05437956]]
Defined in ../src/operator/random/pdf_op.cc:L308
Parameters
----------
sample : Symbol
Samples from the distributions.
k : Symbol
Limits of unsuccessful experiments.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
p : Symbol
Failure probabilities in each experiment.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_normal(sample=None, mu=None, sigma=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
normal distributions with parameters *mu* (mean) and *sigma* (standard deviation).
*mu* and *sigma* must have the same shape, which must match the leftmost subshape
of *sample*. That is, *sample* can have the same shape as *mu* and *sigma*, in which
case the output contains one density per distribution, or *sample* can be a tensor
of tensors with that shape, in which case the output is a tensor of densities such that
the densities at index *i* in the output are given by the samples at index *i* in *sample*
parameterized by the values of *mu* and *sigma* at index *i*.
Examples::
sample = [[-2, -1, 0, 1, 2]]
random_pdf_normal(sample=sample, mu=[0], sigma=[1]) =
[[0.05399097, 0.24197073, 0.3989423, 0.24197073, 0.05399097]]
random_pdf_normal(sample=sample*2, mu=[0,0], sigma=[1,2]) =
[[0.05399097, 0.24197073, 0.3989423, 0.24197073, 0.05399097],
[0.12098537, 0.17603266, 0.19947115, 0.17603266, 0.12098537]]
Defined in ../src/operator/random/pdf_op.cc:L299
Parameters
----------
sample : Symbol
Samples from the distributions.
mu : Symbol
Means of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
sigma : Symbol
Standard deviations of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_poisson(sample=None, lam=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
Poisson distributions with parameters *lam* (rate).
The shape of *lam* must match the leftmost subshape of *sample*. That is, *sample*
can have the same shape as *lam*, in which case the output contains one density per
distribution, or *sample* can be a tensor of tensors with that shape, in which case
the output is a tensor of densities such that the densities at index *i* in the output
are given by the samples at index *i* in *sample* parameterized by the value of *lam*
at index *i*.
Examples::
random_pdf_poisson(sample=[[0,1,2,3]], lam=[1]) =
[[0.36787945, 0.36787945, 0.18393973, 0.06131324]]
sample = [[0,1,2,3],
[0,1,2,3],
[0,1,2,3]]
random_pdf_poisson(sample=sample, lam=[1,2,3]) =
[[0.36787945, 0.36787945, 0.18393973, 0.06131324],
[0.13533528, 0.27067056, 0.27067056, 0.18044704],
[0.04978707, 0.14936121, 0.22404182, 0.22404182]]
Defined in ../src/operator/random/pdf_op.cc:L306
Parameters
----------
sample : Symbol
Samples from the distributions.
lam : Symbol
Lambda (rate) parameters of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_pdf_uniform(sample=None, low=None, high=None, is_log=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the value of the PDF of *sample* of
uniform distributions on the intervals given by *[low,high)*.
*low* and *high* must have the same shape, which must match the leftmost subshape
of *sample*. That is, *sample* can have the same shape as *low* and *high*, in which
case the output contains one density per distribution, or *sample* can be a tensor
of tensors with that shape, in which case the output is a tensor of densities such that
the densities at index *i* in the output are given by the samples at index *i* in *sample*
parameterized by the values of *low* and *high* at index *i*.
Examples::
random_pdf_uniform(sample=[[1,2,3,4]], low=[0], high=[10]) = [0.1, 0.1, 0.1, 0.1]
sample = [[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]]]
low = [[0, 0],
[0, 0]]
high = [[ 5, 10],
[15, 20]]
random_pdf_uniform(sample=sample, low=low, high=high) =
[[[0.2, 0.2, 0.2 ],
[0.1, 0.1, 0.1 ]],
[[0.06667, 0.06667, 0.06667],
[0.05, 0.05, 0.05 ]]]
Defined in ../src/operator/random/pdf_op.cc:L297
Parameters
----------
sample : Symbol
Samples from the distributions.
low : Symbol
Lower bounds of the distributions.
is_log : boolean, optional, default=0
If set, compute the density of the log-probability instead of the probability.
high : Symbol
Upper bounds of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_poisson(lam=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized by *lambda* (rate).
Samples will always be returned as a floating point data type.
Example::
poisson(lam=4, shape=(2,2)) = [[ 5., 2.],
[ 4., 6.]]
Defined in ../src/operator/random/sample_op.cc:L150
Parameters
----------
lam : float, optional, default=1
Lambda parameter (rate) of the Poisson distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_randint(low=_Null, high=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a discrete uniform distribution.
Samples are uniformly distributed over the half-open interval *[low, high)*
(includes *low*, but excludes *high*).
Example::
randint(low=0, high=5, shape=(2,2)) = [[ 0, 2],
[ 3, 1]]
Defined in ../src/operator/random/sample_op.cc:L194
Parameters
----------
low : long, required
Lower bound of the distribution.
high : long, required
Upper bound of the distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'int32', 'int64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to int32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def random_uniform(low=_Null, high=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a uniform distribution.
.. note:: The existing alias ``uniform`` is deprecated.
Samples are uniformly distributed over the half-open interval *[low, high)*
(includes *low*, but excludes *high*).
Example::
uniform(low=0, high=1, shape=(2,2)) = [[ 0.60276335, 0.85794562],
[ 0.54488319, 0.84725171]]
Defined in ../src/operator/random/sample_op.cc:L96
Parameters
----------
low : float, optional, default=0
Lower bound of the distribution.
high : float, optional, default=1
Upper bound of the distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def ravel_multi_index(data=None, shape=_Null, name=None, attr=None, out=None, **kwargs):
r"""Converts a batch of index arrays into an array of flat indices. The operator follows numpy conventions so a single multi index is given by a column of the input matrix. The leading dimension may be left unspecified by using -1 as placeholder.
Examples::
A = [[3,6,6],[4,5,1]]
ravel(A, shape=(7,6)) = [22,41,37]
ravel(A, shape=(-1,6)) = [22,41,37]
Defined in ../src/operator/tensor/ravel.cc:L42
Parameters
----------
data : Symbol
Batch of multi-indices
shape : Shape(tuple), optional, default=None
Shape of the array into which the multi-indices apply.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def rcbrt(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse cube-root value of the input.
.. math::
rcbrt(x) = 1/\sqrt[3]{x}
Example::
rcbrt([1,8,-125]) = [1.0, 0.5, -0.2]
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L323
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def reciprocal(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the reciprocal of the argument, element-wise.
Calculates 1/x.
Example::
reciprocal([-2, 1, 3, 1.6, 0.2]) = [-0.5, 1.0, 0.33333334, 0.625, 5.0]
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L43
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def relu(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes rectified linear activation.
.. math::
max(features, 0)
The storage type of ``relu`` output depends upon the input storage type:
- relu(default) = default
- relu(row_sparse) = row_sparse
- relu(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L85
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def repeat(data=None, repeats=_Null, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Repeats elements of an array.
By default, ``repeat`` flattens the input array into 1-D and then repeats the
elements::
x = [[ 1, 2],
[ 3, 4]]
repeat(x, repeats=2) = [ 1., 1., 2., 2., 3., 3., 4., 4.]
The parameter ``axis`` specifies the axis along which to perform repeat::
repeat(x, repeats=2, axis=1) = [[ 1., 1., 2., 2.],
[ 3., 3., 4., 4.]]
repeat(x, repeats=2, axis=0) = [[ 1., 2.],
[ 1., 2.],
[ 3., 4.],
[ 3., 4.]]
repeat(x, repeats=2, axis=-1) = [[ 1., 1., 2., 2.],
[ 3., 3., 4., 4.]]
Defined in ../src/operator/tensor/matrix_op.cc:L760
Parameters
----------
data : Symbol
Input data array
repeats : int, required
The number of repetitions for each element.
axis : int or None, optional, default='None'
The axis along which to repeat values. The negative numbers are interpreted counting from the backward. By default, use the flattened input array, and return a flat output array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def reset_arrays(*data, **kwargs):
r"""Set to zero multiple arrays
Defined in ../src/operator/contrib/reset_arrays.cc:L36
Parameters
----------
data : Symbol[]
Arrays
num_arrays : int, required
number of input arrays.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def reshape(data=None, shape=_Null, reverse=_Null, target_shape=_Null, keep_highest=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reshapes the input array.
.. note:: ``Reshape`` is deprecated, use ``reshape``
Given an array and a shape, this function returns a copy of the array in the new shape.
The shape is a tuple of integers such as (2,3,4). The size of the new shape should be same as the size of the input array.
Example::
reshape([1,2,3,4], shape=(2,2)) = [[1,2], [3,4]]
Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}. The significance of each is explained below:
- ``0`` copy this dimension from the input to the output shape.
Example::
- input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)
- input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)
- ``-1`` infers the dimension of the output shape by using the remainder of the input dimensions
keeping the size of the new array same as that of the input array.
At most one dimension of shape can be -1.
Example::
- input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)
- input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)
- input shape = (2,3,4), shape=(-1,), output shape = (24,)
- ``-2`` copy all/remainder of the input dimensions to the output shape.
Example::
- input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)
- input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)
- input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)
- ``-3`` use the product of two consecutive dimensions of the input shape as the output dimension.
Example::
- input shape = (2,3,4), shape = (-3,4), output shape = (6,4)
- input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)
- input shape = (2,3,4), shape = (0,-3), output shape = (2,12)
- input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)
- ``-4`` split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).
Example::
- input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)
- input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)
If the argument `reverse` is set to 1, then the special values are inferred from right to left.
Example::
- without reverse=1, for input shape = (10,5,4), shape = (-1,0), output shape would be (40,5)
- with reverse=1, output shape will be (50,4).
Defined in ../src/operator/tensor/matrix_op.cc:L175
Parameters
----------
data : Symbol
Input data to reshape.
shape : Shape(tuple), optional, default=[]
The target shape
reverse : boolean, optional, default=0
If true then the special values are inferred from right to left
target_shape : Shape(tuple), optional, default=[]
(Deprecated! Use ``shape`` instead.) Target new shape. One and only one dim can be 0, in which case it will be inferred from the rest of dims
keep_highest : boolean, optional, default=0
(Deprecated! Use ``shape`` instead.) Whether keep the highest dim unchanged.If set to true, then the first dim in target_shape is ignored,and always fixed as input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def reshape_like(lhs=None, rhs=None, lhs_begin=_Null, lhs_end=_Null, rhs_begin=_Null, rhs_end=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reshape some or all dimensions of `lhs` to have the same shape as some or all dimensions of `rhs`.
Returns a **view** of the `lhs` array with a new shape without altering any data.
Example::
x = [1, 2, 3, 4, 5, 6]
y = [[0, -4], [3, 2], [2, 2]]
reshape_like(x, y) = [[1, 2], [3, 4], [5, 6]]
More precise control over how dimensions are inherited is achieved by specifying \
slices over the `lhs` and `rhs` array dimensions. Only the sliced `lhs` dimensions \
are reshaped to the `rhs` sliced dimensions, with the non-sliced `lhs` dimensions staying the same.
Examples::
- lhs shape = (30,7), rhs shape = (15,2,4), lhs_begin=0, lhs_end=1, rhs_begin=0, rhs_end=2, output shape = (15,2,7)
- lhs shape = (3, 5), rhs shape = (1,15,4), lhs_begin=0, lhs_end=2, rhs_begin=1, rhs_end=2, output shape = (15)
Negative indices are supported, and `None` can be used for either `lhs_end` or `rhs_end` to indicate the end of the range.
Example::
- lhs shape = (30, 12), rhs shape = (4, 2, 2, 3), lhs_begin=-1, lhs_end=None, rhs_begin=1, rhs_end=None, output shape = (30, 2, 2, 3)
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L511
Parameters
----------
lhs : Symbol
First input.
rhs : Symbol
Second input.
lhs_begin : int or None, optional, default='None'
Defaults to 0. The beginning index along which the lhs dimensions are to be reshaped. Supports negative indices.
lhs_end : int or None, optional, default='None'
Defaults to None. The ending index along which the lhs dimensions are to be used for reshaping. Supports negative indices.
rhs_begin : int or None, optional, default='None'
Defaults to 0. The beginning index along which the rhs dimensions are to be used for reshaping. Supports negative indices.
rhs_end : int or None, optional, default='None'
Defaults to None. The ending index along which the rhs dimensions are to be used for reshaping. Supports negative indices.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def reverse(data=None, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Reverses the order of elements along given axis while preserving array shape.
Note: reverse and flip are equivalent. We use reverse in the following examples.
Examples::
x = [[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]]
reverse(x, axis=0) = [[ 5., 6., 7., 8., 9.],
[ 0., 1., 2., 3., 4.]]
reverse(x, axis=1) = [[ 4., 3., 2., 1., 0.],
[ 9., 8., 7., 6., 5.]]
Defined in ../src/operator/tensor/matrix_op.cc:L848
Parameters
----------
data : Symbol
Input data array
axis : Shape(tuple), required
The axis which to reverse elements.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def rint(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise rounded value to the nearest integer of the input.
.. note::
- For input ``n.5`` ``rint`` returns ``n`` while ``round`` returns ``n+1``.
- For input ``-n.5`` both ``rint`` and ``round`` returns ``-n-1``.
Example::
rint([-1.5, 1.5, -1.9, 1.9, 2.1]) = [-2., 1., -2., 2., 2.]
The storage type of ``rint`` output depends upon the input storage type:
- rint(default) = default
- rint(row_sparse) = row_sparse
- rint(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L796
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def rmsprop_update(weight=None, grad=None, n=None, lr=_Null, gamma1=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, clip_weights=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for `RMSProp` optimizer.
`RMSprop` is a variant of stochastic gradient descent where the gradients are
divided by a cache which grows with the sum of squares of recent gradients?
`RMSProp` is similar to `AdaGrad`, a popular variant of `SGD` which adaptively
tunes the learning rate of each parameter. `AdaGrad` lowers the learning rate for
each parameter monotonically over the course of training.
While this is analytically motivated for convex optimizations, it may not be ideal
for non-convex problems. `RMSProp` deals with this heuristically by allowing the
learning rates to rebound as the denominator decays over time.
Define the Root Mean Square (RMS) error criterion of the gradient as
:math:`RMS[g]_t = \sqrt{E[g^2]_t + \epsilon}`, where :math:`g` represents
gradient and :math:`E[g^2]_t` is the decaying average over past squared gradient.
The :math:`E[g^2]_t` is given by:
.. math::
E[g^2]_t = \gamma * E[g^2]_{t-1} + (1-\gamma) * g_t^2
The update step is
.. math::
\theta_{t+1} = \theta_t - \frac{\eta}{RMS[g]_t} g_t
The RMSProp code follows the version in
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
Tieleman & Hinton, 2012.
Hinton suggests the momentum term :math:`\gamma` to be 0.9 and the learning rate
:math:`\eta` to be 0.001.
Defined in ../src/operator/optimizer_op.cc:L866
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
n : Symbol
n
lr : float, required
Learning rate
gamma1 : float, optional, default=0.949999988
The decay rate of momentum estimates.
epsilon : float, optional, default=9.99999994e-09
A small constant for numerical stability.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
clip_weights : float, optional, default=-1
Clip weights to the range of [-clip_weights, clip_weights] If clip_weights <= 0, weight clipping is turned off. weights = max(min(weights, clip_weights), -clip_weights).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def rmspropalex_update(weight=None, grad=None, n=None, g=None, delta=None, lr=_Null, gamma1=_Null, gamma2=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, clip_weights=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for RMSPropAlex optimizer.
`RMSPropAlex` is non-centered version of `RMSProp`.
Define :math:`E[g^2]_t` is the decaying average over past squared gradient and
:math:`E[g]_t` is the decaying average over past gradient.
.. math::
E[g^2]_t = \gamma_1 * E[g^2]_{t-1} + (1 - \gamma_1) * g_t^2\\
E[g]_t = \gamma_1 * E[g]_{t-1} + (1 - \gamma_1) * g_t\\
\Delta_t = \gamma_2 * \Delta_{t-1} - \frac{\eta}{\sqrt{E[g^2]_t - E[g]_t^2 + \epsilon}} g_t\\
The update step is
.. math::
\theta_{t+1} = \theta_t + \Delta_t
The RMSPropAlex code follows the version in
http://arxiv.org/pdf/1308.0850v5.pdf Eq(38) - Eq(45) by Alex Graves, 2013.
Graves suggests the momentum term :math:`\gamma_1` to be 0.95, :math:`\gamma_2`
to be 0.9 and the learning rate :math:`\eta` to be 0.0001.
Defined in ../src/operator/optimizer_op.cc:L905
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
n : Symbol
n
g : Symbol
g
delta : Symbol
delta
lr : float, required
Learning rate
gamma1 : float, optional, default=0.949999988
Decay rate.
gamma2 : float, optional, default=0.899999976
Decay rate.
epsilon : float, optional, default=9.99999994e-09
A small constant for numerical stability.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
clip_weights : float, optional, default=-1
Clip weights to the range of [-clip_weights, clip_weights] If clip_weights <= 0, weight clipping is turned off. weights = max(min(weights, clip_weights), -clip_weights).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def round(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise rounded value to the nearest integer of the input.
Example::
round([-1.5, 1.5, -1.9, 1.9, 2.1]) = [-2., 2., -2., 2., 2.]
The storage type of ``round`` output depends upon the input storage type:
- round(default) = default
- round(row_sparse) = row_sparse
- round(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L775
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def rsqrt(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise inverse square-root value of the input.
.. math::
rsqrt(x) = 1/\sqrt{x}
Example::
rsqrt([4,9,16]) = [0.5, 0.33333334, 0.25]
The storage type of ``rsqrt`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L221
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_exponential(lam=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
exponential distributions with parameters lambda (rate).
The parameters of the distributions are provided as an input array.
Let *[s]* be the shape of the input array, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input array, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input value at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input array.
Examples::
lam = [ 1.0, 8.5 ]
// Draw a single sample for each distribution
sample_exponential(lam) = [ 0.51837951, 0.09994757]
// Draw a vector containing two samples for each distribution
sample_exponential(lam, shape=(2)) = [[ 0.51837951, 0.19866663],
[ 0.09994757, 0.50447971]]
Defined in ../src/operator/random/multisample_op.cc:L283
Parameters
----------
lam : Symbol
Lambda (rate) parameters of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_gamma(alpha=None, beta=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
gamma distributions with parameters *alpha* (shape) and *beta* (scale).
The parameters of the distributions are provided as input arrays.
Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input values at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input arrays.
Examples::
alpha = [ 0.0, 2.5 ]
beta = [ 1.0, 0.7 ]
// Draw a single sample for each distribution
sample_gamma(alpha, beta) = [ 0. , 2.25797319]
// Draw a vector containing two samples for each distribution
sample_gamma(alpha, beta, shape=(2)) = [[ 0. , 0. ],
[ 2.25797319, 1.70734084]]
Defined in ../src/operator/random/multisample_op.cc:L280
Parameters
----------
alpha : Symbol
Alpha (shape) parameters of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
beta : Symbol
Beta (scale) parameters of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_generalized_negative_binomial(mu=None, alpha=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
generalized negative binomial distributions with parameters *mu* (mean) and *alpha* (dispersion).
The parameters of the distributions are provided as input arrays.
Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input values at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input arrays.
Samples will always be returned as a floating point data type.
Examples::
mu = [ 2.0, 2.5 ]
alpha = [ 1.0, 0.1 ]
// Draw a single sample for each distribution
sample_generalized_negative_binomial(mu, alpha) = [ 0., 3.]
// Draw a vector containing two samples for each distribution
sample_generalized_negative_binomial(mu, alpha, shape=(2)) = [[ 0., 3.],
[ 3., 1.]]
Defined in ../src/operator/random/multisample_op.cc:L290
Parameters
----------
mu : Symbol
Means of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
alpha : Symbol
Alpha (dispersion) parameters of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_multinomial(data=None, shape=_Null, get_prob=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple multinomial distributions.
*data* is an *n* dimensional array whose last dimension has length *k*, where
*k* is the number of possible outcomes of each multinomial distribution. This
operator will draw *shape* samples from each distribution. If shape is empty
one sample will be drawn from each distribution.
If *get_prob* is true, a second array containing log likelihood of the drawn
samples will also be returned. This is usually used for reinforcement learning
where you can provide reward as head gradient for this array to estimate
gradient.
Note that the input distribution must be normalized, i.e. *data* must sum to
1 along its last axis.
Examples::
probs = [[0, 0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1, 0]]
// Draw a single sample for each distribution
sample_multinomial(probs) = [3, 0]
// Draw a vector containing two samples for each distribution
sample_multinomial(probs, shape=(2)) = [[4, 2],
[0, 0]]
// requests log likelihood
sample_multinomial(probs, get_prob=True) = [2, 1], [0.2, 0.3]
Parameters
----------
data : Symbol
Distribution probabilities. Must sum to one on the last axis.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
get_prob : boolean, optional, default=0
Whether to also return the log probability of sampled result. This is usually used for differentiating through stochastic variables, e.g. in reinforcement learning.
dtype : {'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='int32'
DType of the output in case this can't be inferred.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_negative_binomial(k=None, p=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
negative binomial distributions with parameters *k* (failure limit) and *p* (failure probability).
The parameters of the distributions are provided as input arrays.
Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input values at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input arrays.
Samples will always be returned as a floating point data type.
Examples::
k = [ 20, 49 ]
p = [ 0.4 , 0.77 ]
// Draw a single sample for each distribution
sample_negative_binomial(k, p) = [ 15., 16.]
// Draw a vector containing two samples for each distribution
sample_negative_binomial(k, p, shape=(2)) = [[ 15., 50.],
[ 16., 12.]]
Defined in ../src/operator/random/multisample_op.cc:L287
Parameters
----------
k : Symbol
Limits of unsuccessful experiments.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
p : Symbol
Failure probabilities in each experiment.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_normal(mu=None, sigma=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
normal distributions with parameters *mu* (mean) and *sigma* (standard deviation).
The parameters of the distributions are provided as input arrays.
Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input values at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input arrays.
Examples::
mu = [ 0.0, 2.5 ]
sigma = [ 1.0, 3.7 ]
// Draw a single sample for each distribution
sample_normal(mu, sigma) = [-0.56410581, 0.95934606]
// Draw a vector containing two samples for each distribution
sample_normal(mu, sigma, shape=(2)) = [[-0.56410581, 0.2928229 ],
[ 0.95934606, 4.48287058]]
Defined in ../src/operator/random/multisample_op.cc:L278
Parameters
----------
mu : Symbol
Means of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
sigma : Symbol
Standard deviations of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_poisson(lam=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
Poisson distributions with parameters lambda (rate).
The parameters of the distributions are provided as an input array.
Let *[s]* be the shape of the input array, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input array, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input value at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input array.
Samples will always be returned as a floating point data type.
Examples::
lam = [ 1.0, 8.5 ]
// Draw a single sample for each distribution
sample_poisson(lam) = [ 0., 13.]
// Draw a vector containing two samples for each distribution
sample_poisson(lam, shape=(2)) = [[ 0., 4.],
[ 13., 8.]]
Defined in ../src/operator/random/multisample_op.cc:L285
Parameters
----------
lam : Symbol
Lambda (rate) parameters of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sample_uniform(low=None, high=None, shape=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Concurrent sampling from multiple
uniform distributions on the intervals given by *[low,high)*.
The parameters of the distributions are provided as input arrays.
Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
be the shape specified as the parameter of the operator, and *m* be the dimension
of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
will be an *m*-dimensional array that holds randomly drawn samples from the distribution
which is parameterized by the input values at index *i*. If the shape parameter of the
operator is not set, then one sample will be drawn per distribution and the output array
has the same shape as the input arrays.
Examples::
low = [ 0.0, 2.5 ]
high = [ 1.0, 3.7 ]
// Draw a single sample for each distribution
sample_uniform(low, high) = [ 0.40451524, 3.18687344]
// Draw a vector containing two samples for each distribution
sample_uniform(low, high, shape=(2)) = [[ 0.40451524, 0.18017688],
[ 3.18687344, 3.68352246]]
Defined in ../src/operator/random/multisample_op.cc:L276
Parameters
----------
low : Symbol
Lower bounds of the distributions.
shape : Shape(tuple), optional, default=[]
Shape to be sampled from each random distribution.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
high : Symbol
Upper bounds of the distributions.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def scatter_nd(data=None, indices=None, shape=_Null, name=None, attr=None, out=None, **kwargs):
r"""Scatters data into a new tensor according to indices.
Given `data` with shape `(Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1})` and indices with shape
`(M, Y_0, ..., Y_{K-1})`, the output will have shape `(X_0, X_1, ..., X_{N-1})`,
where `M <= N`. If `M == N`, data shape should simply be `(Y_0, ..., Y_{K-1})`.
The elements in output is defined as follows::
output[indices[0, y_0, ..., y_{K-1}],
...,
indices[M-1, y_0, ..., y_{K-1}],
x_M, ..., x_{N-1}] = data[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}]
all other entries in output are 0.
.. warning::
If the indices have duplicates, the result will be non-deterministic and
the gradient of `scatter_nd` will not be correct!!
Examples::
data = [2, 3, 0]
indices = [[1, 1, 0], [0, 1, 0]]
shape = (2, 2)
scatter_nd(data, indices, shape) = [[0, 0], [2, 3]]
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
indices = [[0, 1], [1, 1]]
shape = (2, 2, 2, 2)
scatter_nd(data, indices, shape) = [[[[0, 0],
[0, 0]],
[[1, 2],
[3, 4]]],
[[[0, 0],
[0, 0]],
[[5, 6],
[7, 8]]]]
Parameters
----------
data : Symbol
data
indices : Symbol
indices
shape : Shape(tuple), required
Shape of output.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sgd_mom_update(weight=None, grad=None, mom=None, lr=_Null, momentum=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, lazy_update=_Null, name=None, attr=None, out=None, **kwargs):
r"""Momentum update function for Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \nabla J(W_{t-1})\\
W_t = W_{t-1} + \alpha * v_t
It updates the weights using::
v = momentum * v - gradient
weight += learning_rate * v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
However, if grad's storage type is ``row_sparse``, ``lazy_update`` is True and weight's storage
type is the same as momentum's storage type,
only the row slices whose indices appear in grad.indices are updated (for both weight and momentum)::
for row in gradient.indices:
v[row] = momentum[row] * v[row] - gradient[row]
weight[row] += learning_rate * v[row]
Defined in ../src/operator/optimizer_op.cc:L563
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mom : Symbol
Momentum
lr : float, required
Learning rate
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
lazy_update : boolean, optional, default=1
If true, lazy updates are applied if gradient's stype is row_sparse and both weight and momentum have the same stype
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sgd_update(weight=None, grad=None, lr=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, lazy_update=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for Stochastic Gradient Descent (SGD) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
However, if gradient is of ``row_sparse`` storage type and ``lazy_update`` is True,
only the row slices whose indices appear in grad.indices are updated::
for row in gradient.indices:
weight[row] = weight[row] - learning_rate * (gradient[row] + wd * weight[row])
Defined in ../src/operator/optimizer_op.cc:L522
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
lr : float, required
Learning rate
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
lazy_update : boolean, optional, default=1
If true, lazy updates are applied if gradient's stype is row_sparse.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def shape_array(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns a 1D int64 array containing the shape of data.
Example::
shape_array([[1,2,3,4], [5,6,7,8]]) = [2,4]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L573
Parameters
----------
data : Symbol
Input Array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def shuffle(data=None, name=None, attr=None, out=None, **kwargs):
r"""Randomly shuffle the elements.
This shuffles the array along the first axis.
The order of the elements in each subarray does not change.
For example, if a 2D array is given, the order of the rows randomly changes,
but the order of the elements in each row does not change.
Parameters
----------
data : Symbol
Data to be shuffled.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sigmoid(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes sigmoid of x element-wise.
.. math::
y = 1 / (1 + exp(-x))
The storage type of ``sigmoid`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L119
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sign(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise sign of the input.
Example::
sign([-2, 0, 3]) = [-1, 0, 1]
The storage type of ``sign`` output depends upon the input storage type:
- sign(default) = default
- sign(row_sparse) = row_sparse
- sign(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L758
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def signsgd_update(weight=None, grad=None, lr=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, name=None, attr=None, out=None, **kwargs):
r"""Update function for SignSGD optimizer.
.. math::
g_t = \nabla J(W_{t-1})\\
W_t = W_{t-1} - \eta_t \text{sign}(g_t)
It updates the weights using::
weight = weight - learning_rate * sign(gradient)
.. note::
- sparse ndarray not supported for this optimizer yet.
Defined in ../src/operator/optimizer_op.cc:L63
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
lr : float, required
Learning rate
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def signum_update(weight=None, grad=None, mom=None, lr=_Null, momentum=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, wd_lh=_Null, name=None, attr=None, out=None, **kwargs):
r"""SIGN momentUM (Signum) optimizer.
.. math::
g_t = \nabla J(W_{t-1})\\
m_t = \beta m_{t-1} + (1 - \beta) g_t\\
W_t = W_{t-1} - \eta_t \text{sign}(m_t)
It updates the weights using::
state = momentum * state + (1-momentum) * gradient
weight = weight - learning_rate * sign(state)
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
.. note::
- sparse ndarray not supported for this optimizer yet.
Defined in ../src/operator/optimizer_op.cc:L92
Parameters
----------
weight : Symbol
Weight
grad : Symbol
Gradient
mom : Symbol
Momentum
lr : float, required
Learning rate
momentum : float, optional, default=0
The decay rate of momentum estimates at each epoch.
wd : float, optional, default=0
Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
rescale_grad : float, optional, default=1
Rescale gradient to grad = rescale_grad*grad.
clip_gradient : float, optional, default=-1
Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
wd_lh : float, optional, default=0
The amount of weight decay that does not go into gradient/momentum calculationsotherwise do weight decay algorithmically only.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sin(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes the element-wise sine of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
sin([0, \pi/4, \pi/2]) = [0, 0.707, 1]
The storage type of ``sin`` output depends upon the input storage type:
- sin(default) = default
- sin(row_sparse) = row_sparse
- sin(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L47
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sinh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the hyperbolic sine of the input array, computed element-wise.
.. math::
sinh(x) = 0.5\times(exp(x) - exp(-x))
The storage type of ``sinh`` output depends upon the input storage type:
- sinh(default) = default
- sinh(row_sparse) = row_sparse
- sinh(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L371
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def size_array(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns a 1D int64 array containing the size of data.
Example::
size_array([[1,2,3,4], [5,6,7,8]]) = [8]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L624
Parameters
----------
data : Symbol
Input Array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def slice(data=None, begin=_Null, end=_Null, step=_Null, name=None, attr=None, out=None, **kwargs):
r"""Slices a region of the array.
.. note:: ``crop`` is deprecated. Use ``slice`` instead.
This function returns a sliced array between the indices given
by `begin` and `end` with the corresponding `step`.
For an input array of ``shape=(d_0, d_1, ..., d_n-1)``,
slice operation with ``begin=(b_0, b_1...b_m-1)``,
``end=(e_0, e_1, ..., e_m-1)``, and ``step=(s_0, s_1, ..., s_m-1)``,
where m <= n, results in an array with the shape
``(|e_0-b_0|/|s_0|, ..., |e_m-1-b_m-1|/|s_m-1|, d_m, ..., d_n-1)``.
The resulting array's *k*-th dimension contains elements
from the *k*-th dimension of the input array starting
from index ``b_k`` (inclusive) with step ``s_k``
until reaching ``e_k`` (exclusive).
If the *k*-th elements are `None` in the sequence of `begin`, `end`,
and `step`, the following rule will be used to set default values.
If `s_k` is `None`, set `s_k=1`. If `s_k > 0`, set `b_k=0`, `e_k=d_k`;
else, set `b_k=d_k-1`, `e_k=-1`.
The storage type of ``slice`` output depends on storage types of inputs
- slice(csr) = csr
- otherwise, ``slice`` generates output with default storage
.. note:: When input data storage type is csr, it only supports
step=(), or step=(None,), or step=(1,) to generate a csr output.
For other step parameter values, it falls back to slicing
a dense tensor.
Example::
x = [[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]
slice(x, begin=(0,1), end=(2,4)) = [[ 2., 3., 4.],
[ 6., 7., 8.]]
slice(x, begin=(None, 0), end=(None, 3), step=(-1, 2)) = [[9., 11.],
[5., 7.],
[1., 3.]]
Defined in ../src/operator/tensor/matrix_op.cc:L498
Parameters
----------
data : Symbol
Source input
begin : Shape(tuple), required
starting indices for the slice operation, supports negative indices.
end : Shape(tuple), required
ending indices for the slice operation, supports negative indices.
step : Shape(tuple), optional, default=[]
step for the slice operation, supports negative values.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def slice_axis(data=None, axis=_Null, begin=_Null, end=_Null, name=None, attr=None, out=None, **kwargs):
r"""Slices along a given axis.
Returns an array slice along a given `axis` starting from the `begin` index
to the `end` index.
Examples::
x = [[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]
slice_axis(x, axis=0, begin=1, end=3) = [[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]
slice_axis(x, axis=1, begin=0, end=2) = [[ 1., 2.],
[ 5., 6.],
[ 9., 10.]]
slice_axis(x, axis=1, begin=-3, end=-1) = [[ 2., 3.],
[ 6., 7.],
[ 10., 11.]]
Defined in ../src/operator/tensor/matrix_op.cc:L587
Parameters
----------
data : Symbol
Source input
axis : int, required
Axis along which to be sliced, supports negative indexes.
begin : int, required
The beginning index along the axis to be sliced, supports negative indexes.
end : int or None, required
The ending index along the axis to be sliced, supports negative indexes.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def slice_like(data=None, shape_like=None, axes=_Null, name=None, attr=None, out=None, **kwargs):
r"""Slices a region of the array like the shape of another array.
This function is similar to ``slice``, however, the `begin` are always `0`s
and `end` of specific axes are inferred from the second input `shape_like`.
Given the second `shape_like` input of ``shape=(d_0, d_1, ..., d_n-1)``,
a ``slice_like`` operator with default empty `axes`, it performs the
following operation:
`` out = slice(input, begin=(0, 0, ..., 0), end=(d_0, d_1, ..., d_n-1))``.
When `axes` is not empty, it is used to speficy which axes are being sliced.
Given a 4-d input data, ``slice_like`` operator with ``axes=(0, 2, -1)``
will perform the following operation:
`` out = slice(input, begin=(0, 0, 0, 0), end=(d_0, None, d_2, d_3))``.
Note that it is allowed to have first and second input with different dimensions,
however, you have to make sure the `axes` are specified and not exceeding the
dimension limits.
For example, given `input_1` with ``shape=(2,3,4,5)`` and `input_2` with
``shape=(1,2,3)``, it is not allowed to use:
`` out = slice_like(a, b)`` because ndim of `input_1` is 4, and ndim of `input_2`
is 3.
The following is allowed in this situation:
`` out = slice_like(a, b, axes=(0, 2))``
Example::
x = [[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]
y = [[ 0., 0., 0.],
[ 0., 0., 0.]]
slice_like(x, y) = [[ 1., 2., 3.]
[ 5., 6., 7.]]
slice_like(x, y, axes=(0, 1)) = [[ 1., 2., 3.]
[ 5., 6., 7.]]
slice_like(x, y, axes=(0)) = [[ 1., 2., 3., 4.]
[ 5., 6., 7., 8.]]
slice_like(x, y, axes=(-1)) = [[ 1., 2., 3.]
[ 5., 6., 7.]
[ 9., 10., 11.]]
Defined in ../src/operator/tensor/matrix_op.cc:L641
Parameters
----------
data : Symbol
Source input
shape_like : Symbol
Shape like input
axes : Shape(tuple), optional, default=[]
List of axes on which input data will be sliced according to the corresponding size of the second input. By default will slice on all axes. Negative axes are supported.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def smooth_l1(data=None, scalar=_Null, name=None, attr=None, out=None, **kwargs):
r"""Calculate Smooth L1 Loss(lhs, scalar) by summing
.. math::
f(x) =
\begin{cases}
(\sigma x)^2/2,& \text{if }x < 1/\sigma^2\\
|x|-0.5/\sigma^2,& \text{otherwise}
\end{cases}
where :math:`x` is an element of the tensor *lhs* and :math:`\sigma` is the scalar.
Example::
smooth_l1([1, 2, 3, 4]) = [0.5, 1.5, 2.5, 3.5]
smooth_l1([1, 2, 3, 4], scalar=1) = [0.5, 1.5, 2.5, 3.5]
Defined in ../src/operator/tensor/elemwise_binary_scalar_op_extended.cc:L109
Parameters
----------
data : Symbol
source input
scalar : float
scalar input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def softmax(data=None, length=None, axis=_Null, temperature=_Null, dtype=_Null, use_length=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies the softmax function.
The resulting array contains elements in the range (0,1) and the elements along the given axis sum up to 1.
.. math::
softmax(\mathbf{z/t})_j = \frac{e^{z_j/t}}{\sum_{k=1}^K e^{z_k/t}}
for :math:`j = 1, ..., K`
t is the temperature parameter in softmax function. By default, t equals 1.0
Example::
x = [[ 1. 1. 1.]
[ 1. 1. 1.]]
softmax(x,axis=0) = [[ 0.5 0.5 0.5]
[ 0.5 0.5 0.5]]
softmax(x,axis=1) = [[ 0.33333334, 0.33333334, 0.33333334],
[ 0.33333334, 0.33333334, 0.33333334]]
Defined in ../src/operator/nn/softmax.cc:L136
Parameters
----------
data : Symbol
The input array.
length : Symbol
The length array.
axis : int, optional, default='-1'
The axis along which to compute softmax.
temperature : double or None, optional, default=None
Temperature parameter in softmax
dtype : {None, 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None).
use_length : boolean or None, optional, default=0
Whether to use the length input as a mask over the data input.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def softmax_cross_entropy(data=None, label=None, name=None, attr=None, out=None, **kwargs):
r"""Calculate cross entropy of softmax output and one-hot label.
- This operator computes the cross entropy in two steps:
- Applies softmax function on the input array.
- Computes and returns the cross entropy loss between the softmax output and the labels.
- The softmax function and cross entropy loss is given by:
- Softmax Function:
.. math:: \text{softmax}(x)_i = \frac{exp(x_i)}{\sum_j exp(x_j)}
- Cross Entropy Function:
.. math:: \text{CE(label, output)} = - \sum_i \text{label}_i \log(\text{output}_i)
Example::
x = [[1, 2, 3],
[11, 7, 5]]
label = [2, 0]
softmax(x) = [[0.09003057, 0.24472848, 0.66524094],
[0.97962922, 0.01794253, 0.00242826]]
softmax_cross_entropy(data, label) = - log(0.66524084) - log(0.97962922) = 0.4281871
Defined in ../src/operator/loss_binary_op.cc:L59
Parameters
----------
data : Symbol
Input data
label : Symbol
Input label
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def softmin(data=None, axis=_Null, temperature=_Null, dtype=_Null, use_length=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies the softmin function.
The resulting array contains elements in the range (0,1) and the elements along the given axis sum
up to 1.
.. math::
softmin(\mathbf{z/t})_j = \frac{e^{-z_j/t}}{\sum_{k=1}^K e^{-z_k/t}}
for :math:`j = 1, ..., K`
t is the temperature parameter in softmax function. By default, t equals 1.0
Example::
x = [[ 1. 2. 3.]
[ 3. 2. 1.]]
softmin(x,axis=0) = [[ 0.88079703, 0.5, 0.11920292],
[ 0.11920292, 0.5, 0.88079703]]
softmin(x,axis=1) = [[ 0.66524094, 0.24472848, 0.09003057],
[ 0.09003057, 0.24472848, 0.66524094]]
Defined in ../src/operator/nn/softmin.cc:L57
Parameters
----------
data : Symbol
The input array.
axis : int, optional, default='-1'
The axis along which to compute softmax.
temperature : double or None, optional, default=None
Temperature parameter in softmax
dtype : {None, 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None).
use_length : boolean or None, optional, default=0
Whether to use the length input as a mask over the data input.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def softsign(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes softsign of x element-wise.
.. math::
y = x / (1 + abs(x))
The storage type of ``softsign`` output is always dense
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L191
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sort(data=None, axis=_Null, is_ascend=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns a sorted copy of an input array along the given axis.
Examples::
x = [[ 1, 4],
[ 3, 1]]
// sorts along the last axis
sort(x) = [[ 1., 4.],
[ 1., 3.]]
// flattens and then sorts
sort(x, axis=None) = [ 1., 1., 3., 4.]
// sorts along the first axis
sort(x, axis=0) = [[ 1., 1.],
[ 3., 4.]]
// in a descend order
sort(x, is_ascend=0) = [[ 4., 1.],
[ 3., 1.]]
Defined in ../src/operator/tensor/ordering_op.cc:L133
Parameters
----------
data : Symbol
The input array
axis : int or None, optional, default='-1'
Axis along which to choose sort the input tensor. If not given, the flattened array is used. Default is -1.
is_ascend : boolean, optional, default=1
Whether to sort in ascending or descending order.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def space_to_depth(data=None, block_size=_Null, name=None, attr=None, out=None, **kwargs):
r"""Rearranges(permutes) blocks of spatial data into depth.
Similar to ONNX SpaceToDepth operator:
https://github.com/onnx/onnx/blob/master/docs/Operators.md#SpaceToDepth
The output is a new tensor where the values from height and width dimension are
moved to the depth dimension. The reverse of this operation is ``depth_to_space``.
.. math::
\begin{gather*}
x \prime = reshape(x, [N, C, H / block\_size, block\_size, W / block\_size, block\_size]) \\
x \prime \prime = transpose(x \prime, [0, 3, 5, 1, 2, 4]) \\
y = reshape(x \prime \prime, [N, C * (block\_size ^ 2), H / block\_size, W / block\_size])
\end{gather*}
where :math:`x` is an input tensor with default layout as :math:`[N, C, H, W]`: [batch, channels, height, width]
and :math:`y` is the output tensor of layout :math:`[N, C * (block\_size ^ 2), H / block\_size, W / block\_size]`
Example::
x = [[[[0, 6, 1, 7, 2, 8],
[12, 18, 13, 19, 14, 20],
[3, 9, 4, 10, 5, 11],
[15, 21, 16, 22, 17, 23]]]]
space_to_depth(x, 2) = [[[[0, 1, 2],
[3, 4, 5]],
[[6, 7, 8],
[9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23]]]]
Defined in ../src/operator/tensor/matrix_op.cc:L1035
Parameters
----------
data : Symbol
Input ndarray
block_size : int, required
Blocks of [block_size. block_size] are moved
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def split(data=None, num_outputs=_Null, axis=_Null, squeeze_axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Splits an array along a particular axis into multiple sub-arrays.
.. note:: ``SliceChannel`` is deprecated. Use ``split`` instead.
**Note** that `num_outputs` should evenly divide the length of the axis
along which to split the array.
Example::
x = [[[ 1.]
[ 2.]]
[[ 3.]
[ 4.]]
[[ 5.]
[ 6.]]]
x.shape = (3, 2, 1)
y = split(x, axis=1, num_outputs=2) // a list of 2 arrays with shape (3, 1, 1)
y = [[[ 1.]]
[[ 3.]]
[[ 5.]]]
[[[ 2.]]
[[ 4.]]
[[ 6.]]]
y[0].shape = (3, 1, 1)
z = split(x, axis=0, num_outputs=3) // a list of 3 arrays with shape (1, 2, 1)
z = [[[ 1.]
[ 2.]]]
[[[ 3.]
[ 4.]]]
[[[ 5.]
[ 6.]]]
z[0].shape = (1, 2, 1)
`squeeze_axis=1` removes the axis with length 1 from the shapes of the output arrays.
**Note** that setting `squeeze_axis` to ``1`` removes axis with length 1 only
along the `axis` which it is split.
Also `squeeze_axis` can be set to true only if ``input.shape[axis] == num_outputs``.
Example::
z = split(x, axis=0, num_outputs=3, squeeze_axis=1) // a list of 3 arrays with shape (2, 1)
z = [[ 1.]
[ 2.]]
[[ 3.]
[ 4.]]
[[ 5.]
[ 6.]]
z[0].shape = (2 ,1 )
Defined in ../src/operator/slice_channel.cc:L107
Parameters
----------
data : Symbol
The input
num_outputs : int, required
Number of splits. Note that this should evenly divide the length of the `axis`.
axis : int, optional, default='1'
Axis along which to split.
squeeze_axis : boolean, optional, default=0
If true, Removes the axis with length 1 from the shapes of the output arrays. **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1 only along the `axis` which it is split. Also `squeeze_axis` can be set to ``true`` only if ``input.shape[axis] == num_outputs``.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sqrt(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise square-root value of the input.
.. math::
\textrm{sqrt}(x) = \sqrt{x}
Example::
sqrt([4, 9, 16]) = [2, 3, 4]
The storage type of ``sqrt`` output depends upon the input storage type:
- sqrt(default) = default
- sqrt(row_sparse) = row_sparse
- sqrt(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L170
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def square(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns element-wise squared value of the input.
.. math::
square(x) = x^2
Example::
square([2, 3, 4]) = [4, 9, 16]
The storage type of ``square`` output depends upon the input storage type:
- square(default) = default
- square(row_sparse) = row_sparse
- square(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_pow.cc:L119
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def squeeze(data=None, axis=_Null, name=None, attr=None, out=None, **kwargs):
r"""Remove single-dimensional entries from the shape of an array.
Same behavior of defining the output tensor shape as numpy.squeeze for the most of cases.
See the following note for exception.
Examples::
data = [[[0], [1], [2]]]
squeeze(data) = [0, 1, 2]
squeeze(data, axis=0) = [[0], [1], [2]]
squeeze(data, axis=2) = [[0, 1, 2]]
squeeze(data, axis=(0, 2)) = [0, 1, 2]
.. Note::
The output of this operator will keep at least one dimension not removed. For example,
squeeze([[[4]]]) = [4], while in numpy.squeeze, the output will become a scalar.
Parameters
----------
data : Symbol
data to squeeze
axis : Shape or None, optional, default=None
Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def stack(*data, **kwargs):
r"""Join a sequence of arrays along a new axis.
The axis parameter specifies the index of the new axis in the dimensions of the
result. For example, if axis=0 it will be the first dimension and if axis=-1 it
will be the last dimension.
Examples::
x = [1, 2]
y = [3, 4]
stack(x, y) = [[1, 2],
[3, 4]]
stack(x, y, axis=1) = [[1, 3],
[2, 4]]
This function support variable length of positional input.
Parameters
----------
data : Symbol[]
List of arrays to stack
axis : int, optional, default='0'
The axis in the result array along which the input arrays are stacked.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def stop_gradient(data=None, name=None, attr=None, out=None, **kwargs):
r"""Stops gradient computation.
Stops the accumulated gradient of the inputs from flowing through this operator
in the backward direction. In other words, this operator prevents the contribution
of its inputs to be taken into account for computing gradients.
Example::
v1 = [1, 2]
v2 = [0, 1]
a = Variable('a')
b = Variable('b')
b_stop_grad = stop_gradient(3 * b)
loss = MakeLoss(b_stop_grad + a)
executor = loss.simple_bind(ctx=cpu(), a=(1,2), b=(1,2))
executor.forward(is_train=True, a=v1, b=v2)
executor.outputs
[ 1. 5.]
executor.backward()
executor.grad_arrays
[ 0. 0.]
[ 1. 1.]
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L325
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sum(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the sum of array elements over given axes.
.. Note::
`sum` and `sum_axis` are equivalent.
For ndarray of csr storage type summation along axis 0 and axis 1 is supported.
Setting keepdims or exclude to True will cause a fallback to dense operator.
Example::
data = [[[1, 2], [2, 3], [1, 3]],
[[1, 4], [4, 3], [5, 2]],
[[7, 1], [7, 2], [7, 3]]]
sum(data, axis=1)
[[ 4. 8.]
[ 10. 9.]
[ 21. 6.]]
sum(data, axis=[1,2])
[ 12. 19. 27.]
data = [[1, 2, 0],
[3, 0, 1],
[4, 1, 0]]
csr = cast_storage(data, 'csr')
sum(csr, axis=0)
[ 8. 3. 1.]
sum(csr, axis=1)
[ 3. 4. 5.]
Defined in ../src/operator/tensor/broadcast_reduce_sum_value.cc:L67
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def sum_axis(data=None, axis=_Null, keepdims=_Null, exclude=_Null, name=None, attr=None, out=None, **kwargs):
r"""Computes the sum of array elements over given axes.
.. Note::
`sum` and `sum_axis` are equivalent.
For ndarray of csr storage type summation along axis 0 and axis 1 is supported.
Setting keepdims or exclude to True will cause a fallback to dense operator.
Example::
data = [[[1, 2], [2, 3], [1, 3]],
[[1, 4], [4, 3], [5, 2]],
[[7, 1], [7, 2], [7, 3]]]
sum(data, axis=1)
[[ 4. 8.]
[ 10. 9.]
[ 21. 6.]]
sum(data, axis=[1,2])
[ 12. 19. 27.]
data = [[1, 2, 0],
[3, 0, 1],
[4, 1, 0]]
csr = cast_storage(data, 'csr')
sum(csr, axis=0)
[ 8. 3. 1.]
sum(csr, axis=1)
[ 3. 4. 5.]
Defined in ../src/operator/tensor/broadcast_reduce_sum_value.cc:L67
Parameters
----------
data : Symbol
The input
axis : Shape or None, optional, default=None
The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.
keepdims : boolean, optional, default=0
If this is set to `True`, the reduced axes are left in the result as dimension with size one.
exclude : boolean, optional, default=0
Whether to perform reduction on axis that are NOT in axis instead.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def swapaxes(data=None, dim1=_Null, dim2=_Null, name=None, attr=None, out=None, **kwargs):
r"""Interchanges two axes of an array.
Examples::
x = [[1, 2, 3]])
swapaxes(x, 0, 1) = [[ 1],
[ 2],
[ 3]]
x = [[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]] // (2,2,2) array
swapaxes(x, 0, 2) = [[[ 0, 4],
[ 2, 6]],
[[ 1, 5],
[ 3, 7]]]
Defined in ../src/operator/swapaxis.cc:L70
Parameters
----------
data : Symbol
Input array.
dim1 : int, optional, default='0'
the first axis to be swapped.
dim2 : int, optional, default='0'
the second axis to be swapped.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def take(a=None, indices=None, axis=_Null, mode=_Null, name=None, attr=None, out=None, **kwargs):
r"""Takes elements from an input array along the given axis.
This function slices the input array along a particular axis with the provided indices.
Given data tensor of rank r >= 1, and indices tensor of rank q, gather entries of the axis
dimension of data (by default outer-most one as axis=0) indexed by indices, and concatenates them
in an output tensor of rank q + (r - 1).
Examples::
x = [4. 5. 6.]
// Trivial case, take the second element along the first axis.
take(x, [1]) = [ 5. ]
// The other trivial case, axis=-1, take the third element along the first axis
take(x, [3], axis=-1, mode='clip') = [ 6. ]
x = [[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]
// In this case we will get rows 0 and 1, then 1 and 2. Along axis 0
take(x, [[0,1],[1,2]]) = [[[ 1., 2.],
[ 3., 4.]],
[[ 3., 4.],
[ 5., 6.]]]
// In this case we will get rows 0 and 1, then 1 and 2 (calculated by wrapping around).
// Along axis 1
take(x, [[0, 3], [-1, -2]], axis=1, mode='wrap') = [[[ 1. 2.]
[ 2. 1.]]
[[ 3. 4.]
[ 4. 3.]]
[[ 5. 6.]
[ 6. 5.]]]
The storage type of ``take`` output depends upon the input storage type:
- take(default, default) = default
- take(csr, default, axis=0) = csr
Defined in ../src/operator/tensor/indexing_op.cc:L777
Parameters
----------
a : Symbol
The input array.
indices : Symbol
The indices of the values to be extracted.
axis : int, optional, default='0'
The axis of input array to be taken.For input tensor of rank r, it could be in the range of [-r, r-1]
mode : {'clip', 'raise', 'wrap'},optional, default='clip'
Specify how out-of-bound indices bahave. Default is "clip". "clip" means clip to the range. So, if all indices mentioned are too large, they are replaced by the index that addresses the last element along an axis. "wrap" means to wrap around. "raise" means to raise an error when index out of range.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def tan(data=None, name=None, attr=None, out=None, **kwargs):
r"""Computes the element-wise tangent of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
tan([0, \pi/4, \pi/2]) = [0, 1, -inf]
The storage type of ``tan`` output depends upon the input storage type:
- tan(default) = default
- tan(row_sparse) = row_sparse
- tan(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L140
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def tanh(data=None, name=None, attr=None, out=None, **kwargs):
r"""Returns the hyperbolic tangent of the input array, computed element-wise.
.. math::
tanh(x) = sinh(x) / cosh(x)
The storage type of ``tanh`` output depends upon the input storage type:
- tanh(default) = default
- tanh(row_sparse) = row_sparse
- tanh(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_trig.cc:L451
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def tile(data=None, reps=_Null, name=None, attr=None, out=None, **kwargs):
r"""Repeats the whole array multiple times.
If ``reps`` has length *d*, and input array has dimension of *n*. There are
three cases:
- **n=d**. Repeat *i*-th dimension of the input by ``reps[i]`` times::
x = [[1, 2],
[3, 4]]
tile(x, reps=(2,3)) = [[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.],
[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.]]
- **n>d**. ``reps`` is promoted to length *n* by pre-pending 1's to it. Thus for
an input shape ``(2,3)``, ``repos=(2,)`` is treated as ``(1,2)``::
tile(x, reps=(2,)) = [[ 1., 2., 1., 2.],
[ 3., 4., 3., 4.]]
- **n<d**. The input is promoted to be d-dimensional by prepending new axes. So a
shape ``(2,2)`` array is promoted to ``(1,2,2)`` for 3-D replication::
tile(x, reps=(2,2,3)) = [[[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.],
[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.]],
[[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.],
[ 1., 2., 1., 2., 1., 2.],
[ 3., 4., 3., 4., 3., 4.]]]
Defined in ../src/operator/tensor/matrix_op.cc:L812
Parameters
----------
data : Symbol
Input data array
reps : Shape(tuple), required
The number of times for repeating the tensor a. Each dim size of reps must be a positive integer. If reps has length d, the result will have dimension of max(d, a.ndim); If a.ndim < d, a is promoted to be d-dimensional by prepending new axes. If a.ndim > d, reps is promoted to a.ndim by pre-pending 1's to it.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def topk(data=None, axis=_Null, k=_Null, ret_typ=_Null, is_ascend=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Returns the indices of the top *k* elements in an input array along the given
axis (by default).
If ret_type is set to 'value' returns the value of top *k* elements (instead of indices).
In case of ret_type = 'both', both value and index would be returned.
The returned elements will be sorted.
Examples::
x = [[ 0.3, 0.2, 0.4],
[ 0.1, 0.3, 0.2]]
// returns an index of the largest element on last axis
topk(x) = [[ 2.],
[ 1.]]
// returns the value of top-2 largest elements on last axis
topk(x, ret_typ='value', k=2) = [[ 0.4, 0.3],
[ 0.3, 0.2]]
// returns the value of top-2 smallest elements on last axis
topk(x, ret_typ='value', k=2, is_ascend=1) = [[ 0.2 , 0.3],
[ 0.1 , 0.2]]
// returns the value of top-2 largest elements on axis 0
topk(x, axis=0, ret_typ='value', k=2) = [[ 0.3, 0.3, 0.4],
[ 0.1, 0.2, 0.2]]
// flattens and then returns list of both values and indices
topk(x, ret_typ='both', k=2) = [[[ 0.4, 0.3], [ 0.3, 0.2]] , [[ 2., 0.], [ 1., 2.]]]
Defined in ../src/operator/tensor/ordering_op.cc:L68
Parameters
----------
data : Symbol
The input array
axis : int or None, optional, default='-1'
Axis along which to choose the top k indices. If not given, the flattened array is used. Default is -1.
k : int, optional, default='1'
Number of top elements to select, should be always smaller than or equal to the element number in the given axis. A global sort is performed if set k < 1.
ret_typ : {'both', 'indices', 'mask', 'value'},optional, default='indices'
The return type.
"value" means to return the top k values, "indices" means to return the indices of the top k values, "mask" means to return a mask array containing 0 and 1. 1 means the top k values. "both" means to return a list of both values and indices of top k elements.
is_ascend : boolean, optional, default=0
Whether to choose k largest or k smallest elements. Top K largest elements will be chosen if set to false.
dtype : {'float16', 'float32', 'float64', 'int32', 'int64', 'uint8'},optional, default='float32'
DType of the output indices when ret_typ is "indices" or "both". An error will be raised if the selected data type cannot precisely represent the indices.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def transpose(data=None, axes=_Null, name=None, attr=None, out=None, **kwargs):
r"""Permutes the dimensions of an array.
Examples::
x = [[ 1, 2],
[ 3, 4]]
transpose(x) = [[ 1., 3.],
[ 2., 4.]]
x = [[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]]]
transpose(x) = [[[ 1., 5.],
[ 3., 7.]],
[[ 2., 6.],
[ 4., 8.]]]
transpose(x, axes=(1,0,2)) = [[[ 1., 2.],
[ 5., 6.]],
[[ 3., 4.],
[ 7., 8.]]]
Defined in ../src/operator/tensor/matrix_op.cc:L343
Parameters
----------
data : Symbol
Source input
axes : Shape(tuple), optional, default=[]
Target axis order. By default the axes will be inverted.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def trunc(data=None, name=None, attr=None, out=None, **kwargs):
r"""Return the element-wise truncated value of the input.
The truncated value of the scalar x is the nearest integer i which is closer to
zero than x is. In short, the fractional part of the signed number x is discarded.
Example::
trunc([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1., 1., 1., 2.]
The storage type of ``trunc`` output depends upon the input storage type:
- trunc(default) = default
- trunc(row_sparse) = row_sparse
- trunc(csr) = csr
Defined in ../src/operator/tensor/elemwise_unary_op_basic.cc:L854
Parameters
----------
data : Symbol
The input array.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def uniform(low=_Null, high=_Null, shape=_Null, ctx=_Null, dtype=_Null, name=None, attr=None, out=None, **kwargs):
r"""Draw random samples from a uniform distribution.
.. note:: The existing alias ``uniform`` is deprecated.
Samples are uniformly distributed over the half-open interval *[low, high)*
(includes *low*, but excludes *high*).
Example::
uniform(low=0, high=1, shape=(2,2)) = [[ 0.60276335, 0.85794562],
[ 0.54488319, 0.84725171]]
Defined in ../src/operator/random/sample_op.cc:L96
Parameters
----------
low : float, optional, default=0
Lower bound of the distribution.
high : float, optional, default=1
Upper bound of the distribution.
shape : Shape(tuple), optional, default=None
Shape of the output.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype : {'None', 'float16', 'float32', 'float64'},optional, default='None'
DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def unravel_index(data=None, shape=_Null, name=None, attr=None, out=None, **kwargs):
r"""Converts an array of flat indices into a batch of index arrays. The operator follows numpy conventions so a single multi index is given by a column of the output matrix. The leading dimension may be left unspecified by using -1 as placeholder.
Examples::
A = [22,41,37]
unravel(A, shape=(7,6)) = [[3,6,6],[4,5,1]]
unravel(A, shape=(-1,6)) = [[3,6,6],[4,5,1]]
Defined in ../src/operator/tensor/ravel.cc:L68
Parameters
----------
data : Symbol
Array of flat indices
shape : Shape(tuple), optional, default=None
Shape of the array into which the multi-indices apply.
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def where(condition=None, x=None, y=None, name=None, attr=None, out=None, **kwargs):
r"""Return the elements, either from x or y, depending on the condition.
Given three ndarrays, condition, x, and y, return an ndarray with the elements from x or y,
depending on the elements from condition are true or false. x and y must have the same shape.
If condition has the same shape as x, each element in the output array is from x if the
corresponding element in the condition is true, and from y if false.
If condition does not have the same shape as x, it must be a 1D array whose size is
the same as x's first dimension size. Each row of the output array is from x's row
if the corresponding element from condition is true, and from y's row if false.
Note that all non-zero values are interpreted as ``True`` in condition.
Examples::
x = [[1, 2], [3, 4]]
y = [[5, 6], [7, 8]]
cond = [[0, 1], [-1, 0]]
where(cond, x, y) = [[5, 2], [3, 8]]
csr_cond = cast_storage(cond, 'csr')
where(csr_cond, x, y) = [[5, 2], [3, 8]]
Defined in ../src/operator/tensor/control_flow_op.cc:L57
Parameters
----------
condition : Symbol
condition array
x : Symbol
y : Symbol
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
def zeros_like(data=None, name=None, attr=None, out=None, **kwargs):
r"""Return an array of zeros with the same shape, type and storage type
as the input array.
The storage type of ``zeros_like`` output depends on the storage type of the input
- zeros_like(row_sparse) = row_sparse
- zeros_like(csr) = csr
- zeros_like(default) = default
Examples::
x = [[ 1., 1., 1.],
[ 1., 1., 1.]]
zeros_like(x) = [[ 0., 0., 0.],
[ 0., 0., 0.]]
Parameters
----------
data : Symbol
The input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return (0,)
__all__ = ['Activation', 'BNStatsFinalize', 'BatchNorm', 'BatchNormAddRelu', 'BatchNorm_v1', 'BilinearSampler', 'BlockGrad', 'CTCLoss', 'Cast', 'Concat', 'Convolution', 'Convolution_v1', 'Correlation', 'Crop', 'CuDNNBatchNorm', 'Custom', 'Deconvolution', 'Dropout', 'ElementWiseSum', 'Embedding', 'Flatten', 'FullyConnected', 'GridGenerator', 'GroupNorm', 'IdentityAttachKLSparseReg', 'InstanceNorm', 'InstanceNormV2', 'L2Normalization', 'LRN', 'LayerNorm', 'LeakyReLU', 'LinearRegressionOutput', 'LogisticRegressionOutput', 'MAERegressionOutput', 'MakeLoss', 'NormConvolution', 'NormalizedConvolution', 'Pad', 'Pooling', 'Pooling_v1', 'RNN', 'ROIPooling', 'Reshape', 'SVMOutput', 'ScaleBiasAddRelu', 'SequenceLast', 'SequenceMask', 'SequenceReverse', 'SliceChannel', 'Softmax', 'SoftmaxActivation', 'SoftmaxOutput', 'SpatialParallelConvolution', 'SpatialTransformer', 'SwapAxis', 'UpSampling', 'abs', 'adam_update', 'add_n', 'all_finite', 'amp_cast', 'amp_multicast', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh', 'argmax', 'argmax_channel', 'argmin', 'argsort', 'batch_dot', 'batch_take', 'broadcast_add', 'broadcast_axes', 'broadcast_axis', 'broadcast_div', 'broadcast_equal', 'broadcast_greater', 'broadcast_greater_equal', 'broadcast_hypot', 'broadcast_lesser', 'broadcast_lesser_equal', 'broadcast_like', 'broadcast_logical_and', 'broadcast_logical_or', 'broadcast_logical_xor', 'broadcast_maximum', 'broadcast_minimum', 'broadcast_minus', 'broadcast_mod', 'broadcast_mul', 'broadcast_not_equal', 'broadcast_plus', 'broadcast_power', 'broadcast_sub', 'broadcast_to', 'cast', 'cast_storage', 'cbrt', 'ceil', 'choose_element_0index', 'clip', 'col2im', 'concat', 'cos', 'cosh', 'crop', 'ctc_loss', 'cumsum', 'degrees', 'depth_to_space', 'diag', 'dot', 'elemwise_add', 'elemwise_div', 'elemwise_mul', 'elemwise_sub', 'erf', 'erfinv', 'exp', 'expand_dims', 'expm1', 'fill_element_0index', 'fix', 'flatten', 'flip', 'floor', 'ftml_update', 'ftrl_update', 'gamma', 'gammaln', 'gather_nd', 'hard_sigmoid', 'identity', 'im2col', 'khatri_rao', 'lamb_update_phase1', 'lamb_update_phase2', 'lars_multi_mp_sgd_mom_update', 'lars_multi_mp_sgd_update', 'lars_multi_sgd_mom_update', 'lars_multi_sgd_update', 'linalg_det', 'linalg_extractdiag', 'linalg_extracttrian', 'linalg_gelqf', 'linalg_gemm', 'linalg_gemm2', 'linalg_inverse', 'linalg_makediag', 'linalg_maketrian', 'linalg_potrf', 'linalg_potri', 'linalg_slogdet', 'linalg_sumlogdiag', 'linalg_syrk', 'linalg_trmm', 'linalg_trsm', 'log', 'log10', 'log1p', 'log2', 'log_softmax', 'logical_not', 'make_loss', 'max', 'max_axis', 'mean', 'min', 'min_axis', 'moments', 'mp_lamb_update_phase1', 'mp_lamb_update_phase2', 'mp_nag_mom_update', 'mp_sgd_mom_update', 'mp_sgd_update', 'multi_all_finite', 'multi_lars', 'multi_mp_nag_mom_update', 'multi_mp_sgd_mom_update', 'multi_mp_sgd_update', 'multi_nag_mom_update', 'multi_sgd_mom_update', 'multi_sgd_update', 'multi_sum_sq', 'nag_mom_update', 'nanprod', 'nansum', 'negative', 'norm', 'normal', 'one_hot', 'ones_like', 'pad', 'pick', 'prod', 'radians', 'random_exponential', 'random_gamma', 'random_generalized_negative_binomial', 'random_negative_binomial', 'random_normal', 'random_pdf_dirichlet', 'random_pdf_exponential', 'random_pdf_gamma', 'random_pdf_generalized_negative_binomial', 'random_pdf_negative_binomial', 'random_pdf_normal', 'random_pdf_poisson', 'random_pdf_uniform', 'random_poisson', 'random_randint', 'random_uniform', 'ravel_multi_index', 'rcbrt', 'reciprocal', 'relu', 'repeat', 'reset_arrays', 'reshape', 'reshape_like', 'reverse', 'rint', 'rmsprop_update', 'rmspropalex_update', 'round', 'rsqrt', 'sample_exponential', 'sample_gamma', 'sample_generalized_negative_binomial', 'sample_multinomial', 'sample_negative_binomial', 'sample_normal', 'sample_poisson', 'sample_uniform', 'scatter_nd', 'sgd_mom_update', 'sgd_update', 'shape_array', 'shuffle', 'sigmoid', 'sign', 'signsgd_update', 'signum_update', 'sin', 'sinh', 'size_array', 'slice', 'slice_axis', 'slice_like', 'smooth_l1', 'softmax', 'softmax_cross_entropy', 'softmin', 'softsign', 'sort', 'space_to_depth', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'stop_gradient', 'sum', 'sum_axis', 'swapaxes', 'take', 'tan', 'tanh', 'tile', 'topk', 'transpose', 'trunc', 'uniform', 'unravel_index', 'where', 'zeros_like'] |
/home/runner/.cache/pip/pool/5f/95/f1/cc1311c7e8ad01e274ec0d2b6d14d64b05dced62d76fa640d7ee406860 |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Neural Network assisted Euler Integrator #
# Contact [email protected] for details. 06/08/2021 #
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Data points are saved as adaptive-time-step given the stiffness of the ODEs #
# NOTE: Only autonomous system is considered in this solver. #
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
import numpy as np
class NNEIT():
def __init__(self,options):
self.nstp = 0
self.nacc = 0
self.nrej = 0
self.rejlast = False
self.rejmore = False
self.hmin = options['Hmin']
self.hmax = options['Hmax']
self.hstart = options['Hstart']
self.θmin = 1.00017e-04 # 1.14071524448533531626660095e-8
self.eps = options['eps']
self.maxstep = options['MaxStep']
''' This function works just for automonous system '''
def __call__(self,ODEfcn,Tspan,Y0,ODEargs,NNweights):
t = []
y = []
e = []
Tstart,Tend = Tspan
# two-element list, since it is adaptive time step
T = Tstart
H = self.hstart # initial step
Y = Y0*1 # copy an array, Y0.copy() also works
t.append(T)
y.append(Y)
while Tend-T >= self.eps:
if self.nstp > self.maxstep:
break
if T+0.1*H==T:
print('Time step too small, has to quit')
break
H = min(H,Tend-T)
T,Y,H,E = self.findh(H,T,Y,ODEfcn,ODEargs,NNweights)
t.append(T)
y.append(Y)
e.append(E)
# print(T/abs(Tend-Tstart))
self.t = np.array(t)
self.y = np.array(y).T
self.e = np.array(e).T
return self
'''Find the proper time step'''
def findh(self,h,T,Y,ODEfcn,ODEargs,NNweights):
while True: # Until h accepted
if NNweights['func']==1: # will be updated in the future
neuralnetwork = self.NNH2O2
elif NNweights['func']==2:
neuralnetwork = self.NNVerwer
Yν,nerr,err = neuralnetwork(h,Y,ODEfcn,ODEargs,NNweights)
self.nstp += 1
fac = min(10,max(0.1,nerr**(-1/3)))
hnew = h*fac
if (nerr<=1) or (h<=self.hmin): # accept step
self.nacc += 1
Y = Yν
T += h
hnew = max(self.hmin,min(hnew,self.hmax))
if self.rejlast: # no step size increase after rejection
hnew = min(hnew,h)
self.rejlast, self.rejmore = False, False
h = hnew
break
else: # reject step
if self.rejmore:
hnew = h*0.1
self.rejmore = self.rejlast
self.rejlast = True
h = hnew
self.nrej += 1
return T,Y,h,err
'''Calculate νc, nerr, and err for the current step'''
def NNH2O2(self,h,Y,ODEfcn,ODEargs,NNweights):
M_1e6 = ODEargs['M']/ODEargs['cvt'][0]
ci = Y*1
ci[Y<=0] = 1.0e-100 # set non-positive conc to very small value
ss,ps,ls = ODEfcn(ci,**ODEargs) # ppm min-1
ls[ls<1.0e-80] = 1.0e-120
ps[ps<1.0e-80] = 1.0e-120
logcs = np.log(ci)+np.log(M_1e6) # ppm -> molec cm-3
logls = np.log(ls) # ppm
logps = np.log(ps) # ppm
logdt = np.log(h) # min
θ = ls*h/ci
θ[θ<self.θmin] = self.θmin # some issue with values < θmin
ω = (1-np.exp(-θ))/θ
compl = np.hstack([logps,logls])
logpl = np.tanh(logps-logls)
comb = np.hstack([logpl,ω])
wc1, wc2 = NNweights['wc11'],NNweights['wc12']
wt1, wt2 = NNweights['wt11'],NNweights['wt12']
f = NNweights['scale1']
ωn,ft = self.dydtfactor(wc1,wc2,ω,logls,logcs,logdt,compl)
νc = ci + h*ss*ωn*(1+ft) # ppm
νc[νc<=0] = 1.0e-100
comb = np.tanh(wt1.T.dot(comb))
comb = np.tanh(wt2.T.dot(comb))
err = comb*f # Ce/Ctol
nerr = (np.sum(err**2)/len(Y))**0.5
return νc,nerr,err
'''Calculate νc, nerr, and err for the current step'''
def NNVerwer(self,h,Y,ODEfcn,ODEargs,NNweights):
M_1e6 = ODEargs['M']/ODEargs['cvt'][0]
ci = Y*1
ci[Y<=0] = 1.0e-100 # set non-positive conc to very small value
ss,ps,ls = ODEfcn(ci,**ODEargs) # ppm min-1
ls[ls<1.0e-80] = 1.0e-120
ps[ps<1.0e-80] = 1.0e-120
logcs = np.log(ci)+np.log(M_1e6) # ppm -> molec cm-3
logls = np.log(ls) # ppm
logps = np.log(ps) # ppm
logdt = np.log(h) # min
θ = ls*h/ci
θ[θ<self.θmin] = self.θmin # some issue with values < θmin
ω = (1-np.exp(-θ))/θ
logpl = np.tanh(logps-logls)
comb = np.hstack([logpl,ω])
if h < NNweights['r1']:
wc1, wc2 = NNweights['wc11'], NNweights['wc12']
wt1, wt2 = NNweights['wt11'], NNweights['wt12']
f = NNweights['scale1']
elif NNweights['r1'] <= h < NNweights['r2']:
wc1, wc2 = NNweights['wc21'], NNweights['wc22']
wt1, wt2 = NNweights['wt21'], NNweights['wt22']
f = NNweights['scale2']
elif NNweights['r2'] <= h < NNweights['r3']:
wc1, wc2 = NNweights['wc31'], NNweights['wc32']
wt1, wt2 = NNweights['wt31'], NNweights['wt32']
f = NNweights['scale3']
elif NNweights['r3'] <= h < NNweights['r4']:
wc1, wc2 = NNweights['wc41'], NNweights['wc42']
wt1, wt2 = NNweights['wt41'], NNweights['wt42']
f = NNweights['scale4']
else:
wc1, wc2 = NNweights['wc51'], NNweights['wc52']
wt1, wt2 = NNweights['wt51'], NNweights['wt52']
f = NNweights['scale5']
ωn,ft = self.dydtfactor(wc1,wc2,ω,logls,logcs,logdt,logpl)
νc = ci + h*ss*ωn*(1+ft) # ppm
νc[νc<=0] = 1.0e-100
comb = np.tanh(wt1.T.dot(comb))
comb = np.tanh(wt2.T.dot(comb))
err = comb*f # Ce/Ctol
nerr = (np.sum(err**2)/len(Y))**0.5
return νc,nerr,err
def myelu(self,x,α=1.0):
y = x*1.0
y[x<0] = α*(np.exp(x[x<0])-1)
return y
def dydtfactor(self,wc1,wc2,ω,logls,logcs,logdt,logpl):
if len(wc1)==0:
ωn = ω
else:
logθn = np.hstack([logls,logcs,logdt])
θn = np.exp(wc1.T.dot(logθn))
θn[θn<self.θmin] = self.θmin # some issue with values < θmin
ωn = (1-np.exp(-θn))/θn
ft = self.myelu(wc2.T.dot(logpl))
return ωn,ft
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# END OF NNEIT #
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
__author__ = 'joefrancia'
|
import sys
from pyspark import SparkContext
import time
import json
import collections
import copy
import math
import time
from functools import reduce
from itertools import combinations
from operator import add
tickTime = time.time()
sc = SparkContext()
# #FilePaths
# input_file, output_file = sys.argv[1:]
#LocalRun
input_file = "data/HW3/train_review.json"
output_file = "data/HW3/task1_output.json"
#Constants
BUSINESS_ID = "business_id"
USER_ID = "user_id"
primes = [1, 3, 9, 11, 13, 17, 19, 27, 29, 31, 33, 37, 39, 41, 43, 47, 51, 53, 57, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,227]
n_hash_functions = len(primes)
r = 1
b = int(n_hash_functions/ r)
def minHash(x):
# global rows
# global primes
signatures = [min((p*row_no + 1) % rows for row_no in x[1]) for p in primes]
return (x[0], signatures) #business - [hash signatures .. 20 in nos]
def get_signature_bands(x):
business_id = x[0]
signatures = x[1]
bands = []
rowindex = 0
for band_no in range(0, b):
band = []
for row in range(0, r):
band.append(signatures[rowindex])
rowindex = rowindex+1
bands.append(((band_no, tuple(band)), [business_id]))
band.clear()
return bands
def get_candidate_pairs(x):
pair_list = []
b_list = x[1]
b_list.sort()
for i in range(0, len(b_list)):
for j in range(i+1, len(b_list)):
pair_list.append(((b_list[i], b_list[j]), 1))
return pair_list
def find_jaccard_similarity(x):
b1 = x[0][0]
b2 = x[0][1]
users_b1 = set(business_user_rdd[b1])
users_b2 = set(business_user_rdd[b2])
jaccard_sim = float(len(users_b1 & users_b2) / len(users_b1 | users_b2))
return ((b1,b2), jaccard_sim )
#Read input data
text_data= sc.textFile(input_file)
json_data= text_data.map(lambda l: json.loads(l))
business_user_rdd = json_data.map(lambda review: (review[BUSINESS_ID], [review[USER_ID]])).reduceByKey(lambda x, y: x+y).collectAsMap()
allUsers = json_data.map(lambda review: review[USER_ID]).distinct()
allBusiness = json_data.map(lambda review: review[BUSINESS_ID]).distinct()
rows = allUsers.count()
cols = allBusiness.count()
users = allUsers.collect()
business = allBusiness.collect()
# Create index for users and businesses
users_index = {}
for U in range(0, rows):
users_index[users[U]] = U
business_index ={}
for B in range(0, cols):
business_index[business[B]] = B
#Create characteristic matrix i.e business_id - [user_id indices]
char_matrix = json_data.map(lambda a: (a[BUSINESS_ID], [users_index[a[USER_ID]]])).reduceByKey(lambda a, b: a+b)
#create signature matrix business_id - [20 signatures]
buckets = rows/n_hash_functions
sig_matrix = char_matrix.map(lambda business: minHash(business))
#Perform LSH
sig_bands_matrix = sig_matrix.flatMap(lambda x: get_signature_bands(x))
agg_candidates = sig_bands_matrix.reduceByKey(lambda a, b: a+b).filter(lambda business: len(business[1]) > 1)
candidate_pairs = agg_candidates.flatMap(lambda b: get_candidate_pairs(b)).distinct()
# perform Jaccard similarity on candidate pairs
JS_rdd = candidate_pairs.map(lambda x: find_jaccard_similarity(x)).filter(lambda pair: pair[1] >= 0.05)
result_rdd = JS_rdd.map(lambda r: (r[0][1], (r[0][0], r[1]))).sortByKey().map(lambda r: (r[1][0], (r[0], r[1][1]))).sortByKey()
#Write to output file
with open(output_file,'w') as f:
for pair in result_rdd.collect():
json.dump({"b1":pair[0], "b2": pair[1][0], "sim": pair[1][1]}, f)
f.write("\n")
f.close()
tockTime = time.time()
print("Duration: ",tockTime-tickTime)
#Check Precision and recall
ground = sc.textFile("data/HW3/ground.json").map(lambda l: json.loads(l)).map(lambda x: (x["b1"], x["b2"]))
Ground_truth = list(ground.collect())
output = JS_rdd.map(lambda x: (x[0][0], x[0][1]))
Output_pairs = list(output.collect())
TP= list(output.intersection(ground).collect())
precision = len(TP) / len(Output_pairs)
recall = len(TP) / len(Ground_truth)
print("Precision:", precision)
print("Recall: ", recall) |
#!/usr/bin/env python
"""Command-line utility for db setup."""
import os
import logging
import sys
from time import time, sleep
from psycopg2 import connect, sql, OperationalError
db_type = os.getenv("DJANGO_DB_TYPE", "postgres")
db_user = os.getenv("DJANGO_DB_USER","tau_db")
db_name = os.getenv("DJANGO_DB","tau_db")
db_pw = os.getenv("DJANGO_DB_PW","")
check_timeout = os.getenv("POSTGRES_CHECK_TIMEOUT", 30)
check_interval = os.getenv("POSTGRES_CHECK_INTERVAL", 1)
interval_unit = "second" if check_interval == 1 else "seconds"
config = {
"dbname": os.getenv("POSTGRES_DB", "postgres"),
"user": os.getenv(
"PGUSER",
os.getenv("POSTGRES_USER", "postgres")
),
"password": os.getenv(
"PGPASSWORD",
os.getenv("POSTGRES_PASSWORD", "")
),
"host": os.getenv(
"PGHOST",
os.getenv("DJANGO_DB_HOST", "db")
),
"port": os.getenv(
"PGPORT",
os.getenv("DJANGO_DB_PORT", 5432)
)
}
start_time = time()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
def pg_isready(host, user, password, dbname, port):
if db_type != "postgres":
logger.info("DJANGO_DB_TYPE is not set to \"postgres\". Skipping.")
return True
while time() - start_time < check_timeout:
try:
conn = connect(**vars())
conn.autocommit = True
cur = conn.cursor()
cur.execute("SELECT COUNT(*) AS count FROM pg_catalog.pg_user WHERE usename=%s;",(db_user,))
user_count = cur.fetchone()[0]
cur.execute("SELECT COUNT(*) AS count FROM pg_database WHERE datname=%s;",(db_name,))
db_count = cur.fetchone()[0]
if user_count == 0:
logger.info(f"Creating user {db_user}")
add_user_query = f"CREATE USER {db_user} WITH ENCRYPTED PASSWORD '{db_pw}';"
cur.execute(add_user_query)
grant_query = f"GRANT ALL PRIVILEGES ON DATABASE {db_name} TO {db_user};"
cur.execute(grant_query)
else:
logger.info(f"Found a user {db_user}, updating password to current DJANGO_DB_PW value.")
update_user_query = f"ALTER USER {db_user} WITH ENCRYPTED PASSWORD '{db_pw}'"
cur.execute(update_user_query)
if db_count == 0:
logger.info(f"Creating database {db_name}")
add_db_query = f"CREATE DATABASE {db_name};"
cur.execute(add_db_query)
logger.info("Postgres is ready!")
conn.close()
return True
except OperationalError:
logger.info(f"Postgres isn't ready. Waiting for {check_interval} {interval_unit}...")
sleep(check_interval)
logger.error(f"We could not connect to Postgres within {check_timeout} seconds.")
sys.exit(1)
return False
pg_isready(**config)
|
from unittest import TestCase
from unittest.mock import patch
from opwen_email_server.api import client_read
from tests.opwen_email_server.api.api_test_base import AuthTestMixin
class DownloadTests(TestCase, AuthTestMixin):
def test_denies_unknown_client(self):
with self.given_clients(client_read, {'client1': 'bar.com'}):
message, status = client_read.download('unknown')
self.assertEqual(status, 403)
@patch.object(client_read, 'server_datastore')
@patch.object(client_read, 'STORAGE')
def test_uploads_emails_and_marks_as_delivered(
self, storage_mock, datastore_mock):
with self.given_clients(client_read, {'client1': 'bar.com'}):
resource_id = '1234'
emails = [{'to': '[email protected]', '_uid': '1'},
{'to': '[email protected]', '_uid': '2'}]
self.given_index(datastore_mock, storage_mock, emails, resource_id)
response = client_read.download('client1')
self.assertEqual(resource_id, response.get('resource_id'))
self.assertEqual(self.stored_ids, emails)
datastore_mock.mark_emails_as_delivered.\
assert_called_once_with('bar.com', {'1', '2'})
def given_index(self, datastore_mock, storage_mock, emails, resource):
def store_objects(objs):
self.stored_ids = list(objs)
return resource
self.stored_ids = []
datastore_mock.fetch_pending_emails.return_value = emails
storage_mock.store_objects.side_effect = store_objects
|
import datetime
import os.path
import pkg_resources
import re
import flask
import jinja2.loaders
import six
import edera.helpers
URL_PATTERN = "https?://[^\\s]*"
class MonitoringUI(flask.Flask):
"""
A monitoring UI (web-application).
This class aims to render monitoring snapshots and task payloads obtained from a watcher.
Use it as a regular Flask application (either in developer mode or via WSGI).
Attributes:
caption (String) - the caption to show in the header
watcher (MonitorWatcher) - the monitor watcher used to load snapshots
Examples:
Here is how you can run the UI in developer mode using a MongoDB-based storage:
>>> import pymongo
>>> from edera.helpers import Lazy
>>> from edera.storages import MongoStorage
>>> from edera.monitoring import MonitoringUI
>>> from edera.monitoring import MonitorWatcher
>>> monitor = MongoStorage(Lazy[pymongo.MongoClient](), "edera", "monitor")
>>> watcher = MonitorWatcher(monitor)
>>> MonitoringUI("example", watcher).run(debug=True)
See also:
$MonitorWatcher
"""
def __init__(self, caption, watcher):
"""
Args:
caption (String) - a caption to show in the header
watcher (MonitorWatcher) - a monitor watcher to use to load snapshots
"""
flask.Flask.__init__(self, __name__)
self.caption = caption
self.watcher = watcher
self.__configure()
def __configure(self):
@self.template_filter("formatdatetime")
def format_datetime(dt): # pylint: disable=unused-variable
offset = datetime.datetime.now() - datetime.datetime.utcnow()
return (dt + offset).strftime("%Y-%m-%d %H:%M:%S")
@self.template_filter("formattimedelta")
def format_timedelta(td): # pylint: disable=unused-variable
def decompose(seconds):
if seconds >= 86400:
days = int(seconds / 86400)
yield "1 day" if days == 1 else "%d days" % days
seconds -= days * 86400
if seconds >= 3600:
hours = int(seconds / 3600)
yield "1 hour" if hours == 1 else "%d hours" % hours
seconds -= hours * 3600
if seconds >= 60:
minutes = int(seconds / 60)
yield "1 minute" if minutes == 1 else "%d minutes" % minutes
seconds -= minutes * 60
if seconds != 0:
yield "%.3f seconds" % seconds
return " ".join(decompose(td.total_seconds()))
@self.template_filter("hashstring")
def hash_string(string): # pylint: disable=unused-variable
return edera.helpers.sha1(string)[:6]
@self.template_filter("selectkeys")
def select_keys(mapping, keys): # pylint: disable=unused-variable
return {key: mapping[key] for key in keys}
@self.template_filter("highlight")
def highlight(message): # pylint: disable=unused-variable
link = "<a href='\g<0>'>\g<0></a>"
return jinja2.Markup(re.sub(URL_PATTERN, link, str(jinja2.escape(message))))
@self.route("/")
def index(): # pylint: disable=unused-variable
core = self.watcher.load_snapshot_core()
if core is None:
return flask.render_template("void.html", caption=self.caption)
labeling = self.__label_tasks(core)
ranking = self.__rank_tasks(core)
return flask.render_template(
"index.html",
caption=self.caption,
core=core,
labeling=labeling,
ranking=ranking,
mode=flask.request.args.get("mode", "short"))
@self.route("/report/<alias>")
def report(alias): # pylint: disable=unused-variable
core = self.watcher.load_snapshot_core()
if core is None or alias not in core.states:
flask.abort(404)
labeling = self.__label_tasks(core)
payload = self.watcher.load_task_payload(alias)
return flask.render_template(
"report.html",
caption=self.caption,
core=core,
labeling=labeling,
alias=alias,
payload=payload)
self.jinja_loader = jinja2.loaders.PackageLoader(
"edera", package_path="resources/monitoring/ui/templates")
self.static_folder = os.path.abspath(
pkg_resources.resource_filename("edera", "resources/monitoring/ui/static"))
def __label_tasks(self, core):
tasks = list(core.aliases)
aliases = [core.aliases[task] for task in tasks]
labels = edera.helpers.squash_strings(tasks)
return dict(zip(aliases, labels))
def __rank_tasks(self, core):
return {
alias: (
not state.failures,
not state.stale,
state.completed,
state.phony,
not state.runs,
state.name,
)
for alias, state in six.iteritems(core.states)
}
|
# -*- coding: utf-8 -*-
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Luc LEGER / Coopérative ARTEFACTS <[email protected]>
"""
Mission tests
"""
import factory
import pytest
import sys
from django.core.management import call_command
from django.urls import reverse
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APITestCase
from .factories.mission import MissionFactory, MissionCollectionFactory
from .fake_data.fake_sound import CleanMediaMixin
from ..models.mission import Mission
from ..models.fond import Fond
from ..models.collection import Collection
from .keycloak import get_token
# Expected structure for Mission objects
MISSION_STRUCTURE = [
('id', int),
('title', str),
('description', str),
('code', str),
('public_access', str),
('fonds', dict),
('code_partner', str)
]
# Expected keys for MODEL objects
MISSION_FIELDS = sorted([item[0] for item in MISSION_STRUCTURE])
@pytest.mark.django_db
class TestMissionList(CleanMediaMixin, APITestCase):
"""
This class manage all Mission tests
"""
def setUp(self):
"""
Run needed commands to have a fully working project
"""
get_token(self)
# Create a set of sample data
MissionCollectionFactory.create_batch(6, collections__nb_collections=4)
def test_can_get_mission_list(self):
"""
Ensure Mission objects exists
"""
url = reverse('mission-list')
# ORM side
missions = Mission.objects.all()
self.assertEqual(len(missions), 6)
# API side
response = self.client.get(url)
self.assertIsInstance(response.data, list)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 6)
def test_can_get_mission_collections_list(self):
"""
Ensure related collections exist
"""
url = reverse('collection-list')
# ORM side
collections = Collection.objects.all()
self.assertEqual(len(collections), 24)
# API side
response = self.client.get(url)
self.assertIsInstance(response.data, list)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 24)
def test_mission_dates(self):
"""
Max and min dates from the related collections of a mission
"""
item = Mission.objects.first()
url = '/api/mission/' + str(item.id) + "/dates"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 2)
def test_mission_informers(self):
"""
Informers from the related collections of a mission
"""
item = Mission.objects.first()
url = '/api/mission/' + str(item.id) + "/informers"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, list)
def test_mission_collectors(self):
"""
Collectors from the related collections of a mission
"""
item = Mission.objects.first()
url = '/api/mission/' + str(item.id) + "/collectors"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, list)
def test_mission_locations(self):
"""
Locations from the related collections of a mission
"""
item = Mission.objects.first()
url = '/api/mission/' + str(item.id) + "/locations"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, list)
def test_mission_duration(self):
"""
Total duration of a mission : sum of collection/items durations of this mission
"""
item = Mission.objects.first()
url = '/api/mission/' + str(item.id) + "/duration"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, str)
self.assertNotEqual(response.data, "0:00:00")
self.assertNotEqual(response.data, "")
@parameterized.expand(MISSION_STRUCTURE)
def test_has_valid_mission_values(self, attribute, attribute_type):
"""
Ensure Mission objects have valid values
"""
url = reverse('mission-list')
response = self.client.get(url)
self.assertIsInstance(response.data, list)
self.assertEqual(response.status_code, status.HTTP_200_OK)
for mission in response.data:
# Check only expected attributes returned
self.assertEqual(
sorted(mission.keys()), MISSION_FIELDS)
# Ensure type of each attribute
if attribute_type == str:
self.assertIsInstance(mission[attribute], str)
else:
self.assertIsInstance(mission[attribute], attribute_type)
self.assertIsNot(mission[attribute], '')
def test_get_an_mission(self):
"""
Ensure we can get an Mission objects
using an existing id
"""
item = Mission.objects.first()
url = reverse('mission-detail',
kwargs={'pk': item.id})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, dict)
def test_create_an_mission(self):
"""
Ensure we can create an Mission object
"""
data = factory.build(
dict,
FACTORY_CLASS=MissionFactory)
fonds = Fond.objects.first()
data['fonds'] = fonds.id
url = reverse('mission-list')
response = self.client.post(url, data, format='json')
# Check only expected attributes returned
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertIsInstance(response.data, dict)
self.assertEqual(
sorted(response.data.keys()),
MISSION_FIELDS)
url = reverse(
'mission-detail',
kwargs={'pk': response.data['id']}
)
response_get = self.client.get(url)
self.assertEqual(response_get.status_code, status.HTTP_200_OK)
self.assertIsInstance(response_get.data, dict)
def test_update_an_mission(self):
"""
Ensure we can update an Mission object
"""
item = Mission.objects.first()
self.assertNotEqual(item.title, 'foobar_test_put')
# Get existing object from API
url_get = reverse(
'mission-detail',
kwargs={'pk': item.id})
data = self.client.get(url_get).data
data['title'] = 'foobar_test_put'
url = reverse(
'mission-detail',
kwargs={'pk': item.id})
data['fonds'] = data['fonds']['id']
response = self.client.put(url, data, format='json')
# Ensure new name returned
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, dict)
self.assertEqual(
sorted(response.data.keys()),
MISSION_FIELDS)
self.assertEqual(response.data['title'], 'foobar_test_put')
def test_patch_an_mission(self):
"""
Ensure we can patch an Mission object
"""
item = Mission.objects.first()
self.assertNotEqual(item.title, 'foobar_test_patch')
data = {'title': 'foobar_test_patch'}
url = reverse(
'mission-detail',
kwargs={'pk': item.id})
response = self.client.patch(url, data, format='json')
# Ensure new name returned
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsInstance(response.data, dict)
self.assertEqual(
sorted(response.data.keys()),
MISSION_FIELDS)
self.assertEqual(response.data['title'], 'foobar_test_patch')
def test_uniq_code_mission(self):
"""
Ensure we don't validate a non-uniq mission code
"""
item = Mission.objects.first()
code_1 = item.code
item = Mission.objects.last()
data = {'code': code_1}
url = reverse(
'mission-detail',
kwargs={'pk': item.id})
response = self.client.patch(url, data, format='json')
# Ensure code 409 returned
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
def test_delete_an_mission(self):
"""
Ensure we can delete an Mission object
"""
item = Mission.objects.first()
# Delete this object
url = reverse(
'mission-detail',
kwargs={'pk': item.id})
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
# Ensure Mission removed
url_get = reverse(
'mission-detail',
kwargs={'pk': item.id})
response_get = self.client.get(url_get)
self.assertEqual(response_get.status_code, status.HTTP_404_NOT_FOUND)
|
import os
import platform
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
import secret
def add_chrome_webdriver():
print(platform.system())
working_path = os.getcwd()
library = 'library'
path = os.path.join(working_path, library)
os.environ['PATH'] += '{}{}{}'.format(os.pathsep, path, os.pathsep)
print(os.environ['PATH'])
def add_cookie(browser):
browser.delete_all_cookies()
print('before', browser.get_cookies())
for part in secret.cookie.split(';'):
kv = part.split(':', 1)
d = dict(
name=kv[0],
value=kv[1],
path='/',
domain='.zhihu.com',
secure=True
)
print('cookie', d)
browser.add_cookie(d)
print('after', browser.get_cookies())
def scroll_to_end(browser):
browser.execute_script('window.scrollTo(0, document.body.scrollHeight);')
def start_crawler(browser):
# chrome 有 bug https://bugs.chromium.org/p/chromium/issues/detail?id=617931
# 不能 --user-data-dir 和 --headless 一起用
# 改回用 cookie
url = "https://www.zhihu.com/follow"
# 先访问一个 url,才能设置这个 url 对应的 cookie
browser.get("https://www.zhihu.com/404")
add_cookie(browser)
browser.get(url)
while True:
print('拿到更多数据')
cards = browser.find_elements_by_css_selector('.Card.TopstoryItem')
for card in cards:
try:
source = card.find_element_by_css_selector('.FeedSource-firstline')
except NoSuchElementException:
pass
else:
if '1 天前' in source.text:
print('拿到了最近1天动态')
titles = browser.find_elements_by_css_selector('.ContentItem-title')
for title in titles:
print(title.text)
return
# 当这次鼠标滚动找不到数据的时候,执行下一次滚动
scroll_to_end(browser)
def main():
# cookie 要去掉 _xsrf _zap tgw_l7_route 这三个
add_chrome_webdriver()
o = Options()
# o.add_argument("--headless")
browser = webdriver.Chrome(chrome_options=o)
try:
start_crawler(browser)
finally:
browser.quit()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
#--------------------------------------------------------
# Name: bearings.py
# Purpose: Calculate the great circle distance and bearing
# between 2 points
#
# Author: Al Neal
#
# Created: 2015
# Copyright: (c) Al Neal
# Licence: MIT
#--------------------------------------------------------
# The author claims no originality in the mathematics here presented
from math import sin, sqrt, cos, pow, atan2, radians, degrees
"""
Radius (km) * Distance (radians) = Distance of arc (km)
"""
RADIUS_OF_EARTH_KM = 6371.0
RADIUS_OF_EARTH_MI = 3959.0
def distance(lat1,lon1,lat2,lon2):
"""Input 2 points in Lat/Lon degrees.
Calculates the great circle distance between them in radians
"""
rlat1= radians(lat1)
rlon1= radians(lon1)
rlat2= radians(lat2)
rlon2= radians(lon2)
dlat = rlat1 - rlat2
dlon = rlon1 - rlon2
a = pow(sin(dlat/2.0),2) + cos(rlat1)*cos(rlat2)*pow(sin(dlon/2.0),2)
c = 2* atan2(sqrt(a), sqrt(1-a))
return c
def bearing(lat1,lon1,lat2,lon2):
"""Input 2 points in Lat/Lon degrees.
Bearing at point 1 to point 2 calculated in radians
"""
rlat1= radians(lat1)
rlon1= radians(lon1)
rlat2= radians(lat2)
rlon2= radians(lon2)
dlat = rlat1 - rlat2
dlon = rlon1 - rlon2
theta = atan2(sin(dlon)*cos(rlat2), \
cos(rlat1)*sin(rlat2) - sin(rlat1)*cos(rlat2)*cos(dlon) )
return theta
def test():
print distance(51.3975616,-0.9932566,51.3971252,-0.9947758)
print degrees(bearing(51.426,-0.933,51.439,-1.071))
if __name__ == '__main__':
test()
|
class Money:
dollars: int
cents: int
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
@staticmethod
def factory_func_money_from_cents(total_cents): # hacky way to support Polymorphic constructor
# wrapper function to return a Money class object
# this function is not attached or encapsulated with the class
dollars = total_cents // 100
cents = total_cents % 100
return Money(dollars, cents) # problem: change Money -> TipMoney or similar for each subclass
@classmethod
def from_cents(cls, total_cents):
dollars = total_cents // 100
cents = total_cents % 100
return cls(dollars, cents) # resolve the provious problem by using cls
def __str__(self):
return f'${self.dollars}.{self.cents}'
class TipMoney(Money):
pass
if __name__ == "__main__":
a = Money(10, 5)
print(a)
b = Money.factory_func_money_from_cents(1005) # python does not allow Polymorphic constructor
print(b)
c = TipMoney.factory_func_money_from_cents(1020)
print(c)
d = TipMoney.from_cents(1020)
print(d)
|
import re
thisDict = {
"2": "2",
"3": "3",
"5": "5",
"7": "7",
"2 x 2": "{2} x {2}",
"3 x 2": "{3} x {2}",
"4": "{2 x 2}",
"6": "{3 x 2}",
"8": "{2 x 2} x {2}",
"16": "{2 x 2} x {2 x 2}",
"96": "{16} x {6}",
"Model.Root": "{96} bottles of {Favored Beverage} on the {House Element}.",
"Favored Beverage": "b{i}r",
"House Element": "{wl}",
"i": "ee",
"wl": "wall"
}
thisDict["Model.Root"]
def find_value(key):
value = thisDict[key]
search = [x.group() for x in re.finditer(r'{(.*?)}', value)]
# End case
if len(search) == 0:
return value
else:
for i in range(len(search)):
new_val = find_value(search[i][1:-1])
value = value.replace(search[i], new_val, 1)
return value
find_value("Model.Root")
|
import torch
import torch.nn as nn
from torch_sparse import SparseTensor
from torch_geometric.nn import global_mean_pool
from torch_geometric.nn.inits import reset
import torch.nn.functional as F
def to_normalized_sparsetensor(edge_index, N, mode='DA'):
row, col = edge_index
adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
adj = adj.set_diag()
deg = adj.sum(dim=1).to(torch.float)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0
if mode == 'DA':
return deg_inv_sqrt.view(-1,1) * deg_inv_sqrt.view(-1,1) * adj
if mode == 'DAD':
return deg_inv_sqrt.view(-1, 1) * adj * deg_inv_sqrt.view(1, -1)
def approximate_invphi_x(A, x, alpha=1, n_powers=10):
invphi_x = x
# power method
for _ in range(n_powers):
part1 = A.matmul(invphi_x)
invphi_x = alpha/(1+alpha)*part1 + 1/(1+alpha)*x
return invphi_x
class GPCALayer(nn.Module):
def __init__(self, nin, nout, alpha, center=True, n_powers=50, mode='DA'):
super().__init__()
self.weight = nn.Parameter(torch.FloatTensor(nin, nout))
self.bias = nn.Parameter(torch.FloatTensor(1, nout))
self.nin = nin
self.nhid = nout
self.alpha = alpha
self.center = center
self.n_powers = n_powers
self.mode = mode
# init default parameters
self.reset_parameters()
def freeze(self, requires_grad=False):
self.weight.requires_grad = requires_grad
self.bias.requires_grad = requires_grad
def reset_parameters(self):
nn.init.xavier_uniform_(self.weight)
nn.init.constant_(self.bias, 0)
def forward(self, data, return_invphi_x=False, minibatch=False, center=True):
"""
Assume data.adj is SparseTensor and normalized
"""
# inputs
n = data.x.size(0)
edge_index, x = data.edge_index, data.x
A = to_normalized_sparsetensor(edge_index, n, self.mode)
if center:
x = x - x.mean(dim=0)
# calculate inverse of phi times x
if return_invphi_x:
if center:
x = x - x.mean(dim=0) # center
invphi_x = approximate_invphi_x(A, x, self.alpha, self.n_powers)
return invphi_x, x
else:
# AXW + bias
invphi_x = approximate_invphi_x(A, x, self.alpha, self.n_powers)
return invphi_x.mm(self.weight) + self.bias
def init(self, full_data, center=True, posneg=False):
"""
Init always use full batch, same as inference/test.
"""
self.eval()
with torch.no_grad():
invphi_x, x = self.forward(full_data, return_invphi_x=True, center=center)
eig_val, eig_vec = torch.symeig(x.t().mm(invphi_x), eigenvectors=True)
if self.nhid <= (int(posneg)+1)*self.nin:
weight = torch.cat([eig_vec[:,-self.nhid//2:], -eig_vec[:,-self.nhid//2:]], dim=-1) \
if posneg else eig_vec[:, -self.nhid:] #when
elif self.nhid <= 2*(int(posneg)+1)*self.nin:
eig_val1, eig_vec1 = torch.symeig(x.t().mm(x), eigenvectors=True)
m = self.nhid % ((int(posneg)+1)*self.nin)
weight = torch.cat([eig_vec, -eig_vec, eig_vec1[:, -m//2:], -eig_vec1[:, -m//2:]], dim=-1) \
if posneg else torch.cat([eig_vec, eig_vec1[:, -m:]], dim=-1)
elif self.nhid <= 3*(int(posneg)+1)*self.nin:
eig_val1, eig_vec1 = torch.symeig(x.t().mm(x), eigenvectors=True)
eig_val2, eig_vec2 = torch.symeig(invphi_x.t().mm(invphi_x), eigenvectors=True)
m = self.nhid % ((int(posneg)+1)*self.nin)
weight = torch.cat([eig_vec, eig_vec1, eig_vec2[:, -m//2:]
-eig_vec, -eig_vec1, -eig_vec2[:, -m//2:]], dim=-1) \
if posneg else torch.cat([eig_vec, eig_vec1, eig_vec2[:, -m:]], dim=-1)
else:
raise ValueError('Larger hidden size is not supported yet.')
# assign
self.weight.data = weight
class GPCANet(nn.Module):
def __init__(self, dataset, num_layers, hidden, alpha=10,
dropout=0.5, n_powers=5, center=True, act='ReLU',
mode='DA', out_nlayer=2, **kwargs):
super().__init__()
nclass = dataset.num_classes
nfeat = dataset.num_features
nlayer = num_layers
nhid = hidden
self.convs = torch.nn.ModuleList()
for i in range(nlayer-1):
self.convs.append(
GPCALayer(nhid if i>0 else nfeat, nhid, alpha, center, n_powers, mode))
# last layer
self.convs.append(
GPCALayer(nhid if nlayer>1 else nfeat,
nclass if out_nlayer==0 else nhid, alpha, center, n_powers, mode))
"""
out_nlayer = 0 should only be used for non frezzed setting
"""
self.dropout = nn.Dropout(dropout)
self.relu = getattr(nn,act)()
# fc layers
if out_nlayer == 0:
self.out_mlp = nn.Identity()
elif out_nlayer == 1:
self.out_mlp = nn.Sequential(nn.Linear(nhid, nclass))
else:
self.out_mlp = nn.Sequential(nn.Linear(nhid, nhid), self.relu, self.dropout, nn.Linear(nhid, nclass))
self.freeze_status = False # only support full batch
def freeze(self, requires_grad=False):
self.freeze_status = not requires_grad
for conv in self.convs:
conv.freeze(requires_grad)
def reset_parameters(self):
for conv in self.convs:
conv.reset_parameters()
reset(self.out_mlp)
def forward(self, data):
# inputs
# A, x, y, train_mask = data.adj, data.x, data.y, data.train_mask
# n, c = data.num_nodes, data.num_classes
original_x = data.x
for i, conv in enumerate(self.convs):
x = conv(data)
if not self.freeze_status:
x = self.relu(x)
data.x = x
x = global_mean_pool(x, data.batch)
out = self.out_mlp(x)
data.x = original_x # restore
return F.log_softmax(out, dim=-1)
def init(self, full_data, center=True, posneg=False, **kwargs):
"""
Init always use full batch, same as inference/test.
Btw, should we increase the scale of weight based on relu scale?
Think about this later.
"""
self.eval()
with torch.no_grad():
original_x = full_data.x
for i, conv in enumerate(self.convs):
# init
conv.init(full_data, center, posneg) # init using GPCA
# next layer
x = conv(full_data)
#----- init without relu and dropout?
full_data.x = self.relu(x) if posneg else x
# x = self.dropout(x)
full_data.x = original_x # restore
|
from pyapp.checks.registry import register
from .factory import session_factory
register(session_factory)
|
# Copyright (c) 2021 Stephan Gerhold
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the copyright holder 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.
from m5.params import *
from m5.objects.Device import BasicPioDevice
class KecAcc(BasicPioDevice):
type = 'KecAcc'
cxx_header = "dev/kecacc/kecacc.hh"
port = RequestPort("Port to the memory system")
buf_size = Param.MemorySize('512KiB', "Maximum size of processable buffers")
mem_width = Param.Unsigned(16, "Memory width (bytes read/written per cycle)")
pipeline_cycles = Param.Cycles(2, "Cycles for load pipeline overhead")
init_cycles = Param.Cycles(1, "Cycles for initializing state")
load_cycles = Param.Cycles(1, "Cycles for loading state (without memory)")
save_cycles = Param.Cycles(1, "Cycles for saving state (without memory)")
permute_cycles = Param.Cycles(24, "Cycles for Keccak-p[1600, 24]")
pad_cycles = Param.Cycles(1, "Cycles for padding")
|
#!/usr/bin/env python
#
# Copyright (c) 2011 Kyle Gorman
# Modified 2018 Erika Burdon
#
# 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.
#
# trie.py
# Python implementation of the 'trie' data structure
#
# Kyle Gorman <[email protected]>
# Erika Burdon <[email protected]>
import json
from functools import partial
from enum import Enum
class TYPES(Enum):
STANDARD = 1
EXTENDED = 2
class memoize(object):
"""
Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __get__(self, obj, objtype=None):
if obj is '':
return self.func
return partial(self, obj)
def __repr__(self):
return self.func.__doc__
class Trie(object):
"""
A Python implementation of a prefix tree
# initialization
>>> t = Trie()
>>> corpus = 'apple applesauce application applejack apricot'.split()
>>> t.update(corpus)
# check membership
>>> 'appl' in t
False
>>> 'appl' in t # test memoization
False
>>> 'apple' in t
True
>>> 'apples' in t
False
>>> 'foo' in t
False
# autocompletion
>>> ' '.join(sorted(list(t.autocomplete('appl'))))
'apple applejack applesauce application'
>>> ' '.join(sorted(list(t.autocomplete('appl')))) # test memoization
'apple applejack applesauce application'
>>> ' '.join(sorted(list(t.autocomplete('foobar'))))
''
"""
def __init__(self, trie_type=TYPES.STANDARD, delimiter=':'):
self.root = {}
self.type = trie_type
self.delimiter = delimiter
def __repr__(self):
return 'Trie(%r)' % self.root
# pickling and unpickling
def __getstate__(self):
"""
for pickling
"""
return self.root
def __setstate__(self, other):
"""
for unpickling
"""
self.root = other
@memoize
def __contains__(self, word):
"""
True if "word" is a licit completion
"""
curr_node = self.root
iterator = self._get_iterator(word)
for char in iterator:
# try/except is faster than checking for key membership
try:
curr_node = curr_node[char]
except KeyError:
return False
if '' in curr_node: # just make sure it's a licit completion
return True
else: # an incomplete string
return False
def unload(self, filename):
"""
Dump trie as JSON to file.
"""
data = json.dumps(self.root) + '\n'
with open(filename, 'w+') as target_file:
target_file.write(data)
def load(self, filename):
"""
Load JSON file as prefix trie
"""
data = None
with open(filename, 'r') as input_file:
line = input_file.readline()
data = json.loads(line)
self.root = data
def assign(self, word, key, value):
"""
Add node value to leaf word.
"""
curr_node = self.root
iterator = self._get_iterator(word)
for char in iterator:
# try/except is faster than checking for key membership
try:
curr_node = curr_node[char]
except KeyError:
# Do nothing; ignore our problems
return
# Add another item to leaf
# None still represents terminal; trie can access 'value'
curr_node[key] = value
def add(self, word):
"""
add an iterable (probably a string) to the trie
"""
curr_node = self.root
iterator = self._get_iterator(word)
for char in iterator:
# try/except is faster than checking for key membership
try:
curr_node = curr_node[char]
except KeyError:
curr_node[char] = {} # make it
curr_node = curr_node[char] # then enter it
curr_node[''] = word # None is then the "terminal" symbol
def update(self, words):
"""
add all elements in words to the trie
"""
for word in words:
self.add(word)
def _traverse(self, curr_node):
for char in curr_node:
if char == '':
yield curr_node['']
else:
yield self._traverse(curr_node[char])
def _smash(self, iterable):
for i in iterable:
if getattr(i, '__iter__', False):
for j in self._smash(i):
yield j
else: # base case
yield i
def _get_iterator(self, word):
iterator = None
if self.type == TYPES.STANDARD:
# iterate each character in word
iterator = word
elif self.type == TYPES.EXTENDED:
# iterate subsets in extended word
iterator = word.split(self.delimiter)
else:
raise NotImplementedError('Trie type unsupported.')
return iterator
def autocomplete(self, prefix):
"""
returns all licit completions of the prefix iterable
"""
# traverse down to the prefix
curr_node = self.root
for char in prefix:
# try/except is faster than checking for key membership
try:
curr_node = curr_node[char]
except KeyError:
return [] # break out
# recursively follow all the other paths
return self._smash(self._traverse(curr_node))
if __name__ == '__main__':
import doctest
doctest.testmod()
|
import sys
import os
from unittest import mock
import pytest
from click.testing import CliRunner
test_path = os.path.dirname(os.path.abspath(__file__))
modules_path = os.path.dirname(test_path)
sys.path.insert(0, modules_path)
sys.modules['sonic_platform'] = mock.MagicMock()
import psuutil.main as psuutil
class TestPsuutil(object):
def test_version(self):
runner = CliRunner()
result = runner.invoke(psuutil.cli.commands['version'], [])
assert result.output.rstrip() == 'psuutil version {}'.format(psuutil.VERSION)
|
import torch
import numpy as np
import albumentations as albu
import albumentations.pytorch as albu_pytorch
from torch.utils.data import Dataset
from .registry import DATASETS
from .base import BaseDataset
@DATASETS.register_module
class DummyDataset(BaseDataset):
""" DummyDataset
"""
def __init__(self, total=4, transform=None):
super().__init__()
self.total = total
self.a = torch.rand(320, 320, 3).numpy()
self.b = torch.rand(320, 320, 7).numpy()
self.transform = transform
def __getitem__(self, idx):
image, mask = self.process(self.a, self.b)
return image, mask.transpose(0, 2)
def __len__(self):
return self.total
|
from django.contrib import admin
from petstagram2.pets.models import Pet
@admin.register(Pet)
class PetAdmin(admin.ModelAdmin):
list_display = ['name', 'type', 'age']
# admin.site.register(Pet, PetAdmin)
|
class FParser:
"""
The file-parser class is made in such way that can support all bookshelf format benchmarks.
FParser class can be used either in combination with the other classes in order to have a complete
object-oriented version of a benchmark, or can be used separately as a class or not (you'll need to make minor
changes to use it as a standalone version)
"""
def __init__(self, path: str):
self.path = path # File path/name WITHOUT extension
def read_cells(self):
"""
Reads all the files necessary to init cell class.
:return: {'cell1_name': [left-x, low-y, width, height, move-type],...}
Note that non-terminals move-type is None
"""
cells = {}
data = []
with open(self.path + '.pl') as p:
for num, line in enumerate(p):
if not(num == 0 or '#' in line or line == '\n'):
data = line.split()
cells[data[0]] = [float(data[1]), float(data[2])] # cell_name: [left-x, low-y]
data.clear()
with open(self.path + '.nodes') as n:
for num, line in enumerate(n):
if num == 0 or '#' in line or line == '\n' or 'NumNodes' in line or 'NumTerminals' in line:
continue
elif 'terminal' in line or 'terminal_NI' in line:
data = line.split()
cells[data[0]].append(float(data[1]))
cells[data[0]].append(float(data[2]))
cells[data[0]].append(data[3]) # Move-type
else:
data = line.split()
cells[data[0]].append(float(data[1]))
cells[data[0]].append(float(data[2]))
cells[data[0]].append(None) # None = Non-terminal
return cells
def read_nets(self):
"""
Reads all the files necessary to init net class.
:return: {'net_name': [cell1, cell2,...]}
"""
net_counter = -1
nets = {}
nets_index = {}
with open(self.path + '.nets') as n:
for num, line in enumerate(n):
if not(num == 0 or '#' in line or line == '\n' or 'NumNets' in line or 'NumPins' in line):
data = line.split()
if 'NetDegree' in line:
net_counter += 1
nets['n' + str(net_counter)] = []
nets_index[net_counter] = 'n' + str(net_counter)
else:
nets['n' + str(net_counter)].append(data[0])
return nets, nets_index
def read_rows(self):
"""
Reads all the necessary files to init row class
:return: {line_num: [coordinate, height, sitespacing, SubrowOrigin, NumSites], ...}
"""
rows = {}
data = []
row_count = -1
with open(self.path + '.scl') as s:
for _, line in enumerate(s):
if 'CoreRow' in line:
row_count += 1
if 'Coordinate' in line:
data = line.split()
rows[row_count] = [float(data[2])] # Coordinate
if 'Height' in line:
data = line.split()
rows[row_count].append(float(data[2])) # Height
if 'Sitespacing' in line:
data = line.split()
rows[row_count].append(float(data[2])) # Sitespacing
if 'SubrowOrigin' in line:
data = line.split()
rows[row_count].append(float(data[2])) # SubrowOrigin
rows[row_count].append(float(data[5])) # NumSites
return rows
|
# coding: utf-8
#
# Refs: https://github.com/openatx/uiautomator2/blob/d08e2e8468/uiautomator2/adbutils.py
from __future__ import print_function
import datetime
import os
import re
import socket
import stat
import struct
import subprocess
import time
from collections import namedtuple
from contextlib import contextmanager
import six
import whichcraft
_OKAY = "OKAY"
_FAIL = "FAIL"
_DENT = "DENT" # Directory Entity
_DONE = "DONE"
DeviceItem = namedtuple("Device", ["serial", "status"])
ForwardItem = namedtuple("ForwardItem", ["serial", "local", "remote"])
FileInfo = namedtuple("FileInfo", ['mode', 'size', 'mtime', 'name'])
def get_free_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
try:
return s.getsockname()[1]
finally:
s.close()
def adb_path():
path = whichcraft.which("adb")
if path is None:
raise EnvironmentError(
"Can't find the adb, please install adb on your PC")
return path
class AdbError(Exception):
""" adb error """
class _AdbStreamConnection(object):
def __init__(self, host=None, port=None):
# assert isinstance(host, six.string_types)
# assert isinstance(port, int)
self.__host = host
self.__port = port
self.__conn = None
self._connect()
def _connect(self):
adb_host = self.__host or os.environ.get("ANDROID_ADB_SERVER_HOST",
"127.0.0.1")
adb_port = self.__port or int(
os.environ.get("ANDROID_ADB_SERVER_PORT", 5037))
self.__conn
s = self.__conn = socket.socket()
s.connect((adb_host, adb_port))
return self
def close(self):
self.conn.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
self.close()
@property
def conn(self):
return self.__conn
def send(self, cmd):
assert isinstance(cmd, six.string_types)
self.conn.send("{:04x}{}".format(len(cmd), cmd).encode("utf-8"))
def read(self, n):
assert isinstance(n, int)
return self.conn.recv(n).decode()
def read_raw(self, n):
assert isinstance(n, int)
t = n
buffer = b''
while t > 0:
chunk = self.conn.recv(t)
if not chunk:
break
buffer += chunk
t = n - len(buffer)
return buffer
def read_string(self):
size = int(self.read(4), 16)
return self.read(size)
def read_until_close(self):
content = ""
while True:
chunk = self.read(4096)
if not chunk:
break
content += chunk
return content
def check_okay(self):
data = self.read(4)
if data == _FAIL:
raise AdbError(self.read_string())
elif data == _OKAY:
return
raise AdbError("Unknown data: %s" % data)
class AdbClient(object):
def connect(self):
return _AdbStreamConnection()
def server_version(self):
""" 40 will match 1.0.40
Returns:
int
"""
with self.connect() as c:
c.send("host:version")
c.check_okay()
return int(c.read_string(), 16)
def shell(self, serial, command):
"""Run shell in android and return output
Args:
serial (str)
command: list, tuple or str
Returns:
str
"""
assert isinstance(serial, six.string_types)
if isinstance(command, (list, tuple)):
command = subprocess.list2cmdline(command)
assert isinstance(command, six.string_types)
with self.connect() as c:
c.send("host:transport:" + serial)
c.check_okay()
c.send("shell:" + command)
c.check_okay()
return c.read_until_close()
def forward_list(self, serial=None):
list_cmd = "host:list-forward"
if serial:
list_cmd = "host-serial:{}:list-forward".format(serial)
with self.connect() as c:
c.send(list_cmd)
c.check_okay()
content = c.read_string()
for line in content.splitlines():
parts = line.split()
if len(parts) != 3:
continue
yield ForwardItem(*parts)
def forward(self, serial, local, remote, norebind=False):
"""
Args:
serial (str): device serial
local, remote (str): tcp:<port> or localabstract:<name>
norebind (bool): fail if already forwarded when set to true
Raises:
AdbError
Protocol: 0036host-serial:6EB0217704000486:forward:tcp:5533;tcp:9182
"""
with self.connect() as c:
cmds = ["host-serial", serial, "forward"]
if norebind:
cmds.append("norebind")
cmds.append(local + ";" + remote)
c.send(":".join(cmds))
c.check_okay()
def iter_device(self):
"""
Returns:
list of DeviceItem
"""
with self.connect() as c:
c.send("host:devices")
c.check_okay()
output = c.read_string()
for line in output.splitlines():
parts = line.strip().split("\t")
if len(parts) != 2:
continue
if parts[1] == 'device':
yield AdbDevice(self, parts[0])
def devices(self):
return list(self.iter_device())
def must_one_device(self):
ds = self.devices()
if len(ds) == 0:
raise RuntimeError("Can't find any android device/emulator")
if len(ds) > 1:
raise RuntimeError(
"more than one device/emulator, please specify the serial number"
)
return ds[0]
def device_with_serial(self, serial=None):
if not serial:
return self.must_one_device()
return AdbDevice(self, serial)
def sync(self, serial):
return Sync(self, serial)
class AdbDevice(object):
def __init__(self, client, serial):
self._client = client
self._serial = serial
@property
def serial(self):
return self._serial
def __repr__(self):
return "AdbDevice(serial={})".format(self.serial)
@property
def sync(self):
return Sync(self._client, self.serial)
def adb_output(self, *args, **kwargs):
"""Run adb command and get its content
Returns:
string of output
Raises:
EnvironmentError
"""
cmds = [adb_path(), '-s', self._serial
] if self._serial else [adb_path()]
cmds.extend(args)
cmdline = subprocess.list2cmdline(map(str, cmds))
try:
return subprocess.check_output(
cmdline, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
except subprocess.CalledProcessError as e:
if kwargs.get('raise_error', True):
raise EnvironmentError(
"subprocess", cmdline,
e.output.decode('utf-8', errors='ignore'))
def shell_output(self, *args):
return self._client.shell(self._serial, subprocess.list2cmdline(args))
def forward_port(self, remote_port):
assert isinstance(remote_port, int)
for f in self._client.forward_list(self._serial):
if f.serial == self._serial and f.remote == 'tcp:' + str(
remote_port) and f.local.startswith("tcp:"):
return int(f.local[len("tcp:"):])
local_port = get_free_port()
self._client.forward(self._serial, "tcp:" + str(local_port),
"tcp:" + str(remote_port))
return local_port
def push(self, local, remote):
assert isinstance(local, six.string_types)
assert isinstance(remote, six.string_types)
self.adb_output("push", local, remote)
def install(self, apk_path):
"""
sdk = self.getprop('ro.build.version.sdk')
sdk > 23 support -g
"""
assert isinstance(apk_path, six.string_types)
self.adb_output("install", "-r", apk_path)
def uninstall(self, pkg_name):
assert isinstance(pkg_name, six.string_types)
self.adb_output("uninstall", pkg_name)
def getprop(self, prop):
assert isinstance(prop, six.string_types)
return self.shell_output('getprop', prop).strip()
def package_info(self, pkg_name):
assert isinstance(pkg_name, six.string_types)
output = self.shell_output('dumpsys', 'package', pkg_name)
m = re.compile(r'versionName=(?P<name>[\d.]+)').search(output)
version_name = m.group('name') if m else None
m = re.search(r'PackageSignatures\{(.*?)\}', output)
signature = m.group(1) if m else None
if version_name is None and signature is None:
return None
return dict(version_name=version_name, signature=signature)
class Sync():
def __init__(self, adbclient, serial):
self._adbclient = adbclient
self._serial = serial
# self._path = path
@contextmanager
def _prepare_sync(self, path, cmd):
c = self._adbclient.connect()
try:
c.send(":".join(["host", "transport", self._serial]))
c.check_okay()
c.send("sync:")
c.check_okay()
# {COMMAND}{LittleEndianPathLength}{Path}
c.conn.send(
cmd.encode("utf-8") + struct.pack("<I", len(path)) +
path.encode("utf-8"))
yield c
finally:
c.close()
def stat(self, path):
assert isinstance(path, six.string_types)
with self._prepare_sync(path, "STAT") as c:
assert "STAT" == c.read(4)
mode, size, mtime = struct.unpack("<III", c.conn.recv(12))
return FileInfo(mode, size, datetime.datetime.fromtimestamp(mtime),
path)
def iter_directory(self, path):
assert isinstance(path, six.string_types)
with self._prepare_sync(path, "LIST") as c:
while 1:
response = c.read(4)
if response == _DONE:
break
mode, size, mtime, namelen = struct.unpack(
"<IIII", c.conn.recv(16))
name = c.read(namelen)
yield FileInfo(mode, size,
datetime.datetime.fromtimestamp(mtime), name)
def list(self, path):
return list(self.iter_directory(path))
def push(self, src, dst, mode=0o755):
# IFREG: File Regular
# IFDIR: File Directory
assert isinstance(dst, six.string_types)
path = dst + "," + str(stat.S_IFREG | mode)
with self._prepare_sync(path, "SEND") as c:
r = src if hasattr(src, "read") else open(src, "rb")
try:
while True:
chunk = r.read(4096)
if not chunk:
mtime = int(time.time())
c.conn.send(b"DONE" + struct.pack("<I", mtime))
break
c.conn.send(b"DATA" + struct.pack("<I", len(chunk)))
c.conn.send(chunk)
assert c.read(4) == _OKAY
finally:
if hasattr(r, "close"):
r.close()
def pull(self, path):
assert isinstance(path, six.string_types)
with self._prepare_sync(path, "RECV") as c:
while True:
cmd = c.read(4)
if cmd == "DONE":
break
assert cmd == "DATA"
chunk_size = struct.unpack("<I", c.read_raw(4))[0]
chunk = c.read_raw(chunk_size)
if len(chunk) != chunk_size:
raise RuntimeError("read chunk missing")
print("Chunk:", chunk)
adb = AdbClient()
if __name__ == "__main__":
print("server version:", adb.server_version())
print("devices:", adb.devices())
d = adb.devices()[0]
print(d.serial)
for f in adb.sync(d.serial).iter_directory("/data/local/tmp"):
print(f)
# adb.listdir(d.serial, "/data/local/tmp/")
finfo = adb.sync(d.serial).stat("/data/local/tmp")
print(finfo)
import io
sync = adb.sync(d.serial)
sync.push(
io.BytesIO(b"hi5a4de5f4qa6we541fq6w1ef5a61f65ew1rf6we"),
"/data/local/tmp/hi.txt", 0o644)
# sync.mkdir("/data/local/tmp/foo")
sync.pull("/data/local/tmp/hi.txt")
|
'''
Set of tools for processing the
data of mechanical testings.
'''
__name__ = 'mechanical_testing'
__version__ = '0.0.0'
from .TensileTest import TensileTest |
from .bot import Bot
from .errors import *
from .converter import *
from .context import Context
from .core import *
from .cog import Cog
from .help import HelpCommand, DefaultHelpCommand
|
"""Parallel beam search module for online simulation."""
import logging
from pathlib import Path
from typing import List
import yaml
import torch
from espnet_pytorch_library.batch_beam_search import BatchBeamSearch
from espnet_pytorch_library.beam_search import Hypothesis
from espnet_pytorch_library.e2e_asr_common import end_detect
class BatchBeamSearchOnlineSim(BatchBeamSearch):
"""Online beam search implementation.
This simulates streaming decoding.
It requires encoded features of entire utterance and
extracts block by block from it as it shoud be done
in streaming processing.
This is based on Tsunoo et al, "STREAMING TRANSFORMER ASR
WITH BLOCKWISE SYNCHRONOUS BEAM SEARCH"
(https://arxiv.org/abs/2006.14941).
"""
def set_streaming_config(self, asr_config: str):
"""Set config file for streaming decoding.
Args:
asr_config (str): The config file for asr training
"""
train_config_file = Path(asr_config)
self.block_size = None
self.hop_size = None
self.look_ahead = None
config = None
with train_config_file.open("r", encoding="utf-8") as f:
args = yaml.safe_load(f)
if "encoder_conf" in args.keys():
if "block_size" in args["encoder_conf"].keys():
self.block_size = args["encoder_conf"]["block_size"]
if "hop_size" in args["encoder_conf"].keys():
self.hop_size = args["encoder_conf"]["hop_size"]
if "look_ahead" in args["encoder_conf"].keys():
self.look_ahead = args["encoder_conf"]["look_ahead"]
elif "config" in args.keys():
config = args["config"]
if config is None:
logging.info(
"Cannot find config file for streaming decoding: "
+ "apply batch beam search instead."
)
return
if (
self.block_size is None or self.hop_size is None or self.look_ahead is None
) and config is not None:
config_file = Path(config)
with config_file.open("r", encoding="utf-8") as f:
args = yaml.safe_load(f)
if "encoder_conf" in args.keys():
enc_args = args["encoder_conf"]
if enc_args and "block_size" in enc_args:
self.block_size = enc_args["block_size"]
if enc_args and "hop_size" in enc_args:
self.hop_size = enc_args["hop_size"]
if enc_args and "look_ahead" in enc_args:
self.look_ahead = enc_args["look_ahead"]
def set_block_size(self, block_size: int):
"""Set block size for streaming decoding.
Args:
block_size (int): The block size of encoder
"""
self.block_size = block_size
def set_hop_size(self, hop_size: int):
"""Set hop size for streaming decoding.
Args:
hop_size (int): The hop size of encoder
"""
self.hop_size = hop_size
def set_look_ahead(self, look_ahead: int):
"""Set look ahead size for streaming decoding.
Args:
look_ahead (int): The look ahead size of encoder
"""
self.look_ahead = look_ahead
def forward(
self, x: torch.Tensor, maxlenratio: float = 0.0, minlenratio: float = 0.0
) -> List[Hypothesis]:
"""Perform beam search.
Args:
x (torch.Tensor): Encoded speech feature (T, D)
maxlenratio (float): Input length ratio to obtain max output length.
If maxlenratio=0.0 (default), it uses a end-detect function
to automatically find maximum hypothesis lengths
minlenratio (float): Input length ratio to obtain min output length.
Returns:
list[Hypothesis]: N-best decoding results
"""
self.conservative = True # always true
if self.block_size and self.hop_size and self.look_ahead:
cur_end_frame = int(self.block_size - self.look_ahead)
else:
cur_end_frame = x.shape[0]
process_idx = 0
if cur_end_frame < x.shape[0]:
h = x.narrow(0, 0, cur_end_frame)
else:
h = x
# set length bounds
if maxlenratio == 0:
maxlen = x.shape[0]
else:
maxlen = max(1, int(maxlenratio * x.size(0)))
minlen = int(minlenratio * x.size(0))
logging.info("decoder input length: " + str(x.shape[0]))
logging.info("max output length: " + str(maxlen))
logging.info("min output length: " + str(minlen))
# main loop of prefix search
running_hyps = self.init_hyp(h)
prev_hyps = []
ended_hyps = []
prev_repeat = False
continue_decode = True
while continue_decode:
move_to_next_block = False
if cur_end_frame < x.shape[0]:
h = x.narrow(0, 0, cur_end_frame)
else:
h = x
# extend states for ctc
self.extend(h, running_hyps)
while process_idx < maxlen:
logging.debug("position " + str(process_idx))
best = self.search(running_hyps, h)
if process_idx == maxlen - 1:
# end decoding
running_hyps = self.post_process(
process_idx, maxlen, maxlenratio, best, ended_hyps
)
n_batch = best.yseq.shape[0]
local_ended_hyps = []
is_local_eos = (
best.yseq[torch.arange(n_batch), best.length - 1] == self.eos
)
for i in range(is_local_eos.shape[0]):
if is_local_eos[i]:
hyp = self._select(best, i)
local_ended_hyps.append(hyp)
# NOTE(tsunoo): check repetitions here
# This is a implicit implementation of
# Eq (11) in https://arxiv.org/abs/2006.14941
# A flag prev_repeat is used instead of using set
elif (
not prev_repeat
and best.yseq[i, -1] in best.yseq[i, :-1]
and cur_end_frame < x.shape[0]
):
move_to_next_block = True
prev_repeat = True
if maxlenratio == 0.0 and end_detect(
[lh.asdict() for lh in local_ended_hyps], process_idx
):
logging.info(f"end detected at {process_idx}")
continue_decode = False
break
if len(local_ended_hyps) > 0 and cur_end_frame < x.shape[0]:
move_to_next_block = True
if move_to_next_block:
if (
self.hop_size
and cur_end_frame + int(self.hop_size) + int(self.look_ahead)
< x.shape[0]
):
cur_end_frame += int(self.hop_size)
else:
cur_end_frame = x.shape[0]
logging.debug("Going to next block: %d", cur_end_frame)
if process_idx > 1 and len(prev_hyps) > 0 and self.conservative:
running_hyps = prev_hyps
process_idx -= 1
prev_hyps = []
break
prev_repeat = False
prev_hyps = running_hyps
running_hyps = self.post_process(
process_idx, maxlen, maxlenratio, best, ended_hyps
)
if cur_end_frame >= x.shape[0]:
for hyp in local_ended_hyps:
ended_hyps.append(hyp)
if len(running_hyps) == 0:
logging.info("no hypothesis. Finish decoding.")
continue_decode = False
break
else:
logging.debug(f"remained hypotheses: {len(running_hyps)}")
# increment number
process_idx += 1
nbest_hyps = sorted(ended_hyps, key=lambda x: x.score, reverse=True)
# check the number of hypotheses reaching to eos
if len(nbest_hyps) == 0:
logging.warning(
"there is no N-best results, perform recognition "
"again with smaller minlenratio."
)
return (
[]
if minlenratio < 0.1
else self.forward(x, maxlenratio, max(0.0, minlenratio - 0.1))
)
# report the best result
best = nbest_hyps[0]
for k, v in best.scores.items():
logging.info(
f"{v:6.2f} * {self.weights[k]:3} = {v * self.weights[k]:6.2f} for {k}"
)
logging.info(f"total log probability: {best.score:.2f}")
logging.info(f"normalized log probability: {best.score / len(best.yseq):.2f}")
logging.info(f"total number of ended hypotheses: {len(nbest_hyps)}")
if self.token_list is not None:
logging.info(
"best hypo: "
+ "".join([self.token_list[x] for x in best.yseq[1:-1]])
+ "\n"
)
return nbest_hyps
def extend(self, x: torch.Tensor, hyps: Hypothesis) -> List[Hypothesis]:
"""Extend probabilities and states with more encoded chunks.
Args:
x (torch.Tensor): The extended encoder output feature
hyps (Hypothesis): Current list of hypothesis
Returns:
Hypothesis: The exxtended hypothesis
"""
for k, d in self.scorers.items():
if hasattr(d, "extend_prob"):
d.extend_prob(x)
if hasattr(d, "extend_state"):
hyps.states[k] = d.extend_state(hyps.states[k])
|
import plyfile
import numpy as np
from skimage.measure import marching_cubes_lewiner
from mayavi import mlab
def extract_mesh_marching_cubes(volume, color=None, level=0.5,
step_size=1.0, gradient_direction="ascent"):
if level > volume.max() or level < volume.min():
return
verts, faces, normals, values = marching_cubes_lewiner(volume[:, :, :, 0],
level=level,
step_size=step_size,
gradient_direction=gradient_direction)
ply_verts = np.empty(len(verts),
dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
ply_verts["x"] = verts[:, 0]
ply_verts["y"] = verts[:, 1]
ply_verts["z"] = verts[:, 2]
ply_verts = plyfile.PlyElement.describe(ply_verts, "vertex")
if color is None:
ply_faces = np.empty(
len(faces), dtype=[("vertex_indices", "i4", (3,))])
else:
ply_faces = np.empty(
len(faces), dtype=[("vertex_indices", "i4", (3,)),
("red", "u1"), ("green", "u1"), ("blue", "u1")])
ply_faces["red"] = color[0]
ply_faces["green"] = color[1]
ply_faces["blue"] = color[2]
ply_faces["vertex_indices"] = faces
ply_faces = plyfile.PlyElement.describe(ply_faces, "face")
return plyfile.PlyData([ply_verts, ply_faces])
def plot_mesh(mesh):
vertices = mesh['vertex']
# extract vertex coordinates
(x, y, z) = (vertices[t] for t in ('x', 'y', 'z'))
mlab.points3d(x, y, z, color=(1, 1, 1), mode='point')
if 'face' in mesh:
tri_idx = mesh['face']['vertex_indices']
triangles = np.asarray(tri_idx)
mlab.triangular_mesh(x, y, z, triangles)
mlab.show()
def plot_grid(grid, eye=None):
xx, yy , zz = np.where(grid == 1)
mlab.points3d(xx, yy, zz,
mode='cube',
color=(0, 1, 0),
scale_factor=1)
if eye is not None:
xx, yy, zz = eye[:, 0].ravel(), eye[:, 1].ravel(), eye[:, 2].ravel()
mlab.points3d(xx, yy, zz,
mode='cube',
color=(1, 0, 0),
scale_factor=1)
mlab.show()
|
"""
conftest.py
"""
def pytest_addoption(parser):
parser.addoption(
"--no-catalog", action="store_true", default=False, help="skip tests that need catalogs"
)
_SKIP_IF_NO_CATALOG = {
'test_protoDC2.py',
'test_catalogs.py',
}
def pytest_ignore_collect(path, config):
if config.getoption('--no-catalog') and path.basename in _SKIP_IF_NO_CATALOG:
return True
|
class OnlyOne(object):
"""
Signleton class , only one obejct of this type can be created
any class derived from it will be Singleton
"""
__instance = None
def __new__(typ, *args, **kwargs):
if OnlyOne.__instance == None:
obj = object.__new__(typ, *args, **kwargs)
OnlyOne.__instance = obj
return OnlyOne.__instance
print OnlyOne() == OnlyOne()
# testing derived class
class My1(OnlyOne): pass
print My1() == My1()
|
import os
############
#Definitions
############
Import('mode')
use_gcc = GetOption('use_gcc')
std_cc_flags = ['-std=gnu11',
'-Wall',
'-Wextra',
'-pedantic',
'-fPIC',
'-pthread']
std_cxx_flags = ['-std=c++11',
'-Wall',
'-Wextra',
'-pedantic',
'-fPIC']
std_link_flags = ['-pthread']
debug_flags = ['-O0',
'-g']
optimization_flags = ['-O3']
profile_flags = ['-fno-omit-frame-pointer -O2']
if(mode=='debug'):
std_cc_flags = std_cc_flags + debug_flags
std_cxx_flags = std_cxx_flags + debug_flags
std_link_flags = std_link_flags + debug_flags
elif(mode=='profile'):
std_cc_flags = std_cc_flags + profile_flags
std_cxx_flags = std_cxx_flags + profile_flags
std_link_flags = std_link_flags + profile_flags
else:
std_cc_flags = std_cc_flags + optimization_flags
std_cxx_flags = std_cxx_flags + optimization_flags
std_link_flags = std_link_flags + optimization_flags
cc = 'clang'
cxx = 'clang++'
if use_gcc:
cc = 'gcc'
cxx = 'g++'
env = Environment(
ENV = os.environ,
CFLAGS = ' '.join(std_cc_flags),
CXXFLAGS = ' '.join(std_cxx_flags),
CC = cc,
CXX = cxx,
LINKFLAGS = ' '.join(std_link_flags),
CPPPATH = ['src/c/'])
for var in ['CC', 'CXX', 'CFLAGS', 'CXXFLAGS']:
os_value = os.getenv(var)
if os_value is not None:
env[var] = os_value
######
#Build
######
#Tests
######
# env.Program(source='src/c/tests/test_set.c',
# target='test_set')
read_indicator_object = env.Object(source='src/c/read_indicators/reader_groups_read_indicator.c')
ccsynch_lock_object = env.Object(source='src/c/locks/ccsynch_lock.c')
drmcs_lock_object = env.Object(source='src/c/locks/drmcs_lock.c')
mcs_lock_object = env.Object(source='src/c/locks/mcs_lock.c')
mrqd_lock_object = env.Object(source='src/c/locks/mrqd_lock.c')
qd_lock_object = env.Object(source='src/c/locks/qd_lock.c')
tatas_lock_object = env.Object(source='src/c/locks/tatas_lock.c')
lock_dependencies = [read_indicator_object,ccsynch_lock_object,drmcs_lock_object,mcs_lock_object,mrqd_lock_object,qd_lock_object,tatas_lock_object]
chained_hash_set_object = env.Object(source='src/c/data_structures/chained_hash_set.c')
conc_splitch_set_object = env.Object(source='src/c/data_structures/conc_splitch_set.c')
sorted_list_set_object = env.Object(source='src/c/data_structures/sorted_list_set.c')
data_structures_dependencies = [chained_hash_set_object,conc_splitch_set_object,sorted_list_set_object]
dependencies = lock_dependencies + data_structures_dependencies
#Static Library
################
static_lib = env.StaticLibrary(target = 'qd_lock_lib', source = dependencies)
#Dynamic Library
################
dynamic_lib = env.SharedLibrary(target = 'qd_lock_lib',
source =
Glob('src/c/data_structures/*.c') +
Glob('src/c/locks/*.c') +
Glob('src/c/read_indicators/*.c'))
#Tests
######
env.Program(source=['src/c/tests/test_lock.c'] + dependencies,
target='test_lock',
CPPDEFINES=[('LOCK_TYPE', 'OOLock')])
env.Program(source='src/c/tests/test_qd_queue.c',
target='test_qd_queue')
if not use_gcc:
#Plain locks
#type, type name
all_locks = [('TATASLock', 'PLAIN_TATAS_LOCK'),
('QDLock', 'PLAIN_QD_LOCK'),
('MRQDLock', 'PLAIN_MRQD_LOCK'),
('CCSynchLock', 'PLAIN_CCSYNCH_LOCK'),
('MCSLock', 'PLAIN_MCS_LOCK'),
('DRMCSLock', 'PLAIN_DRMCS_LOCK')]
for (lock_type, lock_type_name) in all_locks:
object = env.Object(source='src/c/tests/test_lock.c',
target='objects/test_' + lock_type_name + '.o',
CPPDEFINES=[('LOCK_TYPE', lock_type),
('LOCK_TYPE_NAME', lock_type_name)])
env.Program(source=[object] + dependencies,
target='test_' + lock_type_name)
#Plain Sets
#type, type name
all_sets = [('ChainedHashSet', 'PLAIN_CHAINED_HASH_SET'),
('SortedListSet', 'PLAIN_SORTED_LIST_SET'),
('ConcSplitchSet', 'PLAIN_CONC_SPLITCH_SET')
]
for (set_type, set_type_name) in all_sets:
object = env.Object(source='src/c/tests/test_set.c',
target='objects/test_' + set_type_name + '.o',
CPPDEFINES=[('SET_TYPE', set_type),
('SET_TYPE_NAME', set_type_name)])
env.Program(source=[object] + dependencies,
target='test_' + set_type_name)
#Static Library
################
static_lib = env.StaticLibrary(target = 'qd_lock_lib', source = dependencies)
#Examples
#########
env.Program(source=['src/c/examples/qd_lock_delegate_example.c'] + static_lib,
target='qd_lock_delegate_example')
env.Program(source=['src/c/examples/shared_int_example.c'] + static_lib,
target='shared_int_example')
env.Program(source=['src/c/examples/concurrent_queue_example.c'] + static_lib,
target='concurrent_queue_example')
|
# coding=utf-8
import socket
import ipaddress
import re
import geoip2.database
# 通过VT查询pdns,然后排除国内外常见的cdn段,如果出现极有可能是真实ip
cdns = ['173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15',
'104.16.0.0/12',
'172.64.0.0/13', '131.0.72.0/22', '13.124.199.0/24', '144.220.0.0/16', '34.226.14.0/24', '52.124.128.0/17',
'54.230.0.0/16', '54.239.128.0/18', '52.82.128.0/19', '99.84.0.0/16', '52.15.127.128/26', '35.158.136.0/24',
'52.57.254.0/24', '18.216.170.128/25', '13.54.63.128/26', '13.59.250.0/26', '13.210.67.128/26',
'35.167.191.128/26', '52.47.139.0/24', '52.199.127.192/26', '52.212.248.0/26', '205.251.192.0/19',
'52.66.194.128/26', '54.239.192.0/19', '70.132.0.0/18', '13.32.0.0/15', '13.224.0.0/14', '13.113.203.0/24',
'34.195.252.0/24', '35.162.63.192/26', '34.223.12.224/27', '13.35.0.0/16', '204.246.172.0/23',
'204.246.164.0/22', '52.56.127.0/25', '204.246.168.0/22', '13.228.69.0/24', '34.216.51.0/25',
'71.152.0.0/17', '216.137.32.0/19', '205.251.249.0/24', '99.86.0.0/16', '52.46.0.0/18', '52.84.0.0/15',
'54.233.255.128/26', '130.176.0.0/16', '64.252.64.0/18', '52.52.191.128/26', '204.246.174.0/23',
'64.252.128.0/18', '205.251.254.0/24', '143.204.0.0/16', '205.251.252.0/23', '52.78.247.128/26',
'204.246.176.0/20', '52.220.191.0/26', '13.249.0.0/16', '54.240.128.0/18', '205.251.250.0/23',
'52.222.128.0/17', '54.182.0.0/16', '54.192.0.0/16', '34.232.163.208/29', '58.250.143.0/24',
'58.251.121.0/24', '59.36.120.0/24', '61.151.163.0/24', '101.227.163.0/24', '111.161.109.0/24',
'116.128.128.0/24', '123.151.76.0/24', '125.39.46.0/24', '140.207.120.0/24', '180.163.22.0/24',
'183.3.254.0/24', '223.166.151.0/24', '113.107.238.0/24', '106.42.25.0/24', '183.222.96.0/24',
'117.21.219.0/24', '116.55.250.0/24', '111.202.98.0/24', '111.13.147.0/24', '122.228.238.0/24',
'58.58.81.0/24', '1.31.128.0/24', '123.155.158.0/24', '106.119.182.0/24', '180.97.158.0/24',
'113.207.76.0/24', '117.23.61.0/24', '118.212.233.0/24', '111.47.226.0/24', '219.153.73.0/24',
'113.200.91.0/24', '1.32.240.0/24', '203.90.247.0/24', '183.110.242.0/24', '202.162.109.0/24',
'182.23.211.0/24', '1.32.242.0/24', '1.32.241.0/24', '202.162.108.0/24', '185.254.242.0/24',
'109.94.168.0/24', '109.94.169.0/24', '1.32.243.0/24', '61.120.154.0/24', '1.255.41.0/24',
'112.90.216.0/24', '61.213.176.0/24', '1.32.238.0/24', '1.32.239.0/24', '1.32.244.0/24', '111.32.135.0/24',
'111.32.136.0/24', '125.39.174.0/24', '125.39.239.0/24', '112.65.73.0/24', '112.65.74.0/24',
'112.65.75.0/24', '119.84.92.0/24', '119.84.93.0/24', '113.207.100.0/24', '113.207.101.0/24',
'113.207.102.0/24', '180.163.188.0/24', '180.163.189.0/24', '163.53.89.0/24', '101.227.206.0/24',
'101.227.207.0/24', '119.188.97.0/24', '119.188.9.0/24', '61.155.149.0/24', '61.156.149.0/24',
'61.155.165.0/24', '61.182.137.0/24', '61.182.136.0/24', '120.52.29.0/24', '120.52.113.0/24',
'222.216.190.0/24', '219.159.84.0/24', '183.60.235.0/24', '116.31.126.0/24', '116.31.127.0/24',
'117.34.13.0/24', '117.34.14.0/24', '42.236.93.0/24', '42.236.94.0/24', '119.167.246.0/24',
'150.138.149.0/24', '150.138.150.0/24', '150.138.151.0/24', '117.27.149.0/24', '59.51.81.0/24',
'220.170.185.0/24', '220.170.186.0/24', '183.61.236.0/24', '14.17.71.0/24', '119.147.134.0/24',
'124.95.168.0/24', '124.95.188.0/24', '61.54.46.0/24', '61.54.47.0/24', '101.71.55.0/24', '101.71.56.0/24',
'183.232.51.0/24', '183.232.53.0/24', '157.255.25.0/24', '157.255.26.0/24', '112.25.90.0/24',
'112.25.91.0/24', '58.211.2.0/24', '58.211.137.0/24', '122.190.2.0/24', '122.190.3.0/24', '183.61.177.0/24',
'183.61.190.0/24', '117.148.160.0/24', '117.148.161.0/24', '115.231.186.0/24', '115.231.187.0/24',
'113.31.27.0/24', '222.186.19.0/24', '122.226.182.0/24', '36.99.18.0/24', '123.133.84.0/24',
'221.204.202.0/24', '42.236.6.0/24', '61.130.28.0/24', '61.174.9.0/24', '223.94.66.0/24', '222.88.94.0/24',
'61.163.30.0/24', '223.94.95.0/24', '223.112.227.0/24', '183.250.179.0/24', '120.241.102.0/24',
'125.39.5.0/24', '124.193.166.0/24', '122.70.134.0/24', '111.6.191.0/24', '122.228.198.0/24',
'121.12.98.0/24', '60.12.166.0/24', '118.180.50.0/24', '183.203.7.0/24', '61.133.127.0/24',
'113.7.183.0/24', '210.22.63.0/24', '60.221.236.0/24', '122.227.237.0/24', '123.6.13.0/24',
'202.102.85.0/24', '61.160.224.0/24', '182.140.227.0/24', '221.204.14.0/24', '222.73.144.0/24',
'61.240.144.0/24', '36.27.212.0/24', '125.88.189.0/24', '120.52.18.0/24', '119.84.15.0/24',
'180.163.224.0/24', '46.51.216.0/21']
ASNS = ['55770', '49846', '49249', '48163', '45700', '43639', '39836', '393560', '393234', '36183', '35994', '35993',
'35204', '34850', '34164', '33905', '32787', '31377', '31110', '31109', '31108', '31107', '30675', '24319',
'23903', '23455', '23454', '22207', '21399', '21357', '21342', '20940', '20189', '18717', '18680', '17334',
'16702', '16625', '12222', '61107', '60922', '60626', '49689', '209101', '201585', '136764', '135429', '135295',
'133496', '395747', '394536', '209242', '203898', '202623', '14789', '133877', '13335', '132892']
def iscdn(host):
if not re.search(r'\d+\.\d+\.\d+\.\d+', host):
socket.setdefaulttimeout(1)
host = socket.gethostbyname(host)
result = True
for cdn in cdns:
if (ipaddress.ip_address(host) in ipaddress.ip_network(cdn)):
result = False
try:
with geoip2.database.Reader('db/GeoLite2-ASN.mmdb') as reader:
response = reader.asn(host)
for i in ASNS:
if response.autonomous_system_number == int(i):
result = False
except:
pass
return result
|
import torch
from torch.autograd import Variable
import torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.optim as optim
import math
import numpy as np
import os
import torch.nn.functional as F
import torch.nn.init as init
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import pickle
# Calling Seaborn causes pytorch warnings to be repeated in each loop, so I turned off these redudant warnings, but make sure
# you do not miss something important.
warnings.filterwarnings('ignore')
class CNNVAE1(nn.Module):
def __init__(self, z_dim=2):
super(CNNVAE1, self).__init__()
self.z_dim = z_dim
self.encode = nn.Sequential(
nn.Conv2d(3, 32, 4, 2, 1),
nn.ReLU(True),
nn.Conv2d(32, 32, 4, 2, 1),
nn.ReLU(True),
nn.Conv2d(32, 64, 4, 2, 1),
nn.ReLU(True),
nn.Conv2d(64, 64, 4, 2, 1),
nn.ReLU(True),
nn.Conv2d(64, 128, 4, 2, 1),
nn.ReLU(True),
nn.Conv2d(128, 2 * z_dim, 1),
)
self.decode = nn.Sequential(
nn.Conv2d(z_dim, 128, 1),
nn.ReLU(True),
nn.ConvTranspose2d(128, 128, 4, 2, 1),
nn.ReLU(True),
nn.ConvTranspose2d(128, 64, 4, 2, 1),
nn.ReLU(True),
nn.ConvTranspose2d(64, 64, 4, 2, 1),
nn.ReLU(True),
nn.ConvTranspose2d(64, 32, 4, 2, 1),
nn.ReLU(True),
nn.ConvTranspose2d(32, 3, 4, 2, 1),
nn.Sigmoid(),
)
def reparametrize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
eps = std.data.new(std.size()).normal_()
return eps.mul(std).add_(mu)
def forward(self, x, no_enc=False, no_dec=False):
if no_enc:
gen_z = Variable(torch.randn(100, z_dim, 1, 1), requires_grad=False)
gen_z = gen_z.to(device)
return self.decode(gen_z).view(x.size())
elif no_dec:
stats = self.encode(x)
mu = stats[:, :self.z_dim]
logvar = stats[:, self.z_dim:]
z = self.reparametrize(mu, logvar)
return z.squeeze()
else:
stats = self.encode(x)
mu = stats[:, :self.z_dim]
logvar = stats[:, self.z_dim:]
z = self.reparametrize(mu, logvar)
x_recon = self.decode(z).view(x.size())
return x_recon, mu, logvar, z.squeeze()
def recon_loss(x_recon, x):
n = x.size(0)
loss = F.binary_cross_entropy(x_recon, x, size_average=False).div(n)
return loss
def kl_divergence(mu, logvar):
kld = -0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(1).mean()
return kld
def compute_kernel(x, y):
x_size = x.size(0)
y_size = y.size(0)
dim = x.size(1)
x = x.unsqueeze(1) # (x_size, 1, dim)
y = y.unsqueeze(0) # (1, y_size, dim)
tiled_x = x.expand(x_size, y_size, dim)
tiled_y = y.expand(x_size, y_size, dim)
kernel_input = (tiled_x - tiled_y).pow(2).mean(2)/float(dim)
return torch.exp(-kernel_input) # (x_size, y_size)
def compute_mmd(x, y):
x_kernel = compute_kernel(x, x)
y_kernel = compute_kernel(y, y)
xy_kernel = compute_kernel(x, y)
mmd = x_kernel.mean() + y_kernel.mean() - 2*xy_kernel.mean()
return mmd
use_cuda = torch.cuda.is_available()
device = 'cuda' if use_cuda else 'cpu'
print('This code is running over', device)
max_iter = int(5)
batch_size = 100
z_dim = 500
lr_D = 0.001
beta1_D = 0.9
beta2_D = 0.999
batch_size_test = 500
training_set = datasets.CIFAR10('./tmp/CIFAR10', train=True, download=True, transform=transforms.ToTensor())
test_set = datasets.CIFAR10('./tmp/CIFAR10', train=False, download=True, transform=transforms.ToTensor())
data_loader = DataLoader(training_set, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_set, batch_size=batch_size_test, shuffle=True, num_workers=3)
VAE = CNNVAE1(z_dim).to(device)
optim_VAE = optim.Adam(VAE.parameters(), lr=lr_D, betas=(beta1_D, beta2_D))
Result = []
for epoch in range(max_iter):
train_loss = 0
train_info_loss = 0
Loglikehood_loss = 0
KL_loss = 0
MMD_loss = 0
for batch_idx, (x_true,_) in enumerate(data_loader):
x_true = x_true.to(device)
x_recon, mu, logvar, z = VAE(x_true)
P_z = Variable(torch.randn(batch_size, z_dim), requires_grad=False).to(device)
MMD = compute_mmd(P_z, z)
vae_recon_loss = recon_loss(x_recon, x_true)
vae_kld = kl_divergence(mu, logvar)
vae_loss = vae_recon_loss +0.5*vae_kld + 1000 * MMD
optim_VAE.zero_grad()
vae_loss.backward()
optim_VAE.step()
train_loss += vae_loss.item()
Loglikehood_loss += vae_recon_loss.item()
KL_loss += vae_kld.item()
MMD_loss += MMD
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)] \t Loss: {:.6f} \t Cross Entropy: {:.6f} \t KL Loss: {:.6f} \t MMD: {:.6f}'.format(epoch, batch_idx * len(x_true),
len(data_loader.dataset),
100. * batch_idx / len(data_loader),
vae_loss.item(),
vae_recon_loss.item(),
vae_kld.item(),
MMD
))
print('====> Epoch: {}, \t Average loss: {:.4f}, \t Log Likeihood: {:.4f}, \t KL: {:.4f} \t MMD: {:6f}'
.format(epoch, train_loss / (batch_idx + 1), Loglikehood_loss/ (batch_idx + 1), KL_loss/ (batch_idx + 1), MMD_loss/ (batch_idx + 1)))
Result.append(('====>epoch:', epoch,
'loss:', train_loss / (batch_idx + 1),
'Loglikelihood:', Loglikehood_loss / (batch_idx + 1),
'KL:', KL_loss / (batch_idx + 1),
))
with open("MMD_Plain_CNN_CIFAR10.txt", "w") as output:
output.write(str(Result))
torch.save(VAE.state_dict(), './MMD_Plain_CNN_CIFAR10')
print('The net\'s parameters are saved')
|
from scipy.stats import zscore
class Statseg:
def __init__(self, coordinates, stat_mat, res, eval_func):
# initialization
self.coordinates = coordinates
self.stat_mat = stat_mat
self.norm_stat_mat = zscore(stat_mat, axis=0)
self.res = res
# make var_mat
self.gen_var_mat()
# calculate k change points and k+1 segments
def set_point_num(self, k):
self.cps = self.calc_cps(k)
self.segments = self.calc_segments(self.cps)
# evaluate based on the function take x and label
def scoring(self, eval_func):
val = eval_func(self.norm_stat_mat, self.segments)
return(val)
# generate variance matrix
def gen_var_mat(self):
|
# -*- test-case-name: xquotient.test.test_filter -*-
"""
Defines simple, customizable rule-based Message filtering.
"""
import re
from zope.interface import implements
from twisted.python import reflect, components
from nevow import inevow, athena
from axiom import item, attributes
from axiom.iaxiom import IReliableListener
from axiom.item import Item
from axiom.tags import Catalog
from axiom.dependency import dependsOn
from axiom.upgrade import registerUpgrader
from xmantissa import ixmantissa, webnav, webtheme, liveform
from xquotient import iquotient, mail
from xquotient.mail import MessageSource
from xquotient.equotient import NoSuchHeader
from xquotient.exmess import (
DRAFT_STATUS, OUTBOX_STATUS, BOUNCED_STATUS, SENT_STATUS)
class RuleFilteringPowerup(item.Item):
"""
Filters messages according to a set of user-defined filtering
rules.
"""
typeName = 'xquotient_filter_filteringpowerup'
schemaVersion = 2
tagCatalog = dependsOn(Catalog, doc="""
The catalog in which to tag items to which this action is applied.
""")
messageSource = dependsOn(mail.MessageSource)
filters = attributes.inmemory()
powerupInterfaces = (ixmantissa.INavigableElement,)
def activate(self):
self.filters = None
def installed(self):
self.messageSource.addReliableListener(self)
def getTabs(self):
return [webnav.Tab('Mail', self.storeID, 0.2, children=
[webnav.Tab('Filtering', self.storeID, 0.1)],
authoritative=False)]
def processItem(self, item):
if self.filters is None:
self.filters = list(self.powerupsFor(iquotient.IFilteringRule))
for f in self.filters:
matched, proceed, extraData = f.applyTo(item)
if matched:
f.getAction().actOn(self, f, item, extraData)
if not proceed:
break
def ruleFilter1to2(old):
"""
Add messageSource field since RuleFilteringPowerup depends on
it. Remove installedOn.
"""
return old.upgradeVersion(RuleFilteringPowerup.typeName, 1, 2,
tagCatalog = old.tagCatalog,
messageSource = old.store.findUnique(
mail.MessageSource))
registerUpgrader(ruleFilter1to2, RuleFilteringPowerup.typeName, 1, 2)
class RuleFilterBenefactor(item.Item):
"""
Endows users with RuleFilteringPowerup.
"""
typeName = 'xquotient_filter_filterbenefactor'
implements(ixmantissa.IBenefactor)
powerupNames = ["xquotient.filter.RuleFilteringPowerup"]
installedOn = attributes.reference()
endowed = attributes.integer(default=0)
class MailingListFilterBenefactor(item.Item):
"""
Endows users with MailingListFilteringPowerup.
"""
implements(ixmantissa.IBenefactor)
powerupNames = ["xquotient.filter.MailingListFilteringPowerup"]
installedOn = attributes.reference()
endowed = attributes.integer(default=0)
class FixedTagAction(item.Item):
implements(iquotient.IFilteringAction)
tagName = attributes.text(doc="""
The tag to apply to items to which this action is applied.
""")
def __repr__(self):
return '<FixedTagAction %r>' % (self.tagName,)
def actOn(self, pup, rule, item, extraData):
pup.tagCatalog.tag(item, self.tagName, rule)
class VariableTagAction(item.Item):
implements(iquotient.IFilteringAction)
def __repr__(self):
return '<VariableTagAction>'
def actOn(self, pup, rule, item, extraData):
pup.tagCatalog.tag(item, extraData['tagName'], rule)
class MailingListTagAction(object):
def actOn(self, pup, rule, item, extraData):
pup.tagCatalog.tag(item, extraData['mailingListName'], rule)
EQUALS, STARTSWITH, ENDSWITH, CONTAINS = range(4)
_opsToFunctions = [
lambda a, b: a == b,
unicode.startswith,
unicode.endswith,
unicode.__contains__,
]
_namesToOps = {
'equals': EQUALS,
'startswith': STARTSWITH,
'endswith': ENDSWITH,
'contains': CONTAINS,
}
_opsToNames = {
EQUALS: 'equals',
STARTSWITH: 'startswith',
ENDSWITH: 'endswith',
CONTAINS: 'contains',
}
class HeaderRule(item.Item):
implements(iquotient.IFilteringRule)
headerName = attributes.text(doc="""
Name of the header to which this rule applies.
""", allowNone=False)
negate = attributes.boolean(doc="""
Take the opposite of the operation's result.
""", default=False, allowNone=False)
operation = attributes.integer(doc="""
One of EQUALS, STARTSWITH, ENDSWITH, or CONTAINS.
""", allowNone=False)
value = attributes.text(doc="""
Text which will be used in applying this rule.
""", allowNone=False)
shortCircuit = attributes.boolean(doc="""
Stop all further processing if this rule matches.
""", default=False, allowNone=False)
caseSensitive = attributes.boolean(doc="""
Consider case when applying this rule.
""", default=False, allowNone=False)
action = attributes.reference(doc="""
The L{iquotient.IFilteringAction} to take when this rule matches.
""")
def __repr__(self):
return '<HeaderRule on %r %s%s %r (%s%s)>' % (
self.headerName,
self.negate and '!' or '',
_opsToNames[self.operation],
self.value,
self.caseSensitive and 'case-sensitive' or 'case-insensitive',
self.shortCircuit and ', short-circuit' or '')
def getAction(self):
return self.action
def applyToHeaders(self, headers):
if self.caseSensitive:
value = self.value
else:
value = self.value.lower()
for hdr in headers:
if self.caseSensitive:
hdrval = hdr.value
else:
hdrval = hdr.value.lower()
if _opsToFunctions[self.operation](hdrval, value):
if self.negate:
break
else:
return (True, not self.shortCircuit, None)
else:
if self.negate:
return (True, not self.shortCircuit, None)
return (False, True, None)
def applyTo(self, item):
return self.applyToHeaders(item.impl.getHeaders(self.headerName))
class MailingListRule(item.Item):
implements(iquotient.IFilteringRule)
matchedMessages = attributes.integer(doc="""
Keeps track of the number of messages that have been matched as mailing
list posts.
""", default=0)
def __repr__(self):
return '<MailingListRule>'
def match_ecartis(self, headers):
sender = headers.get('sender', [None])[0]
xlist = headers.get('x-list', [None])[0]
version = headers.get('x-ecartis-version', [None])[0]
if sender and xlist:
domain = sender.rfind('@')
if domain != -1 and version is not None:
return xlist + u'.' + sender[domain + 1:]
def match_yahooGroups(self, headers, listExpr = re.compile(r'''list (?P<listId>[^;]+)''')):
"""Match messages from Yahoo Groups.
It seems the groups which were eGroups match the Ecartis filter,
but some groups do not. This filter matches both the Ecartis
yahoogroups and the others.
"""
# Example header:
# Mailing-List: list [email protected]; contact [email protected]
# Note:
# ezmlm also has a "Mailing-List" header, but it provides the "help"
# contact address only, not the list address:
# Mailing-List: contact [email protected]; run by ezmlm
# I don't match the ezmlm lists. (For that, see svn rev 4561
# branches/glyph/ezmlm-filtering. It matches "list-post", as appears
# in both ezmlm and mailman.)
mlist = headers.get('mailing-list', [None])[0]
if mlist is not None:
m = listExpr.search(mlist)
if m is not None:
listId = m.group('listId')
return listId.replace('@', '.')
def match_mailman(self, headers, listExpr = re.compile(r'''<(?P<listId>[^>]*)>'''), versionHeader = 'x-mailman-version'):
if versionHeader in headers:
listId = headers.get('list-id', [None])[0]
if listId is not None:
m = listExpr.search(listId)
if m is not None:
return m.group('listId')
return listId
def match_majorDomo(self, headers, listExpr = re.compile(r'''<(?P<listId>[^>]*)>''')):
listId = headers.get('x-mailing-list', [None])[0]
if listId is not None:
m = listExpr.search(listId)
if m is not None:
return m.group('listId').replace(u'@', u'.')
return listId.replace(u'@', u'.')
def match_lyris(self, headers, listExpr = re.compile(r"""<mailto:leave-(?P<listname>.*)-.*@(?P<domain>.*)>""")):
msgid = headers.get('message-id', [None])[0]
unsub = headers.get('list-unsubscribe', [None])[0]
if msgid is not None and u"LYRIS" in msgid and unsub is not None:
m = listExpr.search(unsub)
if m is not None:
return u"%s.%s" % (m.group('listname'), m.group('domain'))
def match_requestTracker(self, headers):
ticket = headers.get('rt-ticket', [None])[0]
managedby = headers.get('managed-by', [None])[0]
if ticket is not None and managedby is not None:
if managedby.startswith(u"RT"):
return u"request-tracker"
def match_EZMLM(self, headers, mailtoExpr = re.compile("<mailto:(.*)>")):
# Actually, this seems to be more of a 'catch-all' filter than just
# ezmlm; the information in the List-Id header for mailman is
# replicated (sort of: I imagine the semantics are slightly different)
# in the list-post header.
lp = headers.get('list-post', [None])[0]
if lp is not None:
postAddress = mailtoExpr.findall(lp)
if postAddress:
postAddress = postAddress[0]
return postAddress.replace(u"@", u".")
def getAction(self):
return MailingListTagAction()
def applyTo(self, item):
headers = {}
for hdr in item.impl.getAllHeaders():
headers.setdefault(hdr.name, []).append(hdr.value)
matchers = reflect.prefixedMethodNames(self.__class__, 'match_')
for m in matchers:
tag = getattr(self, 'match_' + m)(headers)
if tag is not None:
self.matchedMessages += 1
assert type(tag) is unicode, "%r was not unicode, came from %r" % (tag, m)
return True, True, {"mailingListName": tag}
return False, True, None
class MailingListFilteringPowerup(item.Item):
"""
Filters mail according to the mailing list it was sent from.
"""
schemaVersion = 2
tagCatalog = dependsOn(Catalog, doc="""
The catalog in which to tag items to which this action is applied.
""")
mailingListRule = dependsOn(MailingListRule, doc="""
The mailing list filter used by this powerup.
""")
messageSource = dependsOn(mail.MessageSource)
def installed(self):
self.messageSource.addReliableListener(self)
def processItem(self, item):
matched, proceed, extraData = self.mailingListRule.applyTo(item)
if matched:
self.mailingListRule.getAction().actOn(self, self.mailingListRule,
item, extraData)
def mailingListFilter1to2(old):
"""
Add messageSource field since MailingListFilteringPowerup depends
on it. Remove installedOn.
"""
return old.upgradeVersion(MailingListFilteringPowerup.typeName, 1, 2,
tagCatalog = old.tagCatalog,
mailingListRule = old.mailingListRule,
messageSource = old.store.findUnique(
mail.MessageSource))
registerUpgrader(mailingListFilter1to2, MailingListFilteringPowerup.typeName, 1, 2)
class FilteringConfigurationFragment(athena.LiveFragment):
implements(ixmantissa.INavigableFragment)
fragmentName = 'filtering-configuration'
live = 'athena'
def head(self):
pass
def render_existingRules(self, ctx, data):
rule = inevow.IQ(ctx.tag).patternGenerator('rule')
for hdrrule in self.original.store.query(HeaderRule):
ctx.tag[rule().fillSlots(
'headerName', hdrrule.headerName).fillSlots(
'negate', hdrrule.negate).fillSlots(
'operation', _opsToNames[hdrrule.operation]).fillSlots(
'value', hdrrule.value).fillSlots(
'shortCircuit', hdrrule.shortCircuit).fillSlots(
'caseSensitive', hdrrule.caseSensitive).fillSlots(
'tagName', hdrrule.action.tagName)]
return ctx.tag
# This stuff is just provisional. It provides a lot of functionality in a
# really simple way. Later on we're going to want something a lot more
# flexible which exposes all the stuff the model is actually capable of.
def render_addRule(self, ctx, data):
f = liveform.LiveForm(
self.addRule,
[liveform.Parameter('headerName', None, lambda s: s.strip().lower()),
liveform.Parameter('negate', None, lambda s: bool([u"does", u"doesn't"].index(s))),
liveform.Parameter('operation', None, _namesToOps.__getitem__),
liveform.Parameter('value', None, unicode),
liveform.Parameter('shortCircuit', None, bool),
liveform.Parameter('caseSensitive', None, bool),
liveform.Parameter('tagName', None, unicode)])
f.jsClass = u'Quotient.Filter.RuleWidget'
f.docFactory = webtheme.getLoader('add-filtering-rule')
f.setFragmentParent(self)
return ctx.tag[f]
def addRule(self, headerName, negate, operation, value, shortCircuit, caseSensitive, tagName):
action = self.original.store.findOrCreate(FixedTagAction, tagName=tagName)
rule = HeaderRule(
store=self.original.store,
headerName=headerName,
negate=negate,
operation=operation,
value=value,
shortCircuit=shortCircuit,
caseSensitive=caseSensitive,
action=action)
self.original.powerUp(rule, iquotient.IFilteringRule)
components.registerAdapter(FilteringConfigurationFragment, RuleFilteringPowerup, ixmantissa.INavigableFragment)
class Focus(Item):
"""
Implement the rules which determine whether a message gets the focused
status or not.
"""
implements(IReliableListener)
messageSource = dependsOn(MessageSource)
def installed(self):
self.messageSource.addReliableListener(self)
def processItem(self, item):
"""
Apply the focus status to any incoming message which is probably not a
mailing list message.
"""
for s in item.iterStatuses():
if s in [DRAFT_STATUS, OUTBOX_STATUS, BOUNCED_STATUS, SENT_STATUS]:
return
part = item.impl
try:
getHeader = part.getHeader
except AttributeError:
pass
else:
try:
precedence = getHeader(u'precedence')
except NoSuchHeader:
item.focus()
else:
if precedence.lower() not in (u'list', u'bulk'):
item.focus()
def suspend(self):
"""
Called when this listener is suspended.
There is no ephemeral state for this listener so this function does
nothing.
"""
def resume(self):
"""
Call when this listener is no longer suspended.
There is no ephemeral state for this listener so this function does
nothing.
"""
|
# PYTHON - MIT - UNICAMP
# =============================================================================
# Created By : Matheus Percário Bruder
# Created Date : February 3rd, 2021
# =============================================================================
dividend = 7
divisor = 2
quocient = 0
if dividend > 0 and divisor > 0:
while quocient * divisor < dividend:
# print(f"{quocient} * {divisor} < {dividend}")
quocient += 1
# Ajustando quociente após 'while'
quocient -= 1
# Encontrar resto da divisão
rest = dividend - quocient * divisor
# Declaração final
out = (quocient, rest)
print(out) # Exibir resultado
|
# Conway's game of life (no frills version)
import random
ROWS = 50
COLS = 70
CELL_SIZE = 10
HEIGHT = (ROWS * CELL_SIZE)
WIDTH = (COLS * CELL_SIZE)
BACK_COLOR = (0, 0, 127)
CELL_COLOR = (0, 200, 0)
def Rule(rule): return [(b != '_') for b in rule]
WAKEUP = Rule('___X_____')
KEEPUP = Rule('__XX_____')
def grid_build(rows, cols):
return [[False for c in range(cols)] for r in range(rows)]
def apply(grid, func):
for r in range(len(grid)):
for c in range(len(grid[r])):
grid[r][c] = func(r, c)
def grid_random(grid):
apply(grid, lambda r, c : (random.randint(0, 7) == 0))
def cell_draw(r, c):
xy = (CELL_SIZE * c, CELL_SIZE * r)
cell_rect = Rect(xy, (CELL_SIZE, CELL_SIZE))
screen.draw.filled_rect(cell_rect, CELL_COLOR)
return True
def draw():
screen.fill(BACK_COLOR)
apply(world, lambda r, c : (cell_draw(r, c) if world[r][c] else False))
def count_neighbors(w, r, c):
sum = -1 if w[r][c] else 0
for nr in range(max(r-1, 0), min(r+1, ROWS-1) + 1):
for nc in range(max(c-1, 0), min(c+1, COLS-1) + 1):
if w[nr][nc]:
sum += 1
return sum
def next_cell(current_world, r, c):
n = count_neighbors(current_world, r, c)
up = current_world[r][c]
return ((not up and WAKEUP[n]) or (up and KEEPUP[n]))
def update():
apply(worldNext, lambda r, c : next_cell(world, r, c))
apply(world, lambda r, c : worldNext[r][c])
world = grid_build(ROWS, COLS)
grid_random(world)
worldNext = grid_build(ROWS, COLS)
|
#!/usr/bin/python
#
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example creates an insertion order."""
import argparse
from datetime import date
from datetime import timedelta
import os
import sys
from googleapiclient.errors import HttpError
sys.path.insert(0, os.path.abspath('..'))
import samples_util
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'advertiser_id', help='The ID of the parent advertiser of the insertion order to be created.')
argparser.add_argument(
'campaign_id', help='The ID of the campaign of the insertion order to be created.')
argparser.add_argument(
'display_name', help='The display name of the insertion order to be created.')
def main(service, flags):
# Create a future insertion order flight start date a week from now.
startDate = date.today() + timedelta(days=7)
# Create a future insertion order flight end date two weeks from now.
endDate = date.today() + timedelta(days=14)
# Create an insertion order object with example values.
insertion_order_obj = {
'campaignId': flags.campaign_id,
'displayName': flags.display_name,
'entityStatus': 'ENTITY_STATUS_DRAFT',
'pacing': {
'pacingPeriod': 'PACING_PERIOD_DAILY',
'pacingType': 'PACING_TYPE_EVEN',
'dailyMaxMicros': 10000
},
'frequencyCap': {
'maxImpressions': 10,
'timeUnit': 'TIME_UNIT_DAYS',
'timeUnitCount': 1
},
'performanceGoal': {
'performanceGoalType': 'PERFORMANCE_GOAL_TYPE_CPC',
'performanceGoalAmountMicros': 1000000
},
'budget': {
'budgetUnit':
'BUDGET_UNIT_CURRENCY',
'budgetSegments': [{
'budgetAmountMicros': 100000,
'dateRange': {
'startDate': {
'year': startDate.year,
'month': startDate.month,
'day': startDate.day
},
'endDate': {
'year': endDate.year,
'month': endDate.month,
'day': endDate.day
}
}
}]
}
}
try:
# Build and execute request.
response = service.advertisers().insertionOrders().create(
advertiserId=flags.advertiser_id, body=insertion_order_obj).execute()
except HttpError as e:
print(e)
sys.exit(1)
# Display the new insertion order.
print(f'Insertion Order {response["name"]} was created.')
if __name__ == '__main__':
# Retrieve command line arguments.
flags = samples_util.get_arguments(sys.argv, __doc__, parents=[argparser])
# Authenticate and construct service.
service = samples_util.get_service(version='v1')
main(service, flags)
|
emojis = {
"happy": [
"😀",
"😁",
"😂",
"🤣",
"😃",
"😄",
"😅",
"😆",
"😉",
"😊",
"😋",
"😎",
"🙂",
"🙃",
"🤓",
"😝",
"😜",
]
}
print(type(emojis))
print("")
question = input("What emoji are you looking for? |> ")
print("")
if question != "":
emoji = emojis.get(question, "Sorry couldn't find emoji, please reference EMOJIS.md ...")
if type(emojis) == "dict":
for emoji in emojis:
print(f"The results of the emoji search are -> {emoji}")
else:
print("Sorry the is no emoji with a blank space ...")
|
import os
import sys
import json
import subprocess
import numpy as np
import torch
from torch import nn
from opts import parse_opts
from model import generate_model
from mean import get_mean
from classify import classify_video
import glob
from tqdm import tqdm
import pdb
import pickle as pkl
def convert_to_np(result):
features = result['feature']
return features
if __name__=="__main__":
opt = parse_opts()
opt.mean = get_mean()
opt.arch = '{}-{}'.format(opt.model_name, opt.model_depth)
opt.sample_size = 112
opt.n_classes = 400
model = generate_model(opt)
print('loading model {}'.format(opt.model))
model_data = torch.load(opt.model)
assert opt.arch == model_data['arch']
model.load_state_dict(model_data['state_dict'])
model.eval()
class_names = []
with open('class_names_list') as f:
for row in f:
class_names.append(row[:-1])
ffmpeg_loglevel = 'quiet'
if os.path.exists(opt.tmp):
subprocess.call('rm -rf {}'.format(opt.tmp), shell=True)
subprocess.call('mkdir {}'.format(opt.tmp), shell=True)
if not os.path.exists(opt.output):
os.makedirs(opt.output)
if 'gif' in opt.video_root:
ext = 'gif'
else:
ext = 'mp4'
files = sorted(glob.glob(opt.video_root + '/*.{}'.format(ext)))
files = files[opt.start_idx:opt.end_idx]
if opt.vidset is not None:
vidset = pkl.load(open(opt.vidset, 'rb'))
else:
vidset = None
for video_path in tqdm(files):
input_file = video_path.split('/')[-1]
video_name = input_file.split('.')[0]
if not os.path.exists(video_path) or (vidset is not None and video_name not in vidset):
continue
subprocess.call('mkdir {}/{}'.format(opt.tmp, video_name), shell=True)
subprocess.call('ffmpeg -loglevel quiet -nostats -i {} -vsync 0 {}/{}/image_%05d.jpg'.format(video_path, opt.tmp, video_name), shell=True)
result = classify_video('{}/{}'.format(opt.tmp, video_name), input_file, class_names, model, opt)
video_name = input_file.split('.')[0]
result['st_feature'].dump(opt.output + '/' + video_name + '.npy')
subprocess.call('rm -rf {}/{}'.format(opt.tmp, video_name), shell=True)
if os.path.exists(opt.tmp):
subprocess.call('rm -rf {}'.format(opt.tmp), shell=True)
|
class Solution:
def findMinMoves(self, machines: List[int]) -> int:
dresses = sum(machines)
if dresses % len(machines) != 0:
return -1
ans = 0
average = dresses // len(machines)
inout = 0
for dress in machines:
inout += dress - average
ans = max(ans, abs(inout), dress - average)
return ans
|
# Update zones table, zone_data - [zone, latitude, longitude, id]
UPDATE_ZONES_TABLE = '''
UPDATE zones
SET zone = ? ,
latitude = ? ,
longitude = ?
WHERE id = ?
'''
# Update locations table, location_data [last_used, usage_cnt, id]
UPDATE_LOCATION_USED = '''
UPDATE locations
SET last_used = ? ,
usage_cnt = ?
WHERE id = ?
'''
# Add zone record - [zone, latitude, longitude]
ADD_ZONE_RECORD = '''
INSERT INTO zones(
zone, latitude, longitude)
VALUES(?,?,?)
'''
# Add location record - [zone_id, lat_long_key, travel_time, distance, added,
# last_used, usage_cnt]
ADD_LOCATION_RECORD = '''
INSERT INTO locations(
zone_id, lat_long_key, travel_time, distance, added, last_used,
usage_cnt)
VALUES(?,?,?,?,?,?,?)
'''
CREATE_ZONES_TABLE = '''
CREATE TABLE IF NOT EXISTS zoness (
id integer PRIMARY KEY,
zone text NOT NULL,
latitude real,
longitude real
);'''
CREATE_LOCATIONs_TABLE = '''
CREATE TABLE IF NOT EXISTS tasks (
id integer PRIMARY KEY,
zone_id integer,
lat_long_key text NOT NULL,
added text,
last_used text,
usage_cnt integer,
FOREIGN KEY (zone_id) REFERENCES zones (id)
);'''
|
"""
Even though orthogonal polynomials created using three terms recurrence is
the recommended approach as it is the most numerical stable method, it can not
be used directly on stochastically dependent random variables. On method that
bypasses this problem is Cholesky decomposition method.
Cholesky exploits the fact that except for polynomials that are constant, there
is a equivalence between orthogonality and uncorrelated. Decorrelation can be
achieved in a simple few steps:
1. Start with any linear independent basis of polynomials :math:`P`.
2. Temporarily remove any constants, if there are any.
3. Construct the covariance matrix :math`C=Cov(P)` of all polynomials.
4. Decompose covariance matrix into two parts :math:`C = L^T L` using Cholesky
decomposition.
5. Multiply the vector of polynomials with the inverse decomposition:
:math:`Q = P L^{-1}`
6. If a constant was removed, subtract the mean from the vector :math`Q=Q-E[Q]`
before adding the constant back into the expansion.
This should work in theory, but in practice step 4 is known to be numerically
unstable. To this end, this step can to a certain degree be regularized using
various methods. To this end a few modified Cholesky decompositions are
available in ``chaospy``.
"""
import numpy
import chaospy
import numpoly
def cholesky(
order,
dist,
normed=False,
graded=True,
reverse=True,
cross_truncation=1.,
retall=False,
):
"""
Create orthogonal polynomial expansion from Cholesky decomposition.
Args:
order (int):
Order of polynomial expansion
dist (Distribution):
Distribution space where polynomials are orthogonal
normed (bool):
If True orthonormal polynomials will be used instead of monic.
graded (bool):
Graded sorting, meaning the indices are always sorted by the index
sum. E.g. ``q0**2*q1**2*q2**2`` has an exponent sum of 6, and will
therefore be consider larger than both ``q0**2*q1*q2``,
``q0*q1**2*q2`` and ``q0*q1*q2**2``, which all have exponent sum of
5.
reverse (bool):
Reverse lexicographical sorting meaning that ``q0*q1**3`` is
considered bigger than ``q0**3*q1``, instead of the opposite.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
retall (bool):
If true return numerical stabilized norms as well. Roughly the same
as ``cp.E(orth**2, dist)``.
Examples:
>>> distribution = chaospy.Normal()
>>> expansion, norms = chaospy.expansion.cholesky(3, distribution, retall=True)
>>> expansion.round(4)
polynomial([1.0, q0, q0**2-1.0, q0**3-3.0*q0])
>>> norms
array([1., 1., 2., 6.])
"""
dim = len(dist)
basis = numpoly.monomial(
start=1,
stop=order+1,
dimensions=dim,
graded=graded,
reverse=reverse,
cross_truncation=cross_truncation,
)
length = len(basis)
covariance = chaospy.descriptives.Cov(basis, dist)
cholmat = gill_king(covariance)
cholmat_inv = numpy.linalg.inv(cholmat.T).T
if not normed:
diag_mesh = numpy.repeat(numpy.diag(cholmat_inv), len(cholmat_inv))
cholmat_inv /= diag_mesh.reshape(cholmat_inv.shape)
norms = numpy.hstack([1, numpy.diag(cholmat)**2])
else:
norms = numpy.ones(length+1, dtype=float)
expected = -numpy.sum(cholmat_inv*chaospy.E(basis, dist), -1)
coeffs = numpy.block([[1., expected],
[numpy.zeros((length, 1)), cholmat_inv.T]])
out = {}
out[(0,)*dim] = coeffs[0]
for idx, key in enumerate(basis.exponents):
out[tuple(key)] = coeffs[idx+1]
names = numpoly.symbols("q:%d" % dim)
polynomials = numpoly.polynomial(out, names=names)
if retall:
return polynomials, norms
return polynomials
def gill_king(mat, tolerance=1e-16):
"""
Gill-King algorithm for modified Cholesky decomposition.
Algorithm 3.4 of 'Numerical Optimization' by Jorge Nocedal and Stephen J.
Wright. This particular implementation is a rewrite of MATLAB code from
Michael L. Overton 2005.
Args:
mat (numpy.ndarray):
Must be a non-singular and symmetric matrix.
tolerance (float):
Error tolerance used in algorithm.
Returns:
(numpy.ndarray):
Lower triangular Cholesky factor.
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> lowtri = gill_king(mat)
>>> lowtri.round(4)
array([[2. , 0. , 0. ],
[1. , 2.2361, 0. ],
[0.5 , 1.118 , 1.2264]])
>>> (lowtri @ lowtri.T).round(4)
array([[4. , 2. , 1. ],
[2. , 6. , 3. ],
[1. , 3. , 3.004]])
"""
mat = numpy.asfarray(mat)
assert numpy.allclose(mat, mat.T)
size = mat.shape[0]
mat_diag = mat.diagonal()
gamma = abs(mat_diag).max()
off_diag = abs(mat - numpy.diag(mat_diag)).max()
delta = tolerance*max(gamma+off_diag, 1)
beta = numpy.sqrt(max(gamma, off_diag/size, tolerance))
# initialize d_vec and lowtri
lowtri = numpy.eye(size)
d_vec = numpy.zeros(size, dtype=float)
# there are no inner for loops, everything implemented with
# vector operations for a reasonable level of efficiency
for idx in range(size):
# column index: all columns to left of diagonal
# d_vec(idz) doesn't work in case idz is empty
idz = numpy.s_[:idx] if idx else []
djtemp = mat[idx, idx]-numpy.dot(
lowtri[idx, idz], d_vec[idz]*lowtri[idx, idz].T)
if idx < size-1:
idy = numpy.s_[idx+1:size]
# row index: all rows below diagonal
ccol = mat[idy, idx]-numpy.dot(
lowtri[idy, idz], d_vec[idz]*lowtri[idx, idz].T)
# C(idy, idx) in book
theta = abs(ccol).max()
# guarantees d_vec(idx) not too small and lowtri(idy, idx) not too
# big in sufficiently positive definite case, d_vec(idx) = djtemp
d_vec[idx] = max(abs(djtemp), (theta/beta)**2, delta)
lowtri[idy, idx] = ccol/d_vec[idx]
else:
d_vec[idx] = max(abs(djtemp), delta)
# convert LDL_t to usual output format LL_t:
lowtri *= numpy.sqrt(d_vec)
return lowtri
|
from random import randint
# Linked List Implementation in python
# Node definition
class LinkedListNode:
def __init__(self, data):
self.data= data
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
s = "["
p = self.head
if p != None :
while p.next != None :
s += str(p.data) + ', '
p = p.next
s += str(p.data) + "]"
return s
def __len__(self):
count = 0
node = self.head
while node:
count += 1
node = node.next
return count
def add(self,data):
if self.head is None: # empty list case
self.tail = self.head = LinkedListNode(data)
else:
self.tail.next = LinkedListNode(data)
self.tail = self.tail.next
# generate linked list with values between min and max
def generate(self, n, min_value, max_value):
self.head = self.tail = None
for i in range(n):
self.add(randint(min_value,max_value))
return self
|
from __future__ import print_function
import numpy as np
import time
# noinspection PyUnresolvedReferences
from std_msgs.msg import Float64MultiArray
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
# noinspection PyUnresolvedReferences
from mpl_toolkits.mplot3d import Axes3D # for: fig.gca(projection = '3d')
glob_curr_pos_x = None
glob_curr_pos_y = None
glob_curr_pos_z = None
try: # Python 2/3 raw input correction
# noinspection PyShadowingBuiltins
input = raw_input # overwrite the use of input with raw_input to support Python 2
except NameError:
pass
class MotionPlanner:
def __init__(self, visual=False, debug=False):
"""
Initialises the MotionPlanner class with preset hard-coded calibration unless the
automatic calibration procedure is implemented.
:param visual: Flag control usage of matplotlib for checking results.
:param debug: Flag for controlling extensive print statements to console.
"""
self.visual = visual
self.dx = 0.005
self.debug = debug
a1_inner = [0.7267045425008777, -0.19296634171907032, -0.06872549226985156]
a8_inner = [0.3927532235233764, -0.18683619713296443, -0.07657893758846493]
h8_inner = [0.4011762302881528, 0.1679801463159881, -0.07535828159982629]
h1_inner = [0.7364192616073851, 0.1560582695967688, -0.06846008006252183]
self.board = [a1_inner, a8_inner, h8_inner, h1_inner]
# Find the maximum z value of the board
self.board_z_max = -0.075
# from Paolo's collected coords
x_vector_1 = [(a8_inner[0] - h8_inner[0]), (a8_inner[1] - h8_inner[1]), self.board_z_max]
x_vector_2 = [(a1_inner[0] - h1_inner[0]), (a1_inner[1] - h1_inner[1]), self.board_z_max]
x_vector = [sum(x)/2 for x in zip(x_vector_1, x_vector_2)]
self.x_unit_vector = [coord/6 for coord in x_vector]
y_vector_1 = [(h1_inner[0] - h8_inner[0]), (h1_inner[1] - h8_inner[1]), self.board_z_max]
y_vector_2 = [(a1_inner[0] - a8_inner[0]), (a1_inner[1] - a8_inner[1]), self.board_z_max]
y_vector = [sum(x)/2 for x in zip(y_vector_1, y_vector_2)]
self.y_unit_vector = [coord/6 for coord in y_vector]
print(self.x_unit_vector)
print(self.y_unit_vector)
print(h8_inner)
self.H8 = [A-B-C for A, B, C in zip(h8_inner, self.x_unit_vector, self.y_unit_vector)]
# self.H8 = h8_inner - self.x_unit_vector - self.y_unit_vector
print(self.H8)
# Find hover height
self.hover_height = self.board_z_max + 0.2 # hard coded hover height
# Find location of dead zone
dead_zone_x_vector = [(vector * 12) for vector in self.x_unit_vector]
dead_zone_y_vector = [vector * 4 for vector in self.y_unit_vector]
dead_zone_z = self.board_z_max + 0.15 # hardcoded z coordinate of dead zone
dead_zone = [sum(elements) for elements in zip(self.H8, dead_zone_x_vector,
dead_zone_y_vector)]
dead_zone[2] = dead_zone_z
self.dead_zone = dead_zone
# Find the location of the rest position
rest_x_vector = [vector * 4 for vector in self.x_unit_vector]
rest_y_vector = [(vector * 4) for vector in self.y_unit_vector]
rest_z = self.board_z_max + 0.5 # hardcoded z coordinate of the rest position
rest = [sum(element) for element in zip(self.H8, rest_x_vector, rest_y_vector)]
rest[2] = rest_z
self.rest = rest
# Find coordinates of each square
self.letter_dict = dict([('h', [vector * 0.5 for vector in self.x_unit_vector]),
('g', [vector * 1.5 for vector in self.x_unit_vector]),
('f', [vector * 2.5 for vector in self.x_unit_vector]),
('e', [vector * 3.5 for vector in self.x_unit_vector]),
('d', [vector * 4.5 for vector in self.x_unit_vector]),
('c', [vector * 5.5 for vector in self.x_unit_vector]),
('b', [vector * 6.5 for vector in self.x_unit_vector]),
('a', [vector * 7.5 for vector in self.x_unit_vector])
])
self.number_dict = dict([('8', [vector * 0.5 for vector in self.y_unit_vector]),
('7', [vector * 1.5 for vector in self.y_unit_vector]),
('6', [vector * 2.5 for vector in self.y_unit_vector]),
('5', [vector * 3.5 for vector in self.y_unit_vector]),
('4', [vector * 4.5 for vector in self.y_unit_vector]),
('3', [vector * 5.5 for vector in self.y_unit_vector]),
('2', [vector * 6.5 for vector in self.y_unit_vector]),
('1', [vector * 7.5 for vector in self.y_unit_vector])
])
# Find the correct displacement for each piece
# Dictionary holds the required gripper width and z offset from table for each piece type
width_offset = 0.05
z_offset = self.board_z_max
self.piece_dims = dict([('p', [(0.061 - width_offset), 0.030+z_offset]),
('k', [(0.064 - width_offset), 0.063+z_offset]),
('q', [(0.065 - width_offset), 0.063+z_offset]),
('b', [(0.066 - width_offset), 0.049+z_offset]),
('n', [(0.060 - width_offset), 0.023+z_offset]),
('r', [(0.063 - width_offset), 0.029+z_offset])
])
@staticmethod
def discretise(point_1, point_2, dx):
"""
Takes a straight line and divides it into smaller defined length segments.
:param point_1: First point in 3D space
:param point_2: Second point in 3D space
:param dx: Distance between points in discretised line.
:return: Numpy array of discretised line.
"""
# create vector from point_1 to point_2
vector = [point_2[0] - point_1[0], point_2[1] - point_1[1], point_2[2] - point_1[2]]
# noinspection PyUnresolvedReferences
distance = np.sqrt(sum(i ** 2 for i in vector))
# number of points on line
i = int(distance / dx)
# discretise by creating new 1d array
line_x = np.linspace(point_1[0], point_2[0], i)
line_y = np.linspace(point_1[1], point_2[1], i)
line_z = np.linspace(point_1[2], point_2[2], i)
line = np.array(np.transpose(np.vstack((line_x, line_y, line_z))))
return line
def discretise_path(self, move, dx):
"""
Discretise a moves path using object defined dx for unit.
:param move: List of points path goes through.
:param dx: Displacement between two points on the target discretised path.
:return: Discretised path as numpy array.
"""
move_discrete = []
# iterate through move segments, discretise and join them
for seg_idx in range(len(move) - 1):
current_segment = self.discretise(move[seg_idx], move[seg_idx + 1], dx)
# print(current_segment)
# we add our discretised segment to our move
if seg_idx > 0:
# if the end of our current move is the same position as the start of our new
# segment then we only want to add the list from the second point onwards
if move_discrete[-1][0] == current_segment[0][0]:
# noinspection PyUnresolvedReferences
move_discrete = np.concatenate((move_discrete, current_segment[1:]))
else:
# noinspection PyUnresolvedReferences
move_discrete = np.concatenate((move_discrete, current_segment))
else: # on first iteration, we store our segment directly
move_discrete = current_segment
return move_discrete
@staticmethod
def smooth_corners(path, size_of_corner, passes):
"""
Takes a discretised path and and rounds the corners using parameters passed into
function call. Minimum number of passes is 1, which results in a chamfer.
**Note** This function is not currently used due to its error in smoothing the corners.
It has not been implemented until a better version can be written.
"""
if not size_of_corner % 2 == 0: # number of steps must be an even number
size_of_corner += 1
steps = size_of_corner
if passes < 1:
raise ValueError("Number of passes must be >= 1")
for i in range(passes):
trajectory_1_x = [item[0] for item in path]
trajectory_1_y = [item[1] for item in path]
trajectory_1_z = [item[2] for item in path]
x_tortoise = trajectory_1_x[:-steps] # remove last few coordinates
x_hare = trajectory_1_x[steps:] # first last few coordinates
x_smooth_path = [(sum(i) / 2) for i in zip(x_tortoise, x_hare)] # average them
y_tortoise = trajectory_1_y[:-steps] # remove last few coordinates
y_hare = trajectory_1_y[steps:] # remove first few coordinates
y_smooth_path = [(sum(i) / 2) for i in zip(y_tortoise, y_hare)]
z_tortoise = trajectory_1_z[:-steps] # remove last few coordinates
z_hare = trajectory_1_z[steps:] # remove first few coordinates
z_smooth_path = [(sum(i) / 2) for i in zip(z_tortoise, z_hare)]
# noinspection PyUnresolvedReferences
smooth_path = np.array(
[list(i) for i in zip(x_smooth_path, y_smooth_path, z_smooth_path)])
# append first 6 coordinates in trajectory_1 to the smooth_path
# print(path[:(steps / 2)])
# print(smooth_path)
# noinspection PyUnresolvedReferences
smooth_path = np.concatenate(
(path[:(steps / 2)], smooth_path, path[-(steps / 2):]), axis=0)
path = smooth_path
return path
@staticmethod
def length_of_path(path):
"""
Calculates the length of a path stored as an array of (n x 3).
:param path: List (length n) of list (length 3) points.
:return: The total length of the path in 3D space.
"""
length = 0
for i in range(len(path) - 1):
point_a = path[i]
point_b = path[i + 1]
length += np.sqrt((point_b[0] - point_a[0]) ** 2 + (point_b[1] - point_a[1]) ** 2
+ (point_b[2] - point_a[2]) ** 2)
return length
def apply_trapezoid_vel(self, path, acceleration=0.02, max_speed=0.8):
"""
Takes a path (currently only a start/end point (straight line), and returns a discretised
trajectory of the path controlled by a trapezium velocity profile generated by the input
parameters.
:param path: List of two points in 3D space.
:param acceleration: Acceleration and deceleration of trapezium profile.
:param max_speed: Target maximum speed of the trapezium profile.
:return: Trajectory as numpy array.
"""
# set rate of message sending: 0.001 sec == dt == 1kHz NOTE THIS IS GLOBALLY SET
dt = 0.005
# set acceleration, start with 0.1 (may need to reduce) NOTE THIS IS GLOBALLY SET
acc = acceleration # max 1.0
# set target travel speed for motion
target_speed = max_speed # max 1.0
# discretise using a max unit of: target_speed * dt
# ideally, we use a dx of: acc * dt**2
dx = acc * dt**2 # this is the ideal delta value
if self.debug:
print("delta displacement (mm): ", dx * 1000)
lop = 0
while lop == 0:
dis_path = self.discretise_path(path, dx)
# SMOOTHING HAPPENS HERE
# if smoothing is going to happen it MUST keep consistent delta displacement
# corner = 0.05 # in meters
# steps = int(corner * 2 / dx)
# print("Steps: ", steps)
# smooth_path = planner.smooth_corners(dis_path, size_of_corner=steps, passes=6)
smooth_path = dis_path # disable smoothing
# find the length of the new path
lop = self.length_of_path(smooth_path)
if self.debug:
print("LOP: ", lop)
if lop == 0:
print("Length of path is zero, adding indistinguishable offset.")
path[1] = [c+0.000001 for c in path[1]]
# check if the length of path is < ( speed**2/acc )
# this means that the length of the path is too short to accelerate all the way to the
# target speed so we scale it down to keep a triangular profile
minimum_path_length = target_speed ** 2 / acc
if self.debug:
print("Minimum path length: ", minimum_path_length)
if lop < minimum_path_length:
# if the length is less we need to reduce target_speed
if self.debug:
print("Path length is too short.")
old_speed = target_speed
target_speed = np.sqrt(lop * acc)
if self.debug:
print("Target speed changed from: ", old_speed, ", to: ", target_speed)
# assert new target_speed is less than old for safety reasons
assert (target_speed <= old_speed)
else:
# we have confirmed the length of the path is long enough for our target speed
if self.debug:
print("Path length ok")
# we now need to create the speed profile graph and define its parameters
# find t for acceleration and deceleration
end_stage_t = target_speed / acc
# find path distance for acc and dec
end_stage_displacement = end_stage_t * target_speed / 2
print("Acc/dec time: ", end_stage_t)
# find displacement for constant speed section of motion
mid_stage_displacement = lop - 2 * end_stage_displacement
# find t for const speed section
mid_stage_t = mid_stage_displacement / target_speed
# find total time
total_time = end_stage_t * 2 + mid_stage_t
if self.debug:
print("total time: ", total_time)
# create a time list using 0->T in steps of dt
time_list = np.arange(start=0, stop=total_time, step=dt)
np.reshape(time_list, (np.shape(time_list)[0], 1))
# sample speed graph to create list to go with time list
speed_values = []
c = (0 - (-acc) * time_list[-1])
for t in time_list:
if t <= end_stage_t:
# acceleration period
speed_values.append(acc * t)
elif t >= end_stage_t + mid_stage_t:
# deceleration stage
speed_values.append(-acc * t + c)
elif t > end_stage_t:
# constant speed at target speed
speed_values.append(target_speed)
# sample path using speed list
# noinspection PyUnboundLocalVariable
trajectory = np.hstack((smooth_path[0, :], speed_values[0])) # send intermediate points
smooth_path_idx = 0
for i in range(1, len(speed_values)):
samples = int(np.rint(speed_values[i] * dt / dx))
smooth_path_idx += samples
if smooth_path_idx > len(smooth_path) - 1:
smooth_path_idx = len(smooth_path) - 1
new_marker = np.hstack((smooth_path[smooth_path_idx], speed_values[i]))
trajectory = np.vstack((trajectory, new_marker))
if self.visual:
# plotting the board
# plot discretised path
# fig = plt.figure()
# ax3d = fig.add_subplot(111, projection='3d')
# ax3d.plot(path[:, 0], path[:, 1], path[:, 2], 'r')
# ax3d.plot(smooth_path[:, 0], smooth_path[:, 1], smooth_path[:, 2], 'b*')
# plot speed profile
fig = plt.figure()
# noinspection PyUnusedLocal
ax3d = fig.add_subplot(111)
plt.plot(time_list[:len(speed_values)], speed_values, 'r*')
plt.ylabel("speed (m/s)")
plt.xlabel("time (s)")
# plot trajectory axes against time
fig = plt.figure()
# noinspection PyUnusedLocal
ax3d = fig.add_subplot(111)
plt.plot(time_list[:len(trajectory[:, 0])], trajectory[:, 0], 'r*')
plt.plot(time_list[:len(trajectory[:, 1])], trajectory[:, 1], 'b*')
plt.plot(time_list[:len(trajectory[:, 2])], trajectory[:, 2], 'g*')
plt.ylabel("x(r) / y(b) / z(g) displacement (m)")
plt.xlabel("time (s)")
# plot trajectory in 3d
# fig = plt.figure()
# ax3d = fig.add_subplot(111, projection='3d')
# ax3d.plot(path[:, 0], path[:, 1], path[:, 2], 'r')
# ax3d.plot(trajectory[:, 0], trajectory[:, 1], trajectory[:, 2], 'g*')
plt.show()
return trajectory
def an_to_coordinates(self, chess_move_an):
"""
Converts chess algebraic notation into real world ``x, y, z`` coordinates.
:param chess_move_an: In form ``[('p','a2a4')]`` or ``[('n','a4'),('p','a2a4')]``.
:return: Tuple of coordinate start(1), goal(2), died(3).
"""
# Extract information from output of game engine
if len(chess_move_an) == 1:
start_an = chess_move_an[0][1][:2]
goal_an = chess_move_an[0][1][2:4]
elif len(chess_move_an) == 2:
start_an = chess_move_an[1][1][:2]
goal_an = chess_move_an[1][1][2:4]
else:
raise ValueError("Chess move was not understood; not 1 or 2 items")
# split start AN location
letter_start = start_an[0]
number_start = start_an[1]
# split goal AN location
letter_goal = goal_an[0]
number_goal = goal_an[1]
# lookup in dictionary
x_in_chess_start = self.number_dict[number_start]
y_in_chess_start = self.letter_dict[letter_start]
x_in_chess_goal = self.number_dict[number_goal]
y_in_chess_goal = self.letter_dict[letter_goal]
# move by dims_in_chess from the H8 coordinate
coord_start = [sum(i) for i in zip(self.H8, x_in_chess_start, y_in_chess_start)]
coord_goal = [sum(i) for i in zip(self.H8, x_in_chess_goal, y_in_chess_goal)]
coord_died = [sum(i) for i in zip(self.H8, x_in_chess_goal, y_in_chess_goal)]
# select z coordinate based on what piece it is
if len(chess_move_an) == 1:
piece = chess_move_an[0][0].lower() # which is the piece?
dims = self.piece_dims[piece] # height and grip dims
coord_start[2] = dims[1] # height dim
coord_goal[2] = dims[1] # height dim
return coord_start, coord_goal
elif len(chess_move_an) == 2:
alive_piece = chess_move_an[1][0].lower() # which is the piece?
dead_piece = chess_move_an[0][0].lower()
alive_dims = self.piece_dims[alive_piece] # height and grip dims
dead_dims = self.piece_dims[dead_piece] # height and grip dims
coord_start[2] = alive_dims[1] # height dim
coord_goal[2] = alive_dims[1] # height dim
coord_died[2] = dead_dims[1]
return coord_start, coord_goal, coord_died
def generate_moves(self, chess_move_an, franka):
"""
Generates a number of segments each a straight line path that will execute the move
generated by the chess engine.
:param chess_move_an: Takes chess move in algebraic notation from chess engine
:param franka: Takes franka control object as argument to find current position
:return: a list of lists that depict the full start to goal trajectory of each segment
"""
if len(chess_move_an) == 1:
move_from, move_to = self.an_to_coordinates(chess_move_an)
# Generate the intermediate positions of the path
move_from_hover = [move_from[0], move_from[1], self.hover_height]
move_to_hover = [move_to[0], move_to[1], self.hover_height]
current_position = [franka.x, franka.y, franka.z]
moves = np.array([[[current_position, self.rest], [current_position, move_from_hover],
[current_position, move_from]],
[[current_position, move_from_hover],
[current_position, move_to_hover], [current_position, move_to]],
[[current_position, move_to_hover], [current_position, self.rest]]])
elif len(chess_move_an) == 2:
move_from, move_to, died = self.an_to_coordinates(chess_move_an)
# Generate the intermediate positions of the path
move_from_hover = [move_from[0], move_from[1], self.hover_height]
move_to_hover = [move_to[0], move_to[1], self.hover_height]
dead_zone_hover = [self.dead_zone[0], self.dead_zone[1], self.hover_height]
current_position = [franka.x, franka.y, franka.z]
moves = np.array([[[current_position, self.rest], [current_position, move_to_hover],
[current_position, died]],
[[current_position, move_to_hover],
[current_position, dead_zone_hover]],
[[current_position, move_from_hover], [current_position, move_from]],
[[current_position, move_from_hover],
[current_position, move_to_hover], [current_position, move_to]],
[[current_position, move_to_hover], [current_position, self.rest]]])
else:
raise ValueError("The length of the chess move was invalid; not 1 or 2 items")
# # plot the trajectory
# if self.visual:
# fig = plt.figure()
# ax3d = fig.add_subplot(111, projection='3d')
# if self.visual:
# # Separate into xyz
# x = [coord[0] for coord in path]
# y = [coord[1] for coord in path]
# z = [coord[2] for coord in path]
#
# # getting board points
# board_x = [coord[0] for coord in self.board]
# board_y = [coord[1] for coord in self.board]
# board_z = [coord[2] for coord in self.board]
# # add the first point to the end of the list to create polygon
# board_x.append(self.board[0][0])
# board_y.append(self.board[0][1])
# board_z.append(self.board[0][2])
#
# # plotting
# fig = plt.figure()
# ax3d = fig.add_subplot(111, projection='3d')
#
# # plot the board
# ax3d.plot(board_x, board_y, board_z, 'y')
# # plot important points
# ax3d.plot([self.rest[0]], [self.rest[1]], [self.rest[2]], 'g*')
# ax3d.plot([self.dead_zone[0]], [self.dead_zone[1]], [self.dead_zone[2]], 'g*')
# # plot the untouched path
# ax3d.plot(x, y, z, 'r')
# plt.show()
return moves
def input_chess_move(self, arm_object, chess_move_an):
"""
After new move is fetched from the game engine, the result is passed to this
function so that a trajectory may be generated. This is then executed on FRANKA.
:param arm_object: Takes object of Franka arm control class.
:param chess_move_an: Takes chess move generated from chess engine.
"""
ungrip_dim = 0.045
gripper_delay = 0.5
if len(chess_move_an) > 1:
chess_play = chess_move_an[1][1]
else:
chess_play = chess_move_an[0][1]
# acceleration improvement if move does not involve protected ranks
ranks = ['8']
if (chess_play[1] not in ranks) and (chess_play[3] not in ranks):
a = 0.08
else:
a = 0.02
moves = self.generate_moves(chess_move_an, arm_object)
current_position = [arm_object.x, arm_object.y, arm_object.z]
for i, series in enumerate(moves):
series = np.array(series)
for path in series:
path = np.array(path)
# we update the starting point to the position of the FRANKA arm currently
path[0] = current_position
# # plot 2 points
# if self.visual:
# ax3d.plot(path[:, 0], path[:, 1], path[:, 2], 'r*')
# ax3d.plot(path[:, 0], path[:, 1], path[:, 2], 'r')
motion_plan = self.apply_trapezoid_vel(path, acceleration=a)
arm_object.send_trajectory(motion_plan)
# for x, y, z, speed in motion_plan:
# # print(x,y,z,speed)
# arm.move_to(x, y, z, speed)
# time.sleep(0.005) # control loop
# update current position
current_position = [arm_object.x, arm_object.y, arm_object.z]
# gripper starts here
if len(chess_move_an) == 1: # if not piece died
piece = chess_move_an[0][0].lower() # which is the piece?
dims = self.piece_dims[piece] # height and grip dims
grip_dim = dims[0] # grip dims
if i == 0:
# grip
time.sleep(gripper_delay)
arm_object.move_gripper(grip_dim, 0.1)
time.sleep(gripper_delay)
elif i == 1:
# release
time.sleep(gripper_delay)
arm_object.move_gripper(ungrip_dim, 0.1)
time.sleep(gripper_delay)
elif len(chess_move_an) == 2:
piece = chess_move_an[0][0].lower()
dims = self.piece_dims[piece]
grip_dim = dims[0]
# PICKING UP DEAD PIECE
if i == 0:
# grip
time.sleep(gripper_delay)
arm_object.move_gripper(grip_dim, 0.1)
time.sleep(gripper_delay)
# DROPPING OFF DEAD PIECE AT DEAD ZONE
elif i == 1:
# release
time.sleep(gripper_delay)
arm_object.move_gripper(ungrip_dim, 0.1)
time.sleep(gripper_delay)
# PICKING UP NEW PIECE
elif i == 2:
piece = chess_move_an[1][0] # change piece dims for second grip
dims = self.piece_dims[piece]
grip_dim = dims[0]
# grip
time.sleep(gripper_delay)
arm_object.move_gripper(grip_dim, 0.1)
time.sleep(gripper_delay)
# DROPPING OFF NEW PIECE TO ITS DESTINATION
elif i == 3:
# release
time.sleep(gripper_delay)
arm_object.move_gripper(ungrip_dim, 0.1)
time.sleep(gripper_delay)
if __name__ == '__main__':
from franka.franka_control_ros import FrankaRos
arm = FrankaRos(init_ros_node=True) # create an arm object for testing motion generation
planner = MotionPlanner(visual=False, debug=True)
# EXAMPLE MOTION TO TEST IF PARTS ARE WORKING
# example_path = np.array([[arm.x, arm.y, arm.z], [arm.x, arm.y + 0.2, arm.z]]) # move +y
# motion_plan = planner.apply_trapezoid_vel(example_path)
# arm.send_trajectory(motion_plan)
if True: # For debugging purposes
# noinspection PyUnresolvedReferences
import rospy
try:
# EXAMPLE CHESS MOVES
chess_move = [('n', 'g8f6')]
# chess_move = [("p", "e4"), ("p", "d5e4")]
planner.input_chess_move(arm, chess_move)
time.sleep(2)
print("finished motion.")
except rospy.ROSInterruptException as e:
print(e)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
"""
from __future__ import unicode_literals
from optparse import OptionParser
from jinja2 import Environment, PackageLoader
from slugify import slugify
import json
CONTENT_FILENAME = "./content.html"
PAGE_FILENAME = "./page.html"
pl = PackageLoader('nvd3', 'templates')
jinja2_env = Environment(lstrip_blocks=True, trim_blocks=True, loader=pl)
template_content = jinja2_env.get_template(CONTENT_FILENAME)
template_page = jinja2_env.get_template(PAGE_FILENAME)
def stab(tab=1):
"""
create space tabulation
"""
return ' ' * 4 * tab
class NVD3Chart(object):
"""
NVD3Chart Base class.
"""
#: chart count
count = 0
#: directory holding the assets (bower_components)
assets_directory = './bower_components/'
# this attribute is overriden by children of this
# class
CHART_FILENAME = None
template_environment = Environment(lstrip_blocks=True, trim_blocks=True,
loader=pl)
def __init__(self, **kwargs):
"""
This is the base class for all the charts. The following keywords are
accepted:
:keyword: **display_container** - default: ``True``
:keyword: **jquery_on_ready** - default: ``False``
:keyword: **charttooltip_dateformat** - default: ``'%d %b %Y'``
:keyword: **name** - default: the class name
``model`` - set the model (e.g. ``pieChart``, `
``LineWithFocusChart``, ``MultiBarChart``).
:keyword: **color_category** - default - ``None``
:keyword: **color_list** - default - ``None``
used by pieChart (e.g. ``['red', 'blue', 'orange']``)
:keyword: **margin_bottom** - default - ``20``
:keyword: **margin_left** - default - ``60``
:keyword: **margin_right** - default - ``60``
:keyword: **margin_top** - default - ``30``
:keyword: **height** - default - ``''``
:keyword: **width** - default - ``''``
:keyword: **stacked** - default - ``False``
:keyword: **resize** - define - ``False``
:keyword: **show_legend** - default - ``True``
:keyword: **show_labels** - default - ``True``
:keyword: **tag_script_js** - default - ``True``
:keyword: **use_interactive_guideline** - default - ``False``
:keyword: **chart_attr** - default - ``None``
:keyword: **extras** - default - ``None``
Extra chart modifiers. Use this to modify different attributes of
the chart.
:keyword: **x_axis_date** - default - False
Signal that x axis is a date axis
:keyword: **date_format** - default - ``%x``
see https://github.com/mbostock/d3/wiki/Time-Formatting
:keyword: **x_axis_format** - default - ``''``.
:keyword: **y_axis_format** - default - ``''``.
:keyword: **style** - default - ``''``
Style modifiers for the DIV container.
:keyword: **color_category** - default - ``category10``
Acceptable values are nvd3 categories such as
``category10``, ``category20``, ``category20c``.
"""
# set the model
self.model = self.__class__.__name__ #: The chart model,
#: an Instance of Jinja2 template
self.template_page_nvd3 = template_page
self.template_content_nvd3 = template_content
self.series = []
self.axislist = {}
# accepted keywords
self.display_container = kwargs.get('display_container', True)
self.charttooltip_dateformat = kwargs.get('charttooltip_dateformat',
'%d %b %Y')
self._slugify_name(kwargs.get('name', self.model))
self.jquery_on_ready = kwargs.get('jquery_on_ready', False)
self.color_category = kwargs.get('color_category', None)
self.color_list = kwargs.get('color_list', None)
self.margin_bottom = kwargs.get('margin_bottom', 20)
self.margin_left = kwargs.get('margin_left', 60)
self.margin_right = kwargs.get('margin_right', 60)
self.margin_top = kwargs.get('margin_top', 30)
self.height = kwargs.get('height', '')
self.width = kwargs.get('width', '')
self.stacked = kwargs.get('stacked', False)
self.resize = kwargs.get('resize', False)
self.show_legend = kwargs.get('show_legend', True)
self.show_labels = kwargs.get('show_labels', True)
self.tag_script_js = kwargs.get('tag_script_js', True)
self.use_interactive_guideline = kwargs.get("use_interactive_guideline",
False)
self.chart_attr = kwargs.get("chart_attr", {})
self.extras = kwargs.get('extras', None)
self.style = kwargs.get('style', '')
self.date_format = kwargs.get('date_format', '%x')
self.x_axis_date = kwargs.get('x_axis_date', False)
#: x-axis contain date format or not
# possible duplicate of x_axis_date
self.date_flag = kwargs.get('date_flag', False)
self.x_axis_format = kwargs.get('x_axis_format', '')
# None keywords attribute that should be modified by methods
# We should change all these to _attr
self.htmlcontent = '' #: written by buildhtml
self.htmlheader = ''
#: Place holder for the graph (the HTML div)
#: Written by ``buildcontainer``
self.container = u''
#: Header for javascript code
self.containerheader = u''
# CDN http://cdnjs.com/libraries/nvd3/ needs to make sure it's up to
# date
self.header_css = [
'<link href="%s" rel="stylesheet" />' % h for h in
(
self.assets_directory + 'nvd3/src/nv.d3.css',
)
]
self.header_js = [
'<script src="%s"></script>' % h for h in
(
self.assets_directory + 'd3/d3.min.js',
self.assets_directory + 'nvd3/nv.d3.min.js'
)
]
#: Javascript code as string
self.jschart = None
self.custom_tooltip_flag = False
self.tooltip_condition_string = ''
self.charttooltip = ''
self.serie_no = 1
def _slugify_name(self, name):
"""Slufigy name with underscore"""
self.name = slugify(name, separator='_')
def add_serie(self, y, x, name=None, extra=None, **kwargs):
"""
add serie - Series are list of data that will be plotted
y {1, 2, 3, 4, 5} / x {1, 2, 3, 4, 5}
**Attributes**:
* ``name`` - set Serie name
* ``x`` - x-axis data
* ``y`` - y-axis data
kwargs:
* ``shape`` - for scatterChart, you can set different shapes (circle, triangle etc...)
* ``size`` - for scatterChart, you can set size of different shapes
* ``type`` - for multiChart, type should be bar
* ``bar`` - to display bars in Chart
* ``color_list`` - define list of colors which will be used by pieChart
* ``color`` - set axis color
* ``disabled`` -
extra:
* ``tooltip`` - set tooltip flag
* ``date_format`` - set date_format for tooltip if x-axis is in date format
"""
if not name:
name = "Serie %d" % (self.serie_no)
# For scatterChart shape & size fields are added in serie
if 'shape' in kwargs or 'size' in kwargs:
csize = kwargs.get('size', 1)
cshape = kwargs.get('shape', 'circle')
serie = [{
'x': x[i],
'y': j,
'shape': cshape,
'size': csize[i] if isinstance(csize, list) else csize
} for i, j in enumerate(y)]
else:
if self.model == 'pieChart':
serie = [{'label': x[i], 'value': y} for i, y in enumerate(y)]
# elif self.model == 'linePlusBarWithFocusChart':
# serie = [[x[i], y] for i, y in enumerate(y)]
else:
serie = [{'x': x[i], 'y': y} for i, y in enumerate(y)]
data_keyvalue = {'values': serie, 'key': name}
# multiChart
# Histogram type='bar' for the series
if 'type' in kwargs and kwargs['type']:
data_keyvalue['type'] = kwargs['type']
# Define on which Y axis the serie is related
# a chart can have 2 Y axis, left and right, by default only one Y Axis is used
if 'yaxis' in kwargs and kwargs['yaxis']:
data_keyvalue['yAxis'] = kwargs['yaxis']
else:
if self.model != 'pieChart' and self.model != 'linePlusBarWithFocusChart':
data_keyvalue['yAxis'] = '1'
if 'bar' in kwargs and kwargs['bar']:
data_keyvalue['bar'] = 'true'
if 'disabled' in kwargs and kwargs['disabled']:
data_keyvalue['disabled'] = 'true'
if 'color' in kwargs and kwargs['color']:
data_keyvalue['color'] = kwargs['color']
if extra:
if self.model == 'pieChart':
if 'color_list' in extra and extra['color_list']:
self.color_list = extra['color_list']
if extra.get('date_format'):
self.charttooltip_dateformat = extra['date_format']
if extra.get('tooltip'):
self.custom_tooltip_flag = True
if self.model != 'pieChart':
_start = extra['tooltip']['y_start']
_end = extra['tooltip']['y_end']
_start = ("'" + str(_start) + "' + ") if _start else ''
_end = (" + '" + str(_end) + "'") if _end else ''
if self.model == 'linePlusBarChart' or self.model == 'linePlusBarWithFocusChart':
if self.tooltip_condition_string:
self.tooltip_condition_string += stab(5)
self.tooltip_condition_string += stab(0) + "if(key.indexOf('" + name + "') > -1 ){\n" +\
stab(6) + "var y = " + _start + " String(graph.point.y) " + _end + ";\n" +\
stab(5) + "}\n"
elif self.model == 'cumulativeLineChart':
self.tooltip_condition_string += stab(0) + "if(key == '" + name + "'){\n" +\
stab(6) + "var y = " + _start + " String(e) " + _end + ";\n" +\
stab(5) + "}\n"
else:
self.tooltip_condition_string += stab(5) + "if(key == '" + name + "'){\n" +\
stab(6) + "var y = " + _start + " String(graph.point.y) " + _end + ";\n" +\
stab(5) + "}\n"
if self.model == 'pieChart':
_start = extra['tooltip']['y_start']
_end = extra['tooltip']['y_end']
_start = ("'" + str(_start) + "' + ") if _start else ''
_end = (" + '" + str(_end) + "'") if _end else ''
self.tooltip_condition_string += "var y = " + _start + " String(y) " + _end + ";\n"
#Increment series counter & append
self.serie_no += 1
self.series.append(data_keyvalue)
def add_chart_extras(self, extras):
"""
Use this method to add extra d3 properties to your chart.
For example, you want to change the text color of the graph::
chart = pieChart(name='pieChart', color_category='category20c', height=400, width=400)
xdata = ["Orange", "Banana", "Pear", "Kiwi", "Apple", "Strawberry", "Pineapple"]
ydata = [3, 4, 0, 1, 5, 7, 3]
extra_serie = {"tooltip": {"y_start": "", "y_end": " cal"}}
chart.add_serie(y=ydata, x=xdata, extra=extra_serie)
The above code will create graph with a black text, the following will change it::
text_white="d3.selectAll('#pieChart text').style('fill', 'white');"
chart.add_chart_extras(text_white)
The above extras will be appended to the java script generated.
Alternatively, you can use the following initialization::
chart = pieChart(name='pieChart',
color_category='category20c',
height=400, width=400,
extras=text_white)
"""
self.extras = extras
def set_graph_height(self, height):
"""Set Graph height"""
self.height = str(height)
def set_graph_width(self, width):
"""Set Graph width"""
self.width = str(width)
def set_containerheader(self, containerheader):
"""Set containerheader"""
self.containerheader = containerheader
def set_date_flag(self, date_flag=False):
"""Set date flag"""
self.date_flag = date_flag
def set_custom_tooltip_flag(self, custom_tooltip_flag):
"""Set custom_tooltip_flag & date_flag"""
self.custom_tooltip_flag = custom_tooltip_flag
def __str__(self):
"""return htmlcontent"""
self.buildhtml()
return self.htmlcontent
def buildcontent(self):
"""Build HTML content only, no header or body tags. To be useful this
will usually require the attribute `juqery_on_ready` to be set which
will wrap the js in $(function(){<regular_js>};)
"""
self.buildcontainer()
# if the subclass has a method buildjs this method will be
# called instead of the method defined here
# when this subclass method is entered it does call
# the method buildjschart defined here
self.buildjschart()
self.htmlcontent = self.template_content_nvd3.render(chart=self)
def buildhtml(self):
"""Build the HTML page
Create the htmlheader with css / js
Create html page
Add Js code for nvd3
"""
self.buildcontent()
self.content = self.htmlcontent
self.htmlcontent = self.template_page_nvd3.render(chart=self)
# this is used by django-nvd3
def buildhtmlheader(self):
"""generate HTML header content"""
self.htmlheader = ''
for css in self.header_css:
self.htmlheader += css
for js in self.header_js:
self.htmlheader += js
def buildcontainer(self):
"""generate HTML div"""
if self.container:
return
# Create SVG div with style
if self.width:
if self.width[-1] != '%':
self.style += 'width:%spx;' % self.width
else:
self.style += 'width:%s;' % self.width
if self.height:
if self.height[-1] != '%':
self.style += 'height:%spx;' % self.height
else:
self.style += 'height:%s;' % self.height
if self.style:
self.style = 'style="%s"' % self.style
self.container = self.containerheader + \
'<div id="%s"><svg %s></svg></div>\n' % (self.name, self.style)
def buildjschart(self):
"""generate javascript code for the chart"""
self.jschart = ''
# add custom tooltip string in jschart
# default condition (if build_custom_tooltip is not called explicitly with date_flag=True)
if self.tooltip_condition_string == '':
self.tooltip_condition_string = 'var y = String(graph.point.y);\n'
# Include data
self.series_js = json.dumps(self.series)
def create_x_axis(self, name, label=None, format=None, date=False, custom_format=False):
"""Create X-axis"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
elif format:
if format == 'AM_PM':
axis['tickFormat'] = "function(d) { return get_am_pm(parseInt(d)); }"
else:
axis['tickFormat'] = "d3.format(',%s')" % format
if label:
axis['axisLabel'] = "'" + label + "'"
# date format : see https://github.com/mbostock/d3/wiki/Time-Formatting
if date:
self.dateformat = format
axis['tickFormat'] = "function(d) { return d3.time.format('%s')(new Date(parseInt(d))) }\n" % \
self.dateformat
# flag is the x Axis is a date
if name[0] == 'x':
self.x_axis_date = True
# Add new axis to list of axis
self.axislist[name] = axis
def create_y_axis(self, name, label=None, format=None, custom_format=False):
"""
Create Y-axis
"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
elif format:
axis['tickFormat'] = "d3.format(',%s')" % format
if label:
axis['axisLabel'] = "'" + label + "'"
# Add new axis to list of axis
self.axislist[name] = axis
class TemplateMixin(object):
"""
A mixin that override buildcontent. Instead of building the complex
content template we exploit Jinja2 inheritance. Thus each chart class
renders it's own chart template which inherits from content.html
"""
def buildcontent(self):
"""Build HTML content only, no header or body tags. To be useful this
will usually require the attribute `juqery_on_ready` to be set which
will wrap the js in $(function(){<regular_js>};)
"""
self.buildcontainer()
# if the subclass has a method buildjs this method will be
# called instead of the method defined here
# when this subclass method is entered it does call
# the method buildjschart defined here
self.buildjschart()
self.htmlcontent = self.template_chart_nvd3.render(chart=self)
def _main():
"""
Parse options and process commands
"""
# Parse arguments
usage = "usage: nvd3.py [options]"
parser = OptionParser(usage=usage, version="python-nvd3 - Charts generator with nvd3.js and d3.js")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print messages to stdout")
(options, args) = parser.parse_args()
if __name__ == '__main__':
_main()
|
"""Top-level package for navigate."""
from navigate.model import QNetwork
__author__ = """Juan Carlos Calvo Jackson"""
__email__ = "[email protected]"
__version__ = "0.1.0"
|
from datetime import date
from dateutil.relativedelta import relativedelta, SU
def get_mothers_day_date(year):
"""Given the passed in year int, return the date Mother's Day
is celebrated assuming it's the 2nd Sunday of May."""
return date(year, 1, 1) + relativedelta(months=+4, weekday=SU(2))
# Pybites solution
MAY = 5
def get_mothers_day_date1(year):
"""Given the passed in year int, return the date Mother's Day
is celebrated assuming it's the 2nd Sunday of May."""
first_of_may = date(year=year, month=MAY, day=1)
return first_of_may + relativedelta(weeks=1, weekday=SU)
|
import param
from nick_derobertis_site.common.page_model import PageModel
class LoadingPageModel(PageModel):
pass |
class BinaryTree:
def __init__(self, size):
self.customList = size * [None]
self.lastUsedIndex = 0
self.maxSize = size
def insertNode(self, value):
if self.lastUsedIndex + 1 == self.maxSize:
return "The Binary tree is full"
self.customList[self.lastUsedIndex + 1] = value
self.lastUsedIndex += 1
return "The value has been inserted"
def searchNode(self, nodeValue):
for i in range(len(self.customList)):
if self.customList[i] == nodeValue:
return "Success"
return "Not Found"
def preOrderTraversal(self, index):
if index > self.lastUsedIndex:
return
print(self.customList[index])
self.preOrderTraversal(index * 2)
self.preOrderTraversal(index * 2 + 1)
def inOrderTraversal(self, index):
if index > self.lastUsedIndex:
return
self.inOrderTraversal(index * 2)
print(self.customList[index])
self.inOrderTraversal(index * 2 + 1)
def postOrderTraversal(self, index):
if index > self.lastUsedIndex:
return
self.postOrderTraversal(index * 2)
self.postOrderTraversal(index * 2 + 1)
print(self.customList[index])
def levelOrderTraversal(self, index):
for i in range(index, self.lastUsedIndex + 1):
print(self.customList[i])
def deleteNode(self, value):
if self.lastUsedIndex == 0:
return "There is not any node to delete"
for i in range(1, self.lastUsedIndex + 1):
if self.customList[i] == value:
self.customList[i] = self.customList[self.lastUsedIndex]
self.customList[self.lastUsedIndex] = None
self.lastUsedIndex -= 1
return "The node has been successfully deleted"
def deleteBT(self):
self.customList = None
return "The BT has been successfully deleted"
newBT = BinaryTree(8)
print(newBT.insertNode("Drinks"))
print(newBT.insertNode("Hot"))
print(newBT.insertNode("Cold"))
|
#!/usr/bin/env python
import hashlib
import sys
if len(sys.argv) < 2:
print('<passwd>')
sys.exit(1)
h = hashlib.sha1()
h.update(sys.argv[1])
print(h.hexdigest())
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: quantizer
# Author: Alexandros-Apostolos A. Boulogeorgos
# Generated: Fri Mar 6 07:02:02 2020
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
from PyQt4 import Qt
from PyQt4.QtCore import QObject, pyqtSlot
from gnuradio import analog
from gnuradio import blocks
from gnuradio import channels
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import qtgui
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from gnuradio.qtgui import Range, RangeWidget
from optparse import OptionParser
import math
import sip
import sys
class Quantizer(gr.top_block, Qt.QWidget):
def __init__(self):
gr.top_block.__init__(self, "quantizer")
Qt.QWidget.__init__(self)
self.setWindowTitle("quantizer")
try:
self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
except:
pass
self.top_scroll_layout = Qt.QVBoxLayout()
self.setLayout(self.top_scroll_layout)
self.top_scroll = Qt.QScrollArea()
self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
self.top_scroll_layout.addWidget(self.top_scroll)
self.top_scroll.setWidgetResizable(True)
self.top_widget = Qt.QWidget()
self.top_scroll.setWidget(self.top_widget)
self.top_layout = Qt.QVBoxLayout(self.top_widget)
self.top_grid_layout = Qt.QGridLayout()
self.top_layout.addLayout(self.top_grid_layout)
self.settings = Qt.QSettings("GNU Radio", "Quantizer")
self.restoreGeometry(self.settings.value("geometry").toByteArray())
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 256e3
self.res = res = 8
self.freq = freq = 1e3
##################################################
# Blocks
##################################################
self._res_options = [2, 3, 4, 5, 6, 7, 8, 12, 16]
self._res_labels = ["2 bits", "3 bits", "4 bits", "5 bits", "6 bits", "7bits", "8 bits", "12 bits", "16 bits"]
self._res_group_box = Qt.QGroupBox('Resolution')
self._res_box = Qt.QHBoxLayout()
class variable_chooser_button_group(Qt.QButtonGroup):
def __init__(self, parent=None):
Qt.QButtonGroup.__init__(self, parent)
@pyqtSlot(int)
def updateButtonChecked(self, button_id):
self.button(button_id).setChecked(True)
self._res_button_group = variable_chooser_button_group()
self._res_group_box.setLayout(self._res_box)
for i, label in enumerate(self._res_labels):
radio_button = Qt.QRadioButton(label)
self._res_box.addWidget(radio_button)
self._res_button_group.addButton(radio_button, i)
self._res_callback = lambda i: Qt.QMetaObject.invokeMethod(self._res_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._res_options.index(i)))
self._res_callback(self.res)
self._res_button_group.buttonClicked[int].connect(
lambda i: self.set_res(self._res_options[i]))
self.top_grid_layout.addWidget(self._res_group_box, 0,0,1,1)
self._freq_range = Range(100, samp_rate/2.0, 10, 1e3, 200)
self._freq_win = RangeWidget(self._freq_range, self.set_freq, 'Frequency', "counter_slider", float)
self.top_grid_layout.addWidget(self._freq_win, 1,0,1,1)
self.qtgui_time_sink_x_0_0 = qtgui.time_sink_f(
1024, #size
samp_rate, #samp_rate
"", #name
1 #number of inputs
)
self.qtgui_time_sink_x_0_0.set_update_time(0.10)
self.qtgui_time_sink_x_0_0.set_y_axis(-0.1, 0.1)
self.qtgui_time_sink_x_0_0.set_y_label('Quantization error', "")
self.qtgui_time_sink_x_0_0.enable_tags(-1, True)
self.qtgui_time_sink_x_0_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
self.qtgui_time_sink_x_0_0.enable_autoscale(True)
self.qtgui_time_sink_x_0_0.enable_grid(False)
self.qtgui_time_sink_x_0_0.enable_axis_labels(True)
self.qtgui_time_sink_x_0_0.enable_control_panel(False)
if not True:
self.qtgui_time_sink_x_0_0.disable_legend()
labels = ['Quantized ', 'Analog', '', '', '',
'', '', '', '', '']
widths = [2, 2, 1, 1, 1,
1, 1, 1, 1, 1]
colors = ["blue", "red", "green", "black", "cyan",
"magenta", "yellow", "dark red", "dark green", "blue"]
styles = [1, 1, 1, 1, 1,
1, 1, 1, 1, 1]
markers = [-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1]
alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0]
for i in xrange(1):
if len(labels[i]) == 0:
self.qtgui_time_sink_x_0_0.set_line_label(i, "Data {0}".format(i))
else:
self.qtgui_time_sink_x_0_0.set_line_label(i, labels[i])
self.qtgui_time_sink_x_0_0.set_line_width(i, widths[i])
self.qtgui_time_sink_x_0_0.set_line_color(i, colors[i])
self.qtgui_time_sink_x_0_0.set_line_style(i, styles[i])
self.qtgui_time_sink_x_0_0.set_line_marker(i, markers[i])
self.qtgui_time_sink_x_0_0.set_line_alpha(i, alphas[i])
self._qtgui_time_sink_x_0_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0_0.pyqwidget(), Qt.QWidget)
self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_0_win, 4,0,1,1)
self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
1024, #size
samp_rate, #samp_rate
"", #name
2 #number of inputs
)
self.qtgui_time_sink_x_0.set_update_time(0.10)
self.qtgui_time_sink_x_0.set_y_axis(-1, 1)
self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")
self.qtgui_time_sink_x_0.enable_tags(-1, True)
self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
self.qtgui_time_sink_x_0.enable_autoscale(False)
self.qtgui_time_sink_x_0.enable_grid(False)
self.qtgui_time_sink_x_0.enable_axis_labels(True)
self.qtgui_time_sink_x_0.enable_control_panel(False)
if not True:
self.qtgui_time_sink_x_0.disable_legend()
labels = ['Quantized ', 'Analog', '', '', '',
'', '', '', '', '']
widths = [2, 2, 1, 1, 1,
1, 1, 1, 1, 1]
colors = ["blue", "red", "green", "black", "cyan",
"magenta", "yellow", "dark red", "dark green", "blue"]
styles = [1, 1, 1, 1, 1,
1, 1, 1, 1, 1]
markers = [-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1]
alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0]
for i in xrange(2):
if len(labels[i]) == 0:
self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
else:
self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])
self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_win, 2,0,1,1)
self.qtgui_freq_sink_x_0 = qtgui.freq_sink_f(
2048, #size
firdes.WIN_BLACKMAN_hARRIS, #wintype
0, #fc
samp_rate, #bw
"", #name
1 #number of inputs
)
self.qtgui_freq_sink_x_0.set_update_time(0.10)
self.qtgui_freq_sink_x_0.set_y_axis(-140, 10)
self.qtgui_freq_sink_x_0.set_y_label('Relative Gain', 'dB')
self.qtgui_freq_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, 0.0, 0, "")
self.qtgui_freq_sink_x_0.enable_autoscale(False)
self.qtgui_freq_sink_x_0.enable_grid(False)
self.qtgui_freq_sink_x_0.set_fft_average(1.0)
self.qtgui_freq_sink_x_0.enable_axis_labels(True)
self.qtgui_freq_sink_x_0.enable_control_panel(False)
if not True:
self.qtgui_freq_sink_x_0.disable_legend()
if "float" == "float" or "float" == "msg_float":
self.qtgui_freq_sink_x_0.set_plot_pos_half(not False)
labels = ['', '', '', '', '',
'', '', '', '', '']
widths = [1, 1, 1, 1, 1,
1, 1, 1, 1, 1]
colors = ["blue", "red", "green", "black", "cyan",
"magenta", "yellow", "dark red", "dark green", "dark blue"]
alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0]
for i in xrange(1):
if len(labels[i]) == 0:
self.qtgui_freq_sink_x_0.set_line_label(i, "Data {0}".format(i))
else:
self.qtgui_freq_sink_x_0.set_line_label(i, labels[i])
self.qtgui_freq_sink_x_0.set_line_width(i, widths[i])
self.qtgui_freq_sink_x_0.set_line_color(i, colors[i])
self.qtgui_freq_sink_x_0.set_line_alpha(i, alphas[i])
self._qtgui_freq_sink_x_0_win = sip.wrapinstance(self.qtgui_freq_sink_x_0.pyqwidget(), Qt.QWidget)
self.top_grid_layout.addWidget(self._qtgui_freq_sink_x_0_win, 3,0,1,1)
self.channels_quantizer_0 = channels.quantizer(res)
self.blocks_throttle_0 = blocks.throttle(gr.sizeof_float*1, samp_rate,True)
self.blocks_sub_xx_0 = blocks.sub_ff(1)
self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, freq, 0.9, 0)
##################################################
# Connections
##################################################
self.connect((self.analog_sig_source_x_0, 0), (self.blocks_sub_xx_0, 0))
self.connect((self.analog_sig_source_x_0, 0), (self.channels_quantizer_0, 0))
self.connect((self.analog_sig_source_x_0, 0), (self.qtgui_time_sink_x_0, 1))
self.connect((self.blocks_sub_xx_0, 0), (self.qtgui_time_sink_x_0_0, 0))
self.connect((self.blocks_throttle_0, 0), (self.qtgui_freq_sink_x_0, 0))
self.connect((self.blocks_throttle_0, 0), (self.qtgui_time_sink_x_0, 0))
self.connect((self.channels_quantizer_0, 0), (self.blocks_sub_xx_0, 1))
self.connect((self.channels_quantizer_0, 0), (self.blocks_throttle_0, 0))
def closeEvent(self, event):
self.settings = Qt.QSettings("GNU Radio", "Quantizer")
self.settings.setValue("geometry", self.saveGeometry())
event.accept()
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.qtgui_time_sink_x_0_0.set_samp_rate(self.samp_rate)
self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate)
self.qtgui_freq_sink_x_0.set_frequency_range(0, self.samp_rate)
self.blocks_throttle_0.set_sample_rate(self.samp_rate)
self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
def get_res(self):
return self.res
def set_res(self, res):
self.res = res
self._res_callback(self.res)
self.channels_quantizer_0.set_bits(self.res)
def get_freq(self):
return self.freq
def set_freq(self, freq):
self.freq = freq
self.analog_sig_source_x_0.set_frequency(self.freq)
def main(top_block_cls=Quantizer, options=None):
from distutils.version import StrictVersion
if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
style = gr.prefs().get_string('qtgui', 'style', 'raster')
Qt.QApplication.setGraphicsSystem(style)
qapp = Qt.QApplication(sys.argv)
tb = top_block_cls()
tb.start()
tb.show()
def quitting():
tb.stop()
tb.wait()
qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
qapp.exec_()
if __name__ == '__main__':
main()
|
#!/usr/bin/pxi2thon
# -*- coding: utf-8 -*-
from sympy import *
from sympy.abc import *
# compute stencil for FE rhs (int phi_i phi_j)
#
xi,xi1,xi2,xi3 = symbols('xi xi1 xi2 xi3')
### 1D element contributions for linear Lagrange ansatz function (phi)
def phi0(xi):
return (1-xi)
def phi1(xi):
return xi
print "1D stencil"
print "=========="
# left node
integrand = phi0(xi)**2
entry0 = integrate(integrand,(xi,0,1))
# right node
integrand = phi0(xi)*phi1(xi)
entry1 = integrate(integrand,(xi,0,1))
print "element contribution:"
print "[",entry0,entry1,"]"
print "nodal stencil:"
print "[",entry1,2*entry0,entry1,"]"
### 2D element contributions for linear Lagrange ansatz function (phi)
# 2 3
# 0 1
def phi0(xi1,xi2):
return (1-xi1)*(1-xi2)
def phi1(xi1,xi2):
return xi1*(1-xi2)
def phi2(xi1,xi2):
return (1-xi1)*xi2
def phi3(xi1,xi2):
return xi1*xi2
print "2D stencil"
print "=========="
# lower left node
integrand = phi0(xi1,xi2)**2
entry00 = integrate(integrand,(xi1,0,1),(xi2,0,1)) # -2/3
# lower right node
integrand = phi0(xi1,xi2)*phi1(xi1,xi2)
entry01 = integrate(integrand,(xi1,0,1),(xi2,0,1)) # 1/6
# upper left node
integrand = phi0(xi1,xi2)*phi2(xi1,xi2)
entry10 = integrate(integrand,(xi1,0,1),(xi2,0,1)) # 1/6
# upper right node
integrand = phi0(xi1,xi2)*phi3(xi1,xi2)
entry11 = integrate(integrand,(xi1,0,1),(xi2,0,1)) # 1/3
print "element contribution:"
print "[",entry10,entry11,"]"
print "[",entry00,entry01,"]"
print "nodal stencil:"
print "[",entry11,2*entry10,entry11,"]"
print "[",2*entry01,4*entry00,2*entry01,"]"
print "[",entry11,2*entry10,entry11,"]"
# the element contribution stencil is
# [ 1/6 1/3 ]
# [ _-2/3_ 1/6 ]
# the full stencil is therefore
# [ 1/3 1/3 1/3 ] [ 1 1 1 ]
# [ 1/3 _-8/3_ 1/3 ] = 1/3 [ 1 _-8_ 1 ]
# [ 1/3 1/3 1/3 ] [ 1 1 1 ]
### 3D element contributions for linear Lagrange ansatz function (phi)
def phi0(xi1,xi2,xi3):
return (1-xi1)*(1-xi2)*(1-xi3)
def phi1(xi1,xi2,xi3):
return xi1*(1-xi2)*(1-xi3)
def phi2(xi1,xi2,xi3):
return (1-xi1)*xi2*(1-xi3)
def phi3(xi1,xi2,xi3):
return xi1*xi2*(1-xi3)
def phi4(xi1,xi2,xi3):
return (1-xi1)*(1-xi2)*xi3
def phi5(xi1,xi2,xi3):
return xi1*(1-xi2)*xi3
def phi6(xi1,xi2,xi3):
return (1-xi1)*xi2*xi3
def phi7(xi1,xi2,xi3):
return xi1*xi2*xi3
print ""
print "3D stencil"
print "=========="
# bottom lower left node
integrand = phi0(xi1,xi2,xi3)*phi0(xi1,xi2,xi3)
entry000 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # -1/3
# bottom lower right node
integrand = phi0(xi1,xi2,xi3)*phi1(xi1,xi2,xi3)
entry001 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 0
# bottom upper left node
integrand = phi0(xi1,xi2,xi3)*phi2(xi1,xi2,xi3)
entry010 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 0
# bottom upper right node
integrand = phi0(xi1,xi2,xi3)*phi3(xi1,xi2,xi3)
entry011 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 1/12
# top lower left node
integrand = phi0(xi1,xi2,xi3)*phi4(xi1,xi2,xi3)
entry100 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 0
# top lower right node
integrand = phi0(xi1,xi2,xi3)*phi5(xi1,xi2,xi3)
entry101 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 1/12
# top upper left node
integrand = phi0(xi1,xi2,xi3)*phi6(xi1,xi2,xi3)
entry110 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 1/12
# top upper right node
integrand = phi0(xi1,xi2,xi3)*phi7(xi1,xi2,xi3)
entry111 = integrate(integrand,(xi1,0,1),(xi2,0,1),(xi3,0,1)) # 1/12
print "element contribution:"
print "center: [",entry010,entry011,"]"
print " [",entry000,entry001,"]"
print ""
print "top: [",entry110,entry111,"]"
print " [",entry100,entry101,"]"
print ""
print "nodal stencil:"
print "bottom: [",entry111,2*entry110,entry111,"]"
print " [",2*entry101,4*entry100,2*entry101,"]"
print " [",entry111,2*entry110,entry111,"]"
print ""
print "center: [",2*entry011,4*entry010,2*entry011,"]"
print " [",4*entry001,8*entry000,4*entry001,"]"
print " [",2*entry011,4*entry010,2*entry011,"]"
print ""
print "top: [",entry111,2*entry110,entry111,"]"
print " [",2*entry101,4*entry100,2*entry101,"]"
print " [",entry111,2*entry110,entry111,"]"
# the element contribution stencil is
# center: [ 0 1/12 ]
# [ _-1/3_ 0 ]
#
# top: [ 1/12 1/12 ]
# [ 0 1/12 ]
# the full stencil is therefore
# bottom: [ 1/3 1/6 1/3 ] [ 1 2 1 ]
# [ 1/6 0 1/6 ] [ 2 0 2 ]
# [ 1/3 1/6 1/3 ] [ 1 2 1 ]
#
# center: [ 1/6 0 1/6 ] [ 2 0 2 ]
# [ 0 _-8/3_ 0 ] = 1/12*[ 0 _-32_ 0 ]
# [ 1/6 0 1/6 ] [ 2 0 2 ]
#
# top: [ 1/3 1/6 1/3 ] [ 1 2 1 ]
# [ 1/6 0 1/6 ] [ 2 0 2 ]
# [ 1/3 1/6 1/3 ] [ 1 2 1 ]
|
from collections import Counter
from importlib.resources import open_text
from typing import Dict, Iterable, NamedTuple, Tuple
from more_itertools import windowed
class Pair(NamedTuple):
left: str
right: str
class Rule(NamedTuple):
left: str
right: str
inner: str
@classmethod
def parse(cls, s: str) -> "Rule":
split = list(map(str.strip, s.split("->")))
if len(split) != 2 or len(split[0]) != 2 or len(split[1]) != 1:
raise ValueError("Expected rule in form 'AB -> C'.")
left = split[0][0]
right = split[0][1]
inner = split[1]
return cls(left, right, inner)
@property
def pair(self) -> Pair:
return Pair(self.left, self.right)
@property
def left_pair(self) -> Pair:
return Pair(self.left, self.inner)
@property
def right_pair(self) -> Pair:
return Pair(self.inner, self.right)
class RuleSet:
def __init__(self, rules: Iterable[Rule]):
self._rules: Dict[Pair] = {r.pair: r for r in rules}
def apply_with_count(self, template: str, steps: int) -> Counter[str]:
if len(template) < 2:
raise ValueError("Expected template with length at least 2.")
# We're not interested in the actual sequence of characters, only their counts.
# Use a counter to store counts for each pair in the sequence and add them as
# the sequence is expanded.
counted_pairs: Counter[Pair] = Counter(Pair(*w) for w in windowed(template, 2))
for _ in range(steps):
counted_pairs = self._apply_with_count(counted_pairs)
counted: Counter[str] = Counter()
for pair, count in counted_pairs.items():
counted[pair.left] += count
# We've only added the counts for the starting character in each pair, which
# does not include the final character.
counted[template[-1]] += 1
return counted
def _apply_with_count(self, counted: Counter[Pair]) -> Counter[Pair]:
new: Counter[Pair] = Counter()
for pair, count in counted.items():
rule = self._rules[pair]
new[rule.left_pair] += count
new[rule.right_pair] += count
return new
def _read_template_and_rules() -> Tuple[str, RuleSet]:
with open_text("aoc21.days", "day14.txt") as f:
lines = iter(f)
# Expect template on first line.
template = next(lines).strip()
# Expect an empty line after template.
next(lines)
# Rest of lines are the insertion rules.
rules = RuleSet(map(Rule.parse, lines))
return template, rules
def part1() -> object:
template, rules = _read_template_and_rules()
counted = rules.apply_with_count(template, 10)
return max(counted.values()) - min(counted.values())
def part2() -> object:
template, rules = _read_template_and_rules()
counted = rules.apply_with_count(template, 40)
return max(counted.values()) - min(counted.values())
|
try:
string = '1'
number = 1
print(string + number)
except TypeError:
print('error')
list1 = [1,2,3,4]
try:
for i in range(10):
print(list1[i])
except IndexError:
print('Vyvyshli za gran spiska!') |
from Line import *
from Date import Date
class Flux(Line):
def __init__(self, name="",iD ="",value =0.0 ,shortInfo="" ,
longInfo="" ,supplier="" , iN=0.0 , out=0.0 ,date="none"):
super(Flux,self).__init__(name,iD,date)
self.value=value
self.shortInfo=shortInfo
self.longInfo=longInfo
self.supplier=supplier
self.iN=iN
self.out=out
if __name__ == "__main__":
a =Flux("theo","bouh-dah", 10.0,"est beau","mais genre vraiment","quelqu'un",1000.0,0.0,Date(3,12,1997))
print(a.name)
print("a.iN = "+a.iN)
print(a.date.getDateString())
|
import numpy as np
import argparse
import os.path
import tools # in https://github.com/abigailStev/whizzy_scripts
__author__ = "Abigail Stevens <A.L.Stevens at uva.nl>"
__version__ = "0.2 2015-06-16"
"""
Converts an RXTE energy channel list to a list of real energy *boundaries* per
detector mode energy channel.
Use this for plotting 2D CCF and lag-energy spectra vs energy in keV instead of
vs detector mode energy channel.
2015
"""
################################################################################
if __name__ == "__main__":
###########################
## Parsing input arguments
###########################
parser = argparse.ArgumentParser(usage="channel_to_energy.py ec_table_file"\
" chan_bin_file out_file", description="Converts an RXTE energy "\
"channel list to a list of real energy *boundaries* per detector "\
"energy channel.", epilog="All arguments are required.")
parser.add_argument('ec_table_file', help="Txt table with energy in keV to"\
" absolute channel conversion for RXTE.")
parser.add_argument('chan_bin_file', help="Txt table with how many "\
"absolute channels to group together for each mode energy channel.")
parser.add_argument('out_file', help="Output file (.txt) for real energy "\
"boundaries per detector energy channel.")
parser.add_argument('obs_epoch', type=tools.type_positive_int, help="RXTE "\
"observation epoch.")
args = parser.parse_args()
################
## Idiot checks
################
assert os.path.isfile(args.ec_table_file), "ERROR: Energy-to-channel "\
"conversion table does not exist."
assert os.path.isfile(args.chan_bin_file), "ERROR: Channel binning file "\
"does not exist."
assert args.obs_epoch <= 5, "ERROR: Invalid observation epoch. Must be an "\
"int between 1 and 5, inclusive."
#############################
## Loading tables from files
#############################
ec_table = np.loadtxt(args.ec_table_file)
chan_bin_table = np.loadtxt(args.chan_bin_file)
## Determining column for ec_table based on observation epoch
if args.obs_epoch <= 4:
ec_col = args.obs_epoch + 1
else:
ec_col = 7
## Extracting specific columns (these numbers don't change)
energies = ec_table[:, ec_col] ## Column with the energy in keV per
## absolute channel
binning = chan_bin_table[:, 2] ## Column telling how many absolute channels
## to bin together for that energy bin
## Initializations
energies = np.append(energies, energies[-1])
energy_array = np.asarray(energies[0])
prev_ind = 0
############################################
## Looping through the energy binning array
############################################
for amt in binning:
en_bin_bound = np.mean(energies[prev_ind + amt - 1:prev_ind + amt + 1])
energy_array = np.append(energy_array, en_bin_bound)
prev_ind += amt
## Chop off the last one to have the correct amount of values in the list
energy_array = energy_array[0:-1]
####################################
## Output energy array to text file
####################################
np.savetxt(args.out_file, energy_array)
################################################################################
|
import re
import sys
from napalm import get_network_driver
from getpass import getpass
def pretty_print(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty_print(value, indent+1)
elif isinstance(value, list):
for e in value:
print('\t' * (indent+1) + str(e))
else:
print('\t' * (indent+1) + str(value))
def build_dict(cfg):
""" Builds nested/deep dictionary from Cisco ios
config using recursion function 'child()', which also
changes "the most child" dictionaries to list if possible.
For global Cisco commands make special keys based on
first word in the command, e.g.: '# aaa #'
"""
def group_global_childless(dct):
for k in list(dct):
if not dct[k]:
dct.pop(k,None)
w = k.split()
if w[0] == 'no':
sec_name = f"# {w[1]} #"
else:
sec_name = f"# {w[0]} #"
if sec_name in dct.keys():
dct[sec_name].append(k)
else:
dct.update({sec_name: [k]})
def child(base_indent):
nonlocal n
result = {}
while True:
if n >= len(lines):
break
stripped = lines[n].lstrip()
indent = len(lines[n]) - len(stripped)
if base_indent >= indent:
break
n = n + 1
result.update({stripped: child(indent)})
# In case we got all values={} transform result to list
if not [v for v in result.values() if v]:
result = [k for k in result.keys()]
return result
n = 0
cfg, special_cases = cut_special_cases(cfg)
lines = cfg.splitlines()
lines = [line for line in lines if line
and not line.startswith('!')
and not line.startswith('end')]
dct = child(base_indent=-1)
dct.update(special_cases)
group_global_childless(dct)
return(dct)
def cut_special_cases(cfg):
""" Cut special cases (banners, boot markers) from config and
put them in special_cases dictionary, that is also returned
"""
special_cases = {}
rgx = r"((?:(?P<type>(?:set\s+)*banner\s\w+\s+)(?P<delim>\S+))((.*\r?\n)+?.*?)(\3).*)"
re_banners = re.findall(rgx,cfg)
for r in re_banners:
cfg = cfg.replace(r[0],"",1)
special_cases.update({f"# {r[1]}#": r[0].splitlines()})
rgx = r"boot-start-marker\r?\n(.*\r?\n)*boot-end-marker"
re_boot = re.search(rgx,cfg)
cfg = cfg.replace(re_boot[0],"",1)
special_cases.update({"# boot #": re_boot[0].splitlines()})
return cfg, special_cases
def main():
""" Reads config from file passed as argument. Or connect
to Cisco ios device asking interactively ip, user, password
Then prints result with indentation
"""
if len(sys.argv) >= 1:
file_name = sys.argv[1]
fp = open(file_name)
content = fp.read()
dct = build_dict(content)
else:
driver = get_network_driver('ios')
ipaddress = input('IP address: ')
username = input('Username: ')
ios_conn = driver(ipaddress, username, getpass())
ios_conn.open()
cfgs = ios_conn.get_config()
dct = build_dict(cfgs['running'])
pretty_print(dct,1)
if __name__ == "__main__":
main()
|
from . import gatingmechanism
from .gatingmechanism import *
__all__ = list(gatingmechanism.__all__)
|
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.models import User
from core.schemes.user import UserInDb
from api.deps import get_current_user, get_db
router = APIRouter()
@router.get('/me', response_model=UserInDb)
def get_me(user: User = Depends(get_current_user)):
return UserInDb.from_orm(user)
@router.get('/{user_id}')
def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter_by(user_id=user_id).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return UserInDb.from_orm(user)
|
import json
from datetime import datetime
from flask import url_for
from werkzeug.security import generate_password_hash, check_password_hash
from apidoc.extensions import db
class Role(db.Model):
""" 角色表 """
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
class ProjectCollect(db.Model):
""" 用户关注的项目的关系表 """
__tablename__ = 'project_collect'
collector_id = db.Column(
db.Integer,
db.ForeignKey('users.id'),
primary_key=True)
collected_id = db.Column(
db.Integer,
db.ForeignKey('projects.id'),
primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship(
'User',
back_populates='project_collections',
lazy='joined')
project = db.relationship(
'Project',
back_populates='project_collectors',
lazy='joined')
class SystemCollect(db.Model):
""" 用户关注的系统的关系表 """
__tablename__ = 'system_collect'
collector_id = db.Column(
db.Integer,
db.ForeignKey('users.id'),
primary_key=True)
collected_id = db.Column(
db.Integer,
db.ForeignKey('systems.id'),
primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship(
'User',
back_populates='system_collections',
lazy='joined')
system = db.relationship(
'System',
back_populates='system_collectors',
lazy='joined')
class URLCollect(db.Model):
""" 用户关注的 url 的关系表 """
__tablename__ = 'url_collect'
collector_id = db.Column(
db.Integer,
db.ForeignKey('users.id'),
primary_key=True)
collected_id = db.Column(
db.Integer,
db.ForeignKey('urls.id'),
primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship(
'User',
back_populates='url_collections',
lazy='joined')
url = db.relationship(
'URL',
back_populates='url_collectors',
lazy='joined')
class User(db.Model):
""" 用户表 """
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
name = db.Column(db.String(20))
username = db.Column(db.String(20), unique=True, index=True)
password_hash = db.Column(db.String(128))
member_since = db.Column(db.DateTime(), default=datetime.utcnow)
projects = db.relationship(
'Project',
back_populates='supporter',
lazy='dynamic')
systems = db.relationship(
'System',
back_populates='supporter',
lazy='dynamic')
urls = db.relationship('URL', back_populates='supporter', lazy='dynamic')
api_docs = db.relationship('APIDoc', back_populates='editor')
project_collections = db.relationship(
'ProjectCollect',
back_populates='user',
cascade='all,delete-orphan')
system_collections = db.relationship(
'SystemCollect',
back_populates='user',
cascade='all, delete-orphan')
url_collections = db.relationship(
'URLCollect',
back_populates='user',
cascade='all, delete-orphan')
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def validate_password(self, password):
return check_password_hash(self.password_hash, password)
def to_json(self):
json_user = {
'id': self.id,
'email': self.email,
'name': self.name or self.username,
'username': self.username,
'avatar': '',
'projects_url': url_for(
endpoint='api_v1.support-projects',
user_id=self.id,
_external=True),
'systems_url': url_for(
endpoint='api_v1.support-systems',
user_id=self.id,
_external=True),
'urls_url': url_for(
endpoint='api_v1.support-urls',
user_id=self.id,
_external=True)}
return json_user
class Project(db.Model):
""" 项目列表 """
__tablename__ = 'projects'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
desc = db.Column(db.Text, default='')
domains = db.Column(db.Text)
c_time = db.Column(db.DateTime, default=datetime.utcnow)
supporter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
supporter = db.relationship('User', back_populates='projects')
systems = db.relationship(
'System',
back_populates='project',
cascade='all',
lazy='dynamic')
project_collectors = db.relationship(
'ProjectCollect',
back_populates='project',
cascade='all, delete-orphan')
def to_json(self, author=True):
json_project = {
'id': self.id,
'name': self.name or '',
'desc': self.desc or self.name,
'domains': json.loads(self.domains or '[]'),
'create_time': str(self.c_time)
}
if author is True:
json_project['supporter'] = self.supporter.to_json()
return json_project
class System(db.Model):
""" 系统列表 """
__tablename__ = 'systems'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
desc = db.Column(db.Text)
domains = db.Column(db.Text, comment="列表 json 串,包含 dev、test、stage、online 环境")
c_time = db.Column(db.DateTime, default=datetime.utcnow)
project_id = db.Column(db.Integer, db.ForeignKey('projects.id'))
supporter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
supporter = db.relationship('User', back_populates='systems')
project = db.relationship('Project', back_populates='systems')
urls = db.relationship(
'URL',
back_populates='system',
cascade='all',
lazy='dynamic')
system_collectors = db.relationship(
'SystemCollect',
back_populates='system',
cascade='all, delete-orphan')
def to_json(self):
json_system = {
'id': self.id,
'name': self.name or '',
'desc': self.desc or self.name,
'domains': json.loads(self.domains or '[]'),
'create_time': str(self.c_time),
'project': self.project.to_json(author=False),
'supporter': self.supporter.to_json()
}
return json_system
class Protocol(db.Model):
""" 协议 """
__tablename__ = 'protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True, comment='协议名称')
urls = db.relationship('URL', back_populates='protocol', cascade='all')
methods = db.relationship(
'Method',
back_populates='protocol',
lazy='dynamic')
def to_json(self):
json_protocol = {
'id': self.id,
'name': self.name,
'methods': [method.to_json() for method in self.methods]
}
return json_protocol
class Method(db.Model):
""" 请求方式列表 """
__tablename__ = 'methods'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True, index=True)
protocol_id = db.Column(db.Integer, db.ForeignKey('protocols.id'))
protocol = db.relationship('Protocol', back_populates='methods')
api_docs = db.relationship('APIDoc', back_populates='method')
def to_json(self):
json_method = {
'id': self.id,
'name': self.name,
'protocol': {
'id': self.protocol.id,
'name': self.protocol.name
}
}
return json_method
class URL(db.Model):
""" 接口列表 """
__tablename__ = 'urls'
id = db.Column(db.Integer, primary_key=True)
path = db.Column(db.String(128), index=True)
desc = db.Column(db.String(128), default='')
c_time = db.Column(db.DateTime, default=datetime.utcnow)
protocol_id = db.Column(db.Integer, db.ForeignKey('protocols.id'))
system_id = db.Column(db.Integer, db.ForeignKey('systems.id'))
supporter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
supporter = db.relationship('User', back_populates='urls')
protocol = db.relationship('Protocol', back_populates='urls')
system = db.relationship('System', back_populates='urls')
api_docs = db.relationship('APIDoc', back_populates='url', lazy='dynamic', cascade='all')
url_collectors = db.relationship(
'URLCollect',
back_populates='url',
cascade='all, delete-orphan')
def to_json(self):
json_url = {
'id': self.id,
'path': self.path,
'desc': self.desc or '',
'create_time': str(self.c_time),
'protocol': self.protocol.to_json(),
'supporter': self.supporter.to_json()
}
return json_url
class APIDoc(db.Model):
__tablename__ = 'api_docs'
id = db.Column(db.Integer, primary_key=True)
request_params = db.Column(db.Text, comment='请求参数')
resp_params = db.Column(db.Text, comment='响应参数')
resp_body = db.Column(db.Text, comment='响应体 json 字符串')
edit_time = db.Column(db.DateTime, default=datetime.utcnow)
url_id = db.Column(db.Integer, db.ForeignKey('urls.id'))
method_id = db.Column(db.Integer, db.ForeignKey('methods.id'))
editor_id = db.Column(db.Integer, db.ForeignKey('users.id'))
editor = db.relationship('User', back_populates='api_docs')
url = db.relationship('URL', back_populates='api_docs')
method = db.relationship('Method', back_populates='api_docs')
def to_json(self):
json_api_doc = {
'id': self.id,
'request_param': self.request_param,
'response_param': self.response_param,
'response_body': self.response_body,
'edit_time': str(self.edit_time),
'editor': self.editor.to_json(),
'url_details': url_for('api_v1.urls', url_id=self.url_id, _external=True)
}
if self.method is not None:
json_api_doc['method'] = self.method.to_json()
return json_api_doc
@db.event.listens_for(APIDoc.edit_time, 'set', named=True)
def update_edit_time(**kwargs):
""" 更新接口文档的编辑时间 """
target = kwargs.get('target')
if target.edit_time is not None:
target.edit_time = datetime.utcnow()
|
'''Breadth-First Search module. '''
from collections import deque
GRAPH = {}
GRAPH["you"] = ["alice", "bob", "claire"]
GRAPH["bob"] = ["anuj", "peggy"]
GRAPH["alice"] = ["peggy"]
GRAPH["claire"] = ["thom", "jonny"]
GRAPH["anuj"] = []
GRAPH["peggy"] = []
GRAPH["thom"] = []
GRAPH["jonny"] = []
def _sells_mango(person):
return person.endswith("m")
def search(name):
'''Search people who sells mango'''
search_queue = deque()
search_queue += GRAPH[name]
verified = []
while search_queue:
person = search_queue.popleft()
if person not in verified:
if _sells_mango(person):
print(f"{person} sells mango!")
return True
search_queue += GRAPH[person]
verified.append(person)
return False
def search_path_bookstyle(name):
'''Returns path to people who sells mango, empty if not found.'''
search_queue = deque([(name, [name]), ])
verified = []
while search_queue:
person, path = search_queue.popleft()
if person not in verified:
if _sells_mango(person):
return path
search_queue += ((next_, path + [next_])
for next_ in GRAPH[person])
verified.append(person)
return []
def search_path(name):
'''Returns path to people who sells mango, empty if not found.'''
search_queue = deque([(name, [name]), ])
while search_queue:
person, path = search_queue.popleft()
for next_ in set(GRAPH[person]) - set(path):
if _sells_mango(next_):
return path + [next_]
search_queue.append((next_, path + [next_]))
return []
def main():
'''Search people who sells mango starting from you.'''
search("you")
print(search_path_bookstyle("you"))
print(search_path("you"))
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.