repo_name
stringlengths
7
94
repo_path
stringlengths
4
237
repo_head_hexsha
stringlengths
40
40
content
stringlengths
10
680k
apis
stringlengths
2
840k
mashton/policyk
policykit/django_db_logger/migrations/0002_initial.py
623523d76d63c06b6d559ad7b477d80512fbd2e7
# Generated by Django 3.2.2 on 2021-09-02 15:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('django_db_logger', '0001_initial'), ('policyengine', '0001_initial'), ] operations = [ migrations.AddField( model_name='evaluationlog', name='community', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='policyengine.community'), ), migrations.AddField( model_name='evaluationlog', name='proposal', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='policyengine.proposal'), ), ]
[((20, 18, 20, 133), 'django.db.models.ForeignKey', 'models.ForeignKey', (), '', False, 'from django.db import migrations, models\n'), ((25, 18, 25, 132), 'django.db.models.ForeignKey', 'models.ForeignKey', (), '', False, 'from django.db import migrations, models\n')]
TanyaAdams1/Charm
Charm/models/risk_functions.py
cc6dd64d01f8cb4cf0eb92dadefcb7575d75ec9d
import numpy as np from mcerp import * from uncertainties.core import AffineScalarFunc class RiskFunction(object): def get_risk(self, bar, p): """ Computes risk for perf array w.r.t. bar. Args: bar: reference performance bar. perfs: performance array-like. Returns: single float (mean risk) """ if isinstance(p, UncertainFunction): return self.func(bar, p._mcpts) elif isinstance(p, AffineScalarFunc): #TODO: what should we return? How to define risk analytically? raise ValueError('Risk -- Undefined behavior.') else: return self.func(bar, [p]) def get_name(self): name = type(self).__name__ return name[:name.find('Function')] class DollarValueFunction(RiskFunction): def dollar_function(self, bar, perf): value = .0 for p in perf: normed_p = float(p)/bar if normed_p < .6: value += 100 elif normed_p < .8: value += 200 elif normed_p < .9: value += 300 elif normed_p < 1.0: value += 600 else: value += 1000 return 1000 - value/len(perf) def __init__(self): self.func = self.dollar_function class StepRiskFunction(RiskFunction): def step_function(self, bar, perf): return float(len([p for p in perf if p < bar]))/len(perf) def __init__(self): self.func = self.step_function class LinearRiskFunction(RiskFunction): def linear_cutoff_function(self, bar, perf): # risk = a * (perf-bar) a = 1 risk = [] for p in perf: base = bar - p if base > 0: risk.append(a * base) return np.mean(risk) if risk else 0 def __init__(self): self.func = self.linear_cutoff_function class QuadraticRiskFunction(RiskFunction): def quadratic_cutoff_function(self, bar, perf): # risk = a * (perf-bar)**2 + b * (perf-bar) + c risk = [] a = 4 b = 0 c = 0 for p in perf: base = (bar - p)/bar if base > 0: risk.append(a*base**2 + b*base + c) return np.mean(risk) if risk else 0 def __init__(self): self.func = self.quadratic_cutoff_function class ExponentialRiskFunction(RiskFunction): def exponential_cutoff_function(self, bar, perf): # risk = a ** (perf-bar) risk = [] a = 2.718 for p in perf: base = (bar - p)/bar if base > 0: risk.append(a ** base) return np.mean(risk) if risk else 0 def __init__(self): self.func = self.exponential_cutoff_function class RiskFunctionCollection(object): funcs = {'step': StepRiskFunction(), 'linear': LinearRiskFunction(), 'quad': QuadraticRiskFunction(), 'exp': ExponentialRiskFunction(), 'dollar': DollarValueFunction()}
[((64, 15, 64, 28), 'numpy.mean', 'np.mean', ({(64, 23, 64, 27): 'risk'}, {}), '(risk)', True, 'import numpy as np\n'), ((80, 15, 80, 28), 'numpy.mean', 'np.mean', ({(80, 23, 80, 27): 'risk'}, {}), '(risk)', True, 'import numpy as np\n'), ((94, 15, 94, 28), 'numpy.mean', 'np.mean', ({(94, 23, 94, 27): 'risk'}, {}), '(risk)', True, 'import numpy as np\n')]
verazuo/douban_crawler
code/doubanUtils.py
042e870c74df8b6f4eb1cd2af3b90d5b6699ab8f
import requests import re from bs4 import BeautifulSoup def nextPageLink(sess,soup,page,head=""): NextPage=soup.find(class_='next').link.get('href') req=sess.get(head + NextPage) print(f'第{page}页:',req.status_code) return BeautifulSoup(req.text,'html.parser')
[((10, 11, 10, 48), 'bs4.BeautifulSoup', 'BeautifulSoup', ({(10, 25, 10, 33): 'req.text', (10, 34, 10, 47): '"""html.parser"""'}, {}), "(req.text, 'html.parser')", False, 'from bs4 import BeautifulSoup\n')]
kaixiang1992/python-flask
491/491.py
2b4c597d83f5a6ed662d42d7ff692e563a9adbf8
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship # TODO: db_uri # dialect+driver://username:password@host:port/database?charset=utf8 DB_URI = 'mysql+pymysql://root:[email protected]:3300/first_sqlalchemy?charset=utf8' engine = create_engine(DB_URI) Base = declarative_base(bind=engine) session = sessionmaker(bind=engine)() # TODO: 定义User模型 class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(50), nullable=False) def __repr__(self): return '<User(id={id}, name={name})>'.format(id=self.id, name=self.name) # TODO: 创建Article模型 class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(50), nullable=False) # TODO: 外键约束 uid = Column(Integer, ForeignKey('user.id'), nullable=False) authors = relationship('User', backref='articles') # TODO: 删除数据库 # Base.metadata.drop_all() # TODO: 创建数据库 # Base.metadata.create_all() # # user = User(name='zhiliao') # article1 = Article(title='python') # article2 = Article(title='flask') # # user.articles.append(article1) # user.articles.append(article2) # TODO: 提交数据 # session.add(user) # session.commit() # TODO: 1.session.delete进行删除,不指定`nullable=False` # TODO: 2.session.delete进行删除,指定`nullable=False`,避免删除行为 user = session.query(User).first() print(user) session.delete(user) session.commit()
[((9, 9, 9, 30), 'sqlalchemy.create_engine', 'create_engine', ({(9, 23, 9, 29): 'DB_URI'}, {}), '(DB_URI)', False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((11, 7, 11, 36), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', (), '', False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((13, 10, 13, 35), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', (), '', False, 'from sqlalchemy.orm import sessionmaker, relationship\n'), ((19, 9, 19, 62), 'sqlalchemy.Column', 'Column', (), '', False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((29, 9, 29, 62), 'sqlalchemy.Column', 'Column', (), '', False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((34, 14, 34, 54), 'sqlalchemy.orm.relationship', 'relationship', (), '', False, 'from sqlalchemy.orm import sessionmaker, relationship\n'), ((20, 18, 20, 28), 'sqlalchemy.String', 'String', ({(20, 25, 20, 27): '50'}, {}), '(50)', False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((30, 19, 30, 29), 'sqlalchemy.String', 'String', ({(30, 26, 30, 28): '50'}, {}), '(50)', False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((32, 26, 32, 47), 'sqlalchemy.ForeignKey', 'ForeignKey', ({(32, 37, 32, 46): '"""user.id"""'}, {}), "('user.id')", False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n')]
TerminalWitchcraft/spaCy
spacy/tests/tagger/test_lemmatizer.py
29adbef095c04e21a691e912671e4ec21082b047
# coding: utf-8 from __future__ import unicode_literals from ...lemmatizer import read_index, read_exc import pytest @pytest.mark.models @pytest.mark.parametrize('text,lemmas', [("aardwolves", ["aardwolf"]), ("aardwolf", ["aardwolf"]), ("planets", ["planet"]), ("ring", ["ring"]), ("axes", ["axis", "axe", "ax"])]) def test_tagger_lemmatizer_noun_lemmas(lemmatizer, text, lemmas): if lemmatizer is None: return None assert lemmatizer.noun(text) == set(lemmas) @pytest.mark.models def test_tagger_lemmatizer_base_forms(lemmatizer): if lemmatizer is None: return None assert lemmatizer.noun('dive', {'number': 'sing'}) == set(['dive']) assert lemmatizer.noun('dive', {'number': 'plur'}) == set(['diva']) @pytest.mark.models def test_tagger_lemmatizer_base_form_verb(lemmatizer): if lemmatizer is None: return None assert lemmatizer.verb('saw', {'verbform': 'past'}) == set(['see']) @pytest.mark.models def test_tagger_lemmatizer_punct(lemmatizer): if lemmatizer is None: return None assert lemmatizer.punct('“') == set(['"']) assert lemmatizer.punct('“') == set(['"']) @pytest.mark.models def test_tagger_lemmatizer_read_index(path): if path is not None: with (path / 'wordnet' / 'index.noun').open() as file_: index = read_index(file_) assert 'man' in index assert 'plantes' not in index assert 'plant' in index @pytest.mark.models @pytest.mark.parametrize('text,lemma', [("was", "be")]) def test_tagger_lemmatizer_read_exc(path, text, lemma): if path is not None: with (path / 'wordnet' / 'verb.exc').open() as file_: exc = read_exc(file_) assert exc[text] == (lemma,) @pytest.mark.models def test_tagger_lemmatizer_lemma_assignment(EN): text = "Bananas in pyjamas are geese." doc = EN.tokenizer(text) assert all(t.lemma_ == '' for t in doc) EN.tagger(doc) assert all(t.lemma_ != '' for t in doc)
[((10, 1, 14, 74), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(10, 25, 10, 38): '"""text,lemmas"""', (10, 40, 14, 73): "[('aardwolves', ['aardwolf']), ('aardwolf', ['aardwolf']), ('planets', [\n 'planet']), ('ring', ['ring']), ('axes', ['axis', 'axe', 'ax'])]"}, {}), "('text,lemmas', [('aardwolves', ['aardwolf']), (\n 'aardwolf', ['aardwolf']), ('planets', ['planet']), ('ring', ['ring']),\n ('axes', ['axis', 'axe', 'ax'])])", False, 'import pytest\n'), ((55, 1, 55, 55), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ({(55, 25, 55, 37): '"""text,lemma"""', (55, 39, 55, 54): "[('was', 'be')]"}, {}), "('text,lemma', [('was', 'be')])", False, 'import pytest\n')]
RAY-316/azure-sdk-for-python
sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/__init__.py
4f7790deaf46c6f4e965f099f36eb73a7954ad5b
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- try: from ._models_py3 import AcquiredPhoneNumbers from ._models_py3 import CommunicationError from ._models_py3 import CommunicationErrorResponse from ._models_py3 import PhoneNumberCapabilities from ._models_py3 import PhoneNumberCapabilitiesRequest from ._models_py3 import PhoneNumberCost from ._models_py3 import PhoneNumberOperation from ._models_py3 import PhoneNumberPurchaseRequest from ._models_py3 import PhoneNumberSearchRequest from ._models_py3 import PhoneNumberSearchResult from ._models_py3 import PurchasedPhoneNumber except (SyntaxError, ImportError): from ._models import AcquiredPhoneNumbers # type: ignore from ._models import CommunicationError # type: ignore from ._models import CommunicationErrorResponse # type: ignore from ._models import PhoneNumberCapabilities # type: ignore from ._models import PhoneNumberCapabilitiesRequest # type: ignore from ._models import PhoneNumberCost # type: ignore from ._models import PhoneNumberOperation # type: ignore from ._models import PhoneNumberPurchaseRequest # type: ignore from ._models import PhoneNumberSearchRequest # type: ignore from ._models import PhoneNumberSearchResult # type: ignore from ._models import PurchasedPhoneNumber # type: ignore from ._phone_numbers_client_enums import ( BillingFrequency, PhoneNumberAssignmentType, PhoneNumberCapabilityType, PhoneNumberOperationStatus, PhoneNumberOperationType, PhoneNumberType, ) __all__ = [ 'AcquiredPhoneNumbers', 'CommunicationError', 'CommunicationErrorResponse', 'PhoneNumberCapabilities', 'PhoneNumberCapabilitiesRequest', 'PhoneNumberCost', 'PhoneNumberOperation', 'PhoneNumberPurchaseRequest', 'PhoneNumberSearchRequest', 'PhoneNumberSearchResult', 'PurchasedPhoneNumber', 'BillingFrequency', 'PhoneNumberAssignmentType', 'PhoneNumberCapabilityType', 'PhoneNumberOperationStatus', 'PhoneNumberOperationType', 'PhoneNumberType', ]
[]
Bhaney44/AlgorandDevelopment
AlgoNet2/Helper.py
309e68337227af879f5c4e92c72156928a39fe32
import numpy as np from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout def visualize_training_results(results): """ Plots the loss and accuracy for the training and testing data """ history = results.history plt.figure(figsize=(12,4)) plt.plot(history['val_loss']) plt.plot(history['loss']) plt.legend(['val_loss', 'loss']) plt.title('Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.show() plt.figure(figsize=(12,4)) plt.plot(history['val_accuracy']) plt.plot(history['accuracy']) plt.legend(['val_accuracy', 'accuracy']) plt.title('Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.show() def split_sequence(seq, n_steps_in, n_steps_out): """ Splits the univariate time sequence """ X, y = [], [] for i in range(len(seq)): end = i + n_steps_in out_end = end + n_steps_out if out_end > len(seq): break seq_x, seq_y = seq[i:end], seq[end:out_end] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) def layer_maker(n_layers, n_nodes, activation, drop=None, d_rate=.5): """ Create a specified number of hidden layers for an RNN Optional: Adds regularization option, dropout layer to prevent potential overfitting if necessary """ model = Sequential() # Creating the specified number of hidden layers with the specified number of nodes for x in range(1,n_layers+1): model.add(LSTM(n_nodes, activation=activation, return_sequences=True)) # Adds a Dropout layer after every Nth hidden layer (the 'drop' variable) try: if x % drop == 0: model.add(Dropout(d_rate)) except: pass
[((55, 12, 55, 24), 'keras.models.Sequential', 'Sequential', ({}, {}), '()', False, 'from keras.models import Sequential\n'), ((47, 11, 47, 22), 'numpy.array', 'np.array', ({(47, 20, 47, 21): 'X'}, {}), '(X)', True, 'import numpy as np\n'), ((47, 24, 47, 35), 'numpy.array', 'np.array', ({(47, 33, 47, 34): 'y'}, {}), '(y)', True, 'import numpy as np\n'), ((58, 18, 58, 77), 'keras.layers.LSTM', 'LSTM', (), '', False, 'from keras.layers import LSTM, Dense, Dropout\n'), ((63, 26, 63, 41), 'keras.layers.Dropout', 'Dropout', ({(63, 34, 63, 40): 'd_rate'}, {}), '(d_rate)', False, 'from keras.layers import LSTM, Dense, Dropout\n')]
Muflhi01/apex
apex/contrib/multihead_attn/self_multihead_attn_func.py
79c018776129aad13abeb4ce63d24e1fbb4cd29e
import torch import torch.nn.functional as F class SelfAttnFunc(torch.autograd.Function): @staticmethod def forward( ctx, use_time_mask, is_training, heads, scale, inputs, input_weights, output_weights, input_biases, output_biases, mask, is_additive_mask, dropout_prob, ): use_biases_t = torch.tensor([input_biases is not None]) heads_t = torch.tensor([heads]) scale_t = torch.tensor([scale]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) head_dim = inputs.size(2) // heads # Input Linear GEMM # input1: (activations) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] (transpose [0,1]) # output: [seql_q, seqs, embed_dim*3] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim*3 ) = (seql_q*seqs x embed_dim*3) if use_biases_t[0]: input_lin_results = torch.addmm( input_biases, inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0, 1), beta=1.0, alpha=1.0, ) else: input_lin_results = torch.mm( inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0, 1) ) input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1), input_weights.size(0)) # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1) * heads, 3, head_dim) queries = input_lin_results[:, :, 0, :] keys = input_lin_results[:, :, 1, :] values = input_lin_results[:, :, 2, :] # Matmul1 Batched GEMMs # The output tensor is specified prior to the Batch GEMM because baddbmm requires its specification # baddbmm is used to apply the scale parameter via the Batched GEMM's alpha parameter instead of # a separate elementwise operation. # Input1: (Queries) [seql_q, seqs*heads, head_dim] tranpose(0,1) # Input2: (Keys) [seql_k, seqs*heads, head_dim] transpose(0,1) # output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul1_results = torch.empty( (queries.size(1), queries.size(0), keys.size(0)), dtype=queries.dtype, device=torch.device("cuda") ) matmul1_results = torch.baddbmm( matmul1_results, queries.transpose(0, 1), keys.transpose(0, 1).transpose(1, 2), out=matmul1_results, beta=0.0, alpha=scale_t[0], ) if mask is not None: # Self Attention Time Mask if use_time_mask: assert len(mask.size()) == 2, "Timing mask is not 2D!" assert mask.size(0) == mask.size(1), "Sequence length should match!" mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask, float("-inf")) # Key Padding Mask else: batches, seql_q, seql_k = matmul1_results.size() seqs = int(batches / heads) matmul1_results = matmul1_results.view(seqs, heads, seql_q, seql_k) if is_additive_mask: matmul1_results = matmul1_results + mask.unsqueeze(1).unsqueeze(2) else: mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask.unsqueeze(1).unsqueeze(2), float("-inf")) matmul1_results = matmul1_results.view(seqs * heads, seql_q, seql_k) softmax_results = F.softmax(matmul1_results, dim=-1) # Dropout - is not executed for inference if is_training: dropout_results, dropout_mask = torch._fused_dropout(softmax_results, p=(1.0 - dropout_prob_t[0])) else: dropout_results = softmax_results dropout_mask = null_tensor # Matmul2 Batched GEMMs # The output tensor specification is needed here to specify the non-standard output. # Given that pytorch cannot currently perform autograd with an output tensor specified, # this requires a backward pass specified. # Input1: from_softmax [seqs*heads, seql_q, seql_k] # Input2: (values) [seql_v, seqs*heads, head_dim] transpose(0,1) # Output: [seql_q, seqs*heads, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = (seql_q x head_dim) matmul2_results = torch.empty( (dropout_results.size(1), dropout_results.size(0), values.size(2)), dtype=dropout_results.dtype, device=torch.device("cuda"), ).transpose(1, 0) matmul2_results = torch.bmm(dropout_results, values.transpose(0, 1), out=matmul2_results) matmul2_results = ( matmul2_results.transpose(0, 1).contiguous().view(inputs.size(0), inputs.size(1), inputs.size(2)) ) # Output Linear GEMM # Input1: (activations) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] transpose(0,1) # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) if use_biases_t[0]: outputs = torch.addmm( output_biases, matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0, 1), beta=1.0, alpha=1.0, ) else: outputs = torch.mm( matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0, 1) ) outputs = outputs.view(inputs.size(0), inputs.size(1), output_weights.size(0)) ctx.save_for_backward( use_biases_t, heads_t, scale_t, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob_t, ) return outputs.detach() @staticmethod def backward(ctx, output_grads): ( use_biases_t, heads_t, scale_t, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob_t, ) = ctx.saved_tensors head_dim = inputs.size(2) // heads_t[0] # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1) * heads_t[0], 3, head_dim) queries = input_lin_results[:, :, 0, :] keys = input_lin_results[:, :, 1, :] values = input_lin_results[:, :, 2, :] # Slice out q,k,v from one big set of gradients entering the input linear's bprop (should only impact meta data, no copies!) # The gradients are identical in size to the Input Linear outputs. # The tensor is declared before hand to properly slice out query, key, and value grads. input_lin_results_grads = torch.empty_like(input_lin_results) queries_grads = input_lin_results_grads[:, :, 0, :] keys_grads = input_lin_results_grads[:, :, 1, :] values_grads = input_lin_results_grads[:, :, 2, :] # Output Linear GEMM - DGRAD # Input1: (data grads) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) output_lin_grads = torch.mm( output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), output_weights ) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1), output_weights.size(1)) # Output Linear GEMM - WGRAD # Input1: (data grads) [seql_q*seqs, embed_dim=heads*head_dim] transpose(0,1) # Input2: (activations) [seql_q*seqs, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = ( embed_dim x embed_dim ) output_weight_grads = torch.mm( output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)).transpose(0, 1), matmul2_results.view(matmul2_results.size(0) * matmul2_results.size(1), matmul2_results.size(2)), ) output_lin_grads = output_lin_grads.view(inputs.size(0), inputs.size(1) * heads_t[0], head_dim).transpose(0, 1) if use_biases_t[0]: output_bias_grads = torch.sum( output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), 0 ) else: output_bias_grads = None # Matmul2 - DGRAD1 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul2_dgrad1 = torch.bmm(output_lin_grads, values.transpose(0, 1).transpose(1, 2)) # Matmul2 - DGRAD2 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) values_grads = torch.bmm(dropout_results.transpose(1, 2), output_lin_grads, out=values_grads.transpose(0, 1)) # Mask and Scaling for Dropout (not a publically documented op) dropout_grads = torch._masked_scale(matmul2_dgrad1, dropout_mask, 1.0 / (1.0 - dropout_prob_t[0])) # Softmax Grad (not a publically documented op) softmax_grads = torch._softmax_backward_data(dropout_grads, softmax_results, -1, softmax_results) # Matmul1 - DGRAD1 # Input1: (data grads) [seqs*heads, seql_q, seql_k] # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_q, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = ( seql_q x head_dim ) queries_grads = torch.baddbmm( queries_grads.transpose(0, 1), softmax_grads, keys.transpose(0, 1), out=queries_grads.transpose(0, 1), beta=0.0, alpha=scale_t[0], ) # Matmul1 - DGRAD2 # Input1: (data grads) [seqs*heads, seql_q, seql_k] transpose(1,2) # Input2: (activations) [seql_q, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_k, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_k x seql_q ) x ( seql_q x head_dim ) = ( seql_k x head_dim ) keys_grads = torch.baddbmm( keys_grads.transpose(0, 1), softmax_grads.transpose(1, 2), queries.transpose(0, 1), out=keys_grads.transpose(0, 1), beta=0.0, alpha=scale_t[0], ) # Input Linear GEMM - DGRAD # input1: (data grads) [seql_q, seqs, 3*embed_dim(3072)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x 3*embed_dim ) x ( 3*embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) input_lin_results_grads = input_lin_results_grads.view( inputs.size(0) * inputs.size(1), heads_t[0] * 3 * head_dim ) input_grads = torch.mm(input_lin_results_grads, input_weights) input_grads = input_grads.view(inputs.size(0), inputs.size(1), inputs.size(2)) # Input Linear GEMM - WGRAD # input1: (data grads) [seql_q*seqs, 3*embed_dim(3072)] # input2: (activations) [seql_q*seqs, embed_dim(1024)] # output: [3*embed_dim, embed_dim] # GEMM: ( 3*embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = (3*embed_dim x embed_dim) input_weight_grads = torch.mm( input_lin_results_grads.transpose(0, 1), inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)) ) if use_biases_t[0]: input_bias_grads = torch.sum(input_lin_results_grads, 0) else: input_bias_grads = None return ( None, None, None, None, input_grads, input_weight_grads, output_weight_grads, input_bias_grads, output_bias_grads, None, None, ) self_attn_func = SelfAttnFunc.apply
[((22, 23, 22, 63), 'torch.tensor', 'torch.tensor', ({(22, 36, 22, 62): '[input_biases is not None]'}, {}), '([input_biases is not None])', False, 'import torch\n'), ((23, 18, 23, 39), 'torch.tensor', 'torch.tensor', ({(23, 31, 23, 38): '[heads]'}, {}), '([heads])', False, 'import torch\n'), ((24, 18, 24, 39), 'torch.tensor', 'torch.tensor', ({(24, 31, 24, 38): '[scale]'}, {}), '([scale])', False, 'import torch\n'), ((25, 25, 25, 53), 'torch.tensor', 'torch.tensor', ({(25, 38, 25, 52): '[dropout_prob]'}, {}), '([dropout_prob])', False, 'import torch\n'), ((26, 22, 26, 38), 'torch.tensor', 'torch.tensor', ({(26, 35, 26, 37): '[]'}, {}), '([])', False, 'import torch\n'), ((96, 26, 96, 60), 'torch.nn.functional.softmax', 'F.softmax', (), '', True, 'import torch.nn.functional as F\n'), ((190, 34, 190, 69), 'torch.empty_like', 'torch.empty_like', ({(190, 51, 190, 68): 'input_lin_results'}, {}), '(input_lin_results)', False, 'import torch\n'), ((236, 24, 236, 106), 'torch._masked_scale', 'torch._masked_scale', ({(236, 44, 236, 58): 'matmul2_dgrad1', (236, 60, 236, 72): 'dropout_mask', (236, 74, 236, 105): '1.0 / (1.0 - dropout_prob_t[0])'}, {}), '(matmul2_dgrad1, dropout_mask, 1.0 / (1.0 -\n dropout_prob_t[0]))', False, 'import torch\n'), ((239, 24, 239, 105), 'torch._softmax_backward_data', 'torch._softmax_backward_data', ({(239, 53, 239, 66): 'dropout_grads', (239, 68, 239, 83): 'softmax_results', (239, 85, 239, 87): '-1', (239, 89, 239, 104): 'softmax_results'}, {}), '(dropout_grads, softmax_results, -1,\n softmax_results)', False, 'import torch\n'), ((276, 22, 276, 70), 'torch.mm', 'torch.mm', ({(276, 31, 276, 54): 'input_lin_results_grads', (276, 56, 276, 69): 'input_weights'}, {}), '(input_lin_results_grads, input_weights)', False, 'import torch\n'), ((100, 44, 100, 110), 'torch._fused_dropout', 'torch._fused_dropout', (), '', False, 'import torch\n'), ((288, 31, 288, 68), 'torch.sum', 'torch.sum', ({(288, 41, 288, 64): 'input_lin_results_grads', (288, 66, 288, 67): '0'}, {}), '(input_lin_results_grads, 0)', False, 'import torch\n'), ((66, 90, 66, 110), 'torch.device', 'torch.device', ({(66, 103, 66, 109): '"""cuda"""'}, {}), "('cuda')", False, 'import torch\n'), ((116, 19, 116, 39), 'torch.device', 'torch.device', ({(116, 32, 116, 38): '"""cuda"""'}, {}), "('cuda')", False, 'import torch\n')]
NikolaSiplakova/Baobab
api/app/reviews/models.py
180cd3cb492ed47d38ca0b473572fad0ac6f604b
from datetime import datetime from app import db from app.utils import misc class ReviewForm(db.Model): id = db.Column(db.Integer(), primary_key=True) application_form_id = db.Column(db.Integer(), db.ForeignKey('application_form.id'), nullable=False) is_open = db.Column(db.Boolean(), nullable=False) deadline = db.Column(db.DateTime(), nullable=False) application_form = db.relationship('ApplicationForm', foreign_keys=[application_form_id]) review_questions = db.relationship('ReviewQuestion') def __init__(self, application_form_id, deadline): self.application_form_id = application_form_id self.is_open = True self.deadline = deadline def close(self): self.is_open = False class ReviewQuestion(db.Model): id = db.Column(db.Integer, primary_key=True) review_form_id = db.Column(db.Integer(), db.ForeignKey('review_form.id'), nullable=False) question_id = db.Column(db.Integer(), db.ForeignKey('question.id'), nullable=True) type = db.Column(db.String(), nullable=False) is_required = db.Column(db.Boolean(), nullable=False) order = db.Column(db.Integer(), nullable=False) weight = db.Column(db.Float(), nullable=False) review_form = db.relationship('ReviewForm', foreign_keys=[review_form_id]) question = db.relationship('Question', foreign_keys=[question_id]) translations = db.relationship('ReviewQuestionTranslation', lazy='dynamic') def __init__(self, review_form_id, question_id, type, is_required, order, weight): self.review_form_id = review_form_id self.question_id = question_id self.type = type self.is_required = is_required self.order = order self.weight = weight def get_translation(self, language): translation = self.translations.filter_by(language=language).first() return translation class ReviewQuestionTranslation(db.Model): __tablename__ = 'review_question_translation' __table_args__ = tuple([db.UniqueConstraint('review_question_id', 'language', name='uq_review_question_id_language')]) id = db.Column(db.Integer(), primary_key=True) review_question_id = db.Column(db.Integer(), db.ForeignKey('review_question.id'), nullable=False) language = db.Column(db.String(2), nullable=False) description = db.Column(db.String(), nullable=True) headline = db.Column(db.String(), nullable=True) placeholder = db.Column(db.String(), nullable=True) options = db.Column(db.JSON(), nullable=True) validation_regex = db.Column(db.String(), nullable=True) validation_text = db.Column(db.String(), nullable=True) def __init__(self, review_question_id, language, description=None, headline=None, placeholder=None, options=None, validation_regex=None, validation_text=None): self.review_question_id = review_question_id self.language = language self.description = description self.headline = headline self.placeholder = placeholder self.options = options self.validation_regex = validation_regex self.validation_text = validation_text class ReviewResponse(db.Model): id = db.Column(db.Integer(), primary_key=True) review_form_id = db.Column(db.Integer(), db.ForeignKey('review_form.id'), nullable=False) reviewer_user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'), nullable=False) response_id = db.Column(db.Integer(), db.ForeignKey('response.id'), nullable=False) submitted_timestamp = db.Column(db.DateTime(), nullable=False) language = db.Column(db.String(2), nullable=False) is_submitted = db.Column(db.Boolean(), nullable=False) submitted_timestamp = db.Column(db.DateTime(), nullable=True) review_form = db.relationship('ReviewForm', foreign_keys=[review_form_id]) reviewer_user = db.relationship('AppUser', foreign_keys=[reviewer_user_id]) response = db.relationship('Response', foreign_keys=[response_id]) review_scores = db.relationship('ReviewScore') def __init__(self, review_form_id, reviewer_user_id, response_id, language): self.review_form_id = review_form_id self.reviewer_user_id = reviewer_user_id self.response_id = response_id self.language = language self.is_submitted = False def submit(self): self.is_submitted = True self.submitted_timestamp = datetime.now() def calculate_score(self): return sum([ misc.try_parse_float(score.value) * score.review_question.weight for score in self.review_scores if score.review_question.weight > 0 ]) class ReviewScore(db.Model): id = db.Column(db.Integer(), primary_key=True) review_response_id = db.Column(db.Integer(), db.ForeignKey('review_response.id'), nullable=False) review_question_id = db.Column(db.Integer(), db.ForeignKey('review_question.id'), nullable=False) value = db.Column(db.String(), nullable=False) review_response = db.relationship('ReviewResponse', foreign_keys=[review_response_id]) review_question = db.relationship('ReviewQuestion', foreign_keys=[review_question_id]) def __init__(self, review_question_id, value): self.review_question_id = review_question_id self.value = value class ReviewConfiguration(db.Model): id = db.Column(db.Integer(), primary_key=True) review_form_id = db.Column(db.Integer(), db.ForeignKey('review_form.id'), nullable=False) num_reviews_required = db.Column(db.Integer(), nullable=False) num_optional_reviews = db.Column(db.Integer(), nullable=False) drop_optional_question_id = db.Column(db.Integer(), db.ForeignKey('review_question.id'), nullable=True) drop_optional_agreement_values = db.Column(db.String(), nullable=True) review_form = db.relationship('ReviewForm', foreign_keys=[review_form_id]) review_question = db.relationship('ReviewQuestion', foreign_keys=[drop_optional_question_id])
[((11, 23, 11, 93), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((12, 23, 12, 56), 'app.db.relationship', 'db.relationship', ({(12, 39, 12, 55): '"""ReviewQuestion"""'}, {}), "('ReviewQuestion')", False, 'from app import db\n'), ((24, 9, 24, 48), 'app.db.Column', 'db.Column', (), '', False, 'from app import db\n'), ((33, 18, 33, 78), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((34, 15, 34, 70), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((36, 19, 36, 79), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((101, 18, 101, 78), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((102, 20, 102, 79), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((103, 15, 103, 70), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((104, 20, 104, 50), 'app.db.relationship', 'db.relationship', ({(104, 36, 104, 49): '"""ReviewScore"""'}, {}), "('ReviewScore')", False, 'from app import db\n'), ((134, 22, 134, 90), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((135, 22, 135, 90), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((152, 18, 152, 78), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((153, 22, 153, 97), 'app.db.relationship', 'db.relationship', (), '', False, 'from app import db\n'), ((6, 19, 6, 31), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((7, 36, 7, 48), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((7, 50, 7, 86), 'app.db.ForeignKey', 'db.ForeignKey', ({(7, 64, 7, 85): '"""application_form.id"""'}, {}), "('application_form.id')", False, 'from app import db\n'), ((8, 24, 8, 36), 'app.db.Boolean', 'db.Boolean', ({}, {}), '()', False, 'from app import db\n'), ((9, 25, 9, 38), 'app.db.DateTime', 'db.DateTime', ({}, {}), '()', False, 'from app import db\n'), ((25, 31, 25, 43), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((25, 45, 25, 76), 'app.db.ForeignKey', 'db.ForeignKey', ({(25, 59, 25, 75): '"""review_form.id"""'}, {}), "('review_form.id')", False, 'from app import db\n'), ((26, 28, 26, 40), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((26, 42, 26, 70), 'app.db.ForeignKey', 'db.ForeignKey', ({(26, 56, 26, 69): '"""question.id"""'}, {}), "('question.id')", False, 'from app import db\n'), ((28, 21, 28, 32), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((30, 28, 30, 40), 'app.db.Boolean', 'db.Boolean', ({}, {}), '()', False, 'from app import db\n'), ((31, 22, 31, 34), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((32, 23, 32, 33), 'app.db.Float', 'db.Float', ({}, {}), '()', False, 'from app import db\n'), ((61, 19, 61, 31), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((62, 35, 62, 47), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((62, 49, 62, 84), 'app.db.ForeignKey', 'db.ForeignKey', ({(62, 63, 62, 83): '"""review_question.id"""'}, {}), "('review_question.id')", False, 'from app import db\n'), ((63, 25, 63, 37), 'app.db.String', 'db.String', ({(63, 35, 63, 36): '2'}, {}), '(2)', False, 'from app import db\n'), ((65, 28, 65, 39), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((66, 25, 66, 36), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((67, 28, 67, 39), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((68, 24, 68, 33), 'app.db.JSON', 'db.JSON', ({}, {}), '()', False, 'from app import db\n'), ((69, 33, 69, 44), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((70, 32, 70, 43), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((92, 19, 92, 31), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((93, 31, 93, 43), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((93, 45, 93, 76), 'app.db.ForeignKey', 'db.ForeignKey', ({(93, 59, 93, 75): '"""review_form.id"""'}, {}), "('review_form.id')", False, 'from app import db\n'), ((94, 33, 94, 45), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((94, 47, 94, 75), 'app.db.ForeignKey', 'db.ForeignKey', ({(94, 61, 94, 74): '"""app_user.id"""'}, {}), "('app_user.id')", False, 'from app import db\n'), ((95, 28, 95, 40), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((95, 42, 95, 70), 'app.db.ForeignKey', 'db.ForeignKey', ({(95, 56, 95, 69): '"""response.id"""'}, {}), "('response.id')", False, 'from app import db\n'), ((96, 36, 96, 49), 'app.db.DateTime', 'db.DateTime', ({}, {}), '()', False, 'from app import db\n'), ((97, 25, 97, 37), 'app.db.String', 'db.String', ({(97, 35, 97, 36): '2'}, {}), '(2)', False, 'from app import db\n'), ((98, 29, 98, 41), 'app.db.Boolean', 'db.Boolean', ({}, {}), '()', False, 'from app import db\n'), ((99, 36, 99, 49), 'app.db.DateTime', 'db.DateTime', ({}, {}), '()', False, 'from app import db\n'), ((119, 35, 119, 49), 'datetime.datetime.now', 'datetime.now', ({}, {}), '()', False, 'from datetime import datetime\n'), ((129, 19, 129, 31), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((130, 35, 130, 47), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((130, 49, 130, 84), 'app.db.ForeignKey', 'db.ForeignKey', ({(130, 63, 130, 83): '"""review_response.id"""'}, {}), "('review_response.id')", False, 'from app import db\n'), ((131, 35, 131, 47), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((131, 49, 131, 84), 'app.db.ForeignKey', 'db.ForeignKey', ({(131, 63, 131, 83): '"""review_question.id"""'}, {}), "('review_question.id')", False, 'from app import db\n'), ((132, 22, 132, 33), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((145, 19, 145, 31), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((146, 31, 146, 43), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((146, 45, 146, 76), 'app.db.ForeignKey', 'db.ForeignKey', ({(146, 59, 146, 75): '"""review_form.id"""'}, {}), "('review_form.id')", False, 'from app import db\n'), ((147, 37, 147, 49), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((148, 37, 148, 49), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((149, 42, 149, 54), 'app.db.Integer', 'db.Integer', ({}, {}), '()', False, 'from app import db\n'), ((149, 56, 149, 91), 'app.db.ForeignKey', 'db.ForeignKey', ({(149, 70, 149, 90): '"""review_question.id"""'}, {}), "('review_question.id')", False, 'from app import db\n'), ((150, 47, 150, 58), 'app.db.String', 'db.String', ({}, {}), '()', False, 'from app import db\n'), ((59, 28, 59, 120), 'app.db.UniqueConstraint', 'db.UniqueConstraint', (), '', False, 'from app import db\n'), ((123, 12, 123, 45), 'app.utils.misc.try_parse_float', 'misc.try_parse_float', ({(123, 33, 123, 44): 'score.value'}, {}), '(score.value)', False, 'from app.utils import misc\n')]
Abhranta/speednet
speednet/vae/ConvVae.py
d15971e946cddc62a644d6a6f3be10a4df5b2ce2
import torch.nn as nn import torch from utils import Flatten , Unflatten , weights_init , down_conv , up_conv class Net(nn.Module): def __init__(self , num_layers , img_dim , in_chan , act_func , latent_vector_size): super(Net , self).__init__() assert act_func in ("ReLU" , "LeakyReLU") , "Activation function that can be used now are ReLU and LeakyReLU" assert img_dim % (2**(num_layers)) >= 0 , "Latent vector driven to 0, please increase image size or decreasenumber of layers" self.act_func = act_func self.in_chan = in_chan self.num_layers = num_layers self.latent_vector_size = latent_vector_size self.in_chan2 = self.in_chan self.encoder_net_layers = [] self.decoder_net_layers = [] self.out_chan = 2**5 for _ in range(num_layers): self.encoder_net_layers.append(down_conv(self.in_chan , self.act_func , self.out_chan)) self.in_chan = self.out_chan*2 self.out_chan = self.out_chan*4 self.encoder = nn.Sequential(*self.encoder_net_layers , Flatten() , nn.Linear(((self.out_chan//2)*((img_dim//(2 ** num_layers))**2)) , self.latent_vector_size*4) , nn.ReLU(), nn.Linear(self.latent_vector_size*4 , self.latent_vector_size*2) , nn.ReLU() ) self.mu = nn.Linear(self.latent_vector_size*2 , self.latent_vector_size) self.logvar = nn.Linear(self.latent_vector_size*2 , self.latent_vector_size) self.out_chan2 = self.out_chan for _ in range(num_layers): self.decoder_net_layers.append(up_conv(self.out_chan2//2 , self.act_func , self.out_chan2//4)) self.out_chan2 = self.out_chan2//4 self.decoder = nn.Sequential(nn.Linear(self.latent_vector_size , self.latent_vector_size*4) , nn.ReLU() , nn.Linear(self.latent_vector_size*4 , ((self.out_chan//2)*((img_dim//(2 ** num_layers))**2))) , nn.ReLU() , Unflatten(self.out_chan//2 , (img_dim//(2 ** num_layers)) , (img_dim//(2 ** num_layers)) ) , *self.decoder_net_layers , nn.ConvTranspose2d(self.out_chan2//2 , self.in_chan2 , 3 , 1 , 1)) def encode(self , input_tensor): encoded_vector = self.encoder(input_tensor) mu , logvar = self.mu(encoded_vector) , self.logvar(encoded_vector) return mu , logvar def reparameterize(self , mu , logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) latent = mu + std*eps return latent def decode(self , latent): decoded_vector = self.decoder(latent) return decoded_vector def forward(self , input_tensor): mu , logvar = self.encode(input_tensor) latent_space = self.reparameterize(mu , logvar) return self.decode(latent_space) , mu , logvar
[((33, 18, 33, 80), 'torch.nn.Linear', 'nn.Linear', ({(33, 28, 33, 53): 'self.latent_vector_size * 2', (33, 56, 33, 79): 'self.latent_vector_size'}, {}), '(self.latent_vector_size * 2, self.latent_vector_size)', True, 'import torch.nn as nn\n'), ((34, 22, 34, 84), 'torch.nn.Linear', 'nn.Linear', ({(34, 32, 34, 57): 'self.latent_vector_size * 2', (34, 60, 34, 83): 'self.latent_vector_size'}, {}), '(self.latent_vector_size * 2, self.latent_vector_size)', True, 'import torch.nn as nn\n'), ((57, 14, 57, 37), 'torch.exp', 'torch.exp', ({(57, 24, 57, 36): '0.5 * logvar'}, {}), '(0.5 * logvar)', False, 'import torch\n'), ((58, 14, 58, 35), 'torch.randn_like', 'torch.randn_like', ({(58, 31, 58, 34): 'std'}, {}), '(std)', False, 'import torch\n'), ((27, 37, 27, 46), 'utils.Flatten', 'Flatten', ({}, {}), '()', False, 'from utils import Flatten, Unflatten, weights_init, down_conv, up_conv\n'), ((28, 37, 28, 130), 'torch.nn.Linear', 'nn.Linear', ({(28, 48, 28, 100): 'self.out_chan // 2 * (img_dim // 2 ** num_layers) ** 2', (28, 104, 28, 129): 'self.latent_vector_size * 4'}, {}), '(self.out_chan // 2 * (img_dim // 2 ** num_layers) ** 2, self.\n latent_vector_size * 4)', True, 'import torch.nn as nn\n'), ((29, 37, 29, 46), 'torch.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((30, 37, 30, 101), 'torch.nn.Linear', 'nn.Linear', ({(30, 47, 30, 72): 'self.latent_vector_size * 4', (30, 75, 30, 100): 'self.latent_vector_size * 2'}, {}), '(self.latent_vector_size * 4, self.latent_vector_size * 2)', True, 'import torch.nn as nn\n'), ((31, 37, 31, 46), 'torch.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((43, 37, 43, 99), 'torch.nn.Linear', 'nn.Linear', ({(43, 47, 43, 70): 'self.latent_vector_size', (43, 73, 43, 98): 'self.latent_vector_size * 4'}, {}), '(self.latent_vector_size, self.latent_vector_size * 4)', True, 'import torch.nn as nn\n'), ((44, 36, 44, 45), 'torch.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((45, 36, 45, 129), 'torch.nn.Linear', 'nn.Linear', ({(45, 46, 45, 71): 'self.latent_vector_size * 4', (45, 75, 45, 127): 'self.out_chan // 2 * (img_dim // 2 ** num_layers) ** 2'}, {}), '(self.latent_vector_size * 4, self.out_chan // 2 * (img_dim // 2 **\n num_layers) ** 2)', True, 'import torch.nn as nn\n'), ((46, 36, 46, 45), 'torch.nn.ReLU', 'nn.ReLU', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((47, 36, 47, 126), 'utils.Unflatten', 'Unflatten', ({(47, 46, 47, 62): 'self.out_chan // 2', (47, 66, 47, 92): 'img_dim // 2 ** num_layers', (47, 97, 47, 123): 'img_dim // 2 ** num_layers'}, {}), '(self.out_chan // 2, img_dim // 2 ** num_layers, img_dim // 2 **\n num_layers)', False, 'from utils import Flatten, Unflatten, weights_init, down_conv, up_conv\n'), ((49, 36, 49, 101), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', ({(49, 55, 49, 72): 'self.out_chan2 // 2', (49, 75, 49, 88): 'self.in_chan2', (49, 91, 49, 92): '3', (49, 95, 49, 96): '1', (49, 99, 49, 100): '1'}, {}), '(self.out_chan2 // 2, self.in_chan2, 3, 1, 1)', True, 'import torch.nn as nn\n'), ((23, 43, 23, 98), 'utils.down_conv', 'down_conv', ({(23, 53, 23, 65): 'self.in_chan', (23, 68, 23, 81): 'self.act_func', (23, 84, 23, 97): 'self.out_chan'}, {}), '(self.in_chan, self.act_func, self.out_chan)', False, 'from utils import Flatten, Unflatten, weights_init, down_conv, up_conv\n'), ((38, 43, 38, 105), 'utils.up_conv', 'up_conv', ({(38, 51, 38, 68): '(self.out_chan2 // 2)', (38, 71, 38, 84): 'self.act_func', (38, 87, 38, 104): '(self.out_chan2 // 4)'}, {}), '(self.out_chan2 // 2, self.act_func, self.out_chan2 // 4)', False, 'from utils import Flatten, Unflatten, weights_init, down_conv, up_conv\n')]
IsaacBusaleh/nelpy
nelpy/utils.py
f2663cf6f028c9bd0e630fbf8a527c236f4e0f41
"""This module contains helper functions and utilities for nelpy.""" __all__ = ['spatial_information', 'frange', 'swap_cols', 'swap_rows', 'pairwise', 'is_sorted', 'linear_merge', 'PrettyDuration', 'ddt_asa', 'get_contiguous_segments', 'get_events_boundaries', 'get_threshold_crossing_epochs', '_bst_get_bins'] import numpy as np import logging from itertools import tee, repeat from collections import namedtuple from math import floor from scipy.signal import hilbert import scipy.ndimage.filters #import gaussian_filter1d, gaussian_filter from numpy import log, ceil import copy import sys import ctypes from multiprocessing import Array, cpu_count from multiprocessing.pool import Pool import pdb from . import core # so that core.RegularlySampledAnalogSignalArray is exposed from . import auxiliary # so that auxiliary.TuningCurve1D is epxosed from . import filtering from .utils_.decorators import keyword_deprecation # def sub2ind(array_shape, rows, cols): # ind = rows*array_shape[1] + cols # ind[ind < 0] = -1 # ind[ind >= array_shape[0]*array_shape[1]] = -1 # return ind # def ind2sub(array_shape, ind): # # see also np.unravel_index(ind, array.shape) # ind[ind < 0] = -1 # ind[ind >= array_shape[0]*array_shape[1]] = -1 # rows = (ind.astype('int') / array_shape[1]) # cols = ind % array_shape[1] # return (rows, cols) def ragged_array(arr): """Takes a list of arrays, and returns a ragged array. See https://github.com/numpy/numpy/issues/12468 """ n_elem = len(arr) out = np.array(n_elem*[None]) for ii in range(out.shape[0]): out[ii] = arr[ii] return out def asa_indices_within_epochs(asa, intervalarray): """Return indices of ASA within epochs. [[start, stop] ... [start, stop]] so that data can be associated with asa._data[:,start:stop] for each epoch. """ indices = [] intervalarray = intervalarray[asa.support] for interval in intervalarray.merge().data: a_start = interval[0] a_stop = interval[1] frm, to = np.searchsorted(asa._abscissa_vals, (a_start, a_stop)) indices.append((frm, to)) indices = np.array(indices, ndmin=2) return indices def frange(start, stop, step): """arange with floating point step""" # TODO: this function is not very general; we can extend it to work # for reverse (stop < start), empty, and default args, etc. # there are also many edge cases where this is weird. # see https://stackoverflow.com/questions/7267226/range-for-floats # for better alternatives. num_steps = int(np.floor((stop-start)/step)) return np.linspace(start, stop, num=num_steps, endpoint=False) def spatial_information(ratemap): """Compute the spatial information and firing sparsity... The specificity index examines the amount of information (in bits) that a single spike conveys about the animal's location (i.e., how well cell firing predicts the animal's location).The spatial information content of cell discharge was calculated using the formula: information content = \Sum P_i(R_i/R)log_2(R_i/R) where i is the bin number, P_i, is the probability for occupancy of bin i, R_i, is the mean firing rate for bin i, and R is the overall mean firing rate. In order to account for the effects of low firing rates (with fewer spikes there is a tendency toward higher information content) or random bursts of firing, the spike firing time-series was randomly offset in time from the rat location time-series, and the information content was calculated. A distribution of the information content based on 100 such random shifts was obtained and was used to compute a standardized score (Zscore) of information content for that cell. While the distribution is not composed of independent samples, it was nominally normally distributed, and a Z value of 2.29 was chosen as a cut-off for significance (the equivalent of a one-tailed t-test with P = 0.01 under a normal distribution). Reference(s) ------------ Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L., and Skaggs, W. E. (1994). "Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input", Hippocampus, 4(4), 410-421. Parameters ---------- ratemap : array of shape (n_units, n_bins) Rate map in Hz. Returns ------- si : array of shape (n_units,) spatial information (in bits) per unit """ ratemap = copy.deepcopy(ratemap) # ensure that the ratemap always has nonzero firing rates, # otherwise the spatial information might return NaNs: bkg_rate = ratemap[ratemap>0].min() ratemap[ratemap < bkg_rate] = bkg_rate number_of_spatial_bins = np.prod(ratemap.shape[1:]) weight_per_bin = 1/number_of_spatial_bins Pi = 1 if len(ratemap.shape) == 3: # we have 2D tuning curve, (n_units, n_x, n_y) R = ratemap.mean(axis=1).mean(axis=1) # mean firing rate Ri = np.transpose(ratemap, (2,1,0)) si = np.sum(np.sum((Pi*((Ri / R)*np.log2(Ri / R)).T), axis=1), axis=1) elif len(ratemap.shape) == 2: # we have 1D tuning curve, (n_units, n_x) R = ratemap.mean(axis=1) # mean firing rate Ri = ratemap.T si = np.sum((Pi*((Ri / R)*np.log2(Ri / R)).T), axis=1) else: raise TypeError("rate map shape not supported / understood!") return si/number_of_spatial_bins def spatial_sparsity(ratemap): """Compute the firing sparsity... The specificity index examines the amount of information (in bits) that a single spike conveys about the animal's location (i.e., how well cell firing predicts the animal's location).The spatial information content of cell discharge was calculated using the formula: information content = \Sum P_i(R_i/R)log_2(R_i/R) where i is the bin number, P_i, is the probability for occupancy of bin i, R_i, is the mean firing rate for bin i, and R is the overall mean firing rate. In order to account for the effects of low firing rates (with fewer spikes there is a tendency toward higher information content) or random bursts of firing, the spike firing time-series was randomly offset in time from the rat location time-series, and the information content was calculated. A distribution of the information content based on 100 such random shifts was obtained and was used to compute a standardized score (Zscore) of information content for that cell. While the distribution is not composed of independent samples, it was nominally normally distributed, and a Z value of 2.29 was chosen as a cut-off for significance (the equivalent of a one-tailed t-test with P = 0.01 under a normal distribution). Reference(s) ------------ Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L., and Skaggs, W. E. (1994). "Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input", Hippocampus, 4(4), 410-421. Parameters ---------- occupancy : array of shape (n_bins,) Occupancy of the animal. ratemap : array of shape (n_units, n_bins) Rate map in Hz. Returns ------- si : array of shape (n_units,) spatial information (in bits) per unit sparsity: array of shape (n_units,) sparsity (in percent) for each unit """ number_of_spatial_bins = np.prod(ratemap.shape[1:]) weight_per_bin = 1/number_of_spatial_bins Pi = 1 if len(ratemap.shape) == 3: # we have 2D tuning curve, (n_units, n_x, n_y) R = ratemap.mean(axis=1).mean(axis=1) # mean firing rate Ri = ratemap sparsity = np.sum(np.sum((Ri*Pi), axis=1), axis=1)/(R**2) elif len(ratemap.shape) == 2: # we have 1D tuning curve, (n_units, n_x) R = ratemap.mean(axis=1) # mean firing rate Ri = ratemap.T sparsity = np.sum((Pi*Ri.T), axis=1)/(R**2) else: raise TypeError("rate map shape not supported / understood!") return sparsity/number_of_spatial_bins def _bst_get_bins_inside_interval(interval, ds, w=1): """(np.array) Return bin edges entirely contained inside an interval. Bin edges always start at interval.start, and continue for as many bins as would fit entirely inside the interval. NOTE 1: there are (n+1) bin edges associated with n bins. WARNING: if an interval is smaller than ds, then no bin will be associated with the particular interval. NOTE 2: nelpy uses half-open intervals [a,b), but if the bin width divides b-a, then the bins will cover the entire range. For example, if interval = [0,2) and ds = 1, then bins = [0,1,2], even though [0,2] is not contained in [0,2). There might be numerical precision deviations from this? Parameters ---------- interval : EpochArray EpochArray containing a single interval with a start, and stop ds : float Time bin width, in seconds. w : number of bins to use in a sliding window mode. Default is 1 (no sliding window). For example, 40 ms bins, with a stride of 5 ms, can be achieved by using (ds=0.005, w=8) For now, w has to be an integer, and therefore 5 second bins, with a stride of 2 seconds are not supported within this framework. Returns ------- bins : array Bin edges in an array of shape (n+1,) where n is the number of bins centers : array Bin centers in an array of shape (n,) where n is the number of bins """ if interval.length < ds: return None, None n_bins = int(np.floor(interval.length / ds)) # number of bins # linspace is better than arange for non-integral steps bins = np.linspace(interval.start, interval.start + n_bins*ds, n_bins+1) if w > 1: wn_bins = np.max((1, n_bins - w + 1)) wn_bins = bins[:wn_bins+1] + w/2*ds - ds/2 bins = wn_bins centers = bins[:-1] + (ds / 2) return bins, centers def _bst_get_bins(intervalArray, ds, w=1): """ Docstring goes here. TBD. For use with bins that are contained wholly inside the intervals. """ b = [] # bin list c = [] # centers list left_edges = [] right_edges = [] counter = 0 for interval in intervalArray: bins, centers = _bst_get_bins_inside_interval(interval=interval, ds=ds, w=w) if bins is not None: left_edges.append(counter) counter += len(centers) - 1 right_edges.append(counter) counter += 1 b.extend(bins.tolist()) c.extend(centers.tolist()) bins = np.array(b) bin_centers = np.array(c) le = np.array(left_edges) le = le[:, np.newaxis] re = np.array(right_edges) re = re[:, np.newaxis] binned_support = np.hstack((le, re)) lengths = np.atleast_1d((binned_support[:,1] - binned_support[:,0] + 1).squeeze()) support_starts = bins[np.insert(np.cumsum(lengths+1),0,0)[:-1]] support_stops = bins[np.insert(np.cumsum(lengths+1)-1,0,0)[1:]] supportdata = np.vstack([support_starts, support_stops]).T support = type(intervalArray)(supportdata) # set support to TRUE bin support return bins, bin_centers, binned_support, support @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def get_mua(st, ds=None, sigma=None, truncate=None, _fast=True): """Compute the multiunit activity (MUA) from a spike train. Parameters ---------- st : SpikeTrainArray SpikeTrainArray containing one or more units. -- OR -- st : BinnedSpikeTrainArray BinnedSpikeTrainArray containing multiunit activity. ds : float, optional Time step in which to bin spikes. Default is 1 ms. sigma : float, optional Standard deviation (in seconds) of Gaussian smoothing kernel. Default is 10 ms. If sigma==0 then no smoothing is applied. truncate : float, optional Bandwidth of the Gaussian filter. Default is 6. Returns ------- mua : AnalogSignalArray AnalogSignalArray with MUA. """ if ds is None: ds = 0.001 # 1 ms bin size if sigma is None: sigma = 0.01 # 10 ms standard deviation if truncate is None: truncate = 6 if isinstance(st, core.EventArray): # bin spikes, so that we can count the spikes mua_binned = st.bin(ds=ds).flatten() elif isinstance(st, core.BinnedEventArray): mua_binned = st.flatten() ds = mua_binned.ds else: raise TypeError('st has to be one of (SpikeTrainArray, BinnedSpikeTrainArray)') # make sure data type is float, so that smoothing works, and convert to rate mua_binned._data = mua_binned._data.astype(float) / ds # TODO: now that we can simply cast from BST to ASA and back, the following logic could be simplified: # put mua rate inside an AnalogSignalArray if _fast: mua = core.AnalogSignalArray([], empty=True) mua._data = mua_binned.data mua._abscissa_vals = mua_binned.bin_centers mua._abscissa.support = mua_binned.support else: mua = core.AnalogSignalArray(mua_binned.data, timestamps=mua_binned.bin_centers, fs=1/ds) mua._fs = 1/ds if (sigma != 0) and (truncate > 0): mua = gaussian_filter(mua, sigma=sigma, truncate=truncate) return mua def is_odd(n): """Returns True if n is odd, and False if n is even. Assumes integer. """ return bool(n & 1) def swap_cols(arr, frm, to): """swap columns of a 2D np.array""" if arr.ndim > 1: arr[:,[frm, to]] = arr[:,[to, frm]] else: arr[frm], arr[to] = arr[to], arr[frm] def swap_rows(arr, frm, to): """swap rows of a 2D np.array""" if arr.ndim > 1: arr[[frm, to],:] = arr[[to, frm],:] else: arr[frm], arr[to] = arr[to], arr[frm] def pairwise(iterable): """returns a zip of all neighboring pairs. This is used as a helper function for is_sorted. Example ------- >>> mylist = [2, 3, 6, 8, 7] >>> list(pairwise(mylist)) [(2, 3), (3, 6), (6, 8), (8, 7)] """ a, b = tee(iterable) next(b, None) return zip(a, b) def argsort(seq): # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python return sorted(range(len(seq)), key=seq.__getitem__) def is_sorted_general(iterable, key=lambda a, b: a <= b): """Check to see if iterable is monotonic increasing (sorted).""" return all(key(a, b) for a, b in pairwise(iterable)) def is_sorted(x, chunk_size=None): """Returns True if iterable is monotonic increasing (sorted). NOTE: intended for 1D array, list or tuple. Will not work on more than 1D This function works in-core with memory footrpint XXX. chunk_size = 100000 is probably a good choice. """ if not isinstance(x, (tuple, list, np.ndarray)): raise TypeError("Unsupported type {}".format(type(x))) x = np.atleast_1d(np.array(x).squeeze()) if x.ndim > 1: raise ValueError("Input x must be 1-dimensional") if chunk_size is None: chunk_size = 500000 stop = x.size for chunk_start in range(0, stop, chunk_size): chunk_stop = int(min(stop, chunk_start + chunk_size + 1)) chunk = x[chunk_start:chunk_stop] if not np.all(chunk[:-1] <= chunk[1:]): return False return True def linear_merge(list1, list2): """Merge two SORTED lists in linear time. UPDATED TO WORK WITH PYTHON 3.7+ (see https://stackoverflow.com/questions/51700960/runtimeerror-generator-raised-stopiteration-every-time-i-try-to-run-app) Returns a generator of the merged result. Examples -------- >>> a = [1, 3, 5, 7] >>> b = [2, 4, 6, 8] >>> [i for i in linear_merge(a, b)] [1, 2, 3, 4, 5, 6, 7, 8] >>> [i for i in linear_merge(b, a)] [1, 2, 3, 4, 5, 6, 7, 8] >>> a = [1, 2, 2, 3] >>> b = [2, 2, 4, 4] >>> [i for i in linear_merge(a, b)] [1, 2, 2, 2, 2, 3, 4, 4] """ # if any of the lists are empty, return the other (possibly also # empty) list: (this is necessary because having either list1 or # list2 be empty makes this quite a bit more complicated...) if isinstance(list1, (list, np.ndarray)): if len(list1) == 0: list2 = iter(list2) while True: try: yield next(list2) except StopIteration: return if isinstance(list2, (list, np.ndarray)): if len(list2) == 0: list1 = iter(list1) while True: try: yield next(list1) except StopIteration: return list1 = iter(list1) list2 = iter(list2) value1 = next(list1) value2 = next(list2) # We'll normally exit this loop from a next() call raising # StopIteration, which is how a generator function exits anyway. while True: if value1 <= value2: # Yield the lower value. try: yield value1 except StopIteration: return try: # Grab the next value from list1. value1 = next(list1) except StopIteration: # list1 is empty. Yield the last value we received from list2, then # yield the rest of list2. try: yield value2 except StopIteration: return while True: try: yield next(list2) except StopIteration: return else: try: yield value2 except StopIteration: return try: value2 = next(list2) except StopIteration: # list2 is empty. try: yield value1 except StopIteration: return while True: try: yield next(list1) except StopIteration: return def get_mua_events(mua, fs=None, minLength=None, maxLength=None, PrimaryThreshold=None, minThresholdLength=None, SecondaryThreshold=None): """Determine MUA/PBEs from multiunit activity. MUA : multiunit activity PBE : population burst event Parameters ---------- mua : AnalogSignalArray AnalogSignalArray with one signal, namely the multiunit firing rate [in Hz]. fs : float, optional Sampling frequency of mua, in Hz. If not specified, it will be inferred from mua.fs minLength : float, optional maxLength : float, optional PrimaryThreshold : float, optional SecondaryThreshold : float, optional minThresholdLength : float, optional Returns ------- mua_epochs : EpochArray EpochArray containing all the MUA events / PBEs. Example ------- mua = get_mua(spiketrain) mua_epochs = get_mua_events(mua) PBEs = get_PBEs(spiketrain, min_active=5) = get_PBEs(get_mua_events(get_mua(*)), spiketrain, min_active=5) """ if fs is None: fs = mua.fs if fs is None: raise ValueError("fs must either be specified, or must be contained in mua!") if PrimaryThreshold is None: PrimaryThreshold = mua.mean() + 3*mua.std() if SecondaryThreshold is None: SecondaryThreshold = mua.mean() if minLength is None: minLength = 0.050 # 50 ms minimum event duration if maxLength is None: maxLength = 0.750 # 750 ms maximum event duration if minThresholdLength is None: minThresholdLength = 0.0 # determine MUA event bounds: mua_bounds_idx, maxes, _ = get_events_boundaries( x = mua.data, PrimaryThreshold = PrimaryThreshold, SecondaryThreshold = SecondaryThreshold, minThresholdLength = minThresholdLength, minLength = minLength, maxLength = maxLength, ds = 1/fs ) if len(mua_bounds_idx) == 0: logging.warning("no mua events detected") return core.EpochArray(empty=True) # store MUA bounds in an EpochArray mua_epochs = core.EpochArray(mua.time[mua_bounds_idx]) return mua_epochs @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def get_PBEs(data, fs=None, ds=None, sigma=None, truncate=None, unsorted_id=0, min_active=None, minLength=None, maxLength=None, PrimaryThreshold=None, minThresholdLength=None, SecondaryThreshold=None): """Determine PBEs from multiunit activity or spike trains. Definitions ----------- MUA : multiunit activity PBE : population burst event Summary ------- This function can be used to identify PBE epochs from spike trains, binned spike trains, or multiunit activity (in the form of an AnalogSignalArray). It is recommended to either pass in a SpikeTrainArray or a BinnedSpikeTrainArray, so that a `min_active` number of sorted units can be set. It is also recommended that the unsorted units (but not noise artifacts!) should be included in the spike train that is used to estimate the PBEs. By default, unit_id=0 is assumed to be unsorted, but this can be changed, or if no unsorted units are present, you can set unsorted_id=None. Equivalently, if min_active=0, then no restriction will apply, and the unsorted_id will have no effect on the final PBE epochs. Examples -------- PBE_epochs = get_PBEs(mua_asa) PBE_epochs = get_PBEs(spiketrain, min_active=5) PBE_epochs = get_PBEs(binnedspiketrain, min_active=5) Parameters ---------- data : AnalogSignalArray AnalogSignalArray with one signal, namely the multiunit firing rate [in Hz]. -- OR -- data : SpikeTrainArray SpikeTrainArray with multiple units, including unsorted unit(s), but excluding any noise artifects. -- OR -- data : BinnedSpikeTrainArray BinnedSpikeTrainArray containing multiunit activity. fs : float, optional Sampling frequency of mua, in Hz. If not specified, it will be inferred from data. ds : float, optional Time step in which to bin spikes. Default is 1 ms. sigma : float, optional Standard deviation (in seconds) of Gaussian smoothing kernel. Default is 10 ms. If sigma==0 then no smoothing is applied. truncate : float, optional Bandwidth of the Gaussian filter. Default is 6. unsorted_id : int, optional unit_id of the unsorted unit. Default is 0. If no unsorted unit is present, then set unsorted_id = None min_active : int, optional Minimum number of active units per event, excluding unsorted unit. Default is 5. minLength : float, optional Minimum event duration in seconds. Default is 50 ms. maxLength : float, optional Maximum event duration in seconds. Default is 750 ms. PrimaryThreshold : float, optional Primary threshold to exceed. Default is mean() + 3*std() SecondaryThreshold : float, optional Secondary threshold to fall back to. Default is mean(). minThresholdLength : float, optional Minimum duration to stay above PrimaryThreshold. Default is 0 ms. Returns ------- PBE_epochs : EpochArray EpochArray containing all the PBEs. Future improvements ------------------- As of now, it is possible, but not easy to specify the Primary and Secondary thresholds for event detection. A slight change in API might be needed to make this specification more flexible. """ if sigma is None: sigma = 0.01 # 10 ms standard deviation if truncate is None: truncate = 6 if isinstance(data, core.AnalogSignalArray): # if we have only mua, then we cannot set (ds, unsorted_id, min_active) if ds is not None: raise ValueError('if data is an AnalogSignalArray then ds cannot be specified!') if unsorted_id: raise ValueError('if data is an AnalogSignalArray then unsorted_id cannot be specified!') if min_active is not None: raise ValueError('if data is an AnalogSignalArray then min_active cannot be specified!') mua = data mua._data = mua._data.astype(float) if (sigma != 0) and (truncate > 0): mua = gaussian_filter(mua, sigma=sigma, truncate=truncate) elif isinstance(data, (core.EventArray, core.BinnedEventArray)): # set default parameter values: if ds is None: ds = 0.001 # default 1 ms if min_active is None: min_active = 5 mua = get_mua(data, ds=ds, sigma=sigma, truncate=truncate, _fast=True) else: raise TypeError('data has to be one of (AnalogSignalArray, SpikeTrainArray, BinnedSpikeTrainArray)') # set default parameter values: if fs is None: fs = mua.fs if minLength is None: minLength = 0.050 # 50 ms minimum event duration if maxLength is None: maxLength = 0.750 # 750 ms maximum event duration if minThresholdLength is None: minThresholdLength = 0.0 # if PrimaryThreshold is None: # PrimaryThreshold = # if SecondaryThreshold is None: # SecondaryThreshold = PBE_epochs = get_mua_events(mua=mua, fs=fs, minLength=minLength, maxLength=maxLength, PrimaryThreshold=PrimaryThreshold, minThresholdLength=minThresholdLength, SecondaryThreshold=SecondaryThreshold) # now require min_active number of sorted cells if isinstance(data, (core.EventArray, core.BinnedEventArray)): if min_active > 0: if unsorted_id is not None: # remove unsorted unit, if present: unit_ids = copy.deepcopy(data.unit_ids) try: unit_ids.remove(unsorted_id) except ValueError: pass # data_ = data._unit_subset(unit_ids) data_ = data.loc[:,unit_ids] else: data_ = data # determine number of active units per epoch: n_active = np.array([snippet.n_active for snippet in data_[PBE_epochs]]) active_epochs_idx = np.argwhere(n_active > min_active).squeeze() # only keep those epochs where sufficiently many units are active: PBE_epochs = PBE_epochs[active_epochs_idx] return PBE_epochs def get_contiguous_segments(data, *, step=None, assume_sorted=None, in_core=True, index=False, inclusive=False, fs=None, sort=None, in_memory=None): """Compute contiguous segments (seperated by step) in a list. Note! This function requires that a sorted list is passed. It first checks if the list is sorted O(n), and only sorts O(n log(n)) if necessary. But if you know that the list is already sorted, you can pass assume_sorted=True, in which case it will skip the O(n) check. Returns an array of size (n_segments, 2), with each row being of the form ([start, stop]) [inclusive, exclusive]. NOTE: when possible, use assume_sorted=True, and step=1 as explicit arguments to function call. WARNING! Step is robustly computed in-core (i.e., when in_core is True), but is assumed to be 1 when out-of-core. Example ------- >>> data = [1,2,3,4,10,11,12] >>> get_contiguous_segments(data) ([1,5], [10,13]) >>> get_contiguous_segments(data, index=True) ([0,4], [4,7]) Parameters ---------- data : array-like 1D array of sequential data, typically assumed to be integral (sample numbers). step : float, optional Expected step size for neighboring samples. Default uses numpy to find the median, but it is much faster and memory efficient to explicitly pass in step=1. assume_sorted : bool, optional If assume_sorted == True, then data is not inspected or re-ordered. This can be significantly faster, especially for out-of-core computation, but it should only be used when you are confident that the data is indeed sorted, otherwise the results from get_contiguous_segments will not be reliable. in_core : bool, optional If True, then we use np.diff which requires all the data to fit into memory simultaneously, otherwise we use groupby, which uses a generator to process potentially much larger chunks of data, but also much slower. index : bool, optional If True, the indices of segment boundaries will be returned. Otherwise, the segment boundaries will be returned in terms of the data itself. Default is False. inclusive : bool, optional If True, the boundaries are returned as [(inclusive idx, inclusive idx)] Default is False, and can only be used when index==True. Deprecated ---------- in_memory : bool, optional This is equivalent to the new 'in-core'. sort : bool, optional This is equivalent to the new 'assume_sorted' fs : sampling rate (Hz) used to extend half-open interval support by 1/fs """ # handle deprecated API calls: if in_memory: in_core = in_memory logging.warning("'in_memory' has been deprecated; use 'in_core' instead") if sort: assume_sorted = sort logging.warning("'sort' has been deprecated; use 'assume_sorted' instead") if fs: step = 1/fs logging.warning("'fs' has been deprecated; use 'step' instead") if inclusive: assert index, "option 'inclusive' can only be used with 'index=True'" if in_core: data = np.asarray(data) if not assume_sorted: if not is_sorted(data): data = np.sort(data) # algorithm assumes sorted list if step is None: step = np.median(np.diff(data)) # assuming that data(t1) is sampled somewhere on [t, t+1/fs) we have a 'continuous' signal as long as # data(t2 = t1+1/fs) is sampled somewhere on [t+1/fs, t+2/fs). In the most extreme case, it could happen # that t1 = t and t2 = t + 2/fs, i.e. a difference of 2 steps. if np.any(np.diff(data) < step): logging.warning("some steps in the data are smaller than the requested step size.") breaks = np.argwhere(np.diff(data)>=2*step) starts = np.insert(breaks+1, 0, 0) stops = np.append(breaks, len(data)-1) bdries = np.vstack((data[starts], data[stops] + step)).T if index: if inclusive: indices = np.vstack((starts, stops)).T else: indices = np.vstack((starts, stops + 1)).T return indices else: from itertools import groupby from operator import itemgetter if not assume_sorted: if not is_sorted(data): # data = np.sort(data) # algorithm assumes sorted list raise NotImplementedError("out-of-core sorting has not been implemented yet...") if step is None: step = 1 bdries = [] if not index: for k, g in groupby(enumerate(data), lambda ix: (ix[0] - ix[1])): f = itemgetter(1) gen = (f(x) for x in g) start = next(gen) stop = start for stop in gen: pass bdries.append([start, stop + step]) else: counter = 0 for k, g in groupby(enumerate(data), lambda ix: (ix[0] - ix[1])): f = itemgetter(1) gen = (f(x) for x in g) _ = next(gen) start = counter stop = start for _ in gen: stop +=1 if inclusive: bdries.append([start, stop]) else: bdries.append([start, stop + 1]) counter = stop + 1 return np.asarray(bdries) def get_direction(asa, *, sigma=None): """Return epochs during which an animal was running left to right, or right to left. Parameters ---------- asa : AnalogSignalArray 1D AnalogSignalArray containing the 1D position data. sigma : float, optional Smoothing to apply to position (x) before computing gradient estimate. Default is 0. Returns ------- l2r, r2l : EpochArrays EpochArrays corresponding to left-to-right and right-to-left movement. """ if sigma is None: sigma = 0 if not isinstance(asa, core.AnalogSignalArray): raise TypeError('AnalogSignalArray expected!') assert asa.n_signals == 1, "1D AnalogSignalArray expected!" direction = dxdt_AnalogSignalArray(asa.smooth(sigma=sigma), rectify=False).data direction[direction>=0] = 1 direction[direction<0] = -1 direction = direction.squeeze() l2r = get_contiguous_segments(np.argwhere(direction>0).squeeze(), step=1) l2r[:,1] -= 1 # change bounds from [inclusive, exclusive] to [inclusive, inclusive] l2r = core.EpochArray(asa.abscissa_vals[l2r]) r2l = get_contiguous_segments(np.argwhere(direction<0).squeeze(), step=1) r2l[:,1] -= 1 # change bounds from [inclusive, exclusive] to [inclusive, inclusive] r2l = core.EpochArray(asa.abscissa_vals[r2l]) return l2r, r2l class PrettyBytes(int): """Prints number of bytes in a more readable format""" def __init__(self, val): self.val = val def __str__(self): if self.val < 1024: return '{} bytes'.format(self.val) elif self.val < 1024**2: return '{:.3f} kilobytes'.format(self.val/1024) elif self.val < 1024**3: return '{:.3f} megabytes'.format(self.val/1024**2) elif self.val < 1024**4: return '{:.3f} gigabytes'.format(self.val/1024**3) def __repr__(self): return self.__str__() class PrettyInt(int): """Prints integers in a more readable format""" def __init__(self, val): self.val = val def __str__(self): return '{:,}'.format(self.val) def __repr__(self): return '{:,}'.format(self.val) class PrettyDuration(float): """Time duration with pretty print. Behaves like a float, and can always be cast to a float. """ def __init__(self, seconds): self.duration = seconds def __str__(self): return self.time_string(self.duration) def __repr__(self): return self.time_string(self.duration) @staticmethod def to_dhms(seconds): """convert seconds into hh:mm:ss:ms""" pos = seconds >= 0 if not pos: seconds = -seconds ms = seconds % 1; ms = round(ms*10000)/10 seconds = floor(seconds) m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) Time = namedtuple('Time', 'pos dd hh mm ss ms') time = Time(pos=pos, dd=d, hh=h, mm=m, ss=s, ms=ms) return time @staticmethod def time_string(seconds): """returns a formatted time string.""" if np.isinf(seconds): return 'inf' pos, dd, hh, mm, ss, s = PrettyDuration.to_dhms(seconds) if s > 0: if mm == 0: # in this case, represent milliseconds in terms of # seconds (i.e. a decimal) sstr = str(s/1000).lstrip('0') if s >= 999.5: ss += 1 s = 0 sstr = "" # now propagate the carry: if ss == 60: mm += 1 ss = 0 if mm == 60: hh +=1 mm = 0 if hh == 24: dd += 1 hh = 0 else: # for all other cases, milliseconds will be represented # as an integer if s >= 999.5: ss += 1 s = 0 sstr = "" # now propagate the carry: if ss == 60: mm += 1 ss = 0 if mm == 60: hh +=1 mm = 0 if hh == 24: dd += 1 hh = 0 else: sstr = ":{:03d}".format(int(s)) else: sstr = "" if dd > 0: daystr = "{:01d} days ".format(dd) else: daystr = "" if hh > 0: timestr = daystr + "{:01d}:{:02d}:{:02d}{} hours".format(hh, mm, ss, sstr) elif mm > 0: timestr = daystr + "{:01d}:{:02d}{} minutes".format(mm, ss, sstr) elif ss > 0: timestr = daystr + "{:01d}{} seconds".format(ss, sstr) else: timestr = daystr +"{} milliseconds".format(s) if not pos: timestr = "-" + timestr return timestr def __add__(self, other): """a + b""" return PrettyDuration(self.duration + other) def __radd__(self, other): """b + a""" return self.__add__(other) def __sub__(self, other): """a - b""" return PrettyDuration(self.duration - other) def __rsub__(self, other): """b - a""" return other - self.duration def __mul__(self, other): """a * b""" return PrettyDuration(self.duration * other) def __rmul__(self, other): """b * a""" return self.__mul__(other) def __truediv__(self, other): """a / b""" return PrettyDuration(self.duration / other) def shrinkMatColsTo(mat, numCols): """ Docstring goes here Shrinks a NxM1 matrix down to an NxM2 matrix, where M2 <= M1""" import scipy.ndimage numCells = mat.shape[0] numColsMat = mat.shape[1] a = np.zeros((numCells, numCols)) for row in np.arange(numCells): niurou = scipy.ndimage.interpolation.zoom(input=mat[row,:], zoom=(numCols/numColsMat), order = 1) a[row,:] = niurou return a def find_threshold_crossing_events(x, threshold, *, mode='above'): """Find threshold crossing events. INCLUSIVE Parameters ---------- x : numpy array Input data threshold : float The value whose crossing triggers an event mode : string, optional in ['above', 'below']; default 'above' event triggering above, or below threshold Returns ------- eventlist : list List containing the indices corresponding to threshold crossings eventmax : list List containing the maximum value of each event """ from itertools import groupby from operator import itemgetter if mode == 'below': cross_threshold = np.where(x <= threshold, 1, 0) elif mode == 'above': cross_threshold = np.where(x >= threshold, 1, 0) else: raise NotImplementedError( "mode {} not understood for find_threshold_crossing_events".format(str(mode))) eventlist = [] eventmax = [] for k,v in groupby(enumerate(cross_threshold),key=itemgetter(1)): if k: v = list(v) eventlist.append([v[0][0],v[-1][0]]) try : eventmax.append(x[v[0][0]:(v[-1][0]+1)].max()) except : print(v, x[v[0][0]:v[-1][0]]) eventmax = np.asarray(eventmax) eventlist = np.asarray(eventlist) return eventlist, eventmax def get_events_boundaries(x, *, PrimaryThreshold=None, SecondaryThreshold=None, minThresholdLength=None, minLength=None, maxLength=None, ds=None, mode='above'): """get event boundaries such that event.max >= PrimaryThreshold and the event extent is defined by SecondaryThreshold. Note that when PrimaryThreshold==SecondaryThreshold, then this is a simple threshold crossing algorithm. NB. minLength and maxLength are applied to the SecondaryThreshold events, whereas minThresholdLength is applied to the PrimaryThreshold events. Parameters ---------- x : numpy array Input data mode : string, optional in ['above', 'below']; default 'above' event triggering above, or below threshold PrimaryThreshold : float, optional If mode=='above', requires that event.max >= PrimaryThreshold If mode=='below', requires that event.min <= PrimaryThreshold SecondaryThreshold : float, optional The value that defines the event extent minThresholdLength : float, optional Minimum duration for which the PrimaryThreshold is crossed minLength : float, optional Minimum duration for which the SecondaryThreshold is crossed maxLength : float, optional Maximum duration for which the SecondaryThreshold is crossed ds : float, optional Time step of the input data x Returns ------- returns bounds, maxes, events where bounds <==> SecondaryThreshold to SecondaryThreshold, inclusive maxes <==> maximum value during each event events <==> PrimaryThreshold to PrimaryThreshold, inclusive """ # TODO: x must be a numpy array # TODO: ds is often used, but we have no default, and no check for when # it is left as None. # TODO: the Docstring should equally be improved. x = x.squeeze() if x.ndim > 1: raise TypeError("multidimensional arrays not supported!") if PrimaryThreshold is None: # by default, threshold is 3 SDs above mean of x PrimaryThreshold = np.mean(x) + 3*np.std(x) if SecondaryThreshold is None: # by default, revert back to mean of x SecondaryThreshold = np.mean(x) # + 0*np.std(x) events, _ = \ find_threshold_crossing_events(x=x, threshold=PrimaryThreshold, mode=mode) # apply minThresholdLength criterion: if minThresholdLength is not None and len(events) > 0: durations = (events[:,1] - events[:,0] + 1) * ds events = events[[durations >= minThresholdLength]] if len(events) == 0: bounds, maxes, events = [], [], [] logging.warning("no events satisfied criteria") return bounds, maxes, events # Find periods where value is > SecondaryThreshold; note that the previous periods should be within these! if mode == 'above': assert SecondaryThreshold <= PrimaryThreshold, \ "Secondary Threshold by definition should include more data than Primary Threshold" elif mode == 'below': assert SecondaryThreshold >= PrimaryThreshold, \ "Secondary Threshold by definition should include more data than Primary Threshold" else: raise NotImplementedError( "mode {} not understood for find_threshold_crossing_events".format(str(mode))) bounds, broader_maxes = \ find_threshold_crossing_events(x=x, threshold=SecondaryThreshold, mode=mode) # Find corresponding big windows for potential events # Specifically, look for closest left edge that is just smaller outer_boundary_indices = np.searchsorted(bounds[:,0], events[:,0], side='right') # searchsorted finds the index after, so subtract one to get index before outer_boundary_indices = outer_boundary_indices - 1 # Find extended boundaries for events by pairing to larger windows # (Note that there may be repeats if the larger window contains multiple > 3SD sections) bounds = bounds[outer_boundary_indices,:] maxes = broader_maxes[outer_boundary_indices] if minLength is not None and len(events) > 0: durations = (bounds[:,1] - bounds[:,0] + 1) * ds # TODO: refactor [durations <= maxLength] but be careful about edge cases bounds = bounds[[durations >= minLength]] maxes = maxes[[durations >= minLength]] events = events[[durations >= minLength]] if maxLength is not None and len(events) > 0: durations = (bounds[:,1] - bounds[:,0] + 1) * ds # TODO: refactor [durations <= maxLength] but be careful about edge cases bounds = bounds[[durations <= maxLength]] maxes = maxes[[durations <= maxLength]] events = events[[durations <= maxLength]] if len(events) == 0: bounds, maxes, events = [], [], [] logging.warning("no events satisfied criteria") return bounds, maxes, events # Now, since all that we care about are the larger windows, so we should get rid of repeats _, unique_idx = np.unique(bounds[:,0], return_index=True) bounds = bounds[unique_idx,:] # SecondaryThreshold to SecondaryThreshold maxes = maxes[unique_idx] # maximum value during event events = events[unique_idx,:] # PrimaryThreshold to PrimaryThreshold return bounds, maxes, events def signal_envelope1D(data, *, sigma=None, fs=None): logging.warnings("'signal_envelope1D' is deprecated; use 'signal_envelope_1d' instead!") return signal_envelope_1d(data, sigma=sigma, fs=fs) def signal_envelope_1d(data, *, sigma=None, fs=None): """Finds the signal envelope by taking the absolute value of the Hilbert transform Parameters ---------- data : numpy array, list, or RegularlySampledAnalogSignalArray Input data If data is a numpy array, it is expected to have shape (n_signals, n_samples) If data is a list, it is expected to have length n_signals, where each sublist has length n_samples, i.e. data is not jagged sigma : float, optional Standard deviation of the Gaussian kernel used to smooth the envelope after applying the Hilbert transform. Units of seconds. Default is 4 ms fs : float, optional Sampling rate of the signal Returns ------- out : same type as the input object An object containing the signal envelope TODO: this is not yet epoch-aware! UPDATE: this is actually epoch-aware by now! """ if sigma is None: sigma = 0.004 # 4 ms standard deviation if fs is None: if isinstance(data, (np.ndarray, list)): raise ValueError("sampling frequency must be specified!") elif isinstance(data, core.RegularlySampledAnalogSignalArray): fs = data.fs if isinstance(data, (np.ndarray, list)): data_array = np.array(data) n_dims = np.array(data).ndim assert n_dims <= 2, "Only 1D signals supported!" if n_dims == 1: input_data = data_array.reshape((1, data_array.size)) else: input_data = data_array n_signals, n_samples = input_data.shape # Compute number of samples to compute fast FFTs padlen = nextfastpower(n_samples) - n_samples # Pad data paddeddata = np.hstack( (input_data, np.zeros((n_signals, padlen))) ) # Use hilbert transform to get an envelope envelope = np.absolute(hilbert(paddeddata, axis=-1)) # free up memory del paddeddata # Truncate results back to original length envelope = envelope[..., :n_samples] if sigma: # Smooth envelope with a gaussian (sigma = 4 ms default) EnvelopeSmoothingSD = sigma*fs smoothed_envelope = scipy.ndimage.filters.gaussian_filter1d(envelope, EnvelopeSmoothingSD, mode='constant', axis=-1) envelope = smoothed_envelope if isinstance(data, list): envelope = envelope.tolist() return envelope elif isinstance(data, core.RegularlySampledAnalogSignalArray): # Only ASA data of shape (n_signals, n_timepoints) -> 2D currently supported assert data.data.ndim == 2 cum_lengths = np.insert(np.cumsum(data.lengths), 0, 0) newasa = data.copy() # for segment in data: for idx in range(data.n_epochs): # print('hilberting epoch {}/{}'.format(idx+1, data.n_epochs)) segment_data = data._data[:,cum_lengths[idx]:cum_lengths[idx+1]] n_signals, n_samples = segment_data.shape # Compute number of samples to compute fast FFTs: padlen = nextfastpower(n_samples) - n_samples # Pad data paddeddata = np.hstack( (segment_data, np.zeros((n_signals, padlen))) ) # Use hilbert transform to get an envelope envelope = np.absolute(hilbert(paddeddata, axis=-1)) # free up memory del paddeddata # Truncate results back to original length envelope = envelope[..., :n_samples] if sigma: # Smooth envelope with a gaussian (sigma = 4 ms default) EnvelopeSmoothingSD = sigma*fs smoothed_envelope = scipy.ndimage.filters.gaussian_filter1d(envelope, EnvelopeSmoothingSD, mode='constant', axis=-1) envelope = smoothed_envelope newasa._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = np.atleast_2d(envelope) return newasa def nextpower(n, base=2.0): """Return the next integral power of two greater than the given number. Specifically, return m such that m >= n m == 2**x where x is an integer. Use base argument to specify a base other than 2. This is useful for ensuring fast FFT sizes. From https://gist.github.com/bhawkins/4479607 (Brian Hawkins) """ x = base**ceil (log (n) / log (base)) if type(n) == np.ndarray: return np.asarray (x, dtype=int) else: return int (x) def nextfastpower(n): """Return the next integral power of small factors greater than the given number. Specifically, return m such that m >= n m == 2**x * 3**y * 5**z where x, y, and z are integers. This is useful for ensuring fast FFT sizes. From https://gist.github.com/bhawkins/4479607 (Brian Hawkins) See also http://scipy.github.io/devdocs/generated/scipy.fftpack.next_fast_len.html """ if n < 7: return max (n, 1) # x, y, and z are all bounded from above by the formula of nextpower. # Compute all possible combinations for powers of 3 and 5. # (Not too many for reasonable FFT sizes.) def power_series (x, base): nmax = ceil (log (x) / log (base)) return np.logspace (0.0, nmax, num=nmax+1, base=base) n35 = np.outer (power_series (n, 3.0), power_series (n, 5.0)) n35 = n35[n35<=n] # Lump the powers of 3 and 5 together and solve for the powers of 2. n2 = nextpower (n / n35) return int (min (n2 * n35)) @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def gaussian_filter(obj, *, fs=None, sigma=None, truncate=None, inplace=False, mode=None, cval=None, within_intervals=False): """Smooths with a Gaussian kernel. Smoothing is applied along the abscissa, and the same smoothing is applied to each signal in the RegularlySampledAnalogSignalArray, or to each unit in a BinnedSpikeTrainArray. Smoothing is applied ACROSS intervals, but smoothing WITHIN intervals is also supported. Parameters ---------- obj : RegularlySampledAnalogSignalArray or BinnedSpikeTrainArray. fs : float, optional Sampling rate (in obj.base_unit^-1) of obj. If not provided, it will be inferred. sigma : float, optional Standard deviation of Gaussian kernel, in obj.base_units. Default is 0.05 (50 ms if base_unit=seconds). truncate : float, optional Bandwidth outside of which the filter value will be zero. Default is 4.0. inplace : bool If True the data will be replaced with the smoothed data. Default is False. mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’. cval : scalar, optional Value to fill past edges of input if mode is ‘constant’. Default is 0.0. within_intervals : boolean, optional If True, then smooth within each epoch. Otherwise smooth across epochs. Default is False. Note that when mode = 'wrap', then smoothing within epochs aren't affected by wrapping. Returns ------- out : same type as obj An object with smoothed data is returned. """ if sigma is None: sigma = 0.05 if truncate is None: truncate = 4 if mode is None: mode = 'reflect' if cval is None: cval = 0.0 if not inplace: out = copy.deepcopy(obj) else: out = obj if isinstance(out, core.RegularlySampledAnalogSignalArray): if fs is None: fs = out.fs if fs is None: raise ValueError("fs must either be specified, or must be contained in the {}!".format(out.type_name)) elif isinstance(out, core.BinnedEventArray): bst = out if fs is None: fs = 1/bst.ds if fs is None: raise ValueError("fs must either be specified, or must be contained in the {}!".format(out.type_name)) else: raise NotImplementedError("gaussian_filter for {} is not yet supported!".format(str(type(out)))) sigma = sigma * fs if not within_intervals: # see https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python # (1) if smoothing across intervals, we work on a merged support # (2) build abscissa_vals, including existing ones, and out-of-support ones # (3) to smooth U, build auxiliary arrays V and W, with (V=U).nan=0, and (W=1).nan=0 # (4) Z = smooth(V)/smooth(W) # (5) only keep original support, and original abscissa_vals if isinstance(out, (core.RegularlySampledAnalogSignalArray, core.BinnedEventArray)): support = out._abscissa.support.merge() if not support.domain.is_finite: support.domain = (support.start, support.stop) #TODO: #FIXME might come from abscissa definition, and not from support missing_abscissa_vals = [] for interval in (~support): missing_vals = frange(interval.start, interval.stop, 1/fs) missing_abscissa_vals.extend(missing_vals) if isinstance(out, core.RegularlySampledAnalogSignalArray): n_signals = out.n_signals n_samples = out.n_samples elif isinstance(out, core.BinnedEventArray): n_signals = out.n_series n_samples = out.n_bins V = np.zeros((n_signals, n_samples + len(missing_abscissa_vals))) W = np.ones(V.shape) all_abscissa_vals = np.sort(np.append(out._abscissa_vals, missing_abscissa_vals)) data_idx = np.searchsorted(all_abscissa_vals, out._abscissa_vals) missing_idx = np.searchsorted(all_abscissa_vals, missing_abscissa_vals) V[:, data_idx] = out.data W[:, missing_idx] = 0 VV = scipy.ndimage.filters.gaussian_filter(V, sigma=(0,sigma), truncate=truncate, mode=mode, cval=cval) WW = scipy.ndimage.filters.gaussian_filter(W, sigma=(0,sigma), truncate=truncate, mode=mode, cval=cval) Z = VV[:,data_idx]/WW[:,data_idx] out._data = Z else: raise NotImplementedError("gaussian_filter across intervals for {} is not yet supported!".format(str(type(out)))) else: # within intervals: cum_lengths = np.insert(np.cumsum(out.lengths), 0, 0) out._data = out._data.astype(float) if isinstance(out, core.RegularlySampledAnalogSignalArray): # now smooth each interval separately for idx in range(out.n_intervals): out._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = scipy.ndimage.filters.gaussian_filter(out._data[:,cum_lengths[idx]:cum_lengths[idx+1]], sigma=(0,sigma), truncate=truncate) elif isinstance(out, core.BinnedSpikeTrainArray): # now smooth each interval separately for idx in range(out.n_epochs): out._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = scipy.ndimage.filters.gaussian_filter(out._data[:,cum_lengths[idx]:cum_lengths[idx+1]], sigma=(0,sigma), truncate=truncate) # out._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = self._smooth_array(out._data[:,cum_lengths[idx]:cum_lengths[idx+1]], w=w) return out @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def ddt_asa(asa, *, fs=None, smooth=False, rectify=True, sigma=None, truncate=None, norm=False): """Numerical differentiation of a regularly sampled AnalogSignalArray. Optionally also smooths result with a Gaussian kernel. Smoothing is applied in time, and the same smoothing is applied to each signal in the AnalogSignalArray. Differentiation, (and if requested, smoothing) is applied within each epoch. Parameters ---------- asa : nelpy.RegularlySampledAnalogSignalArray Input object. fs : float, optional Sampling rate (in Hz) of input RSASA. If not provided, it will be obtained from asa.fs. smooth : bool, optional If true, result will be smoothed. Default is False rectify : bool, optional If True, absolute value of derivative is computed. Default is True. sigma : float, optional Standard deviation of Gaussian kernel, in seconds. Default is 0.05 (50 ms). truncate : float, optional Bandwidth outside of which the filter value will be zero. Default is 4.0 norm: boolean, optional If True, then apply the L2 norm to the result. Returns ------- out : nelpy.RegularlySampledAnalogSignalArray A RegularlySampledAnalogSignalArray with derivative data (in units per second) is returned. Notes ----- Central differences are used here. """ if not isinstance(asa, core.RegularlySampledAnalogSignalArray): raise TypeError("Input object must be a RegularlySampledAnalogSignalArray!") if fs is None: fs = asa.fs if sigma is None: sigma = 0.05 # 50 ms default out = asa.copy() cum_lengths = np.insert(np.cumsum(asa.lengths), 0, 0) # ensure that datatype is float # TODO: this will break complex data out._data = out.data.astype(float) # now obtain the derivative for each epoch separately for idx in range(asa.n_epochs): # if 1D: if asa.n_signals == 1: if (cum_lengths[idx+1]-cum_lengths[idx]) < 2: # only single sample out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = 0 else: out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = np.gradient(asa._data[[0],cum_lengths[idx]:cum_lengths[idx+1]], axis=1) else: if (cum_lengths[idx+1]-cum_lengths[idx]) < 2: # only single sample out._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = 0 else: out._data[:,cum_lengths[idx]:cum_lengths[idx+1]] = np.gradient(asa._data[:,cum_lengths[idx]:cum_lengths[idx+1]], axis=1) out._data = out._data * fs if norm: out._data = np.atleast_2d(np.linalg.norm(out._data, axis=0)) if rectify: out._data = np.abs(out._data) if smooth: out = gaussian_filter(out, fs=fs, sigma=sigma, truncate=truncate) return out @keyword_deprecation(replace_x_with_y={'bw':'truncate'}) def dxdt_AnalogSignalArray(asa, *, fs=None, smooth=False, rectify=True, sigma=None, truncate=None): """Numerical differentiation of a regularly sampled AnalogSignalArray. Optionally also smooths result with a Gaussian kernel. Smoothing is applied in time, and the same smoothing is applied to each signal in the AnalogSignalArray. Differentiation, (and if requested, smoothing) is applied within each epoch. Parameters ---------- asa : AnalogSignalArray fs : float, optional Sampling rate (in Hz) of AnalogSignalArray. If not provided, it will be obtained from asa.fs smooth : bool, optional If true, result will be smoothed. Default is False rectify : bool, optional If True, absolute value of derivative is computed. Default is True. sigma : float, optional Standard deviation of Gaussian kernel, in seconds. Default is 0.05 (50 ms). truncate : float, optional Bandwidth outside of which the filter value will be zero. Default is 4.0 Returns ------- out : AnalogSignalArray An AnalogSignalArray with derivative data (in units per second) is returned. """ raise DeprecationWarning('use ddt_asa instead!') if fs is None: fs = asa.fs if fs is None: raise ValueError("fs must either be specified, or must be contained in the AnalogSignalArray!") if sigma is None: sigma = 0.05 # 50 ms default out = copy.deepcopy(asa) cum_lengths = np.insert(np.cumsum(asa.lengths), 0, 0) # ensure that datatype is float out._data = out.data.astype(float) if asa.n_signals == 2: out._data = out._data[[0],:] # now obtain the derivative for each epoch separately for idx in range(asa.n_epochs): # if 1D: if asa.n_signals == 1: if (cum_lengths[idx+1]-cum_lengths[idx]) < 2: # only single sample out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = 0 else: out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = np.gradient(asa._data[[0],cum_lengths[idx]:cum_lengths[idx+1]], axis=1) elif asa.n_signals == 2: if (cum_lengths[idx+1]-cum_lengths[idx]) < 2: # only single sample out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = 0 else: out._data[[0],cum_lengths[idx]:cum_lengths[idx+1]] = np.linalg.norm(np.gradient(asa._data[:,cum_lengths[idx]:cum_lengths[idx+1]], axis=1), axis=0) else: raise TypeError("more than 2D not currently supported!") out._data = out._data * fs if rectify: out._data = np.abs(out._data) if smooth: out = gaussian_filter(out, fs=fs, sigma=sigma, truncate=truncate) return out def get_threshold_crossing_epochs(asa, t1=None, t2=None, mode='above'): """Return epochs where a signal crosses a compound threshold specified by t1 and t2. Parameters ---------- asa : AnalogSignalArray AnalogSignalArray containing a single channel t1 : float, optional Primary threshold. Minimum signal value that has to be reached / exceeded during an event. Default is 3 standard deviations above signal mean. t2 : float, optional Secondary threshold. Signal value that defines the event boundaries. Default is signal mean. mode : string, optional Mode of operation. One of ['above', 'below']. If 'above', then return epochs where the signal exceeds the compound threshold, and if 'below', then return epochs where the signal falls below the compound threshold. Default is 'above'. Returns ------- epochs : EpochArray EpochArray with all the epochs where the signal satisfied the criteria. """ if asa.n_signals > 1: raise TypeError("multidimensional AnalogSignalArrays not supported!") x = asa.data.squeeze() if t1 is None: # by default, threshold is 3 SDs above mean of x t1 = np.mean(x) + 3*np.std(x) if t2 is None: # by default, revert back to mean of x t2 = np.mean(x) # compute periods where signal exceeds compound threshold epoch_bounds, _, _ = get_events_boundaries( x=x, PrimaryThreshold=t1, SecondaryThreshold=t2, mode=mode ) # convert bounds to time in seconds epoch_bounds = asa.time[epoch_bounds] if len(epoch_bounds) == 0: return type(asa._abscissa.support)(empty=True) # add 1/fs to stops for open interval epoch_bounds[:,1] += 1/asa.fs # create EpochArray with threshould exceeding bounds epochs = type(asa._abscissa.support)(epoch_bounds) return epochs def get_run_epochs(speed, v1=10, v2=8): """Return epochs where animal is running at least as fast as specified by v1 and v2. Parameters ---------- speed : AnalogSignalArray AnalogSignalArray containing single channel speed, in units/sec v1 : float, optional Minimum speed (in same units as speed) that has to be reached / exceeded during an event. Default is 10 [units/sec] v2 : float, optional Speed that defines the event boundaries. Default is 8 [units/sec] Returns ------- run_epochs : EpochArray EpochArray with all the epochs where speed satisfied the criteria. """ run_epochs = get_threshold_crossing_epochs(asa=speed, t1=v1, t2=v2, mode='above') return run_epochs def get_inactive_epochs(speed, v1=5, v2=7): """Return epochs where animal is running no faster than specified by v1 and v2. Parameters ---------- speed : AnalogSignalArray AnalogSignalArray containing single channel speed, in units/sec v1 : float, optional Minimum speed (in same units as speed) that has to be reached / exceeded during an event. Default is 10 [units/sec] v2 : float, optional Speed that defines the event boundaries. Default is 8 [units/sec] Returns ------- inactive_epochs : EpochArray EpochArray with all the epochs where speed satisfied the criteria. """ inactive_epochs = get_threshold_crossing_epochs(asa=speed, t1=v1, t2=v2, mode='below') return inactive_epochs def spiketrain_union(st1, st2): """Join two spiketrains together. WARNING! This function should be improved a lot! """ assert st1.n_units == st2.n_units support = st1.support.join(st2.support) newdata = [] for unit in range(st1.n_units): newdata.append(np.append(st1.time[unit], st2.time[unit])) fs = None if st1.fs == st2.fs: fs = st1.fs return core.SpikeTrainArray(newdata, support=support, fs=fs) ######################################################################## # uncurated below this line! ######################################################################## def find_nearest_idx(array, val): """Finds nearest index in array to value. Parameters ---------- array : np.array val : float Returns ------- Index into array that is closest to val TODO: this is a better version that should be incorporated: # Based on answer here: http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array def find_nearest(array,values): right_idxs = np.searchsorted(array, values, side="left") left_idxs = np.where(right_idxs > 0, right_idxs-1, right_idxs) right_idxs = np.where(right_idxs == len(array), len(array)-1, right_idxs) closest_idx = np.where(np.abs(values - array[right_idxs]) < np.abs(values - array[left_idxs]), right_idxs, left_idxs) return closest_idx """ return (np.abs(array-val)).argmin() def find_nearest_indices(array, vals): """Finds nearest index in array to value. Parameters ---------- array : np.array This is the array you wish to index into. vals : np.array This is the array that you are getting your indices from. Returns ------- Indices into array that is closest to vals. Notes ----- Wrapper around find_nearest_idx(). """ return np.array([find_nearest_idx(array, val) for val in vals], dtype=int) def get_sort_idx(tuning_curves): """Finds indices to sort neurons by max firing in tuning curve. Parameters ---------- tuning_curves : list of lists Where each inner list is the tuning curves for an individual neuron. Returns ------- sorted_idx : list List of integers that correspond to the neuron in sorted order. """ tc_max_loc = [] for i, neuron_tc in enumerate(tuning_curves): tc_max_loc.append((i, np.where(neuron_tc == np.max(neuron_tc))[0][0])) sorted_by_tc = sorted(tc_max_loc, key=lambda x: x[1]) sorted_idx = [] for idx in sorted_by_tc: sorted_idx.append(idx[0]) return sorted_idx def collapse_time(obj, gap=0): """Collapse all epochs in a SpikeTrainArray and collapse them into a single, contiguous SpikeTrainArray""" # TODO: redo SpikeTrainArray so as to keep the epochs separate!, and to support gaps! # We'll have to ajust all the spikes per epoch... and we'll have to compute a new support. Also set a flag! # If it's a SpikeTrainArray, then we left-shift the spike times. If it's an AnalogSignalArray, then we # left-shift the time and tdata. # Also set a new attribute, with the boundaries in seconds. if isinstance(obj, core.RegularlySampledAnalogSignalArray): new_obj = type(obj)(empty=True) new_obj._data = obj._data durations = obj.support.durations starts = np.insert(np.cumsum(durations + gap),0,0)[:-1] stops = starts + durations newsupport = type(obj._abscissa.support)(np.vstack((starts, stops)).T) new_obj._support = newsupport new_time = obj.time.astype(float) # fast copy time_idx = np.insert(np.cumsum(obj.lengths),0,0) new_offset = 0 for epidx in range(obj.n_epochs): if epidx > 0: new_time[time_idx[epidx]:time_idx[epidx+1]] = new_time[time_idx[epidx]:time_idx[epidx+1]] - obj.time[time_idx[epidx]] + new_offset + gap new_offset += durations[epidx] + gap else: new_time[time_idx[epidx]:time_idx[epidx+1]] = new_time[time_idx[epidx]:time_idx[epidx+1]] - obj.time[time_idx[epidx]] + new_offset new_offset += durations[epidx] new_obj._time = new_time new_obj._fs = obj._fs elif isinstance(obj, core.EventArray): if gap > 0: raise ValueError("gaps not supported for SpikeTrainArrays yet!") new_obj = type(obj)(empty=True) new_time = [[] for _ in range(obj.n_series)] duration = 0 for st_ in obj: le = st_.support.start for unit_ in range(obj.n_series): new_time[unit_].extend(st_._data[unit_] - le + duration) duration += st_.support.duration new_time = np.asanyarray([np.asanyarray(unittime) for unittime in new_time]) new_obj._data = new_time new_obj.support = type(obj._abscissa.support)([0, duration]) new_obj._series_ids = obj._series_ids new_obj._series_labels = obj._series_labels new_obj._series_tags = obj._series_tags elif isinstance(obj, core.BinnedEventArray): raise NotImplementedError("BinnedEventArrays are not yet supported, but bst.data is essentially already collapsed!") else: raise TypeError("unsupported type for collapse_time") return new_obj def cartesian(xcenters, ycenters): """Finds every combination of elements in two arrays. Parameters ---------- xcenters : np.array ycenters : np.array Returns ------- cartesian : np.array With shape(n_sample, 2). """ return np.transpose([np.tile(xcenters, len(ycenters)), np.repeat(ycenters, len(xcenters))])
[((58, 10, 58, 33), 'numpy.array', 'np.array', ({(58, 19, 58, 32): 'n_elem * [None]'}, {}), '(n_elem * [None])', True, 'import numpy as np\n'), ((79, 14, 79, 40), 'numpy.array', 'np.array', (), '', True, 'import numpy as np\n'), ((91, 11, 91, 66), 'numpy.linspace', 'np.linspace', (), '', True, 'import numpy as np\n'), ((136, 18, 136, 40), 'copy.deepcopy', 'copy.deepcopy', ({(136, 32, 136, 39): 'ratemap'}, {}), '(ratemap)', False, 'import copy\n'), ((142, 33, 142, 59), 'numpy.prod', 'np.prod', ({(142, 41, 142, 58): 'ratemap.shape[1:]'}, {}), '(ratemap.shape[1:])', True, 'import numpy as np\n'), ((208, 33, 208, 59), 'numpy.prod', 'np.prod', ({(208, 41, 208, 58): 'ratemap.shape[1:]'}, {}), '(ratemap.shape[1:])', True, 'import numpy as np\n'), ((271, 11, 271, 76), 'numpy.linspace', 'np.linspace', ({(271, 23, 271, 37): 'interval.start', (271, 39, 271, 65): 'interval.start + n_bins * ds', (271, 67, 271, 75): 'n_bins + 1'}, {}), '(interval.start, interval.start + n_bins * ds, n_bins + 1)', True, 'import numpy as np\n'), ((302, 11, 302, 22), 'numpy.array', 'np.array', ({(302, 20, 302, 21): 'b'}, {}), '(b)', True, 'import numpy as np\n'), ((303, 18, 303, 29), 'numpy.array', 'np.array', ({(303, 27, 303, 28): 'c'}, {}), '(c)', True, 'import numpy as np\n'), ((305, 9, 305, 29), 'numpy.array', 'np.array', ({(305, 18, 305, 28): 'left_edges'}, {}), '(left_edges)', True, 'import numpy as np\n'), ((307, 9, 307, 30), 'numpy.array', 'np.array', ({(307, 18, 307, 29): 'right_edges'}, {}), '(right_edges)', True, 'import numpy as np\n'), ((309, 21, 309, 40), 'numpy.hstack', 'np.hstack', ({(309, 31, 309, 39): '(le, re)'}, {}), '((le, re))', True, 'import numpy as np\n'), ((409, 11, 409, 24), 'itertools.tee', 'tee', ({(409, 15, 409, 23): 'iterable'}, {}), '(iterable)', False, 'from itertools import tee, repeat\n'), ((907, 11, 907, 29), 'numpy.asarray', 'np.asarray', ({(907, 22, 907, 28): 'bdries'}, {}), '(bdries)', True, 'import numpy as np\n'), ((1106, 8, 1106, 37), 'numpy.zeros', 'np.zeros', ({(1106, 17, 1106, 36): '(numCells, numCols)'}, {}), '((numCells, numCols))', True, 'import numpy as np\n'), ((1107, 15, 1107, 34), 'numpy.arange', 'np.arange', ({(1107, 25, 1107, 33): 'numCells'}, {}), '(numCells)', True, 'import numpy as np\n'), ((1151, 15, 1151, 35), 'numpy.asarray', 'np.asarray', ({(1151, 26, 1151, 34): 'eventmax'}, {}), '(eventmax)', True, 'import numpy as np\n'), ((1152, 16, 1152, 37), 'numpy.asarray', 'np.asarray', ({(1152, 27, 1152, 36): 'eventlist'}, {}), '(eventlist)', True, 'import numpy as np\n'), ((1245, 29, 1245, 84), 'numpy.searchsorted', 'np.searchsorted', (), '', True, 'import numpy as np\n'), ((1274, 20, 1274, 61), 'numpy.unique', 'np.unique', (), '', True, 'import numpy as np\n'), ((1282, 4, 1282, 92), 'logging.warnings', 'logging.warnings', ({(1282, 21, 1282, 91): '"""\'signal_envelope1D\' is deprecated; use \'signal_envelope_1d\' instead!"""'}, {}), '(\n "\'signal_envelope1D\' is deprecated; use \'signal_envelope_1d\' instead!")', False, 'import logging\n'), ((1675, 10, 1675, 28), 'copy.deepcopy', 'copy.deepcopy', ({(1675, 24, 1675, 27): 'asa'}, {}), '(asa)', False, 'import copy\n'), ((77, 18, 77, 72), 'numpy.searchsorted', 'np.searchsorted', ({(77, 34, 77, 52): 'asa._abscissa_vals', (77, 54, 77, 71): '(a_start, a_stop)'}, {}), '(asa._abscissa_vals, (a_start, a_stop))', True, 'import numpy as np\n'), ((90, 20, 90, 47), 'numpy.floor', 'np.floor', ({(90, 29, 90, 46): '(stop - start) / step'}, {}), '((stop - start) / step)', True, 'import numpy as np\n'), ((149, 17, 149, 47), 'numpy.transpose', 'np.transpose', ({(149, 30, 149, 37): 'ratemap', (149, 39, 149, 46): '(2, 1, 0)'}, {}), '(ratemap, (2, 1, 0))', True, 'import numpy as np\n'), ((268, 17, 268, 47), 'numpy.floor', 'np.floor', ({(268, 26, 268, 46): 'interval.length / ds'}, {}), '(interval.length / ds)', True, 'import numpy as np\n'), ((274, 18, 274, 45), 'numpy.max', 'np.max', ({(274, 25, 274, 44): '(1, n_bins - w + 1)'}, {}), '((1, n_bins - w + 1))', True, 'import numpy as np\n'), ((313, 18, 313, 60), 'numpy.vstack', 'np.vstack', ({(313, 28, 313, 59): '[support_starts, support_stops]'}, {}), '([support_starts, support_stops])', True, 'import numpy as np\n'), ((601, 8, 601, 49), 'logging.warning', 'logging.warning', ({(601, 24, 601, 48): '"""no mua events detected"""'}, {}), "('no mua events detected')", False, 'import logging\n'), ((831, 8, 831, 81), 'logging.warning', 'logging.warning', ({(831, 24, 831, 80): '"""\'in_memory\' has been deprecated; use \'in_core\' instead"""'}, {}), '("\'in_memory\' has been deprecated; use \'in_core\' instead")', False, 'import logging\n'), ((834, 8, 834, 82), 'logging.warning', 'logging.warning', ({(834, 24, 834, 81): '"""\'sort\' has been deprecated; use \'assume_sorted\' instead"""'}, {}), '("\'sort\' has been deprecated; use \'assume_sorted\' instead")', False, 'import logging\n'), ((837, 8, 837, 71), 'logging.warning', 'logging.warning', ({(837, 24, 837, 70): '"""\'fs\' has been deprecated; use \'step\' instead"""'}, {}), '("\'fs\' has been deprecated; use \'step\' instead")', False, 'import logging\n'), ((842, 15, 842, 31), 'numpy.asarray', 'np.asarray', ({(842, 26, 842, 30): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((859, 17, 859, 42), 'numpy.insert', 'np.insert', ({(859, 27, 859, 35): 'breaks + 1', (859, 37, 859, 38): '0', (859, 40, 859, 41): '0'}, {}), '(breaks + 1, 0, 0)', True, 'import numpy as np\n'), ((1001, 18, 1001, 32), 'math.floor', 'floor', ({(1001, 24, 1001, 31): 'seconds'}, {}), '(seconds)', False, 'from math import floor\n'), ((1005, 15, 1005, 55), 'collections.namedtuple', 'namedtuple', ({(1005, 26, 1005, 32): '"""Time"""', (1005, 34, 1005, 54): '"""pos dd hh mm ss ms"""'}, {}), "('Time', 'pos dd hh mm ss ms')", False, 'from collections import namedtuple\n'), ((1012, 11, 1012, 28), 'numpy.isinf', 'np.isinf', ({(1012, 20, 1012, 27): 'seconds'}, {}), '(seconds)', True, 'import numpy as np\n'), ((1135, 26, 1135, 56), 'numpy.where', 'np.where', ({(1135, 35, 1135, 49): 'x <= threshold', (1135, 51, 1135, 52): '1', (1135, 54, 1135, 55): '0'}, {}), '(x <= threshold, 1, 0)', True, 'import numpy as np\n'), ((1210, 29, 1210, 39), 'numpy.mean', 'np.mean', ({(1210, 37, 1210, 38): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((1224, 8, 1224, 55), 'logging.warning', 'logging.warning', ({(1224, 24, 1224, 54): '"""no events satisfied criteria"""'}, {}), "('no events satisfied criteria')", False, 'import logging\n'), ((1270, 8, 1270, 55), 'logging.warning', 'logging.warning', ({(1270, 24, 1270, 54): '"""no events satisfied criteria"""'}, {}), "('no events satisfied criteria')", False, 'import logging\n'), ((1323, 21, 1323, 35), 'numpy.array', 'np.array', ({(1323, 30, 1323, 34): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((1392, 15, 1392, 40), 'numpy.asarray', 'np.asarray', (), '', True, 'import numpy as np\n'), ((1415, 15, 1415, 61), 'numpy.logspace', 'np.logspace', (), '', True, 'import numpy as np\n'), ((1473, 14, 1473, 32), 'copy.deepcopy', 'copy.deepcopy', ({(1473, 28, 1473, 31): 'obj'}, {}), '(obj)', False, 'import copy\n'), ((1598, 28, 1598, 50), 'numpy.cumsum', 'np.cumsum', ({(1598, 38, 1598, 49): 'asa.lengths'}, {}), '(asa.lengths)', True, 'import numpy as np\n'), ((1626, 20, 1626, 37), 'numpy.abs', 'np.abs', ({(1626, 27, 1626, 36): 'out._data'}, {}), '(out._data)', True, 'import numpy as np\n'), ((1676, 28, 1676, 50), 'numpy.cumsum', 'np.cumsum', ({(1676, 38, 1676, 49): 'asa.lengths'}, {}), '(asa.lengths)', True, 'import numpy as np\n'), ((1705, 20, 1705, 37), 'numpy.abs', 'np.abs', ({(1705, 27, 1705, 36): 'out._data'}, {}), '(out._data)', True, 'import numpy as np\n'), ((1747, 13, 1747, 23), 'numpy.mean', 'np.mean', ({(1747, 21, 1747, 22): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((444, 15, 444, 46), 'numpy.all', 'np.all', ({(444, 22, 444, 45): '(chunk[:-1] <= chunk[1:])'}, {}), '(chunk[:-1] <= chunk[1:])', True, 'import numpy as np\n'), ((757, 23, 757, 84), 'numpy.array', 'np.array', ({(757, 32, 757, 83): '[snippet.n_active for snippet in data_[PBE_epochs]]'}, {}), '([snippet.n_active for snippet in data_[PBE_epochs]])', True, 'import numpy as np\n'), ((856, 12, 856, 95), 'logging.warning', 'logging.warning', ({(856, 28, 856, 94): '"""some steps in the data are smaller than the requested step size."""'}, {}), "(\n 'some steps in the data are smaller than the requested step size.')", False, 'import logging\n'), ((861, 17, 861, 62), 'numpy.vstack', 'np.vstack', ({(861, 27, 861, 61): '(data[starts], data[stops] + step)'}, {}), '((data[starts], data[stops] + step))', True, 'import numpy as np\n'), ((1137, 26, 1137, 56), 'numpy.where', 'np.where', ({(1137, 35, 1137, 49): 'x >= threshold', (1137, 51, 1137, 52): '1', (1137, 54, 1137, 55): '0'}, {}), '(x >= threshold, 1, 0)', True, 'import numpy as np\n'), ((1143, 54, 1143, 67), 'operator.itemgetter', 'itemgetter', ({(1143, 65, 1143, 66): '(1)'}, {}), '(1)', False, 'from operator import itemgetter\n'), ((1207, 27, 1207, 37), 'numpy.mean', 'np.mean', ({(1207, 35, 1207, 36): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((1324, 17, 1324, 31), 'numpy.array', 'np.array', ({(1324, 26, 1324, 30): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((1336, 31, 1336, 59), 'scipy.signal.hilbert', 'hilbert', (), '', False, 'from scipy.signal import hilbert\n'), ((1519, 16, 1519, 32), 'numpy.ones', 'np.ones', ({(1519, 24, 1519, 31): 'V.shape'}, {}), '(V.shape)', True, 'import numpy as np\n'), ((1521, 23, 1521, 77), 'numpy.searchsorted', 'np.searchsorted', ({(1521, 39, 1521, 56): 'all_abscissa_vals', (1521, 58, 1521, 76): 'out._abscissa_vals'}, {}), '(all_abscissa_vals, out._abscissa_vals)', True, 'import numpy as np\n'), ((1522, 26, 1522, 83), 'numpy.searchsorted', 'np.searchsorted', ({(1522, 42, 1522, 59): 'all_abscissa_vals', (1522, 61, 1522, 82): 'missing_abscissa_vals'}, {}), '(all_abscissa_vals, missing_abscissa_vals)', True, 'import numpy as np\n'), ((1535, 32, 1535, 54), 'numpy.cumsum', 'np.cumsum', ({(1535, 42, 1535, 53): 'out.lengths'}, {}), '(out.lengths)', True, 'import numpy as np\n'), ((1623, 34, 1623, 67), 'numpy.linalg.norm', 'np.linalg.norm', (), '', True, 'import numpy as np\n'), ((1744, 13, 1744, 23), 'numpy.mean', 'np.mean', ({(1744, 21, 1744, 22): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((1821, 23, 1821, 64), 'numpy.append', 'np.append', ({(1821, 33, 1821, 47): 'st1.time[unit]', (1821, 49, 1821, 63): 'st2.time[unit]'}, {}), '(st1.time[unit], st2.time[unit])', True, 'import numpy as np\n'), ((1856, 12, 1856, 29), 'numpy.abs', 'np.abs', ({(1856, 19, 1856, 28): '(array - val)'}, {}), '(array - val)', True, 'import numpy as np\n'), ((1929, 29, 1929, 51), 'numpy.cumsum', 'np.cumsum', ({(1929, 39, 1929, 50): 'obj.lengths'}, {}), '(obj.lengths)', True, 'import numpy as np\n'), ((216, 30, 216, 53), 'numpy.sum', 'np.sum', (), '', True, 'import numpy as np\n'), ((221, 23, 221, 48), 'numpy.sum', 'np.sum', (), '', True, 'import numpy as np\n'), ((434, 22, 434, 33), 'numpy.array', 'np.array', ({(434, 31, 434, 32): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((747, 27, 747, 55), 'copy.deepcopy', 'copy.deepcopy', ({(747, 41, 747, 54): 'data.unit_ids'}, {}), '(data.unit_ids)', False, 'import copy\n'), ((846, 23, 846, 36), 'numpy.sort', 'np.sort', ({(846, 31, 846, 35): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((849, 29, 849, 42), 'numpy.diff', 'np.diff', ({(849, 37, 849, 41): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((855, 18, 855, 31), 'numpy.diff', 'np.diff', ({(855, 26, 855, 30): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((858, 29, 858, 42), 'numpy.diff', 'np.diff', ({(858, 37, 858, 41): 'data'}, {}), '(data)', True, 'import numpy as np\n'), ((884, 20, 884, 33), 'operator.itemgetter', 'itemgetter', ({(884, 31, 884, 32): '1'}, {}), '(1)', False, 'from operator import itemgetter\n'), ((894, 20, 894, 33), 'operator.itemgetter', 'itemgetter', ({(894, 31, 894, 32): '1'}, {}), '(1)', False, 'from operator import itemgetter\n'), ((938, 34, 938, 58), 'numpy.argwhere', 'np.argwhere', ({(938, 46, 938, 57): 'direction > 0'}, {}), '(direction > 0)', True, 'import numpy as np\n'), ((942, 34, 942, 58), 'numpy.argwhere', 'np.argwhere', ({(942, 46, 942, 57): 'direction < 0'}, {}), '(direction < 0)', True, 'import numpy as np\n'), ((1207, 42, 1207, 51), 'numpy.std', 'np.std', ({(1207, 49, 1207, 50): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((1334, 45, 1334, 74), 'numpy.zeros', 'np.zeros', ({(1334, 54, 1334, 73): '(n_signals, padlen)'}, {}), '((n_signals, padlen))', True, 'import numpy as np\n'), ((1353, 32, 1353, 55), 'numpy.cumsum', 'np.cumsum', ({(1353, 42, 1353, 54): 'data.lengths'}, {}), '(data.lengths)', True, 'import numpy as np\n'), ((1377, 66, 1377, 89), 'numpy.atleast_2d', 'np.atleast_2d', ({(1377, 80, 1377, 88): 'envelope'}, {}), '(envelope)', True, 'import numpy as np\n'), ((1390, 20, 1390, 27), 'numpy.log', 'log', ({(1390, 25, 1390, 26): 'n'}, {}), '(n)', False, 'from numpy import log, ceil\n'), ((1390, 30, 1390, 40), 'numpy.log', 'log', ({(1390, 35, 1390, 39): 'base'}, {}), '(base)', False, 'from numpy import log, ceil\n'), ((1414, 21, 1414, 28), 'numpy.log', 'log', ({(1414, 26, 1414, 27): 'x'}, {}), '(x)', False, 'from numpy import log, ceil\n'), ((1414, 31, 1414, 41), 'numpy.log', 'log', ({(1414, 36, 1414, 40): 'base'}, {}), '(base)', False, 'from numpy import log, ceil\n'), ((1520, 40, 1520, 92), 'numpy.append', 'np.append', ({(1520, 50, 1520, 68): 'out._abscissa_vals', (1520, 70, 1520, 91): 'missing_abscissa_vals'}, {}), '(out._abscissa_vals, missing_abscissa_vals)', True, 'import numpy as np\n'), ((1612, 69, 1612, 140), 'numpy.gradient', 'np.gradient', (), '', True, 'import numpy as np\n'), ((1618, 67, 1618, 136), 'numpy.gradient', 'np.gradient', (), '', True, 'import numpy as np\n'), ((1692, 69, 1692, 140), 'numpy.gradient', 'np.gradient', (), '', True, 'import numpy as np\n'), ((1744, 28, 1744, 37), 'numpy.std', 'np.std', ({(1744, 35, 1744, 36): 'x'}, {}), '(x)', True, 'import numpy as np\n'), ((1923, 27, 1923, 53), 'numpy.cumsum', 'np.cumsum', ({(1923, 37, 1923, 52): '(durations + gap)'}, {}), '(durations + gap)', True, 'import numpy as np\n'), ((1925, 49, 1925, 75), 'numpy.vstack', 'np.vstack', ({(1925, 59, 1925, 74): '(starts, stops)'}, {}), '((starts, stops))', True, 'import numpy as np\n'), ((311, 36, 311, 56), 'numpy.cumsum', 'np.cumsum', ({(311, 46, 311, 55): '(lengths + 1)'}, {}), '(lengths + 1)', True, 'import numpy as np\n'), ((758, 32, 758, 66), 'numpy.argwhere', 'np.argwhere', ({(758, 44, 758, 65): 'n_active > min_active'}, {}), '(n_active > min_active)', True, 'import numpy as np\n'), ((864, 26, 864, 52), 'numpy.vstack', 'np.vstack', ({(864, 36, 864, 51): '(starts, stops)'}, {}), '((starts, stops))', True, 'import numpy as np\n'), ((866, 26, 866, 56), 'numpy.vstack', 'np.vstack', ({(866, 36, 866, 55): '(starts, stops + 1)'}, {}), '((starts, stops + 1))', True, 'import numpy as np\n'), ((1366, 35, 1366, 63), 'scipy.signal.hilbert', 'hilbert', (), '', False, 'from scipy.signal import hilbert\n'), ((1954, 34, 1954, 57), 'numpy.asanyarray', 'np.asanyarray', ({(1954, 48, 1954, 56): 'unittime'}, {}), '(unittime)', True, 'import numpy as np\n'), ((312, 35, 312, 55), 'numpy.cumsum', 'np.cumsum', ({(312, 45, 312, 54): '(lengths + 1)'}, {}), '(lengths + 1)', True, 'import numpy as np\n'), ((1364, 51, 1364, 80), 'numpy.zeros', 'np.zeros', ({(1364, 60, 1364, 79): '(n_signals, padlen)'}, {}), '((n_signals, padlen))', True, 'import numpy as np\n'), ((1698, 84, 1698, 153), 'numpy.gradient', 'np.gradient', (), '', True, 'import numpy as np\n'), ((150, 45, 150, 60), 'numpy.log2', 'np.log2', ({(150, 53, 150, 59): 'Ri / R'}, {}), '(Ri / R)', True, 'import numpy as np\n'), ((155, 38, 155, 53), 'numpy.log2', 'np.log2', ({(155, 46, 155, 52): 'Ri / R'}, {}), '(Ri / R)', True, 'import numpy as np\n'), ((1897, 52, 1897, 69), 'numpy.max', 'np.max', ({(1897, 59, 1897, 68): 'neuron_tc'}, {}), '(neuron_tc)', True, 'import numpy as np\n')]
logan-siyao-peng/Paddle
python/paddle/fluid/contrib/slim/quantization/imperative/qat.py
10a8f3e5c3151c1abb810fba2994cc30e1232bec
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import logging import numpy as np import sys import os import paddle from paddle.fluid import dygraph, core, framework from paddle.fluid.executor import Executor from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX from paddle.nn import Linear, Conv2D, Conv2DTranspose, MaxPool2D, MaxPool1D, BatchNorm1D, BatchNorm2D, BatchNorm3D from paddle.fluid.dygraph.nn import BatchNorm, Pool2D from paddle.fluid.io import load_inference_model, save_inference_model from paddle.nn.layer.activation import ReLU, LeakyReLU, Sigmoid, ReLU6, Tanh, Softmax, PReLU, Swish from paddle.fluid.log_helper import get_logger from . import quant_nn from .. import quantization_pass __all__ = ['ImperativeQuantAware', 'ImperativeCalcOutScale'] _logger = get_logger( __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s') _op_real_in_out_name = { "conv2d": [["Input", "Filter"], ["Output"]], "conv2d_transpose": [["Input", "Filter"], ["Output"]], "pool2d": [["X"], ["Out"]], "elementwise_add": [["X", "Y"], ["Out"]], "softmax": [["X"], ["Out"]], "relu": [["X"], ["Out"]], "relu6": [["X"], ["Out"]], "leaky_relu": [["X"], ["Out"]], "prelu": [["X"], ["Out"]], "tanh": [["X"], ["Out"]], "batch_norm": [["X"], ["Y"]], "sigmoid": [["X"], ["Out"]], "swish": [["X"], ["Out"]], } class ImperativeQuantAware(object): """ Add the fake quant logic for given quantizable layers, namely add the quant_dequant computational logic both for activation inputs and weight inputs. """ def __init__(self, weight_bits=8, activation_bits=8, weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max', moving_rate=0.9, quantizable_layer_type=['Conv2D', 'Linear'], weight_preprocess_layer=None, act_preprocess_layer=None, weight_quantize_layer=None, act_quantize_layer=None): r""" The constructor for ImperativeQuantAware. Args: weight_bits(int): quantization bit number for weights, whereas the bias is not quantized. activation_bits(int): quantization bit number for activations. weight_quantize_type(str): quantization type for weights, which supports 'abs_max' now. The 'moving_average_abs_max' usually is not used for weights, since weights are fixed once the model is well trained. activation_quantize_type(str): quantization type for activations, which supports 'abs_max' and 'moving_average_abs_max' now. If using 'abs_max' mode, the quantization scale will be calculated dynamically each step in both training and testing period. If using 'moving_average_abs_max', the static quantization scale will be calculated during training and used in inference. moving_rate(float): the parameter for 'moving_average_abs_max' quantization. quantizable_layer_type(list[str]): List the type of layers that will be quantized. Default is ['Conv2D', 'Linear']. The quantizable_op_type in QuantizationFreezePass and ConvertToInt8Pass must be the same as this. weight_preprocess_layer(paddle.nn.Layer, optional): A paddle Layer that defines how to preprocess weight before quantization. Using this can quickly test if user's preprocess method works or not. The input is non-quantized weight and function returns processed weight to be quantized. If None, the weight will be quantized directly. Default is None. act_preprocess_layer(paddle.nn.Layer, optional): A paddle Layer that defines how to preprocess activation before quantization. Using this can quickly test if user's preprocess method works or not. The input is non-quantized activation and function returns processed activation to be quantized. If None, the activation will be quantized directly. Default is None. weight_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that defines how to quantize weight. Using this can quickly test if user's quantization method works or not. In this layer, user should both define quantization method and dequantization method, that is, the function's input is non-quantized weight and returns dequantized weight. If None, will use quantization op defined by 'weight_quantize_type'. Default is None. act_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that defines how to quantize activation. Using this can quickly test if user's quantization method works or not. In this layer, user should both define quantization method and dequantization method, that is, the function's input is non-quantized activation and returns dequantized activation. If None, will use quantization op defined by 'activation_quantize_type'. Default is None. Note: If user sets attribute 'skip_quant' to a Layer that support dynamic quantization and sets it to true, the layer would not be quantized during training. If this attribute is not sets or the attribute is false, the Layer would be qunatized in training. Examples 1: .. code-block:: python import paddle from paddle.fluid.contrib.slim.quantization \ import ImperativeQuantAware from paddle.vision.models \ import resnet model = resnet.resnet50(pretrained=True) imperative_qat = ImperativeQuantAware( weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max') # Add the fake quant logical. # The original model will be rewrite. # The outscale of outputs in supportted layers would be calculated. imperative_qat.quantize(model) # Fine-tune the quantized model # ... # Save quant model for the inference. imperative_qat.save_quantized_model( layer=model, model_path="./resnet50_qat", input_spec=[ paddle.static.InputSpec( shape=[None, 3, 224, 224], dtype='float32')]) Examples 2: .. code-block:: python import paddle from paddle.fluid.contrib.slim.quantization \ import ImperativeQuantAware class ImperativeModel(paddle.nn.Layer): def __init__(self): super(ImperativeModel, self).__init__() # self.linear_0 would skip the quantization. self.linear_0 = paddle.nn.Linear(784, 400) self.linear_0.skip_quant = True # self.linear_1 would not skip the quantization. self.linear_1 = paddle.nn.Linear(400, 10) self.linear_1.skip_quant = False def forward(self, inputs): x = self.linear_0(inputs) x = self.linear_1(inputs) return x model = ImperativeModel() imperative_qat = ImperativeQuantAware( weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max') # Add the fake quant logical. # The original model will be rewrite. # # There is only one Layer(self.linear1) would be added the # fake quant logical. imperative_qat.quantize(model) # Fine-tune the quantized model # ... # Save quant model for the inference. imperative_qat.save_quantized_model( layer=model, model_path="./imperative_model_qat") """ super(ImperativeQuantAware, self).__init__() self._weight_bits = weight_bits self._activation_bits = activation_bits self._moving_rate = moving_rate self._activation_quantize_type = activation_quantize_type self._weight_quantize_type = weight_quantize_type self._weight_pre_layer = weight_preprocess_layer self._act_pre_layer = act_preprocess_layer self._weight_quant_layer = weight_quantize_layer self._act_quant_layer = act_quantize_layer self._out_scale = ImperativeCalcOutScale() t_check = lambda method: method is None or issubclass(method, dygraph.layers.Layer) assert t_check( self._weight_pre_layer), "weight_preprocess should be nn.Layer" assert t_check(self._act_pre_layer), "act_preprocess should be nn.Layer" assert t_check( self._weight_quant_layer), "weight_quantize should be nn.Layer" assert t_check(self._act_quant_layer), "act_quantize should be nn.Layer" quant_type = { 'abs_max', 'moving_average_abs_max', 'channel_wise_abs_max' } assert activation_quantize_type != 'channel_wise_abs_max', \ "The activation quantization type does not support 'channel_wise_abs_max'." if activation_quantize_type not in quant_type: raise ValueError( "Unknown activation_quantize_type : '%s'. It can only be " "'abs_max' or 'moving_average_abs_max' now." % (str(activation_quantize_type))) if weight_quantize_type not in quant_type: raise ValueError( "Unknown weight_quantize_type: '%s'. It can only be " "'abs_max' or 'moving_average_abs_max' or 'channel_wise_abs_max' now." % (str(weight_quantize_type))) self._quant_layers_map = { 'Conv2D': Conv2D, 'Linear': Linear, 'Pool2D': Pool2D, 'ReLU': ReLU, 'LeakyReLU': LeakyReLU, 'ReLU6': ReLU6, 'Softmax': Softmax, 'Tanh': Tanh, 'Swish': Swish } self._quantizable_layer_type = tuple( self._quant_layers_map[layer] if layer in self._quant_layers_map else layer for layer in quantizable_layer_type) for layer in self._quantizable_layer_type: assert not isinstance( layer, str), "{} is unspported to be quantized.".format(layer) def quantize(self, model): """ According to weights' and activations' quantization types, the model will be added some fake quant ops, such as fake_quantize_dequantize_moving_average_abs_max, fake_quantize_dequantize_abs_max and so on. At the same time, the out_scale value of outputs would be calculated. Args: model(fluid.dygraph.Layer): the model to be quantized. Returns: None """ for name, layer in model.named_sublayers(): if not isinstance(layer, self._quantizable_layer_type): continue if hasattr(layer, "skip_quant") and layer.skip_quant == True: continue scopes = name.split('.') target = scopes[-1] obj = model parent = model for i in range(len(scopes) - 1): obj = getattr(parent, scopes[i]) parent = obj quant_layer = self._get_quantized_counterpart(layer) setattr(quant_layer, "layer_name", layer.full_name()) setattr(obj, target, quant_layer) self._out_scale.calc_out_scale(model) def _get_quantized_counterpart(self, layer): quant_layers = tuple(self._quant_layers_map.values()) quantized_counterpart = tuple('Quantized' + k for k in self._quant_layers_map.keys()) predicate = lambda value: isinstance(layer, value) index_generator = (i for i, v in enumerate(quant_layers) if predicate(v)) try: index = next(index_generator) except StopIteration: _logger.fatal("The layer {} is unsupported to be quantized.".format( layer.full_name())) sys.exit(-1) layer_with_weight = ['QuantizedConv2D', 'QuantizedLinear'] if quantized_counterpart[index] not in layer_with_weight: quant_layer_class_name = 'QuantizedNoweightLayer' else: quant_layer_class_name = quantized_counterpart[index] quantized_layer = quant_nn.__dict__[quant_layer_class_name]( layer, self._weight_bits, self._activation_bits, self._moving_rate, self._weight_quantize_type, self._activation_quantize_type, self._weight_pre_layer, self._act_pre_layer, self._weight_quant_layer, self._act_quant_layer) return quantized_layer def save_quantized_model(self, layer, path, input_spec=None, **config): self._out_scale.save_quantized_model(layer, path, input_spec, **config) class ImperativeCalcOutScale(object): def __init__(self, moving_rate=0.9): """ Add the logic of calculating and setting output quantization scales of some layers. These output quantization scales may be used by tensorRT or some other inference engines. Args: moving_rate(float): The decay coefficient of moving average. The default value is 0.9. """ super(ImperativeCalcOutScale, self).__init__() self._moving_rate = moving_rate self._out_scale_layer_type_list = ( BatchNorm, BatchNorm1D, BatchNorm2D, BatchNorm3D, Conv2D, Conv2DTranspose, LeakyReLU, Linear, PReLU, Pool2D, MaxPool1D, MaxPool2D, ReLU, ReLU6, Sigmoid, Softmax, Tanh, Swish) self._register_hook_handle_list = [] self._out_scale_dict = collections.OrderedDict() def calc_out_scale(self, model): """ Insert the `moving_average_abs_max_scale` op to calculate output scale of Specific layers in model. Args: model(fluid.dygraph.Layer): The target model which would be calculate the output quantization scale. Returns: None """ assert isinstance( model, dygraph.Layer), "model must be the instance of dygraph.Layer" for _, layer in model.named_sublayers(): if not isinstance(layer, self._out_scale_layer_type_list): if 'quantized_' not in layer.full_name(): continue forward_post_hook_handle = layer.register_forward_post_hook( self._forward_post_hook) self._register_hook_handle_list.append(forward_post_hook_handle) def save_quantized_model(self, layer, path, input_spec=None, **config): """ Save the quantized model for the inference. Args: layer (Layer): The Layer to be saved. path (str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``. input_spec (list[InputSpec|Tensor], optional): Describes the input of the saved model's forward method, which can be described by InputSpec or example Tensor. If None, all input variables of the original Layer's forward method would be the inputs of the saved model. Default None. **configs (dict, optional): Other save configuration options for compatibility. We do not recommend using these configurations, they may be removed in the future. If not necessary, DO NOT use them. Default None. The following options are currently supported: (1) output_spec (list[Tensor]): Selects the output targets of the saved model. By default, all return variables of original Layer's forward method are kept as the output of the saved model. If the provided ``output_spec`` list is not all output variables, the saved model will be pruned according to the given ``output_spec`` list. Returns: None """ assert isinstance( layer, dygraph.Layer), "model must be the instance of dygraph.Layer" is_dynamic_mode = False with dygraph.guard(): layer.eval() for handle in self._register_hook_handle_list: handle.remove() for key in self._out_scale_dict: self._out_scale_dict[key] = float(self._out_scale_dict[key] .numpy()) if paddle.in_dynamic_mode(): is_dynamic_mode = True paddle.enable_static() paddle.jit.save(layer=layer, path=path, input_spec=input_spec, **config) if core.is_compiled_with_cuda(): place = core.CUDAPlace(0) else: place = core.CPUPlace() exe = Executor(place) file_prefix = os.path.basename(path) dirname = os.path.dirname(path) model_filename = file_prefix + INFER_MODEL_SUFFIX params_filename = file_prefix + INFER_PARAMS_SUFFIX [inference_program, feed_target_names, fetch_targets] = ( load_inference_model( dirname=dirname, executor=exe, model_filename=model_filename, params_filename=params_filename)) # Traverse all ops in the program and find out the op matching # the Layer in the dynamic graph. layer_var_dict = {} ops_list = [key for key, _ in self._out_scale_dict.items()] op_count = 0 for block in inference_program.blocks: for op in block.ops: if op.type in _op_real_in_out_name: if op.type in ["batch_norm", "pool2d"]: if op.type == "pool2d" and op.attr( "pooling_type") != "max": continue op_count = self.op_match(op, ops_list, op_count) if op_count >= len(ops_list): continue op._set_attr('out_threshold', self._out_scale_dict[ops_list[op_count]]) op_count += 1 else: output_var_names = quantization_pass._get_op_output_var_names( op) for output_var_name in output_var_names: output_var_tensor = block.var(output_var_name) if output_var_tensor.dtype not in [ core.VarDesc.VarType.FP64, core.VarDesc.VarType.FP32 ]: continue # Because the Layer in dygraph may correspond to multiple ops # in static program after being saved. To ensure correctness, # the outscale collected for output of dygraph Layer can only # be set to the last op in the corresponding ops in static program. # # We can judge the execution order of the ops which corresponding # to dygraph Layer by the name of output. And use dict to save # the corresponding relationship between the dygraph Layer and the # static graph op that needs to set the outscale attribute. if '.' not in output_var_name: continue dynamic_layer_name, var_name_suffix = output_var_name.split( ".") if dynamic_layer_name in layer_var_dict: if layer_var_dict[dynamic_layer_name][ 0] < var_name_suffix: layer_var_dict[dynamic_layer_name] = [ var_name_suffix, op ] else: layer_var_dict[dynamic_layer_name] = [ var_name_suffix, op ] # Because the naming styles of static and dynamic graph are different, # in order to avoid mistakes, we unify the name here. for (layer_name, var_name_op_list) in layer_var_dict.items(): if 'prelu' in layer_name: layer_name = layer_name.replace('prelu', 'p_re_lu') if 'relu' in layer_name: layer_name = layer_name.replace('relu', 're_lu') if layer_name not in self._out_scale_dict: continue var_name_op_list[1]._set_attr('out_threshold', self._out_scale_dict[layer_name]) # Save the processed program. save_inference_model( dirname=dirname, feeded_var_names=feed_target_names, target_vars=fetch_targets, executor=exe, main_program=inference_program.clone(), model_filename=model_filename, params_filename=params_filename) if is_dynamic_mode: paddle.disable_static() def op_match(self, op, ops_list, op_count): while op_count < len(ops_list) and op.type not in ops_list[op_count]: op_count += 1 while op_count < len(ops_list) and op.type is "pool2d" and op.attr( "pooling_type") != "max": op_count += 1 return op_count def _forward_post_hook(self, layer, input, output): assert isinstance( output, (core.VarBase, framework.Variable) ), "Multiple outputs are not currently supported in ImperativeOutScale." if output.dtype not in [ core.VarDesc.VarType.FP32, core.VarDesc.VarType.FP64 ]: return if not hasattr(layer, "_out_scale"): layer._out_scale = quant_nn.MovingAverageAbsMaxScale( output.name, self._moving_rate, output.dtype) scale_out = layer._out_scale(output) if hasattr(layer, 'layer_name'): layer_name = layer.layer_name else: layer_name = layer.full_name() self._out_scale_dict[layer_name] = scale_out
[((34, 10, 35, 73), 'paddle.fluid.log_helper.get_logger', 'get_logger', (), '', False, 'from paddle.fluid.log_helper import get_logger\n'), ((329, 31, 329, 56), 'collections.OrderedDict', 'collections.OrderedDict', ({}, {}), '()', False, 'import collections\n'), ((385, 11, 385, 35), 'paddle.in_dynamic_mode', 'paddle.in_dynamic_mode', ({}, {}), '()', False, 'import paddle\n'), ((389, 8, 389, 80), 'paddle.jit.save', 'paddle.jit.save', (), '', False, 'import paddle\n'), ((391, 11, 391, 39), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ({}, {}), '()', False, 'from paddle.fluid import dygraph, core, framework\n'), ((395, 14, 395, 29), 'paddle.fluid.executor.Executor', 'Executor', ({(395, 23, 395, 28): 'place'}, {}), '(place)', False, 'from paddle.fluid.executor import Executor\n'), ((397, 22, 397, 44), 'os.path.basename', 'os.path.basename', ({(397, 39, 397, 43): 'path'}, {}), '(path)', False, 'import os\n'), ((398, 18, 398, 39), 'os.path.dirname', 'os.path.dirname', ({(398, 34, 398, 38): 'path'}, {}), '(path)', False, 'import os\n'), ((403, 12, 407, 48), 'paddle.fluid.io.load_inference_model', 'load_inference_model', (), '', False, 'from paddle.fluid.io import load_inference_model, save_inference_model\n'), ((377, 13, 377, 28), 'paddle.fluid.dygraph.guard', 'dygraph.guard', ({}, {}), '()', False, 'from paddle.fluid import dygraph, core, framework\n'), ((387, 12, 387, 34), 'paddle.enable_static', 'paddle.enable_static', ({}, {}), '()', False, 'import paddle\n'), ((392, 20, 392, 37), 'paddle.fluid.core.CUDAPlace', 'core.CUDAPlace', ({(392, 35, 392, 36): '0'}, {}), '(0)', False, 'from paddle.fluid import dygraph, core, framework\n'), ((394, 20, 394, 35), 'paddle.fluid.core.CPUPlace', 'core.CPUPlace', ({}, {}), '()', False, 'from paddle.fluid import dygraph, core, framework\n'), ((484, 12, 484, 35), 'paddle.disable_static', 'paddle.disable_static', ({}, {}), '()', False, 'import paddle\n'), ((295, 12, 295, 24), 'sys.exit', 'sys.exit', ({(295, 21, 295, 23): '(-1)'}, {}), '(-1)', False, 'import sys\n')]
elliotgunn/DS-Unit-3-Sprint-2-SQL-and-Databases
sc/northwind.py
c730e2b3e66199226fa7549511cbb7801eb7a694
import pandas as pd import sqlite3 from pandas import DataFrame n_conn = sqlite3.connect('northwind_small.sqlite3') n_curs = n_conn.cursor() # What are the ten most expensive items (per unit price) in the database? query = """ SELECT ProductName, UnitPrice FROM Product ORDER BY UnitPrice DESC LIMIT 10 """ n_curs.execute(query) print(n_curs.fetchall()) # What is the average age of an employee at the time of their hiring? (Hint: a # lot of arithmetic works with dates.) query = """ SELECT AVG(HireDate-BirthDate) FROM Employee """ n_curs.execute(query) print(n_curs.fetchall()) # answer: 37.22 # (*Stretch*) How does the average age of employee at hire vary by city? query = """SELECT City, AVG(HireDate-BirthDate) FROM Employee GROUP BY City """ n_curs.execute(query) print(n_curs.fetchall()) # What are the ten most expensive items (per unit price) # in the database *and* their suppliers? query = """ SELECT ProductName, UnitPrice, CompanyName FROM Product as p JOIN Supplier as s ON p.SupplierID = s.ID ORDER BY UnitPrice DESC LIMIT 10 """ n_curs.execute(query) print(n_curs.fetchall()) # What is the largest category (by number of unique products in it)? query = """ SELECT CategoryName, COUNT(CategoryName) FROM Category as c JOIN Product as p ON c.ID=p.CategoryID GROUP BY CategoryName ORDER by COUNT(CategoryName) DESC """ n_curs.execute(query) print(n_curs.fetchall()) # largest category is Confections 13 # (*Stretch*) Who's the employee with the most territories? Use `TerritoryId` # (not name, region, or other fields) as the unique identifier for territories. # EMPLOYEE ID 7 query = """ SELECT EmployeeId, TerritoryId, COUNT(DISTINCT TerritoryId) FROM EmployeeTerritory GROUP BY EmployeeId ORDER BY COUNT(DISTINCT TerritoryId) DESC """ n_curs.execute(query) print(n_curs.fetchall())
[((5, 9, 5, 51), 'sqlite3.connect', 'sqlite3.connect', ({(5, 25, 5, 50): '"""northwind_small.sqlite3"""'}, {}), "('northwind_small.sqlite3')", False, 'import sqlite3\n')]
Pijuli/django-jazzmin
tests/test_app/library/loans/admin.py
e3f9d45183d58f78bf4c6793969490631a84681d
from django.contrib import admin from django.urls import path from .models import BookLoan, Library from .views import CustomView class BookLoanInline(admin.StackedInline): model = BookLoan extra = 1 readonly_fields = ("id", "duration") fields = ( "book", "imprint", "status", "due_back", "borrower", "loan_start", "duration", ) @admin.register(BookLoan) class BookLoanAdmin(admin.ModelAdmin): list_display = ("book", "status", "borrower", "due_back", "id") list_filter = ("status", "due_back") autocomplete_fields = ("borrower",) search_fields = ("book__title",) readonly_fields = ("id",) fieldsets = ( (None, {"fields": ("book", "imprint", "id")}), ("Availability", {"fields": ("status", "due_back", "duration", "borrower")}), ) def get_urls(self): """ Add in a custom view to demonstrate = """ urls = super().get_urls() return urls + [path("custom_view", CustomView.as_view(), name="custom_view")] def response_change(self, request, obj): ret = super().response_change(request, obj) if "reserve" in request.POST: obj.status = "r" obj.save() return ret @admin.register(Library) class LibraryAdmin(admin.ModelAdmin): list_display = ("name", "address", "librarian")
[((23, 1, 23, 25), 'django.contrib.admin.register', 'admin.register', ({(23, 16, 23, 24): 'BookLoan'}, {}), '(BookLoan)', False, 'from django.contrib import admin\n'), ((51, 1, 51, 24), 'django.contrib.admin.register', 'admin.register', ({(51, 16, 51, 23): 'Library'}, {}), '(Library)', False, 'from django.contrib import admin\n')]
jeffkimbrel/MergeMetabolicAnnotations
lib/MergeMetabolicAnnotations/utils/CompareAnnotationsUtil.py
ec971d114d57942cef73dc2980c8faf48cea7afe
import os import datetime import logging import json import uuid from installed_clients.WorkspaceClient import Workspace as Workspace from installed_clients.KBaseReportClient import KBaseReport from installed_clients.annotation_ontology_apiServiceClient import annotation_ontology_api import MergeMetabolicAnnotations.utils.functions as f class CompareAnnotationsUtil: def __init__(self, config): self.config = config self.timestamp = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") self.callback_url = config['SDK_CALLBACK_URL'] self.scratch = config['scratch'] self.kbr = KBaseReport(self.callback_url) self.anno_api = annotation_ontology_api() self.ws_client = Workspace(config["workspace-url"]) def run(self, ctx, params): get_ontology_results = self.anno_api.get_annotation_ontology_events({ "input_ref": params['genome'], "workspace-url": self.config["workspace-url"] }) ontology_selected = f.filter_selected_ontologies( get_ontology_results, params, workflow="compare") with open(os.path.join(self.scratch, "get_ontology_dump.json"), 'w') as outfile: json.dump(ontology_selected, outfile, indent=2) # make reports html_reports = [] output_directory = os.path.join(self.scratch, str(uuid.uuid4())) os.mkdir(output_directory) event_summary = f.get_event_lists(ontology_selected) html_reports = f.compare_report_stack(html_reports, event_summary, output_directory) # finalize html reports report_params = { 'message': '', 'html_links': html_reports, 'direct_html_link_index': 0, 'workspace_name': params['workspace_name'], 'report_object_name': f'compare_annotations_{uuid.uuid4()}'} report_output = self.kbr.create_extended_report(report_params) return {'report_name': report_output['name'], 'report_ref': report_output['ref']}
[((21, 19, 21, 49), 'installed_clients.KBaseReportClient.KBaseReport', 'KBaseReport', ({(21, 31, 21, 48): 'self.callback_url'}, {}), '(self.callback_url)', False, 'from installed_clients.KBaseReportClient import KBaseReport\n'), ((22, 24, 22, 49), 'installed_clients.annotation_ontology_apiServiceClient.annotation_ontology_api', 'annotation_ontology_api', ({}, {}), '()', False, 'from installed_clients.annotation_ontology_apiServiceClient import annotation_ontology_api\n'), ((23, 25, 23, 59), 'installed_clients.WorkspaceClient.Workspace', 'Workspace', ({(23, 35, 23, 58): "config['workspace-url']"}, {}), "(config['workspace-url'])", True, 'from installed_clients.WorkspaceClient import Workspace as Workspace\n'), ((31, 28, 32, 61), 'MergeMetabolicAnnotations.utils.functions.filter_selected_ontologies', 'f.filter_selected_ontologies', (), '', True, 'import MergeMetabolicAnnotations.utils.functions as f\n'), ((39, 8, 39, 34), 'os.mkdir', 'os.mkdir', ({(39, 17, 39, 33): 'output_directory'}, {}), '(output_directory)', False, 'import os\n'), ((41, 24, 41, 60), 'MergeMetabolicAnnotations.utils.functions.get_event_lists', 'f.get_event_lists', ({(41, 42, 41, 59): 'ontology_selected'}, {}), '(ontology_selected)', True, 'import MergeMetabolicAnnotations.utils.functions as f\n'), ((42, 23, 42, 92), 'MergeMetabolicAnnotations.utils.functions.compare_report_stack', 'f.compare_report_stack', ({(42, 46, 42, 58): 'html_reports', (42, 60, 42, 73): 'event_summary', (42, 75, 42, 91): 'output_directory'}, {}), '(html_reports, event_summary, output_directory)', True, 'import MergeMetabolicAnnotations.utils.functions as f\n'), ((34, 12, 34, 59), 'json.dump', 'json.dump', (), '', False, 'import json\n'), ((18, 25, 18, 48), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((33, 18, 33, 70), 'os.path.join', 'os.path.join', ({(33, 31, 33, 43): 'self.scratch', (33, 45, 33, 69): '"""get_ontology_dump.json"""'}, {}), "(self.scratch, 'get_ontology_dump.json')", False, 'import os\n'), ((38, 58, 38, 70), 'uuid.uuid4', 'uuid.uuid4', ({}, {}), '()', False, 'import uuid\n'), ((50, 57, 50, 69), 'uuid.uuid4', 'uuid.uuid4', ({}, {}), '()', False, 'import uuid\n')]
TvSeriesFans/CineMonster
models/__init__.py
036a3223618afd536932d21b0e86d18d0fba3b28
from models.Model import Player, Group, Session, engine
[]
ToJestKrzysio/TheJungleGame
src/backend/tests/test_game/test_models.py
904dd4adc937145df2c8c353eb83bec3b5dd1f7e
from unittest.mock import Mock, patch import numpy as np from game.models import ValuePolicyModel def test_predict(): mask = np.zeros((9, 7, 8), dtype=bool) mask[1, 2, 3] = 1 mask[6, 6, 6] = 1 tensor_mock = Mock() policy_tensor = np.zeros((9, 7, 8), dtype=float) policy_tensor[0, 0, 0] = 10 policy_tensor[1, 2, 3] = 100 policy_tensor[6, 6, 6] = 100 policy_tensor = policy_tensor.reshape(-1) value = np.array([[0.7]], dtype=float) get_prediction_mock = Mock(return_value=(value, policy_tensor)) network_mock = Mock(spec=ValuePolicyModel, output_shape=(9, 7, 8), input_shape=(9, 7, 178), _get_prediction=get_prediction_mock) result_value, result_policy = ValuePolicyModel.predict( self=network_mock, tensor=tensor_mock, mask=mask) get_prediction_mock.assert_called_once_with(tensor_mock) expected_value = 0.7 expected_policy = np.zeros((9, 7, 8)) expected_policy[1, 2, 3] = 0.5 expected_policy[6, 6, 6] = 0.5 assert isinstance(result_value, float) assert result_value == expected_value assert np.array_equal(result_policy, expected_policy)
[((9, 11, 9, 42), 'numpy.zeros', 'np.zeros', (), '', True, 'import numpy as np\n'), ((13, 18, 13, 24), 'unittest.mock.Mock', 'Mock', ({}, {}), '()', False, 'from unittest.mock import Mock, patch\n'), ((15, 20, 15, 52), 'numpy.zeros', 'np.zeros', (), '', True, 'import numpy as np\n'), ((21, 12, 21, 42), 'numpy.array', 'np.array', (), '', True, 'import numpy as np\n'), ((23, 26, 23, 67), 'unittest.mock.Mock', 'Mock', (), '', False, 'from unittest.mock import Mock, patch\n'), ((24, 19, 25, 85), 'unittest.mock.Mock', 'Mock', (), '', False, 'from unittest.mock import Mock, patch\n'), ((27, 34, 28, 57), 'game.models.ValuePolicyModel.predict', 'ValuePolicyModel.predict', (), '', False, 'from game.models import ValuePolicyModel\n'), ((34, 22, 34, 41), 'numpy.zeros', 'np.zeros', ({(34, 31, 34, 40): '(9, 7, 8)'}, {}), '((9, 7, 8))', True, 'import numpy as np\n'), ((41, 11, 41, 57), 'numpy.array_equal', 'np.array_equal', ({(41, 26, 41, 39): 'result_policy', (41, 41, 41, 56): 'expected_policy'}, {}), '(result_policy, expected_policy)', True, 'import numpy as np\n')]
yanwen0614/Weibo
sina_spider/items.py
5d85e39d0cf7fc848bf5a06df08acbf38661db8d
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field class TweetsItem(Item): # define the fields for your item here like: Author = Field() Title = Field() Create_time = Field() Id = Field() Context = Field() Source = Field() Url = Field() class TopicItem(Item): Url = Field() Title = Field() Category = Field() context = Field() Id = Field() Hotlevel = Field() Time = Field() def main(): item = TopicItem() pass if __name__ == '__main__': main()
[((13, 13, 13, 20), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((14, 12, 14, 19), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((15, 18, 15, 25), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((16, 9, 16, 16), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((17, 14, 17, 21), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((18, 13, 18, 20), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((19, 10, 19, 17), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((23, 10, 23, 17), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((24, 12, 24, 19), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((25, 15, 25, 22), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((26, 14, 26, 21), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((27, 9, 27, 16), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((28, 15, 28, 22), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n'), ((29, 11, 29, 18), 'scrapy.Field', 'Field', ({}, {}), '()', False, 'from scrapy import Item, Field\n')]
Andrew-Tan/e-mission-server
emission/core/wrapper/client.py
91d59bee86e63d803e401f10f4b6a2502effedda
import json import logging import dateutil.parser from datetime import datetime # Our imports from emission.core.get_database import get_profile_db, get_client_db, get_pending_signup_db import emission.clients.common class Client: def __init__(self, clientName): # TODO: write background process to ensure that there is only one client with each name # Maybe clean up unused clients? self.clientName = clientName self.settings_filename = "emission/clients/%s/settings.json" % self.clientName self.__reload() def __reload(self): self.clientJSON = None if self.clientName is not None: self.clientJSON = get_client_db().find_one({'name': self.clientName}) # clientJSON can be None if we are creating an entry for the first time if self.clientJSON is None: # Avoid Attribute error while trying to determine whether the client is active self.startDatetime = None self.endDatetime = None else: # Do eagerly or lazily? Can also do super lazily and have self.startDatetime = dateutil.parser.parse(self.clientJSON['start_date']) self.endDatetime = dateutil.parser.parse(self.clientJSON['end_date']) def isActive(self, now): logging.debug("Comparing %s to %s and %s" % (now, self.startDatetime, self.endDatetime)) if self.startDatetime is None: return False else: if self.startDatetime > now: # Study has not yet started return False else: if self.endDatetime is None: # Study has no end time return True else: if self.endDatetime > now: # study has not yet ended return True else: # study has already ended return False # Smart settings call, which returns the override settings if the client is # active, and def getSettings(self): if (self.isActive(datetime.now())): logging.debug("For client %s, returning settings %s" % (self.clientName, self.clientJSON['client_settings'])) return self.clientJSON['client_settings'] else: # Returning empty dict instead of None to make the client code, which # will want to merge this, easier logging.debug("For client %s, active = false, returning {}" % (self.clientName)) return {} def getDates(self): return (self.startDatetime, self.endDatetime) # Figure out if the JSON object here should always be passed in # Having it be passed in is a lot more flexible # Let's compromise for now by passing it in and seeing how much of a hassle it is # That will also ensure that the update_client script is not a complete NOP def __update(self, newEntry): get_client_db().update({'name': self.clientName}, newEntry, upsert = True) self.__reload() def update(self, createKey = True): import uuid newEntry = json.load(open(self.settings_filename)) if createKey: newEntry['key'] = str(uuid.uuid4()) # logging.info("Updating with new entry %s" % newEntry) self.__update(newEntry) return newEntry['key'] def __loadModule(self): import importlib clientModule = importlib.import_module("emission.clients.%s.%s" % (self.clientName, self.clientName)) return clientModule def callMethod(self, methodName, request): clientModule = self.__loadModule() logging.debug("called client with %s %s" % (self.clientName, methodName)) # import clients.carshare.carshare as clientModule method = getattr(clientModule, methodName) logging.debug("Invoking %s on module %s" % (method, clientModule)) return method(request) def getClientKey(self): if self.clientJSON is None: return None logging.debug("About to return %s from JSON %s" % (self.clientJSON['key'], self.clientJSON)) return self.clientJSON['key'] def __validateKey(self, clientKey): if (not self.isActive(datetime.now())): logging.info("Client %s is not yet active, so key %s is not valid" % (self.clientName, clientKey)) return False client_key = self.getClientKey() if client_key == clientKey: return True else: logging.info("For client %s, incoming key %s does not match stored key %s!" % (self.clientName, clientKey, client_key)) return False # What should we do if a user registers again after they have installed the app? # Options are: # - NOP # - update the study field # - Return error # For now, we update the study field, pending discussions with Maita on error reporting # What should we do if a user registers for a study after having installed # the app or having participated in a different study? # - add the study to the list of registered studies (but we don't support multiple studies!) # - update the registered study # - return an error # For now, we update the registered study since it makes life easiest for us # TODO: Figure out what to do here # Also, note that always inserting it is also fine if we move to an eventual # consistency model, since we will eventually clean it up again. The end # result will still be a NOP, though def __preRegister(self, userEmail): from emission.core.wrapper.user import User from emission.analysis.result import userclient if User.isRegistered(userEmail): User.fromEmail(userEmail).setStudy(self.clientName) else: pendingDoc = { 'user_email': userEmail, 'study': self.clientName, 'last_update': datetime.now()} # Should I do insert or upsert here? If a user has pre-registered for one # study and then pre-registers for another study before registering, do we # want to throw an error or just update silently? # Update silently for now writeResult = get_pending_signup_db().update({'user_email': userEmail}, pendingDoc, upsert=True) print 'in __preRegister, writeResult = %s' % writeResult if 'err' in writeResult and writeResult['err'] is not None: e = Exception() e.code = writeResult['err'][0]["code"] e.msg = writeResult['err'][0]["errmsg"] raise e return (get_pending_signup_db().find({'study': self.clientName}).count(), userclient.countForStudy(self.clientName)) def preRegister(self, clientKey, userEmail): if not self.__validateKey(clientKey): e = Exception() e.code = 403 e.msg = "This is not the client key for your study, or your study has already ended. Please contact [email protected] to obtain a client key, or restart your study" raise e return self.__preRegister(userEmail) def __callJavascriptCallback(self, methodName, params): if self.isActive(datetime.now()): clientModule = self.__loadModule() method = getattr(clientModule, methodName) return method(params) else: return None def callJavascriptCallback(self, clientKey, method, request): if not self.__validateKey(clientKey): e = Exception() e.code = 403 e.msg = "This is not the client key for your study, or your study has already ended. Please contact [email protected] to obtain a client key, or restart your study" raise e return self.__callJavascriptCallback(method, request) # BEGIN: Standard customization hooks def getClientConfirmedModeQuery(self, mode): if self.isActive(datetime.now()): clientModeField = self.getClientConfirmedModeField() return {clientModeField: mode} else: return {} def getClientConfirmedModeField(self): if self.isActive(datetime.now()): clientModule = self.__loadModule() return clientModule.getClientConfirmedModeField() else: return None def getSectionFilter(self, uuid): if self.isActive(datetime.now()): return self.__loadModule().getSectionFilter(uuid) else: return [] def getResult(self, uuid): if self.isActive(datetime.now()): return self.__loadModule().getResult(uuid) else: return None def clientSpecificSetters(self, uuid, sectionId, predictedModeMap): if self.isActive(datetime.now()): return self.__loadModule().clientSpecificSetters(uuid, sectionId, predictedModeMap) else: return None def runBackgroundTasks(self, uuid): if self.isActive(datetime.now()): self.__loadModule().runBackgroundTasks(uuid) else: logging.debug("Client is not active, skipping call...") # END: Standard customization hooks # This reads the combined set of queries from all clients # Read the design decisions for an example of how to improve this @staticmethod def getClientConfirmedModeQueries(mode): queryList = emission.clients.common.getConfirmFields() queryListWithMode = [{query: mode} for query in queryList] return [{'$or': queryListWithMode}] @staticmethod def getPendingClientRegs(userName): studyList = [] userEmailQuery = {'user_email': userName} pendingReg = get_pending_signup_db().find_one(userEmailQuery) if pendingReg != None: studyList = [pendingReg['study']] return studyList @staticmethod def deletePendingClientRegs(userName): userEmailQuery = {'user_email': userName} get_pending_signup_db().remove(userEmailQuery)
[]
karianjahi/advent_of_code
setup.py
16939cc7c475465c35d8750328b9b7aef60fc4d6
import setuptools setuptools.setup(name='advent_of_code')
[((2, 0, 2, 39), 'setuptools.setup', 'setuptools.setup', (), '', False, 'import setuptools\n')]
imco/nmx
src/csvutils.py
5c6303ece6148a83963b2e6524d6f94b450ad659
def escapeQuotes(string): return string.replace('"','""');
[]
amithbraj/vpp
test/sanity_import_vpp_papi.py
edf1da94dc099c6e2ab1d455ce8652fada3cdb04
#!/usr/bin/env python3 """ sanity check script """ import vpp_papi
[]
yarikoptic/nipy
examples/labs/demo_dmtx.py
749302c7ffa8ea714cc32d405f0df521102bbc6f
#!/usr/bin/env python # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from __future__ import print_function # Python 2/3 compatibility __doc__ = """ Examples of design matrices specification and and computation (event-related design, FIR design, etc) Requires matplotlib Author : Bertrand Thirion: 2009-2010 """ print(__doc__) import numpy as np try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError("This script needs the matplotlib library") from nipy.modalities.fmri.design_matrix import make_dmtx from nipy.modalities.fmri.experimental_paradigm import (EventRelatedParadigm, BlockParadigm) # frame times tr = 1.0 nscans = 128 frametimes = np.linspace(0, (nscans - 1) * tr, nscans) # experimental paradigm conditions = ['c0', 'c0', 'c0', 'c1', 'c1', 'c1', 'c3', 'c3', 'c3'] onsets = [30, 70, 100, 10, 30, 90, 30, 40, 60] hrf_model = 'canonical' motion = np.cumsum(np.random.randn(128, 6), 0) add_reg_names = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'] #event-related design matrix paradigm = EventRelatedParadigm(conditions, onsets) X1 = make_dmtx( frametimes, paradigm, drift_model='polynomial', drift_order=3, add_regs=motion, add_reg_names=add_reg_names) # block design matrix duration = 7 * np.ones(9) paradigm = BlockParadigm(con_id=conditions, onset=onsets, duration=duration) X2 = make_dmtx(frametimes, paradigm, drift_model='polynomial', drift_order=3) # FIR model paradigm = EventRelatedParadigm(conditions, onsets) hrf_model = 'FIR' X3 = make_dmtx(frametimes, paradigm, hrf_model='fir', drift_model='polynomial', drift_order=3, fir_delays=np.arange(1, 6)) # plot the results fig = plt.figure(figsize=(10, 6)) ax = plt.subplot(1, 3, 1) X1.show(ax=ax) ax.set_title('Event-related design matrix', fontsize=12) ax = plt.subplot(1, 3, 2) X2.show(ax=ax) ax.set_title('Block design matrix', fontsize=12) ax = plt.subplot(1, 3, 3) X3.show(ax=ax) ax.set_title('FIR design matrix', fontsize=12) plt.subplots_adjust(top=0.9, bottom=0.25) plt.show()
[((29, 13, 29, 54), 'numpy.linspace', 'np.linspace', ({(29, 25, 29, 26): '0', (29, 28, 29, 45): '(nscans - 1) * tr', (29, 47, 29, 53): 'nscans'}, {}), '(0, (nscans - 1) * tr, nscans)', True, 'import numpy as np\n'), ((39, 11, 39, 51), 'nipy.modalities.fmri.experimental_paradigm.EventRelatedParadigm', 'EventRelatedParadigm', ({(39, 32, 39, 42): 'conditions', (39, 44, 39, 50): 'onsets'}, {}), '(conditions, onsets)', False, 'from nipy.modalities.fmri.experimental_paradigm import EventRelatedParadigm, BlockParadigm\n'), ((41, 5, 43, 49), 'nipy.modalities.fmri.design_matrix.make_dmtx', 'make_dmtx', (), '', False, 'from nipy.modalities.fmri.design_matrix import make_dmtx\n'), ((47, 11, 48, 47), 'nipy.modalities.fmri.experimental_paradigm.BlockParadigm', 'BlockParadigm', (), '', False, 'from nipy.modalities.fmri.experimental_paradigm import EventRelatedParadigm, BlockParadigm\n'), ((50, 5, 51, 29), 'nipy.modalities.fmri.design_matrix.make_dmtx', 'make_dmtx', (), '', False, 'from nipy.modalities.fmri.design_matrix import make_dmtx\n'), ((54, 11, 54, 51), 'nipy.modalities.fmri.experimental_paradigm.EventRelatedParadigm', 'EventRelatedParadigm', ({(54, 32, 54, 42): 'conditions', (54, 44, 54, 50): 'onsets'}, {}), '(conditions, onsets)', False, 'from nipy.modalities.fmri.experimental_paradigm import EventRelatedParadigm, BlockParadigm\n'), ((61, 6, 61, 33), 'matplotlib.pyplot.figure', 'plt.figure', (), '', True, 'import matplotlib.pyplot as plt\n'), ((62, 5, 62, 25), 'matplotlib.pyplot.subplot', 'plt.subplot', ({(62, 17, 62, 18): '1', (62, 20, 62, 21): '3', (62, 23, 62, 24): '1'}, {}), '(1, 3, 1)', True, 'import matplotlib.pyplot as plt\n'), ((65, 5, 65, 25), 'matplotlib.pyplot.subplot', 'plt.subplot', ({(65, 17, 65, 18): '1', (65, 20, 65, 21): '3', (65, 23, 65, 24): '2'}, {}), '(1, 3, 2)', True, 'import matplotlib.pyplot as plt\n'), ((68, 5, 68, 25), 'matplotlib.pyplot.subplot', 'plt.subplot', ({(68, 17, 68, 18): '1', (68, 20, 68, 21): '3', (68, 23, 68, 24): '3'}, {}), '(1, 3, 3)', True, 'import matplotlib.pyplot as plt\n'), ((71, 0, 71, 41), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', (), '', True, 'import matplotlib.pyplot as plt\n'), ((72, 0, 72, 10), 'matplotlib.pyplot.show', 'plt.show', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((35, 19, 35, 42), 'numpy.random.randn', 'np.random.randn', ({(35, 35, 35, 38): '128', (35, 40, 35, 41): '6'}, {}), '(128, 6)', True, 'import numpy as np\n'), ((46, 15, 46, 25), 'numpy.ones', 'np.ones', ({(46, 23, 46, 24): '(9)'}, {}), '(9)', True, 'import numpy as np\n'), ((58, 26, 58, 41), 'numpy.arange', 'np.arange', ({(58, 36, 58, 37): '1', (58, 39, 58, 40): '6'}, {}), '(1, 6)', True, 'import numpy as np\n')]
yelixu2/fbpcs
fbpcs/private_computation/test/service/test_private_computation.py
31b1154bf1a207471fa207a0b0e4c74693f09608
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest from collections import defaultdict from typing import List, Optional, Tuple from unittest.mock import MagicMock, call, patch from fbpcp.entity.container_instance import ContainerInstance, ContainerInstanceStatus from fbpcp.service.mpc import MPCInstanceStatus, MPCParty, MPCService from fbpcp.service.onedocker import OneDockerService from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance from fbpcs.data_processing.lift_id_combiner.lift_id_spine_combiner_cpp import ( CppLiftIdSpineCombinerService, ) from fbpcs.data_processing.sharding.sharding_cpp import CppShardingService from fbpcs.onedocker_binary_config import OneDockerBinaryConfig from fbpcs.onedocker_binary_names import OneDockerBinaryNames from fbpcs.onedocker_service_config import OneDockerServiceConfig from fbpcs.pcf.tests.async_utils import to_sync from fbpcs.pid.entity.pid_instance import ( PIDInstance, PIDInstanceStatus, PIDProtocol, PIDRole, ) from fbpcs.pid.service.pid_service.pid import PIDService from fbpcs.private_computation.entity.private_computation_instance import ( PrivateComputationGameType, PrivateComputationInstance, PrivateComputationInstanceStatus, PrivateComputationRole, UnionedPCInstance, ) from fbpcs.private_computation.entity.private_computation_stage_type import ( PrivateComputationStageType, ) from fbpcs.private_computation.repository.private_computation_game import GameNames from fbpcs.private_computation.service.errors import ( PrivateComputationServiceValidationError, ) from fbpcs.private_computation.service.private_computation import ( PrivateComputationService, NUM_NEW_SHARDS_PER_FILE, DEFAULT_K_ANONYMITY_THRESHOLD, ) from fbpcs.private_computation.service.private_computation_stage_service import ( PrivateComputationStageService, ) # TODO T94666166: libfb won't work in OSS from libfb.py.asyncio.mock import AsyncMock from libfb.py.testutil import data_provider from fbpcs.private_computation.service.utils import ( create_and_start_mpc_instance, gen_mpc_game_args_to_retry, map_private_computation_role_to_mpc_party, DEFAULT_CONTAINER_TIMEOUT_IN_SEC, ) def _get_valid_stages_data() -> List[Tuple[PrivateComputationStageType]]: return [ (PrivateComputationStageType.ID_MATCH,), (PrivateComputationStageType.COMPUTE,), (PrivateComputationStageType.AGGREGATE,), (PrivateComputationStageType.POST_PROCESSING_HANDLERS,), ] class TestPrivateComputationService(unittest.TestCase): def setUp(self): container_svc_patcher = patch("fbpcp.service.container_aws.AWSContainerService") storage_svc_patcher = patch("fbpcp.service.storage_s3.S3StorageService") mpc_instance_repo_patcher = patch( "fbpcs.common.repository.mpc_instance_local.LocalMPCInstanceRepository" ) pid_instance_repo_patcher = patch( "fbpcs.pid.repository.pid_instance_local.LocalPIDInstanceRepository" ) private_computation_instance_repo_patcher = patch( "fbpcs.private_computation.repository.private_computation_instance_local.LocalPrivateComputationInstanceRepository" ) mpc_game_svc_patcher = patch("fbpcp.service.mpc_game.MPCGameService") container_svc = container_svc_patcher.start() storage_svc = storage_svc_patcher.start() mpc_instance_repository = mpc_instance_repo_patcher.start() pid_instance_repository = pid_instance_repo_patcher.start() private_computation_instance_repository = ( private_computation_instance_repo_patcher.start() ) mpc_game_svc = mpc_game_svc_patcher.start() for patcher in ( container_svc_patcher, storage_svc_patcher, mpc_instance_repo_patcher, pid_instance_repo_patcher, private_computation_instance_repo_patcher, mpc_game_svc_patcher, ): self.addCleanup(patcher.stop) self.onedocker_service_config = OneDockerServiceConfig( task_definition="test_task_definition", ) self.onedocker_binary_config_map = defaultdict( lambda: OneDockerBinaryConfig( tmp_directory="/test_tmp_directory/", binary_version="latest" ) ) self.onedocker_service = OneDockerService( container_svc, self.onedocker_service_config.task_definition ) self.mpc_service = MPCService( container_svc=container_svc, instance_repository=mpc_instance_repository, task_definition="test_task_definition", mpc_game_svc=mpc_game_svc, ) self.pid_service = PIDService( instance_repository=pid_instance_repository, storage_svc=storage_svc, onedocker_svc=self.onedocker_service, onedocker_binary_config_map=self.onedocker_binary_config_map, ) self.private_computation_service = PrivateComputationService( instance_repository=private_computation_instance_repository, mpc_svc=self.mpc_service, pid_svc=self.pid_service, onedocker_svc=self.onedocker_service, onedocker_binary_config_map=self.onedocker_binary_config_map, ) self.test_private_computation_id = "test_private_computation_id" self.test_num_containers = 2 self.test_input_path = "in_path" self.test_output_dir = "out_dir" self.test_game_type = PrivateComputationGameType.LIFT self.test_concurrency = 1 def test_create_instance(self): test_role = PrivateComputationRole.PUBLISHER self.private_computation_service.create_instance( instance_id=self.test_private_computation_id, role=test_role, game_type=self.test_game_type, input_path=self.test_input_path, output_dir=self.test_output_dir, num_pid_containers=self.test_num_containers, num_mpc_containers=self.test_num_containers, concurrency=self.test_concurrency, num_files_per_mpc_container=NUM_NEW_SHARDS_PER_FILE, ) # check instance_repository.create is called with the correct arguments self.private_computation_service.instance_repository.create.assert_called() args = self.private_computation_service.instance_repository.create.call_args[0][ 0 ] self.assertEqual(self.test_private_computation_id, args.instance_id) self.assertEqual(test_role, args.role) self.assertEqual(PrivateComputationInstanceStatus.CREATED, args.status) def test_update_instance(self): test_pid_id = self.test_private_computation_id + "_id_match" test_pid_protocol = PIDProtocol.UNION_PID test_pid_role = PIDRole.PUBLISHER test_input_path = "pid_in" test_output_path = "pid_out" # create one PID instance to be put into PrivateComputationInstance pid_instance = PIDInstance( instance_id=test_pid_id, protocol=test_pid_protocol, pid_role=test_pid_role, num_shards=self.test_num_containers, input_path=test_input_path, output_path=test_output_path, status=PIDInstanceStatus.STARTED, ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.ID_MATCHING_STARTED, instances=[pid_instance], ) updated_pid_instance = pid_instance updated_pid_instance.status = PIDInstanceStatus.COMPLETED self.private_computation_service.pid_svc.update_instance = MagicMock( return_value=updated_pid_instance ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) # call update on the PrivateComputationInstance updated_instance = self.private_computation_service.update_instance( instance_id=self.test_private_computation_id ) # check update instance called on the right pid instance self.private_computation_service.pid_svc.update_instance.assert_called() self.assertEqual( test_pid_id, self.private_computation_service.pid_svc.update_instance.call_args[0][0], ) # check update instance called on the right private lift instance self.private_computation_service.instance_repository.update.assert_called() self.assertEqual( private_computation_instance, self.private_computation_service.instance_repository.update.call_args[0][0], ) # check updated_instance has new status self.assertEqual( PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED, updated_instance.status, ) # create one MPC instance to be put into PrivateComputationInstance test_mpc_id = "test_mpc_id" mpc_instance = PCSMPCInstance.create_instance( instance_id=test_mpc_id, game_name=GameNames.LIFT.value, mpc_party=MPCParty.SERVER, num_workers=2, ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_STARTED, instances=[mpc_instance], ) updated_mpc_instance = mpc_instance updated_mpc_instance.status = MPCInstanceStatus.COMPLETED self.private_computation_service.mpc_svc.update_instance = MagicMock( return_value=updated_mpc_instance ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) # call update on the PrivateComputationInstance updated_instance = self.private_computation_service.update_instance( instance_id=self.test_private_computation_id ) # check update instance called on the right mpc instance self.private_computation_service.mpc_svc.update_instance.assert_called() self.assertEqual( test_mpc_id, self.private_computation_service.mpc_svc.update_instance.call_args[0][0], ) # check update instance called on the right private lift instance self.private_computation_service.instance_repository.update.assert_called() self.assertEqual( private_computation_instance, self.private_computation_service.instance_repository.update.call_args[0][0], ) # check updated_instance has new status self.assertEqual( PrivateComputationInstanceStatus.COMPUTATION_COMPLETED, updated_instance.status, ) @staticmethod def _get_dummy_stage_svc( stage_type: PrivateComputationStageType, ) -> PrivateComputationStageService: """create a DummyTestStageService class and instantiate an instance of it""" return type( "DummyTestStageService", (PrivateComputationStageService,), { "run_async": AsyncMock( # run_async will return whatever pc_instance privatelift.run_stage passes it side_effect=lambda pc_instance, *args, **kwargs: pc_instance ), "stage_type": stage_type, }, )() @data_provider(_get_valid_stages_data) def test_run_stage_correct_stage_order( self, stage_type: PrivateComputationStageType ) -> None: """ tests that run_stage runs stage_svc when the stage_svc is the next stage in the sequence """ ################# PREVIOUS STAGE COMPLETED OR RETRY ####################### stage_svc = self._get_dummy_stage_svc(stage_type) for status in ( stage_type.previous_stage.completed_status, stage_type.failed_status, ): pl_instance = self.create_sample_instance(status=status) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc ) self.assertEqual(pl_instance.status, stage_type.start_status) @data_provider(_get_valid_stages_data) def test_run_stage_status_already_started( self, stage_type: PrivateComputationStageType ) -> None: """ tests that run_stage does not run stage_svc when the instance status is already started """ ################# CURRENT STAGE STATUS NOT VALID ####################### stage_svc = self._get_dummy_stage_svc(stage_type) pl_instance = self.create_sample_instance(status=stage_type.start_status) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) with self.assertRaises(ValueError): pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc ) @data_provider(_get_valid_stages_data) def test_run_stage_out_of_order_with_dry_run( self, stage_type: PrivateComputationStageType ) -> None: """ tests that run_stage runs stage_svc out of order when dry run is passed """ ################ STAGE OUT OF ORDER WITH DRY RUN ##################### stage_svc = self._get_dummy_stage_svc(stage_type) pl_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.UNKNOWN ) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc, dry_run=True ) self.assertEqual(pl_instance.status, stage_type.start_status) @data_provider(_get_valid_stages_data) def test_run_stage_out_of_order_without_dry_run( self, stage_type: PrivateComputationStageType ) -> None: """ tests that run_stage does not run stage_svc out of order when dry run is not passed """ ####################### STAGE OUT OF ORDER NO DRY RUN ############################ stage_svc = self._get_dummy_stage_svc(stage_type) pl_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.UNKNOWN ) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) with self.assertRaises(ValueError): pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc, dry_run=False ) @data_provider(_get_valid_stages_data) def test_run_stage_partner_no_server_ips( self, stage_type: PrivateComputationStageType ) -> None: """ tests that run_stage does not if role is partner and no server ips are specified """ ####################### PARTNER NO SERVER IPS ############################ stage_svc = self._get_dummy_stage_svc(stage_type) pl_instance = self.create_sample_instance( status=stage_type.previous_stage.completed_status, role=PrivateComputationRole.PARTNER, ) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) with self.assertRaises(ValueError): pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc ) @data_provider(_get_valid_stages_data) def test_run_stage_fails(self, stage_type: PrivateComputationStageType) -> None: """ tests that statuses are set properly when a run fails """ ######################### STAGE FAILS #################################### stage_svc = self._get_dummy_stage_svc(stage_type) pl_instance = self.create_sample_instance( status=stage_type.previous_stage.completed_status ) self.private_computation_service.instance_repository.read = MagicMock( return_value=pl_instance ) # create a custom exception class to make sure we have a unique exception for the test stage_failure_exception = type("TestStageFailureException", (Exception,), {}) stage_svc.run_async = AsyncMock(side_effect=stage_failure_exception()) with self.assertRaises(stage_failure_exception): pl_instance = self.private_computation_service.run_stage( pl_instance.instance_id, stage_svc ) self.assertEqual(pl_instance.status, stage_type.failed_status) def test_partner_missing_server_ips(self): test_private_computation_id = "test_private_computation_id" private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED, ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) # exception because role is partner but server ips are not given with self.assertRaises(ValueError): self.private_computation_service.aggregate_shards( instance_id=test_private_computation_id, ) @patch("fbpcp.service.mpc.MPCService") @patch( "fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance" ) def test_aggregate_shards(self, mock_create_and_start_mpc_instance, mock_mpc_svc): # construct a private_computation_instance with an mpc_instance handling metrics computation test_mpc_id = self.test_private_computation_id + "_compute_metrics" mpc_instance = PCSMPCInstance.create_instance( instance_id=test_mpc_id, game_name=GameNames.LIFT.value, mpc_party=MPCParty.SERVER, num_workers=self.test_num_containers, status=MPCInstanceStatus.COMPLETED, ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_COMPLETED, instances=[mpc_instance], ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) mock_mpc_svc.update_instance = MagicMock(return_value=mpc_instance) # call aggregate_shards self.private_computation_service.aggregate_shards( instance_id=self.test_private_computation_id, server_ips=["192.0.2.0", "192.0.2.1"], ) test_game_args = [ { "input_base_path": private_computation_instance.compute_stage_output_base_path, "metrics_format_type": "lift", "num_shards": self.test_num_containers * NUM_NEW_SHARDS_PER_FILE, "output_path": private_computation_instance.shard_aggregate_stage_output_path, "threshold": private_computation_instance.k_anonymity_threshold, "run_name": "", } ] # check a new MPC instance handling metrics aggregation was to be created self.assertEqual( GameNames.SHARD_AGGREGATOR.value, mock_create_and_start_mpc_instance.call_args[1]["game_name"], ) self.assertEqual( test_game_args, mock_create_and_start_mpc_instance.call_args[1]["game_args"], ) self.private_computation_service.instance_repository.update.assert_called() self.assertEqual( PrivateComputationInstanceStatus.AGGREGATION_STARTED, private_computation_instance.status, ) @patch("fbpcp.service.mpc.MPCService") @patch( "fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance" ) def test_aggregate_shards_rerun( self, mock_create_and_start_mpc_instance, mock_mpc_svc ): # construct a private_computation_instance test_private_computation_id = "test_private_computation_id" mpc_instance = PCSMPCInstance.create_instance( instance_id=test_private_computation_id + "_aggregate_shards", game_name=GameNames.SHARD_AGGREGATOR.value, mpc_party=MPCParty.SERVER, num_workers=2, status=MPCInstanceStatus.FAILED, ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.AGGREGATION_FAILED, instances=[mpc_instance], ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) mock_mpc_svc.update_instance = MagicMock(return_value=mpc_instance) # call aggregate_shards self.private_computation_service.aggregate_shards( instance_id=test_private_computation_id, server_ips=["192.0.2.0", "192.0.2.1"], ) # check that the retry counter has been incremented self.assertEqual(private_computation_instance.retry_counter, 1) # check a new MPC instance handling metrics aggregation was to be created self.assertEqual(2, len(private_computation_instance.instances)) self.assertEqual( test_private_computation_id + "_aggregate_shards1", mock_create_and_start_mpc_instance.call_args[1]["instance_id"], ) self.assertEqual( PrivateComputationInstanceStatus.AGGREGATION_STARTED, private_computation_instance.status, ) @patch("fbpcp.service.mpc.MPCService") @patch( "fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance" ) def test_aggregate_shards_dry_run( self, mock_create_and_start_mpc_instance, mock_mpc_svc ): # construct a private_computation_instance private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_FAILED, ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) # call aggregate_shards with ad-hoc input_path and num_shards test_format_type = "lift" test_game_args = [ { "input_base_path": private_computation_instance.compute_stage_output_base_path, "num_shards": self.test_num_containers * NUM_NEW_SHARDS_PER_FILE, "metrics_format_type": test_format_type, "output_path": private_computation_instance.shard_aggregate_stage_output_path, "threshold": private_computation_instance.k_anonymity_threshold, "run_name": "", } ] self.private_computation_service.aggregate_shards( instance_id=self.test_private_computation_id, server_ips=["192.0.2.0", "192.0.2.1"], dry_run=True, ) # check a new MPC instance handling metrics aggregation was to be created # with the overwritten input_path and num_shards self.assertEqual( GameNames.SHARD_AGGREGATOR.value, mock_create_and_start_mpc_instance.call_args[1]["game_name"], ) self.assertEqual( test_game_args, mock_create_and_start_mpc_instance.call_args[1]["game_args"], ) self.private_computation_service.instance_repository.update.assert_called() self.assertEqual( PrivateComputationInstanceStatus.AGGREGATION_STARTED, private_computation_instance.status, ) @to_sync @patch("fbpcp.service.mpc.MPCService") async def test_create_and_start_mpc_instance(self, mock_mpc_svc): mock_mpc_svc.create_instance = MagicMock() mock_mpc_svc.start_instance_async = AsyncMock() instance_id = "test_instance_id" game_name = GameNames.LIFT.value mpc_party = MPCParty.CLIENT num_containers = 4 input_file = "input_file" output_file = "output_file" input_directory = "input_directory" output_directory = "output_directory" server_ips = ["192.0.2.0", "192.0.2.1"] game_args = { "input_filenames": input_file, "input_directory": input_directory, "output_filenames": output_file, "output_directory": output_directory, "concurrency": 1, } binary_version = self.onedocker_binary_config_map[ OneDockerBinaryNames.LIFT_COMPUTE.value ].binary_version await create_and_start_mpc_instance( mpc_svc=mock_mpc_svc, instance_id=instance_id, game_name=game_name, mpc_party=mpc_party, num_containers=num_containers, binary_version=binary_version, container_timeout=DEFAULT_CONTAINER_TIMEOUT_IN_SEC, server_ips=server_ips, game_args=game_args, ) # check create_instance and start_instance were called with the right parameters self.assertEqual( call( instance_id=instance_id, game_name=game_name, mpc_party=mpc_party, num_workers=num_containers, game_args=game_args, ), mock_mpc_svc.create_instance.call_args, ) self.assertEqual( call( instance_id=instance_id, server_ips=server_ips, timeout=DEFAULT_CONTAINER_TIMEOUT_IN_SEC, version=binary_version, ), mock_mpc_svc.start_instance_async.call_args, ) def test_map_private_computation_role_to_mpc_party(self): self.assertEqual( MPCParty.SERVER, map_private_computation_role_to_mpc_party(PrivateComputationRole.PUBLISHER), ) self.assertEqual( MPCParty.CLIENT, map_private_computation_role_to_mpc_party(PrivateComputationRole.PARTNER), ) def test_get_status_from_stage(self): # Test get status from an MPC stage mpc_instance = PCSMPCInstance.create_instance( instance_id="test_mpc_id", game_name=GameNames.SHARD_AGGREGATOR.value, mpc_party=MPCParty.SERVER, num_workers=2, status=MPCInstanceStatus.FAILED, ) self.assertEqual( PrivateComputationInstanceStatus.AGGREGATION_FAILED, self.private_computation_service._get_status_from_stage(mpc_instance), ) # Test get status from the PID stage pid_instance = PIDInstance( instance_id="test_pid_id", protocol=PIDProtocol.UNION_PID, pid_role=PIDRole.PUBLISHER, num_shards=4, input_path="input", output_path="output", stages_containers={}, stages_status={}, status=PIDInstanceStatus.COMPLETED, ) self.assertEqual( PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED, self.private_computation_service._get_status_from_stage(pid_instance), ) def test_prepare_data(self): private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.CREATED, ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) with patch.object( CppLiftIdSpineCombinerService, "combine_on_container_async", ) as mock_combine, patch.object( CppShardingService, "shard_on_container_async", ) as mock_shard: # call prepare_data self.private_computation_service.prepare_data( instance_id=self.test_private_computation_id, dry_run=True, ) binary_config = self.onedocker_binary_config_map[ OneDockerBinaryNames.LIFT_ID_SPINE_COMBINER.value ] mock_combine.assert_called_once_with( spine_path=private_computation_instance.pid_stage_output_spine_path, data_path=private_computation_instance.pid_stage_output_data_path, output_path=private_computation_instance.data_processing_output_path + "_combine", num_shards=self.test_num_containers, onedocker_svc=self.onedocker_service, binary_version=binary_config.binary_version, tmp_directory=binary_config.tmp_directory, ) mock_shard.assert_called() def test_prepare_data_tasks_skipped(self): private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_FAILED, ) private_computation_instance.partial_container_retry_enabled = True self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) with patch.object( CppLiftIdSpineCombinerService, "combine_on_container_async", ) as mock_combine, patch.object( CppShardingService, "shard_on_container_async", ) as mock_shard: # call prepare_data self.private_computation_service.prepare_data( instance_id=self.test_private_computation_id, ) # expect combining and sharding skipped because this private_computation_instance has # status PrivateComputationInstanceStatus.COMPUTATION_FAILED, so this run # is to recover from a previous compute metrics failure, meaning data # preparation should have been done mock_combine.assert_not_called() mock_shard.assert_not_called() def test_validate_metrics_results_doesnt_match(self): self.private_computation_service.pid_svc.storage_svc.read = MagicMock() self.private_computation_service.pid_svc.storage_svc.read.side_effect = [ '{"subGroupMetrics":[],"metrics":{"controlClicks":1,"testSpend":0,"controlImpressions":0,"testImpressions":0,"controlMatchCount":0,"testMatchCount":0,"controlNumConvSquared":0,"testNumConvSquared":0,"testValueSquared":0,"controlValue":0,"testValue":0,"testConverters":0,"testConversions":0,"testPopulation":0,"controlClickers":0,"testClickers":0,"controlReach":0,"testReach":0,"controlSpend":0,"testClicks":0,"controlValueSquared":0,"controlConverters":0,"controlConversions":0,"controlPopulation":0}}', '{"subGroupMetrics":[],"metrics":{"testSpend":0,"controlClicks":0,"controlImpressions":0,"testImpressions":0,"controlMatchCount":0,"testMatchCount":0,"controlNumConvSquared":0,"testNumConvSquared":0,"testValueSquared":0,"controlValue":0,"testValue":0,"testConverters":0,"testConversions":0,"testPopulation":0,"controlClickers":0,"testClickers":0,"controlReach":0,"testReach":0,"controlSpend":0,"testClicks":0,"controlValueSquared":0,"controlConverters":0,"controlConversions":0,"controlPopulation":0}}', ] with self.assertRaises(PrivateComputationServiceValidationError): self.private_computation_service.validate_metrics( instance_id="test_id", aggregated_result_path="aggregated_result_path", expected_result_path="expected_result_path", ) def test_cancel_current_stage(self): test_mpc_id = self.test_private_computation_id + "_compute_metrics" test_game_name = GameNames.LIFT.value test_mpc_party = MPCParty.CLIENT # prepare the pl instance that will be read in to memory from the repository # at the beginning of the cancel_current_stage function mpc_instance_started = PCSMPCInstance.create_instance( instance_id=test_mpc_id, game_name=test_game_name, mpc_party=test_mpc_party, num_workers=self.test_num_containers, status=MPCInstanceStatus.STARTED, ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_STARTED, role=PrivateComputationRole.PARTNER, instances=[mpc_instance_started], ) self.private_computation_service.instance_repository.read = MagicMock( return_value=private_computation_instance ) # prepare the mpc instance that's returned from mpc_service.stop_instance() mpc_instance_canceled = PCSMPCInstance.create_instance( instance_id=test_mpc_id, game_name=test_game_name, mpc_party=test_mpc_party, num_workers=self.test_num_containers, status=MPCInstanceStatus.CANCELED, ) self.private_computation_service.mpc_svc.stop_instance = MagicMock( return_value=mpc_instance_canceled ) self.private_computation_service.mpc_svc.instance_repository.read = MagicMock( return_value=mpc_instance_canceled ) # call cancel, expect no exception private_computation_instance = ( self.private_computation_service.cancel_current_stage( instance_id=self.test_private_computation_id, ) ) # assert the pl instance returned has the correct status self.assertEqual( PrivateComputationInstanceStatus.COMPUTATION_FAILED, private_computation_instance.status, ) def test_gen_game_args_to_retry(self): test_input = "test_input_retry" mpc_instance = PCSMPCInstance.create_instance( instance_id="mpc_instance", game_name=GameNames.LIFT.value, mpc_party=MPCParty.SERVER, num_workers=2, status=MPCInstanceStatus.FAILED, containers=[ ContainerInstance( instance_id="container_instance_0", status=ContainerInstanceStatus.FAILED, ), ContainerInstance( instance_id="container_instance_1", status=ContainerInstanceStatus.COMPLETED, ), ], game_args=[ { "input_filenames": test_input, }, { "input_filenames": "input_filenames", }, ], ) private_computation_instance = self.create_sample_instance( status=PrivateComputationInstanceStatus.COMPUTATION_FAILED, instances=[mpc_instance], ) game_args = gen_mpc_game_args_to_retry( private_computation_instance ) self.assertEqual(1, len(game_args)) # only 1 failed container self.assertEqual(test_input, game_args[0]["input_filenames"]) def create_sample_instance( self, status: PrivateComputationInstanceStatus, role: PrivateComputationRole = PrivateComputationRole.PUBLISHER, instances: Optional[List[UnionedPCInstance]] = None, ) -> PrivateComputationInstance: return PrivateComputationInstance( instance_id=self.test_private_computation_id, role=role, instances=instances or [], status=status, status_update_ts=1600000000, num_pid_containers=self.test_num_containers, num_mpc_containers=self.test_num_containers, concurrency=self.test_concurrency, num_files_per_mpc_container=NUM_NEW_SHARDS_PER_FILE, game_type=PrivateComputationGameType.LIFT, input_path=self.test_input_path, output_dir=self.test_output_dir, fail_fast=True, k_anonymity_threshold=DEFAULT_K_ANONYMITY_THRESHOLD, )
[((296, 5, 296, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(296, 19, 296, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((319, 5, 319, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(319, 19, 319, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((339, 5, 339, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(339, 19, 339, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((361, 5, 361, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(361, 19, 361, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((383, 5, 383, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(383, 19, 383, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((406, 5, 406, 42), 'libfb.py.testutil.data_provider', 'data_provider', ({(406, 19, 406, 41): '_get_valid_stages_data'}, {}), '(_get_valid_stages_data)', False, 'from libfb.py.testutil import data_provider\n'), ((449, 5, 449, 42), 'unittest.mock.patch', 'patch', ({(449, 11, 449, 41): '"""fbpcp.service.mpc.MPCService"""'}, {}), "('fbpcp.service.mpc.MPCService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((450, 5, 452, 5), 'unittest.mock.patch', 'patch', ({(451, 8, 451, 93): '"""fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance"""'}, {}), "(\n 'fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance'\n )", False, 'from unittest.mock import MagicMock, call, patch\n'), ((503, 5, 503, 42), 'unittest.mock.patch', 'patch', ({(503, 11, 503, 41): '"""fbpcp.service.mpc.MPCService"""'}, {}), "('fbpcp.service.mpc.MPCService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((504, 5, 506, 5), 'unittest.mock.patch', 'patch', ({(505, 8, 505, 93): '"""fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance"""'}, {}), "(\n 'fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance'\n )", False, 'from unittest.mock import MagicMock, call, patch\n'), ((549, 5, 549, 42), 'unittest.mock.patch', 'patch', ({(549, 11, 549, 41): '"""fbpcp.service.mpc.MPCService"""'}, {}), "('fbpcp.service.mpc.MPCService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((550, 5, 552, 5), 'unittest.mock.patch', 'patch', ({(551, 8, 551, 93): '"""fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance"""'}, {}), "(\n 'fbpcs.private_computation.service.private_computation.create_and_start_mpc_instance'\n )", False, 'from unittest.mock import MagicMock, call, patch\n'), ((599, 5, 599, 42), 'unittest.mock.patch', 'patch', ({(599, 11, 599, 41): '"""fbpcp.service.mpc.MPCService"""'}, {}), "('fbpcp.service.mpc.MPCService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((77, 32, 77, 88), 'unittest.mock.patch', 'patch', ({(77, 38, 77, 87): '"""fbpcp.service.container_aws.AWSContainerService"""'}, {}), "('fbpcp.service.container_aws.AWSContainerService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((78, 30, 78, 80), 'unittest.mock.patch', 'patch', ({(78, 36, 78, 79): '"""fbpcp.service.storage_s3.S3StorageService"""'}, {}), "('fbpcp.service.storage_s3.S3StorageService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((79, 36, 81, 9), 'unittest.mock.patch', 'patch', ({(80, 12, 80, 83): '"""fbpcs.common.repository.mpc_instance_local.LocalMPCInstanceRepository"""'}, {}), "('fbpcs.common.repository.mpc_instance_local.LocalMPCInstanceRepository')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((82, 36, 84, 9), 'unittest.mock.patch', 'patch', ({(83, 12, 83, 80): '"""fbpcs.pid.repository.pid_instance_local.LocalPIDInstanceRepository"""'}, {}), "('fbpcs.pid.repository.pid_instance_local.LocalPIDInstanceRepository')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((85, 52, 87, 9), 'unittest.mock.patch', 'patch', ({(86, 12, 86, 127): '"""fbpcs.private_computation.repository.private_computation_instance_local.LocalPrivateComputationInstanceRepository"""'}, {}), "(\n 'fbpcs.private_computation.repository.private_computation_instance_local.LocalPrivateComputationInstanceRepository'\n )", False, 'from unittest.mock import MagicMock, call, patch\n'), ((88, 31, 88, 77), 'unittest.mock.patch', 'patch', ({(88, 37, 88, 76): '"""fbpcp.service.mpc_game.MPCGameService"""'}, {}), "('fbpcp.service.mpc_game.MPCGameService')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((108, 40, 110, 9), 'fbpcs.onedocker_service_config.OneDockerServiceConfig', 'OneDockerServiceConfig', (), '', False, 'from fbpcs.onedocker_service_config import OneDockerServiceConfig\n'), ((118, 33, 120, 9), 'fbpcp.service.onedocker.OneDockerService', 'OneDockerService', ({(119, 12, 119, 25): 'container_svc', (119, 27, 119, 72): 'self.onedocker_service_config.task_definition'}, {}), '(container_svc, self.onedocker_service_config.task_definition)', False, 'from fbpcp.service.onedocker import OneDockerService\n'), ((122, 27, 127, 9), 'fbpcp.service.mpc.MPCService', 'MPCService', (), '', False, 'from fbpcp.service.mpc import MPCInstanceStatus, MPCParty, MPCService\n'), ((129, 27, 134, 9), 'fbpcs.pid.service.pid_service.pid.PIDService', 'PIDService', (), '', False, 'from fbpcs.pid.service.pid_service.pid import PIDService\n'), ((136, 43, 142, 9), 'fbpcs.private_computation.service.private_computation.PrivateComputationService', 'PrivateComputationService', (), '', False, 'from fbpcs.private_computation.service.private_computation import PrivateComputationService, NUM_NEW_SHARDS_PER_FILE, DEFAULT_K_ANONYMITY_THRESHOLD\n'), ((180, 23, 188, 9), 'fbpcs.pid.entity.pid_instance.PIDInstance', 'PIDInstance', (), '', False, 'from fbpcs.pid.entity.pid_instance import PIDInstance, PIDInstanceStatus, PIDProtocol, PIDRole\n'), ((197, 67, 199, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((201, 68, 203, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((232, 23, 237, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((246, 67, 248, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((250, 68, 252, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((330, 68, 332, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((352, 68, 354, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((374, 68, 376, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((397, 68, 399, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((417, 68, 419, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((439, 68, 441, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((456, 23, 462, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((467, 68, 469, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((470, 39, 470, 75), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((512, 23, 518, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((524, 68, 526, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((527, 39, 527, 75), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((560, 68, 562, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((601, 39, 601, 50), 'unittest.mock.MagicMock', 'MagicMock', ({}, {}), '()', False, 'from unittest.mock import MagicMock, call, patch\n'), ((602, 44, 602, 55), 'libfb.py.asyncio.mock.AsyncMock', 'AsyncMock', ({}, {}), '()', False, 'from libfb.py.asyncio.mock import AsyncMock\n'), ((670, 23, 676, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((683, 23, 693, 9), 'fbpcs.pid.entity.pid_instance.PIDInstance', 'PIDInstance', (), '', False, 'from fbpcs.pid.entity.pid_instance import PIDInstance, PIDInstanceStatus, PIDProtocol, PIDRole\n'), ((703, 68, 705, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((739, 68, 741, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((762, 68, 762, 79), 'unittest.mock.MagicMock', 'MagicMock', ({}, {}), '()', False, 'from unittest.mock import MagicMock, call, patch\n'), ((781, 31, 787, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((793, 68, 795, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((798, 32, 804, 9), 'fbpcs.common.entity.pcs_mpc_instance.PCSMPCInstance.create_instance', 'PCSMPCInstance.create_instance', (), '', False, 'from fbpcs.common.entity.pcs_mpc_instance import PCSMPCInstance\n'), ((805, 65, 807, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((808, 76, 810, 9), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((857, 20, 859, 9), 'fbpcs.private_computation.service.utils.gen_mpc_game_args_to_retry', 'gen_mpc_game_args_to_retry', ({(858, 12, 858, 40): 'private_computation_instance'}, {}), '(private_computation_instance)', False, 'from fbpcs.private_computation.service.utils import create_and_start_mpc_instance, gen_mpc_game_args_to_retry, map_private_computation_role_to_mpc_party, DEFAULT_CONTAINER_TIMEOUT_IN_SEC\n'), ((870, 15, 885, 9), 'fbpcs.private_computation.entity.private_computation_instance.PrivateComputationInstance', 'PrivateComputationInstance', (), '', False, 'from fbpcs.private_computation.entity.private_computation_instance import PrivateComputationGameType, PrivateComputationInstance, PrivateComputationInstanceStatus, PrivateComputationRole, UnionedPCInstance\n'), ((310, 72, 312, 13), 'unittest.mock.MagicMock', 'MagicMock', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((624, 14, 634, 9), 'fbpcs.private_computation.service.utils.create_and_start_mpc_instance', 'create_and_start_mpc_instance', (), '', False, 'from fbpcs.private_computation.service.utils import create_and_start_mpc_instance, gen_mpc_game_args_to_retry, map_private_computation_role_to_mpc_party, DEFAULT_CONTAINER_TIMEOUT_IN_SEC\n'), ((638, 12, 644, 13), 'unittest.mock.call', 'call', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((649, 12, 654, 13), 'unittest.mock.call', 'call', (), '', False, 'from unittest.mock import MagicMock, call, patch\n'), ((661, 12, 661, 87), 'fbpcs.private_computation.service.utils.map_private_computation_role_to_mpc_party', 'map_private_computation_role_to_mpc_party', ({(661, 54, 661, 86): 'PrivateComputationRole.PUBLISHER'}, {}), '(PrivateComputationRole.PUBLISHER)', False, 'from fbpcs.private_computation.service.utils import create_and_start_mpc_instance, gen_mpc_game_args_to_retry, map_private_computation_role_to_mpc_party, DEFAULT_CONTAINER_TIMEOUT_IN_SEC\n'), ((665, 12, 665, 85), 'fbpcs.private_computation.service.utils.map_private_computation_role_to_mpc_party', 'map_private_computation_role_to_mpc_party', ({(665, 54, 665, 84): 'PrivateComputationRole.PARTNER'}, {}), '(PrivateComputationRole.PARTNER)', False, 'from fbpcs.private_computation.service.utils import create_and_start_mpc_instance, gen_mpc_game_args_to_retry, map_private_computation_role_to_mpc_party, DEFAULT_CONTAINER_TIMEOUT_IN_SEC\n'), ((707, 13, 710, 9), 'unittest.mock.patch.object', 'patch.object', ({(708, 12, 708, 41): 'CppLiftIdSpineCombinerService', (709, 12, 709, 40): '"""combine_on_container_async"""'}, {}), "(CppLiftIdSpineCombinerService, 'combine_on_container_async')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((710, 27, 713, 9), 'unittest.mock.patch.object', 'patch.object', ({(711, 12, 711, 30): 'CppShardingService', (712, 12, 712, 38): '"""shard_on_container_async"""'}, {}), "(CppShardingService, 'shard_on_container_async')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((743, 13, 746, 9), 'unittest.mock.patch.object', 'patch.object', ({(744, 12, 744, 41): 'CppLiftIdSpineCombinerService', (745, 12, 745, 40): '"""combine_on_container_async"""'}, {}), "(CppLiftIdSpineCombinerService, 'combine_on_container_async')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((746, 27, 749, 9), 'unittest.mock.patch.object', 'patch.object', ({(747, 12, 747, 30): 'CppShardingService', (748, 12, 748, 38): '"""shard_on_container_async"""'}, {}), "(CppShardingService, 'shard_on_container_async')", False, 'from unittest.mock import MagicMock, call, patch\n'), ((113, 20, 115, 13), 'fbpcs.onedocker_binary_config.OneDockerBinaryConfig', 'OneDockerBinaryConfig', (), '', False, 'from fbpcs.onedocker_binary_config import OneDockerBinaryConfig\n'), ((288, 29, 291, 17), 'libfb.py.asyncio.mock.AsyncMock', 'AsyncMock', (), '', False, 'from libfb.py.asyncio.mock import AsyncMock\n'), ((834, 16, 837, 17), 'fbpcp.entity.container_instance.ContainerInstance', 'ContainerInstance', (), '', False, 'from fbpcp.entity.container_instance import ContainerInstance, ContainerInstanceStatus\n'), ((838, 16, 841, 17), 'fbpcp.entity.container_instance.ContainerInstance', 'ContainerInstance', (), '', False, 'from fbpcp.entity.container_instance import ContainerInstance, ContainerInstanceStatus\n')]
Eubule/Store-Manager-With-Datastructure
app.py
c21a7307cc59b53516fb40437b1a359ca48a4f2e
from app import app from app.database.db import Database if __name__ == "__main__": db = Database() db.create_tables() db.create_admin() app.run(debug=True)
[((6, 9, 6, 19), 'app.database.db.Database', 'Database', ({}, {}), '()', False, 'from app.database.db import Database\n'), ((9, 4, 9, 23), 'app.app.run', 'app.run', (), '', False, 'from app import app\n')]
ryuichi1208/scraping-py
src/main.py
43036dff75cc47d3169e012096f0de70dea0296b
# -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False import views
[]
Maxahoy/ClassVolumeSilencer
HoursSelect.py
9a05f9dd4efbbbddc74377a27027fa40b2167d02
""" This is how I'm gonna schedule hours IDEA: import the format example file that I'm using and is saved in the same directory """ import csv import pprint from tkinter import * from tkinter.filedialog import askopenfilename import StringProcessing def selectHoursFile(): Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file print(filename) return filename """ Receives a file location, opens the csv The format looks like this: CLASS STARTS,Class name (optional),MON,TUES,WED,THURS,FRI,,CLASS ENDS,MON,TUES,WED,THURS,FRI 1, Stats, 10:20:00 AM,,10:20:00 AM,,10:20:00 AM,,,11:15:00 AM,,11:15:00 AM,,11:15:00 AM 2,,,09:35:00 AM,,09:35:00 AM,,,,,10:55:00 AM,,10:55:00 AM, 3,,,11:30:00 AM,11:30:00 AM,11:30:00 AM,11:30:00 AM,,,,12:25:00 PM,12:25:00 PM,12:25:00 PM,12:25:00 PM 4,,,,,,09:10:00 AM,,,,,,,10:05:00 AM 5,,12:00:00 PM,01:00:00 PM,01:00:00 PM,01:00:00 PM,01:00:00 PM,,,,04:30:00 PM,04:30:00 PM,04:30:00 PM,04:30:00 PM 6,,,,,,,,,,,,, 7,,,,,,,,,,,,, 8,,,,,,,,,,,,, 9,,,,,,,,,,,,, 10,,,,,,,,,,,,, 11,,,,,,,,,,,,, 12,,,,,,,,,,,,, 13,,,,,,,,,,,,, 14,,,,,,,,,,,,, 15,,,,,,,,,,,,, """ def interpretCSVFormat(csvFile): #first open the file with the filepath classList = dict() with open(csvFile, "r") as csvOpen: #next populate a temporary dictionary for the classes tempDict = dict() classID = 0 rowReader = csv.reader(csvOpen, delimiter=',', quotechar="'") for row in rowReader: #dictionary format: class ID::string of class days classTimes = row #print(row) tempDict[classID] = str(classTimes) classID = classID + 1 print(StringProcessing.lineList(str(classTimes))) del tempDict[0] pp = pprint.PrettyPrinter(indent=4) #pp.pprint(tempDict) #TODO: make the sections using ClassScheduleStorage
[((19, 15, 19, 32), 'tkinter.filedialog.askopenfilename', 'askopenfilename', ({}, {}), '()', False, 'from tkinter.filedialog import askopenfilename\n'), ((53, 20, 53, 69), 'csv.reader', 'csv.reader', (), '', False, 'import csv\n'), ((64, 13, 64, 43), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', (), '', False, 'import pprint\n')]
IvanKosik/bone-age-models
src/bsmu/bone_age/models/dense_net/configs.py
07f20a94951a3b584ee7b6d9a11805c37878214a
from pathlib import Path from bsmu.bone_age.models import constants IMAGE_DIR = Path('C:/MyDiskBackup/Projects/BoneAge/Data/SmallImages500_NoPads') TRAIN_DATA_CSV_PATH = constants.TRAIN_DATA_CSV_PATH VALID_DATA_CSV_PATH = constants.VALID_DATA_CSV_PATH TEST_DATA_CSV_PATH = constants.TEST_DATA_CSV_PATH BATCH_SIZE = 7 MODEL_NAME_PREFIX = 'DenseNet169' MODEL_NAME_POSTFIX = 'AllImages3_MoreAugments'
[((5, 12, 5, 79), 'pathlib.Path', 'Path', ({(5, 17, 5, 78): '"""C:/MyDiskBackup/Projects/BoneAge/Data/SmallImages500_NoPads"""'}, {}), "('C:/MyDiskBackup/Projects/BoneAge/Data/SmallImages500_NoPads')", False, 'from pathlib import Path\n')]
ogawan/nisa
projection.py
d758e41e4983cc35477e81d944689b0226f00ef5
from matplotlib import pyplot as plt def nisa_projection(years=30, annual_deposit=80, initial_budget=100): """ This is a function to plot deposit of TSUMITATE NISA Parameters: --------------- years: integer How many years are you going to continue? annual_depoist: integer Annual deposit into the NISA account. initial_budget: integer The initial budget. Returns: -------------- matplotlib figure """ for j in [1.00,1.01, 1.02, 1.03, 1.04, 1.05]: original = initial_budget ganbon = [] box = [] for i in range(0,years): if i == 0: box.append(original) ganbon.append(original) gan = ganbon[-1] + annual_deposit original = original * j + annual_deposit if i > 0: box.append(original) ganbon.append(gan) plt.scatter(list(range(0,years)), box) plt.legend(["0%", "1%", "2%", "3%", "4%", "5%"]) plt.xlabel("Years") plt.ylabel("Money (Man yen)") # Reference: https://plotly.com/python/figure-labels/ import pandas as pd import plotly.graph_objects as go def nisa_projection_plotly(years=30, annual_deposit=80, initial_budget=100): """ This is a function to plot deposit of TSUMITATE NISA Parameters: --------------- years: integer How many years are you going to continue? annual_depoist: integer Annual deposit into the NISA account. initial_budget: integer The initial budget. Returns: -------------- plotly figures. """ dic_ = {} for j in [1.00,1.01, 1.02, 1.03, 1.04, 1.05]: original = initial_budget ganbon = [] box = [] for i in range(0,years): if i == 0: box.append(original) ganbon.append(original) gan = ganbon[-1] + annual_deposit original = original * j + annual_deposit if i > 0: box.append(original) ganbon.append(gan) dic_["{} %".format(str(j)[-1])] = box df = pd.DataFrame(dic_) fig = go.Figure() for i in df.columns: fig.add_trace(go.Scatter(x=df.index, y=df[i],name=i)) fig.update_layout( title="NISA PLOT", xaxis_title="Years", yaxis_title="Man Yen", width=500, height=400, ) fig.show() nisa_projection(30, 80, 100) nisa_projection_plotly(30, 80, 100)
[((89, 7, 89, 25), 'pandas.DataFrame', 'pd.DataFrame', ({(89, 20, 89, 24): 'dic_'}, {}), '(dic_)', True, 'import pandas as pd\n'), ((91, 8, 91, 19), 'plotly.graph_objects.Figure', 'go.Figure', ({}, {}), '()', True, 'import plotly.graph_objects as go\n'), ((41, 4, 41, 52), 'matplotlib.pyplot.legend', 'plt.legend', ({(41, 15, 41, 51): "['0%', '1%', '2%', '3%', '4%', '5%']"}, {}), "(['0%', '1%', '2%', '3%', '4%', '5%'])", True, 'from matplotlib import pyplot as plt\n'), ((42, 4, 42, 23), 'matplotlib.pyplot.xlabel', 'plt.xlabel', ({(42, 15, 42, 22): '"""Years"""'}, {}), "('Years')", True, 'from matplotlib import pyplot as plt\n'), ((43, 4, 43, 33), 'matplotlib.pyplot.ylabel', 'plt.ylabel', ({(43, 15, 43, 32): '"""Money (Man yen)"""'}, {}), "('Money (Man yen)')", True, 'from matplotlib import pyplot as plt\n'), ((93, 18, 93, 56), 'plotly.graph_objects.Scatter', 'go.Scatter', (), '', True, 'import plotly.graph_objects as go\n')]
wumo/sim-world
tensorflow-ops-generator/resources/gen_ops/gen_math_ops.py
2a3a5118239b27eeb268cd1e7bdbfe5f5604dab6
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: math_ops.cc """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _core from tensorflow.python.eager import execute as _execute from tensorflow.python.framework import dtypes as _dtypes from tensorflow.python.framework import errors as _errors from tensorflow.python.framework import tensor_shape as _tensor_shape from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 # Needed to trigger the call to _set_call_cpp_shape_fn. from tensorflow.python.framework import common_shapes as _common_shapes from tensorflow.python.framework import op_def_registry as _op_def_registry from tensorflow.python.framework import ops as _ops from tensorflow.python.framework import op_def_library as _op_def_library from tensorflow.python.util.tf_export import tf_export def _abs(x, name=None): r"""Computes the absolute value of a tensor. Given a tensor `x`, this operation returns a tensor containing the absolute value of each element in `x`. For example, if x is an input element and y is an output element, this operation computes \\(y = |x|\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Abs", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Abs", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Abs", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return _abs_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _abs_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _abs """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Abs", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Abs", _inputs_flat, _attrs, _result, name) _result, = _result return _result def accumulate_nv2(inputs, shape, name=None): r"""Returns the element-wise sum of a list of tensors. `tf.accumulate_n_v2` performs the same operation as `tf.add_n`, but does not wait for all of its inputs to be ready before beginning to sum. This can save memory if inputs are ready at different times, since minimum temporary storage is proportional to the output size rather than the inputs size. Unlike the original `accumulate_n`, `accumulate_n_v2` is differentiable. Returns a `Tensor` of same shape and type as the elements of `inputs`. Args: inputs: A list of at least 1 `Tensor` objects with the same type in: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. A list of `Tensor` objects, each with same shape and type. shape: A `tf.TensorShape` or list of `ints`. Shape of elements of `inputs`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `inputs`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(inputs, (list, tuple)): raise TypeError( "Expected list for 'inputs' argument to " "'accumulate_nv2' Op, not %r." % inputs) _attr_N = len(inputs) shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "AccumulateNV2", inputs=inputs, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T"), "shape", _op.get_attr("shape")) _execute.record_gradient( "AccumulateNV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "AccumulateNV2", name, _ctx._post_execution_callbacks, inputs, "shape", shape) return _result except _core._FallbackException: return accumulate_nv2_eager_fallback( inputs, shape=shape, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def accumulate_nv2_eager_fallback(inputs, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function accumulate_nv2 """ _ctx = ctx if ctx else _context.context() if not isinstance(inputs, (list, tuple)): raise TypeError( "Expected list for 'inputs' argument to " "'accumulate_nv2' Op, not %r." % inputs) _attr_N = len(inputs) shape = _execute.make_shape(shape, "shape") _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), _ctx) _inputs_flat = list(inputs) _attrs = ("N", _attr_N, "T", _attr_T, "shape", shape) _result = _execute.execute(b"AccumulateNV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "AccumulateNV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.acos', 'acos') def acos(x, name=None): r"""Computes acos of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Acos", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Acos", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Acos", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return acos_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def acos_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function acos """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Acos", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Acos", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.acosh', 'acosh') def acosh(x, name=None): r"""Computes inverse hyperbolic cosine of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Acosh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Acosh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Acosh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return acosh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def acosh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function acosh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Acosh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Acosh", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.add', 'add') def add(x, y, name=None): r"""Returns x + y element-wise. *NOTE*: `math.add` supports broadcasting. `AddN` does not. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `string`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Add", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Add", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Add", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return add_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def add_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function add """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Add", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Add", _inputs_flat, _attrs, _result, name) _result, = _result return _result def add_n(inputs, name=None): r"""Add all input tensors element wise. Args: inputs: A list of at least 1 `Tensor` objects with the same type in: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `variant`. Must all be the same size and shape. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `inputs`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(inputs, (list, tuple)): raise TypeError( "Expected list for 'inputs' argument to " "'add_n' Op, not %r." % inputs) _attr_N = len(inputs) _, _, _op = _op_def_lib._apply_op_helper( "AddN", inputs=inputs, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T")) _execute.record_gradient( "AddN", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "AddN", name, _ctx._post_execution_callbacks, inputs) return _result except _core._FallbackException: return add_n_eager_fallback( inputs, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def add_n_eager_fallback(inputs, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function add_n """ _ctx = ctx if ctx else _context.context() if not isinstance(inputs, (list, tuple)): raise TypeError( "Expected list for 'inputs' argument to " "'add_n' Op, not %r." % inputs) _attr_N = len(inputs) _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), _ctx) _inputs_flat = list(inputs) _attrs = ("N", _attr_N, "T", _attr_T) _result = _execute.execute(b"AddN", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "AddN", _inputs_flat, _attrs, _result, name) _result, = _result return _result def add_v2(x, y, name=None): r"""Returns x + y element-wise. *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "AddV2", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "AddV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "AddV2", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return add_v2_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def add_v2_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function add_v2 """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"AddV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "AddV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _all(input, axis, keep_dims=False, name=None): r"""Computes the "logical and" of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor` of type `bool`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "All", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "All", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "All", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return _all_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _all_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _all """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) input = _ops.convert_to_tensor(input, _dtypes.bool) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "Tidx", _attr_Tidx) _result = _execute.execute(b"All", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "All", _inputs_flat, _attrs, _result, name) _result, = _result return _result def angle(input, Tout=_dtypes.float32, name=None): r"""Returns the argument of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of type `float` that is the argument of each element in `input`. All elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. The argument returned by this operation is of the form \\(atan2(b, a)\\). For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.angle(input) ==> [2.0132, 1.056] ``` @compatibility(numpy) Equivalent to np.angle. @end_compatibility Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. name: A name for the operation (optional). Returns: A `Tensor` of type `Tout`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _, _, _op = _op_def_lib._apply_op_helper( "Angle", input=input, Tout=Tout, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tout", _op.get_attr("Tout")) _execute.record_gradient( "Angle", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Angle", name, _ctx._post_execution_callbacks, input, "Tout", Tout) return _result except _core._FallbackException: return angle_eager_fallback( input, Tout=Tout, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def angle_eager_fallback(input, Tout=_dtypes.float32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function angle """ _ctx = ctx if ctx else _context.context() if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx, _dtypes.complex64) _inputs_flat = [input] _attrs = ("T", _attr_T, "Tout", Tout) _result = _execute.execute(b"Angle", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Angle", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _any(input, axis, keep_dims=False, name=None): r"""Computes the "logical or" of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor` of type `bool`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Any", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Any", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Any", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return _any_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _any_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _any """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) input = _ops.convert_to_tensor(input, _dtypes.bool) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "Tidx", _attr_Tidx) _result = _execute.execute(b"Any", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Any", _inputs_flat, _attrs, _result, name) _result, = _result return _result def approximate_equal(x, y, tolerance=1e-05, name=None): r"""Returns the truth value of abs(x-y) < tolerance element-wise. Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. y: A `Tensor`. Must have the same type as `x`. tolerance: An optional `float`. Defaults to `1e-05`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if tolerance is None: tolerance = 1e-05 tolerance = _execute.make_float(tolerance, "tolerance") _, _, _op = _op_def_lib._apply_op_helper( "ApproximateEqual", x=x, y=y, tolerance=tolerance, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "tolerance", _op.get_attr("tolerance")) _execute.record_gradient( "ApproximateEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ApproximateEqual", name, _ctx._post_execution_callbacks, x, y, "tolerance", tolerance) return _result except _core._FallbackException: return approximate_equal_eager_fallback( x, y, tolerance=tolerance, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def approximate_equal_eager_fallback(x, y, tolerance=1e-05, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function approximate_equal """ _ctx = ctx if ctx else _context.context() if tolerance is None: tolerance = 1e-05 tolerance = _execute.make_float(tolerance, "tolerance") _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T, "tolerance", tolerance) _result = _execute.execute(b"ApproximateEqual", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ApproximateEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result def arg_max(input, dimension, output_type=_dtypes.int64, name=None): r"""Returns the index with the largest value across dimensions of a tensor. Note that in case of ties the identity of the return value is not guaranteed. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. dimension: A `Tensor`. Must be one of the following types: `int32`, `int64`. int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which dimension of the input Tensor to reduce across. For vectors, use dimension = 0. output_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. name: A name for the operation (optional). Returns: A `Tensor` of type `output_type`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if output_type is None: output_type = _dtypes.int64 output_type = _execute.make_type(output_type, "output_type") _, _, _op = _op_def_lib._apply_op_helper( "ArgMax", input=input, dimension=dimension, output_type=output_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx"), "output_type", _op.get_attr("output_type")) _execute.record_gradient( "ArgMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ArgMax", name, _ctx._post_execution_callbacks, input, dimension, "output_type", output_type) return _result except _core._FallbackException: return arg_max_eager_fallback( input, dimension, output_type=output_type, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def arg_max_eager_fallback(input, dimension, output_type=_dtypes.int64, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function arg_max """ _ctx = ctx if ctx else _context.context() if output_type is None: output_type = _dtypes.int64 output_type = _execute.make_type(output_type, "output_type") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (dimension,) = _execute.args_to_matching_eager([dimension], _ctx, _dtypes.int32) _inputs_flat = [input, dimension] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "output_type", output_type) _result = _execute.execute(b"ArgMax", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ArgMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result def arg_min(input, dimension, output_type=_dtypes.int64, name=None): r"""Returns the index with the smallest value across dimensions of a tensor. Note that in case of ties the identity of the return value is not guaranteed. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. dimension: A `Tensor`. Must be one of the following types: `int32`, `int64`. int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which dimension of the input Tensor to reduce across. For vectors, use dimension = 0. output_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. name: A name for the operation (optional). Returns: A `Tensor` of type `output_type`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if output_type is None: output_type = _dtypes.int64 output_type = _execute.make_type(output_type, "output_type") _, _, _op = _op_def_lib._apply_op_helper( "ArgMin", input=input, dimension=dimension, output_type=output_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx"), "output_type", _op.get_attr("output_type")) _execute.record_gradient( "ArgMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ArgMin", name, _ctx._post_execution_callbacks, input, dimension, "output_type", output_type) return _result except _core._FallbackException: return arg_min_eager_fallback( input, dimension, output_type=output_type, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def arg_min_eager_fallback(input, dimension, output_type=_dtypes.int64, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function arg_min """ _ctx = ctx if ctx else _context.context() if output_type is None: output_type = _dtypes.int64 output_type = _execute.make_type(output_type, "output_type") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (dimension,) = _execute.args_to_matching_eager([dimension], _ctx, _dtypes.int32) _inputs_flat = [input, dimension] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "output_type", output_type) _result = _execute.execute(b"ArgMin", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ArgMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.asin', 'asin') def asin(x, name=None): r"""Computes asin of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Asin", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Asin", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Asin", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return asin_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def asin_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function asin """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Asin", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Asin", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.asinh', 'asinh') def asinh(x, name=None): r"""Computes inverse hyperbolic sine of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Asinh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Asinh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Asinh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return asinh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def asinh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function asinh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Asinh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Asinh", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.atan', 'atan') def atan(x, name=None): r"""Computes atan of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Atan", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Atan", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Atan", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return atan_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def atan_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function atan """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Atan", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Atan", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.atan2', 'atan2') def atan2(y, x, name=None): r"""Computes arctangent of `y/x` element-wise, respecting signs of the arguments. This is the angle \( \theta \in [-\pi, \pi] \) such that \[ x = r \cos(\theta) \] and \[ y = r \sin(\theta) \] where \(r = \sqrt(x^2 + y^2) \). Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. x: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Atan2", y=y, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Atan2", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Atan2", name, _ctx._post_execution_callbacks, y, x) return _result except _core._FallbackException: return atan2_eager_fallback( y, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def atan2_eager_fallback(y, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function atan2 """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, x], _ctx) (y, x) = _inputs_T _inputs_flat = [y, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Atan2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Atan2", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.atanh', 'atanh') def atanh(x, name=None): r"""Computes inverse hyperbolic tangent of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Atanh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Atanh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Atanh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return atanh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def atanh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function atanh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Atanh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Atanh", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_mat_mul(x, y, adj_x=False, adj_y=False, name=None): r"""Multiplies slices of two tensors in batches. Multiplies all slices of `Tensor` `x` and `y` (each slice can be viewed as an element of a batch), and arranges the individual results in a single output tensor of the same batch size. Each of the individual slices can optionally be adjointed (to adjoint a matrix means to transpose and conjugate it) before multiplication by setting the `adj_x` or `adj_y` flag to `True`, which are by default `False`. The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` and `[..., r_y, c_y]`. The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: r_o = c_x if adj_x else r_x c_o = r_y if adj_y else c_y It is computed as: output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `complex64`, `complex128`. 2-D or higher with shape `[..., r_x, c_x]`. y: A `Tensor`. Must have the same type as `x`. 2-D or higher with shape `[..., r_y, c_y]`. adj_x: An optional `bool`. Defaults to `False`. If `True`, adjoint the slices of `x`. Defaults to `False`. adj_y: An optional `bool`. Defaults to `False`. If `True`, adjoint the slices of `y`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if adj_x is None: adj_x = False adj_x = _execute.make_bool(adj_x, "adj_x") if adj_y is None: adj_y = False adj_y = _execute.make_bool(adj_y, "adj_y") _, _, _op = _op_def_lib._apply_op_helper( "BatchMatMul", x=x, y=y, adj_x=adj_x, adj_y=adj_y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "adj_x", _op.get_attr("adj_x"), "adj_y", _op.get_attr("adj_y")) _execute.record_gradient( "BatchMatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchMatMul", name, _ctx._post_execution_callbacks, x, y, "adj_x", adj_x, "adj_y", adj_y) return _result except _core._FallbackException: return batch_mat_mul_eager_fallback( x, y, adj_x=adj_x, adj_y=adj_y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def batch_mat_mul_eager_fallback(x, y, adj_x=False, adj_y=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_mat_mul """ _ctx = ctx if ctx else _context.context() if adj_x is None: adj_x = False adj_x = _execute.make_bool(adj_x, "adj_x") if adj_y is None: adj_y = False adj_y = _execute.make_bool(adj_y, "adj_y") _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T, "adj_x", adj_x, "adj_y", adj_y) _result = _execute.execute(b"BatchMatMul", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchMatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result def bessel_i0e(x, name=None): r"""Computes the Bessel i0e function of `x` element-wise. Exponentially scaled modified Bessel function of order 0 defined as `bessel_i0e(x) = exp(-abs(x)) bessel_i0(x)`. This function is faster and numerically stabler than `bessel_i0(x)`. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "BesselI0e", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BesselI0e", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BesselI0e", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return bessel_i0e_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def bessel_i0e_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function bessel_i0e """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"BesselI0e", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BesselI0e", _inputs_flat, _attrs, _result, name) _result, = _result return _result def bessel_i1e(x, name=None): r"""Computes the Bessel i1e function of `x` element-wise. Exponentially scaled modified Bessel function of order 0 defined as `bessel_i1e(x) = exp(-abs(x)) bessel_i1(x)`. This function is faster and numerically stabler than `bessel_i1(x)`. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "BesselI1e", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BesselI1e", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BesselI1e", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return bessel_i1e_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def bessel_i1e_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function bessel_i1e """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"BesselI1e", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BesselI1e", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.betainc', 'betainc') def betainc(a, b, x, name=None): r"""Compute the regularized incomplete beta integral \\(I_x(a, b)\\). The regularized incomplete beta integral is defined as: \\(I_x(a, b) = \frac{B(x; a, b)}{B(a, b)}\\) where \\(B(x; a, b) = \int_0^x t^{a-1} (1 - t)^{b-1} dt\\) is the incomplete beta function and \\(B(a, b)\\) is the *complete* beta function. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`. b: A `Tensor`. Must have the same type as `a`. x: A `Tensor`. Must have the same type as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Betainc", a=a, b=b, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Betainc", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Betainc", name, _ctx._post_execution_callbacks, a, b, x) return _result except _core._FallbackException: return betainc_eager_fallback( a, b, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def betainc_eager_fallback(a, b, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function betainc """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b, x], _ctx) (a, b, x) = _inputs_T _inputs_flat = [a, b, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Betainc", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Betainc", _inputs_flat, _attrs, _result, name) _result, = _result return _result def bincount(arr, size, weights, name=None): r"""Counts the number of occurrences of each value in an integer array. Outputs a vector with length `size` and the same dtype as `weights`. If `weights` are empty, then index `i` stores the number of times the value `i` is counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of the value in `weights` at each index where the corresponding value in `arr` is `i`. Values in `arr` outside of the range [0, size) are ignored. Args: arr: A `Tensor` of type `int32`. int32 `Tensor`. size: A `Tensor` of type `int32`. non-negative int32 scalar `Tensor`. weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. is an int32, int64, float32, or float64 `Tensor` with the same shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights equal to 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `weights`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Bincount", arr=arr, size=size, weights=weights, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Bincount", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Bincount", name, _ctx._post_execution_callbacks, arr, size, weights) return _result except _core._FallbackException: return bincount_eager_fallback( arr, size, weights, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def bincount_eager_fallback(arr, size, weights, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function bincount """ _ctx = ctx if ctx else _context.context() _attr_T, (weights,) = _execute.args_to_matching_eager([weights], _ctx) arr = _ops.convert_to_tensor(arr, _dtypes.int32) size = _ops.convert_to_tensor(size, _dtypes.int32) _inputs_flat = [arr, size, weights] _attrs = ("T", _attr_T) _result = _execute.execute(b"Bincount", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Bincount", _inputs_flat, _attrs, _result, name) _result, = _result return _result def bucketize(input, boundaries, name=None): r"""Bucketizes 'input' based on 'boundaries'. For example, if the inputs are boundaries = [0, 10, 100] input = [[-5, 10000] [150, 10] [5, 100]] then the output will be output = [[0, 3] [3, 2] [1, 3]] Args: input: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. Any shape of Tensor contains with int or float type. boundaries: A list of `floats`. A sorted list of floats gives the boundary of the buckets. name: A name for the operation (optional). Returns: A `Tensor` of type `int32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(boundaries, (list, tuple)): raise TypeError( "Expected list for 'boundaries' argument to " "'bucketize' Op, not %r." % boundaries) boundaries = [_execute.make_float(_f, "boundaries") for _f in boundaries] _, _, _op = _op_def_lib._apply_op_helper( "Bucketize", input=input, boundaries=boundaries, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "boundaries", _op.get_attr("boundaries")) _execute.record_gradient( "Bucketize", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Bucketize", name, _ctx._post_execution_callbacks, input, "boundaries", boundaries) return _result except _core._FallbackException: return bucketize_eager_fallback( input, boundaries=boundaries, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def bucketize_eager_fallback(input, boundaries, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function bucketize """ _ctx = ctx if ctx else _context.context() if not isinstance(boundaries, (list, tuple)): raise TypeError( "Expected list for 'boundaries' argument to " "'bucketize' Op, not %r." % boundaries) boundaries = [_execute.make_float(_f, "boundaries") for _f in boundaries] _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "boundaries", boundaries) _result = _execute.execute(b"Bucketize", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Bucketize", _inputs_flat, _attrs, _result, name) _result, = _result return _result def cast(x, DstT, name=None): r"""Cast x of type SrcT to y of DstT. Args: x: A `Tensor`. DstT: A `tf.DType`. name: A name for the operation (optional). Returns: A `Tensor` of type `DstT`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: DstT = _execute.make_type(DstT, "DstT") _, _, _op = _op_def_lib._apply_op_helper( "Cast", x=x, DstT=DstT, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("SrcT", _op.get_attr("SrcT"), "DstT", _op.get_attr("DstT")) _execute.record_gradient( "Cast", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cast", name, _ctx._post_execution_callbacks, x, "DstT", DstT) return _result except _core._FallbackException: return cast_eager_fallback( x, DstT=DstT, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cast_eager_fallback(x, DstT, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cast """ _ctx = ctx if ctx else _context.context() DstT = _execute.make_type(DstT, "DstT") _attr_SrcT, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("SrcT", _attr_SrcT, "DstT", DstT) _result = _execute.execute(b"Cast", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cast", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.ceil', 'ceil') def ceil(x, name=None): r"""Returns element-wise smallest integer in not less than x. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Ceil", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Ceil", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Ceil", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return ceil_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def ceil_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function ceil """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Ceil", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Ceil", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _clip_by_value(t, clip_value_min, clip_value_max, name=None): r"""Clips tensor values to a specified min and max. Given a tensor `t`, this operation returns a tensor of the same type and shape as `t` with its values clipped to `clip_value_min` and `clip_value_max`. Any values less than `clip_value_min` are set to `clip_value_min`. Any values greater than `clip_value_max` are set to `clip_value_max`. Args: t: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. A `Tensor`. clip_value_min: A `Tensor`. Must have the same type as `t`. A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape as `t`. The minimum value to clip by. clip_value_max: A `Tensor`. Must have the same type as `t`. A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape as `t`. The maximum value to clip by. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `t`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "ClipByValue", t=t, clip_value_min=clip_value_min, clip_value_max=clip_value_max, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "ClipByValue", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ClipByValue", name, _ctx._post_execution_callbacks, t, clip_value_min, clip_value_max) return _result except _core._FallbackException: return _clip_by_value_eager_fallback( t, clip_value_min, clip_value_max, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _clip_by_value_eager_fallback(t, clip_value_min, clip_value_max, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _clip_by_value """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([t, clip_value_min, clip_value_max], _ctx) (t, clip_value_min, clip_value_max) = _inputs_T _inputs_flat = [t, clip_value_min, clip_value_max] _attrs = ("T", _attr_T) _result = _execute.execute(b"ClipByValue", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ClipByValue", _inputs_flat, _attrs, _result, name) _result, = _result return _result def compare_and_bitpack(input, threshold, name=None): r"""Compare values of `input` to `threshold` and pack resulting bits into a `uint8`. Each comparison returns a boolean `true` (if `input_value > threshold`) or and `false` otherwise. This operation is useful for Locality-Sensitive-Hashing (LSH) and other algorithms that use hashing approximations of cosine and `L2` distances; codes can be generated from an input via: ```python codebook_size = 50 codebook_bits = codebook_size * 32 codebook = tf.get_variable('codebook', [x.shape[-1].value, codebook_bits], dtype=x.dtype, initializer=tf.orthogonal_initializer()) codes = compare_and_threshold(tf.matmul(x, codebook), threshold=0.) codes = tf.bitcast(codes, tf.int32) # go from uint8 to int32 # now codes has shape x.shape[:-1] + [codebook_size] ``` **NOTE**: Currently, the innermost dimension of the tensor must be divisible by 8. Given an `input` shaped `[s0, s1, ..., s_n]`, the output is a `uint8` tensor shaped `[s0, s1, ..., s_n / 8]`. Args: input: A `Tensor`. Must be one of the following types: `bool`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`. Values to compare against `threshold` and bitpack. threshold: A `Tensor`. Must have the same type as `input`. Threshold to compare against. name: A name for the operation (optional). Returns: A `Tensor` of type `uint8`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "CompareAndBitpack", input=input, threshold=threshold, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "CompareAndBitpack", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "CompareAndBitpack", name, _ctx._post_execution_callbacks, input, threshold) return _result except _core._FallbackException: return compare_and_bitpack_eager_fallback( input, threshold, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def compare_and_bitpack_eager_fallback(input, threshold, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function compare_and_bitpack """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([input, threshold], _ctx) (input, threshold) = _inputs_T _inputs_flat = [input, threshold] _attrs = ("T", _attr_T) _result = _execute.execute(b"CompareAndBitpack", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "CompareAndBitpack", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _complex(real, imag, Tout=_dtypes.complex64, name=None): r"""Converts two real numbers to a complex number. Given a tensor `real` representing the real part of a complex number, and a tensor `imag` representing the imaginary part of a complex number, this operation returns complex numbers elementwise of the form \\(a + bj\\), where *a* represents the `real` part and *b* represents the `imag` part. The input tensors `real` and `imag` must have the same shape. For example: ``` # tensor 'real' is [2.25, 3.25] # tensor `imag` is [4.75, 5.75] tf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]] ``` Args: real: A `Tensor`. Must be one of the following types: `float32`, `float64`. imag: A `Tensor`. Must have the same type as `real`. Tout: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. name: A name for the operation (optional). Returns: A `Tensor` of type `Tout`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Tout is None: Tout = _dtypes.complex64 Tout = _execute.make_type(Tout, "Tout") _, _, _op = _op_def_lib._apply_op_helper( "Complex", real=real, imag=imag, Tout=Tout, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tout", _op.get_attr("Tout")) _execute.record_gradient( "Complex", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Complex", name, _ctx._post_execution_callbacks, real, imag, "Tout", Tout) return _result except _core._FallbackException: return _complex_eager_fallback( real, imag, Tout=Tout, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _complex_eager_fallback(real, imag, Tout=_dtypes.complex64, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _complex """ _ctx = ctx if ctx else _context.context() if Tout is None: Tout = _dtypes.complex64 Tout = _execute.make_type(Tout, "Tout") _attr_T, _inputs_T = _execute.args_to_matching_eager([real, imag], _ctx, _dtypes.float32) (real, imag) = _inputs_T _inputs_flat = [real, imag] _attrs = ("T", _attr_T, "Tout", Tout) _result = _execute.execute(b"Complex", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Complex", _inputs_flat, _attrs, _result, name) _result, = _result return _result def complex_abs(x, Tout=_dtypes.float32, name=None): r"""Computes the complex absolute value of a tensor. Given a tensor `x` of complex numbers, this operation returns a tensor of type `float` or `double` that is the absolute value of each element in `x`. All elements in `x` must be complex numbers of the form \\(a + bj\\). The absolute value is computed as \\( \sqrt{a^2 + b^2}\\). Args: x: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. name: A name for the operation (optional). Returns: A `Tensor` of type `Tout`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _, _, _op = _op_def_lib._apply_op_helper( "ComplexAbs", x=x, Tout=Tout, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tout", _op.get_attr("Tout")) _execute.record_gradient( "ComplexAbs", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ComplexAbs", name, _ctx._post_execution_callbacks, x, "Tout", Tout) return _result except _core._FallbackException: return complex_abs_eager_fallback( x, Tout=Tout, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def complex_abs_eager_fallback(x, Tout=_dtypes.float32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function complex_abs """ _ctx = ctx if ctx else _context.context() if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx, _dtypes.complex64) _inputs_flat = [x] _attrs = ("T", _attr_T, "Tout", Tout) _result = _execute.execute(b"ComplexAbs", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ComplexAbs", _inputs_flat, _attrs, _result, name) _result, = _result return _result def conj(input, name=None): r"""Returns the complex conjugate of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of complex numbers that are the complex conjugate of each element in `input`. The complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. The complex conjugate returned by this operation is of the form \\(a - bj\\). For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j] ``` Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`, `variant`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Conj", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Conj", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Conj", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: return conj_eager_fallback( input, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def conj_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function conj """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx, _dtypes.complex64) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"Conj", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Conj", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.cos', 'cos') def cos(x, name=None): r"""Computes cos of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Cos", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Cos", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cos", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return cos_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cos_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cos """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Cos", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cos", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.cosh', 'cosh') def cosh(x, name=None): r"""Computes hyperbolic cosine of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Cosh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Cosh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cosh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return cosh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cosh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cosh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Cosh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cosh", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('linalg.cross', 'cross') def cross(a, b, name=None): r"""Compute the pairwise cross product. `a` and `b` must be the same shape; they can either be simple 3-element vectors, or any shape where the innermost dimension is 3. In the latter case, each pair of corresponding 3-element vectors is cross-multiplied independently. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. A tensor containing 3-element vectors. b: A `Tensor`. Must have the same type as `a`. Another tensor, of same type and shape as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Cross", a=a, b=b, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Cross", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cross", name, _ctx._post_execution_callbacks, a, b) return _result except _core._FallbackException: return cross_eager_fallback( a, b, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cross_eager_fallback(a, b, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cross """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], _ctx) (a, b) = _inputs_T _inputs_flat = [a, b] _attrs = ("T", _attr_T) _result = _execute.execute(b"Cross", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cross", _inputs_flat, _attrs, _result, name) _result, = _result return _result def cumprod(x, axis, exclusive=False, reverse=False, name=None): r"""Compute the cumulative product of the tensor `x` along `axis`. By default, this op performs an inclusive cumprod, which means that the first element of the input is identical to the first element of the output: ```python tf.cumprod([a, b, c]) # => [a, a * b, a * b * c] ``` By setting the `exclusive` kwarg to `True`, an exclusive cumprod is performed instead: ```python tf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b] ``` By setting the `reverse` kwarg to `True`, the cumprod is performed in the opposite direction: ```python tf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c] ``` This is more efficient than using separate `tf.reverse` ops. The `reverse` and `exclusive` kwargs can also be combined: ```python tf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1] ``` Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. A `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. A `Tensor` of type `int32` (default: 0). Must be in the range `[-rank(x), rank(x))`. exclusive: An optional `bool`. Defaults to `False`. If `True`, perform exclusive cumprod. reverse: An optional `bool`. Defaults to `False`. A `bool` (default: False). name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if exclusive is None: exclusive = False exclusive = _execute.make_bool(exclusive, "exclusive") if reverse is None: reverse = False reverse = _execute.make_bool(reverse, "reverse") _, _, _op = _op_def_lib._apply_op_helper( "Cumprod", x=x, axis=axis, exclusive=exclusive, reverse=reverse, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("exclusive", _op.get_attr("exclusive"), "reverse", _op.get_attr("reverse"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Cumprod", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cumprod", name, _ctx._post_execution_callbacks, x, axis, "exclusive", exclusive, "reverse", reverse) return _result except _core._FallbackException: return cumprod_eager_fallback( x, axis, exclusive=exclusive, reverse=reverse, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cumprod_eager_fallback(x, axis, exclusive=False, reverse=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cumprod """ _ctx = ctx if ctx else _context.context() if exclusive is None: exclusive = False exclusive = _execute.make_bool(exclusive, "exclusive") if reverse is None: reverse = False reverse = _execute.make_bool(reverse, "reverse") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [x, axis] _attrs = ("exclusive", exclusive, "reverse", reverse, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Cumprod", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cumprod", _inputs_flat, _attrs, _result, name) _result, = _result return _result def cumsum(x, axis, exclusive=False, reverse=False, name=None): r"""Compute the cumulative sum of the tensor `x` along `axis`. By default, this op performs an inclusive cumsum, which means that the first element of the input is identical to the first element of the output: ```python tf.cumsum([a, b, c]) # => [a, a + b, a + b + c] ``` By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed instead: ```python tf.cumsum([a, b, c], exclusive=True) # => [0, a, a + b] ``` By setting the `reverse` kwarg to `True`, the cumsum is performed in the opposite direction: ```python tf.cumsum([a, b, c], reverse=True) # => [a + b + c, b + c, c] ``` This is more efficient than using separate `tf.reverse` ops. The `reverse` and `exclusive` kwargs can also be combined: ```python tf.cumsum([a, b, c], exclusive=True, reverse=True) # => [b + c, c, 0] ``` Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. A `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. A `Tensor` of type `int32` (default: 0). Must be in the range `[-rank(x), rank(x))`. exclusive: An optional `bool`. Defaults to `False`. If `True`, perform exclusive cumsum. reverse: An optional `bool`. Defaults to `False`. A `bool` (default: False). name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if exclusive is None: exclusive = False exclusive = _execute.make_bool(exclusive, "exclusive") if reverse is None: reverse = False reverse = _execute.make_bool(reverse, "reverse") _, _, _op = _op_def_lib._apply_op_helper( "Cumsum", x=x, axis=axis, exclusive=exclusive, reverse=reverse, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("exclusive", _op.get_attr("exclusive"), "reverse", _op.get_attr("reverse"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Cumsum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cumsum", name, _ctx._post_execution_callbacks, x, axis, "exclusive", exclusive, "reverse", reverse) return _result except _core._FallbackException: return cumsum_eager_fallback( x, axis, exclusive=exclusive, reverse=reverse, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def cumsum_eager_fallback(x, axis, exclusive=False, reverse=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function cumsum """ _ctx = ctx if ctx else _context.context() if exclusive is None: exclusive = False exclusive = _execute.make_bool(exclusive, "exclusive") if reverse is None: reverse = False reverse = _execute.make_bool(reverse, "reverse") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [x, axis] _attrs = ("exclusive", exclusive, "reverse", reverse, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Cumsum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Cumsum", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.digamma', 'digamma') def digamma(x, name=None): r"""Computes Psi, the derivative of Lgamma (the log of the absolute value of `Gamma(x)`), element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Digamma", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Digamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Digamma", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return digamma_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def digamma_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function digamma """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Digamma", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Digamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result def div(x, y, name=None): r"""Returns x / y element-wise. *NOTE*: `Div` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Div", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Div", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Div", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return div_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def div_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function div """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Div", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Div", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.equal', 'equal') def equal(x, y, name=None): r"""Returns the truth value of (x == y) element-wise. *NOTE*: `math.equal` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Equal", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Equal", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Equal", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return equal_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def equal_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function equal """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Equal", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Equal", _inputs_flat, _attrs, _result, name) _result, = _result return _result def erf(x, name=None): r"""Computes the Gauss error function of `x` element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Erf", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Erf", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Erf", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return erf_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def erf_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function erf """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Erf", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Erf", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.erfc', 'erfc') def erfc(x, name=None): r"""Computes the complementary error function of `x` element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Erfc", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Erfc", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Erfc", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return erfc_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def erfc_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function erfc """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Erfc", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Erfc", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.exp', 'exp') def exp(x, name=None): r"""Computes exponential of x element-wise. \\(y = e^x\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Exp", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Exp", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Exp", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return exp_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def exp_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function exp """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Exp", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Exp", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.expm1', 'expm1') def expm1(x, name=None): r"""Computes exponential of x - 1 element-wise. I.e., \\(y = (\exp x) - 1\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Expm1", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Expm1", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Expm1", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return expm1_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def expm1_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function expm1 """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Expm1", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Expm1", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.floor', 'floor') def floor(x, name=None): r"""Returns element-wise largest integer not greater than x. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Floor", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Floor", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Floor", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return floor_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def floor_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function floor """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Floor", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Floor", _inputs_flat, _attrs, _result, name) _result, = _result return _result def floor_div(x, y, name=None): r"""Returns x // y element-wise. *NOTE*: `FloorDiv` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "FloorDiv", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "FloorDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FloorDiv", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return floor_div_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def floor_div_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function floor_div """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"FloorDiv", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FloorDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result def floor_mod(x, y, name=None): r"""Returns element-wise remainder of division. When `x < 0` xor `y < 0` is true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`. *NOTE*: `FloorMod` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `int32`, `int64`, `bfloat16`, `half`, `float32`, `float64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "FloorMod", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "FloorMod", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FloorMod", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return floor_mod_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def floor_mod_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function floor_mod """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"FloorMod", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FloorMod", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.greater', 'greater') def greater(x, y, name=None): r"""Returns the truth value of (x > y) element-wise. *NOTE*: `math.greater` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Greater", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Greater", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Greater", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return greater_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def greater_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function greater """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Greater", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Greater", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.greater_equal', 'greater_equal') def greater_equal(x, y, name=None): r"""Returns the truth value of (x >= y) element-wise. *NOTE*: `math.greater_equal` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "GreaterEqual", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "GreaterEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "GreaterEqual", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return greater_equal_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def greater_equal_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function greater_equal """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"GreaterEqual", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "GreaterEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _histogram_fixed_width(values, value_range, nbins, dtype=_dtypes.int32, name=None): r"""Return histogram of values. Given the tensor `values`, this operation returns a rank 1 histogram counting the number of entries in `values` that fall into every bin. The bins are equal width and determined by the arguments `value_range` and `nbins`. ```python # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) nbins = 5 value_range = [0.0, 5.0] new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] with tf.get_default_session() as sess: hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) variables.global_variables_initializer().run() sess.run(hist) => [2, 1, 1, 0, 2] ``` Args: values: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. Numeric `Tensor`. value_range: A `Tensor`. Must have the same type as `values`. Shape [2] `Tensor` of same `dtype` as `values`. values <= value_range[0] will be mapped to hist[0], values >= value_range[1] will be mapped to hist[-1]. nbins: A `Tensor` of type `int32`. Scalar `int32 Tensor`. Number of histogram bins. dtype: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if dtype is None: dtype = _dtypes.int32 dtype = _execute.make_type(dtype, "dtype") _, _, _op = _op_def_lib._apply_op_helper( "HistogramFixedWidth", values=values, value_range=value_range, nbins=nbins, dtype=dtype, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "dtype", _op.get_attr("dtype")) _execute.record_gradient( "HistogramFixedWidth", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "HistogramFixedWidth", name, _ctx._post_execution_callbacks, values, value_range, nbins, "dtype", dtype) return _result except _core._FallbackException: return _histogram_fixed_width_eager_fallback( values, value_range, nbins, dtype=dtype, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _histogram_fixed_width_eager_fallback(values, value_range, nbins, dtype=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _histogram_fixed_width """ _ctx = ctx if ctx else _context.context() if dtype is None: dtype = _dtypes.int32 dtype = _execute.make_type(dtype, "dtype") _attr_T, _inputs_T = _execute.args_to_matching_eager([values, value_range], _ctx) (values, value_range) = _inputs_T nbins = _ops.convert_to_tensor(nbins, _dtypes.int32) _inputs_flat = [values, value_range, nbins] _attrs = ("T", _attr_T, "dtype", dtype) _result = _execute.execute(b"HistogramFixedWidth", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "HistogramFixedWidth", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.igamma', 'igamma') def igamma(a, x, name=None): r"""Compute the lower regularized incomplete Gamma function `Q(a, x)`. The lower regularized incomplete Gamma function is defined as: \\(P(a, x) = gamma(a, x) / Gamma(a) = 1 - Q(a, x)\\) where \\(gamma(a, x) = int_{0}^{x} t^{a-1} exp(-t) dt\\) is the lower incomplete Gamma function. Note, above `Q(a, x)` (`Igammac`) is the upper regularized complete Gamma function. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`. x: A `Tensor`. Must have the same type as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Igamma", a=a, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Igamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Igamma", name, _ctx._post_execution_callbacks, a, x) return _result except _core._FallbackException: return igamma_eager_fallback( a, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def igamma_eager_fallback(a, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function igamma """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], _ctx) (a, x) = _inputs_T _inputs_flat = [a, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Igamma", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Igamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result def igamma_grad_a(a, x, name=None): r"""Computes the gradient of `igamma(a, x)` wrt `a`. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`. x: A `Tensor`. Must have the same type as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "IgammaGradA", a=a, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "IgammaGradA", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "IgammaGradA", name, _ctx._post_execution_callbacks, a, x) return _result except _core._FallbackException: return igamma_grad_a_eager_fallback( a, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def igamma_grad_a_eager_fallback(a, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function igamma_grad_a """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], _ctx) (a, x) = _inputs_T _inputs_flat = [a, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"IgammaGradA", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "IgammaGradA", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.igammac', 'igammac') def igammac(a, x, name=None): r"""Compute the upper regularized incomplete Gamma function `Q(a, x)`. The upper regularized incomplete Gamma function is defined as: \\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\) where \\(Gamma(a, x) = int_{x}^{\infty} t^{a-1} exp(-t) dt\\) is the upper incomplete Gama function. Note, above `P(a, x)` (`Igamma`) is the lower regularized complete Gamma function. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`. x: A `Tensor`. Must have the same type as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Igammac", a=a, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Igammac", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Igammac", name, _ctx._post_execution_callbacks, a, x) return _result except _core._FallbackException: return igammac_eager_fallback( a, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def igammac_eager_fallback(a, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function igammac """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], _ctx) (a, x) = _inputs_T _inputs_flat = [a, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Igammac", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Igammac", _inputs_flat, _attrs, _result, name) _result, = _result return _result def imag(input, Tout=_dtypes.float32, name=None): r"""Returns the imaginary part of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of type `float` that is the imaginary part of each element in `input`. All elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part returned by this operation. For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.imag(input) ==> [4.75, 5.75] ``` Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. name: A name for the operation (optional). Returns: A `Tensor` of type `Tout`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _, _, _op = _op_def_lib._apply_op_helper( "Imag", input=input, Tout=Tout, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tout", _op.get_attr("Tout")) _execute.record_gradient( "Imag", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Imag", name, _ctx._post_execution_callbacks, input, "Tout", Tout) return _result except _core._FallbackException: return imag_eager_fallback( input, Tout=Tout, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def imag_eager_fallback(input, Tout=_dtypes.float32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function imag """ _ctx = ctx if ctx else _context.context() if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx, _dtypes.complex64) _inputs_flat = [input] _attrs = ("T", _attr_T, "Tout", Tout) _result = _execute.execute(b"Imag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Imag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inv(x, name=None): r"""Computes the reciprocal of x element-wise. I.e., \\(y = 1 / x\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Inv", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Inv", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Inv", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return inv_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def inv_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function inv """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Inv", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Inv", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inv_grad(y, dy, name=None): r"""Computes the gradient for the inverse of `x` wrt its input. Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "InvGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "InvGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "InvGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return inv_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def inv_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function inv_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"InvGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "InvGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('debugging.is_finite', 'is_finite') def is_finite(x, name=None): r"""Returns which elements of x are finite. @compatibility(numpy) Equivalent to np.isfinite @end_compatibility Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "IsFinite", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "IsFinite", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "IsFinite", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return is_finite_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def is_finite_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function is_finite """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"IsFinite", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "IsFinite", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('debugging.is_inf', 'is_inf') def is_inf(x, name=None): r"""Returns which elements of x are Inf. @compatibility(numpy) Equivalent to np.isinf @end_compatibility Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "IsInf", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "IsInf", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "IsInf", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return is_inf_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def is_inf_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function is_inf """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"IsInf", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "IsInf", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('debugging.is_nan', 'is_nan') def is_nan(x, name=None): r"""Returns which elements of x are NaN. @compatibility(numpy) Equivalent to np.isnan @end_compatibility Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "IsNan", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "IsNan", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "IsNan", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return is_nan_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def is_nan_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function is_nan """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"IsNan", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "IsNan", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.less', 'less') def less(x, y, name=None): r"""Returns the truth value of (x < y) element-wise. *NOTE*: `math.less` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Less", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Less", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Less", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return less_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def less_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function less """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Less", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Less", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.less_equal', 'less_equal') def less_equal(x, y, name=None): r"""Returns the truth value of (x <= y) element-wise. *NOTE*: `math.less_equal` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "LessEqual", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "LessEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LessEqual", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return less_equal_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def less_equal_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function less_equal """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"LessEqual", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LessEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.lgamma', 'lgamma') def lgamma(x, name=None): r"""Computes the log of the absolute value of `Gamma(x)` element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Lgamma", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Lgamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Lgamma", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return lgamma_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def lgamma_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function lgamma """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Lgamma", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Lgamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('lin_space', 'linspace') def lin_space(start, stop, num, name=None): r"""Generates values in an interval. A sequence of `num` evenly-spaced values are generated beginning at `start`. If `num > 1`, the values in the sequence increase by `stop - start / num - 1`, so that the last one is exactly `stop`. For example: ``` tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0] ``` Args: start: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `float64`. 0-D tensor. First entry in the range. stop: A `Tensor`. Must have the same type as `start`. 0-D tensor. Last entry in the range. num: A `Tensor`. Must be one of the following types: `int32`, `int64`. 0-D tensor. Number of values to generate. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `start`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "LinSpace", start=start, stop=stop, num=num, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "LinSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LinSpace", name, _ctx._post_execution_callbacks, start, stop, num) return _result except _core._FallbackException: return lin_space_eager_fallback( start, stop, num, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def lin_space_eager_fallback(start, stop, num, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function lin_space """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([start, stop], _ctx) (start, stop) = _inputs_T _attr_Tidx, (num,) = _execute.args_to_matching_eager([num], _ctx, _dtypes.int32) _inputs_flat = [start, stop, num] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"LinSpace", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LinSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.log', 'log') def log(x, name=None): r"""Computes natural logarithm of x element-wise. I.e., \\(y = \log_e x\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Log", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Log", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Log", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return log_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def log_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function log """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Log", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Log", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.log1p', 'log1p') def log1p(x, name=None): r"""Computes natural logarithm of (1 + x) element-wise. I.e., \\(y = \log_e (1 + x)\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Log1p", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Log1p", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Log1p", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return log1p_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def log1p_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function log1p """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Log1p", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Log1p", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.logical_and', 'logical_and') def logical_and(x, y, name=None): r"""Returns the truth value of x AND y element-wise. *NOTE*: `math.logical_and` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor` of type `bool`. y: A `Tensor` of type `bool`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "LogicalAnd", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = None _execute.record_gradient( "LogicalAnd", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LogicalAnd", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return logical_and_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def logical_and_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function logical_and """ _ctx = ctx if ctx else _context.context() x = _ops.convert_to_tensor(x, _dtypes.bool) y = _ops.convert_to_tensor(y, _dtypes.bool) _inputs_flat = [x, y] _attrs = None _result = _execute.execute(b"LogicalAnd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LogicalAnd", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.logical_not', 'logical_not') def logical_not(x, name=None): r"""Returns the truth value of NOT x element-wise. Args: x: A `Tensor` of type `bool`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "LogicalNot", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = None _execute.record_gradient( "LogicalNot", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LogicalNot", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return logical_not_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def logical_not_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function logical_not """ _ctx = ctx if ctx else _context.context() x = _ops.convert_to_tensor(x, _dtypes.bool) _inputs_flat = [x] _attrs = None _result = _execute.execute(b"LogicalNot", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LogicalNot", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.logical_or', 'logical_or') def logical_or(x, y, name=None): r"""Returns the truth value of x OR y element-wise. *NOTE*: `math.logical_or` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor` of type `bool`. y: A `Tensor` of type `bool`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "LogicalOr", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = None _execute.record_gradient( "LogicalOr", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LogicalOr", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return logical_or_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def logical_or_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function logical_or """ _ctx = ctx if ctx else _context.context() x = _ops.convert_to_tensor(x, _dtypes.bool) y = _ops.convert_to_tensor(y, _dtypes.bool) _inputs_flat = [x, y] _attrs = None _result = _execute.execute(b"LogicalOr", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LogicalOr", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mat_mul(a, b, transpose_a=False, transpose_b=False, name=None): r"""Multiply the matrix "a" by the matrix "b". The inputs must be two-dimensional matrices and the inner dimension of "a" (after being transposed if transpose_a is true) must match the outer dimension of "b" (after being transposed if transposed_b is true). *Note*: The default kernel implementation for MatMul on GPUs uses cublas. Args: a: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `complex64`, `complex128`. b: A `Tensor`. Must have the same type as `a`. transpose_a: An optional `bool`. Defaults to `False`. If true, "a" is transposed before multiplication. transpose_b: An optional `bool`. Defaults to `False`. If true, "b" is transposed before multiplication. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") _, _, _op = _op_def_lib._apply_op_helper( "MatMul", a=a, b=b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("transpose_a", _op.get_attr("transpose_a"), "transpose_b", _op.get_attr("transpose_b"), "T", _op.get_attr("T")) _execute.record_gradient( "MatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MatMul", name, _ctx._post_execution_callbacks, a, b, "transpose_a", transpose_a, "transpose_b", transpose_b) return _result except _core._FallbackException: return mat_mul_eager_fallback( a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def mat_mul_eager_fallback(a, b, transpose_a=False, transpose_b=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mat_mul """ _ctx = ctx if ctx else _context.context() if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], _ctx) (a, b) = _inputs_T _inputs_flat = [a, b] _attrs = ("transpose_a", transpose_a, "transpose_b", transpose_b, "T", _attr_T) _result = _execute.execute(b"MatMul", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _max(input, axis, keep_dims=False, name=None): r"""Computes the maximum of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Max", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Max", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Max", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return _max_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _max_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _max """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Max", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Max", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.maximum', 'maximum') def maximum(x, y, name=None): r"""Returns the max of x and y (i.e. x > y ? x : y) element-wise. *NOTE*: `math.maximum` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Maximum", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Maximum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Maximum", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return maximum_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def maximum_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function maximum """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Maximum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Maximum", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mean(input, axis, keep_dims=False, name=None): r"""Computes the mean of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Mean", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Mean", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Mean", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return mean_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def mean_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mean """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Mean", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Mean", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _min(input, axis, keep_dims=False, name=None): r"""Computes the minimum of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Min", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Min", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Min", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return _min_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _min_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _min """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Min", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Min", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.minimum', 'minimum') def minimum(x, y, name=None): r"""Returns the min of x and y (i.e. x < y ? x : y) element-wise. *NOTE*: `math.minimum` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Minimum", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Minimum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Minimum", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return minimum_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def minimum_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function minimum """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Minimum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Minimum", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mod(x, y, name=None): r"""Returns element-wise remainder of division. This emulates C semantics in that the result here is consistent with a truncating divide. E.g. `tf.truncatediv(x, y) * y + truncate_mod(x, y) = x`. *NOTE*: `Mod` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `int32`, `int64`, `half`, `half`, `bfloat16`, `float32`, `float64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Mod", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Mod", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Mod", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return mod_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def mod_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mod """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Mod", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Mod", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mul(x, y, name=None): r"""Returns x * y element-wise. *NOTE*: `Multiply` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Mul", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Mul", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Mul", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return mul_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def mul_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mul """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Mul", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Mul", _inputs_flat, _attrs, _result, name) _result, = _result return _result def neg(x, name=None): r"""Computes numerical negative value element-wise. I.e., \\(y = -x\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Neg", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Neg", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Neg", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return neg_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def neg_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function neg """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Neg", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Neg", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.not_equal', 'not_equal') def not_equal(x, y, name=None): r"""Returns the truth value of (x != y) element-wise. *NOTE*: `math.not_equal` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "NotEqual", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "NotEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "NotEqual", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return not_equal_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def not_equal_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function not_equal """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"NotEqual", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "NotEqual", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.polygamma', 'polygamma') def polygamma(a, x, name=None): r"""Compute the polygamma function \\(\psi^{(n)}(x)\\). The polygamma function is defined as: \\(\psi^{(n)}(x) = \frac{d^n}{dx^n} \psi(x)\\) where \\(\psi(x)\\) is the digamma function. Args: a: A `Tensor`. Must be one of the following types: `float32`, `float64`. x: A `Tensor`. Must have the same type as `a`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `a`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Polygamma", a=a, x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Polygamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Polygamma", name, _ctx._post_execution_callbacks, a, x) return _result except _core._FallbackException: return polygamma_eager_fallback( a, x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def polygamma_eager_fallback(a, x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function polygamma """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], _ctx) (a, x) = _inputs_T _inputs_flat = [a, x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Polygamma", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Polygamma", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _pow(x, y, name=None): r"""Computes the power of one value to another. Given a tensor `x` and a tensor `y`, this operation computes \\(x^y\\) for corresponding elements in `x` and `y`. For example: ``` # tensor 'x' is [[2, 2]], [3, 3]] # tensor 'y' is [[8, 16], [2, 3]] tf.pow(x, y) ==> [[256, 65536], [9, 27]] ``` Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Pow", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Pow", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Pow", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return _pow_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _pow_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _pow """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Pow", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Pow", _inputs_flat, _attrs, _result, name) _result, = _result return _result def prod(input, axis, keep_dims=False, name=None): r"""Computes the product of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Prod", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Prod", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Prod", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return prod_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def prod_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function prod """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Prod", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Prod", _inputs_flat, _attrs, _result, name) _result, = _result return _result _quantize_down_and_shrink_range_outputs = ["output", "output_min", "output_max"] _QuantizeDownAndShrinkRangeOutput = _collections.namedtuple( "QuantizeDownAndShrinkRange", _quantize_down_and_shrink_range_outputs) def quantize_down_and_shrink_range(input, input_min, input_max, out_type, name=None): r"""Convert the quantized 'input' tensor into a lower-precision 'output', using the actual distribution of the values to maximize the usage of the lower bit depth and adjusting the output min and max ranges accordingly. [input_min, input_max] are scalar floats that specify the range for the float interpretation of the 'input' data. For example, if input_min is -1.0f and input_max is 1.0f, and we are dealing with quint16 quantized data, then a 0 value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. This operator tries to squeeze as much precision as possible into an output with a lower bit depth by calculating the actual min and max values found in the data. For example, maybe that quint16 input has no values lower than 16,384 and none higher than 49,152. That means only half the range is actually needed, all the float interpretations are between -0.5f and 0.5f, so if we want to compress the data into a quint8 output, we can use that range rather than the theoretical -1.0f to 1.0f that is suggested by the input min and max. In practice, this is most useful for taking output from operations like QuantizedMatMul that can produce higher bit-depth outputs than their inputs and may have large potential output ranges, but in practice have a distribution of input values that only uses a small fraction of the possible range. By feeding that output into this operator, we can reduce it from 32 bits down to 8 with minimal loss of accuracy. Args: input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. input_min: A `Tensor` of type `float32`. The float value that the minimum quantized input value represents. input_max: A `Tensor` of type `float32`. The float value that the maximum quantized input value represents. out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. The type of the output. Should be a lower bit depth than Tinput. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output, output_min, output_max). output: A `Tensor` of type `out_type`. output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "QuantizeDownAndShrinkRange", input=input, input_min=input_min, input_max=input_max, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tinput", _op.get_attr("Tinput"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "QuantizeDownAndShrinkRange", _inputs_flat, _attrs, _result, name) _result = _QuantizeDownAndShrinkRangeOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizeDownAndShrinkRange", name, _ctx._post_execution_callbacks, input, input_min, input_max, "out_type", out_type) _result = _QuantizeDownAndShrinkRangeOutput._make(_result) return _result except _core._FallbackException: return quantize_down_and_shrink_range_eager_fallback( input, input_min, input_max, out_type=out_type, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def quantize_down_and_shrink_range_eager_fallback(input, input_min, input_max, out_type, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantize_down_and_shrink_range """ _ctx = ctx if ctx else _context.context() out_type = _execute.make_type(out_type, "out_type") _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], _ctx) input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) _inputs_flat = [input, input_min, input_max] _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) _result = _execute.execute(b"QuantizeDownAndShrinkRange", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizeDownAndShrinkRange", _inputs_flat, _attrs, _result, name) _result = _QuantizeDownAndShrinkRangeOutput._make(_result) return _result _quantized_add_outputs = ["z", "min_z", "max_z"] _QuantizedAddOutput = _collections.namedtuple( "QuantizedAdd", _quantized_add_outputs) def quantized_add(x, y, min_x, max_x, min_y, max_y, Toutput=_dtypes.qint32, name=None): r"""Returns x + y element-wise, working on quantized buffers. Args: x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. y: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. min_x: A `Tensor` of type `float32`. The float value that the lowest quantized `x` value represents. max_x: A `Tensor` of type `float32`. The float value that the highest quantized `x` value represents. min_y: A `Tensor` of type `float32`. The float value that the lowest quantized `y` value represents. max_y: A `Tensor` of type `float32`. The float value that the highest quantized `y` value represents. Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (z, min_z, max_z). z: A `Tensor` of type `Toutput`. min_z: A `Tensor` of type `float32`. max_z: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") _, _, _op = _op_def_lib._apply_op_helper( "QuantizedAdd", x=x, y=y, min_x=min_x, max_x=max_x, min_y=min_y, max_y=max_y, Toutput=Toutput, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T1", _op.get_attr("T1"), "T2", _op.get_attr("T2"), "Toutput", _op.get_attr("Toutput")) _execute.record_gradient( "QuantizedAdd", _inputs_flat, _attrs, _result, name) _result = _QuantizedAddOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedAdd", name, _ctx._post_execution_callbacks, x, y, min_x, max_x, min_y, max_y, "Toutput", Toutput) _result = _QuantizedAddOutput._make(_result) return _result except _core._FallbackException: return quantized_add_eager_fallback( x, y, min_x, max_x, min_y, max_y, Toutput=Toutput, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def quantized_add_eager_fallback(x, y, min_x, max_x, min_y, max_y, Toutput=_dtypes.qint32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_add """ _ctx = ctx if ctx else _context.context() if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") _attr_T1, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_T2, (y,) = _execute.args_to_matching_eager([y], _ctx) min_x = _ops.convert_to_tensor(min_x, _dtypes.float32) max_x = _ops.convert_to_tensor(max_x, _dtypes.float32) min_y = _ops.convert_to_tensor(min_y, _dtypes.float32) max_y = _ops.convert_to_tensor(max_y, _dtypes.float32) _inputs_flat = [x, y, min_x, max_x, min_y, max_y] _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput) _result = _execute.execute(b"QuantizedAdd", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedAdd", _inputs_flat, _attrs, _result, name) _result = _QuantizedAddOutput._make(_result) return _result _quantized_mat_mul_outputs = ["out", "min_out", "max_out"] _QuantizedMatMulOutput = _collections.namedtuple( "QuantizedMatMul", _quantized_mat_mul_outputs) def quantized_mat_mul(a, b, min_a, max_a, min_b, max_b, Toutput=_dtypes.qint32, transpose_a=False, transpose_b=False, Tactivation=_dtypes.quint8, name=None): r"""Perform a quantized matrix multiplication of `a` by the matrix `b`. The inputs must be two-dimensional matrices and the inner dimension of `a` (after being transposed if `transpose_a` is non-zero) must match the outer dimension of `b` (after being transposed if `transposed_b` is non-zero). Args: a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. Must be a two-dimensional tensor. b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. Must be a two-dimensional tensor. min_a: A `Tensor` of type `float32`. The float value that the lowest quantized `a` value represents. max_a: A `Tensor` of type `float32`. The float value that the highest quantized `a` value represents. min_b: A `Tensor` of type `float32`. The float value that the lowest quantized `b` value represents. max_b: A `Tensor` of type `float32`. The float value that the highest quantized `b` value represents. Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. transpose_a: An optional `bool`. Defaults to `False`. If true, `a` is transposed before multiplication. transpose_b: An optional `bool`. Defaults to `False`. If true, `b` is transposed before multiplication. Tactivation: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. The type of output produced by activation function following this operation. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (out, min_out, max_out). out: A `Tensor` of type `Toutput`. min_out: A `Tensor` of type `float32`. max_out: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") if Tactivation is None: Tactivation = _dtypes.quint8 Tactivation = _execute.make_type(Tactivation, "Tactivation") _, _, _op = _op_def_lib._apply_op_helper( "QuantizedMatMul", a=a, b=b, min_a=min_a, max_a=max_a, min_b=min_b, max_b=max_b, Toutput=Toutput, transpose_a=transpose_a, transpose_b=transpose_b, Tactivation=Tactivation, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T1", _op.get_attr("T1"), "T2", _op.get_attr("T2"), "Toutput", _op.get_attr("Toutput"), "transpose_a", _op.get_attr("transpose_a"), "transpose_b", _op.get_attr("transpose_b"), "Tactivation", _op.get_attr("Tactivation")) _execute.record_gradient( "QuantizedMatMul", _inputs_flat, _attrs, _result, name) _result = _QuantizedMatMulOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedMatMul", name, _ctx._post_execution_callbacks, a, b, min_a, max_a, min_b, max_b, "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, "Tactivation", Tactivation) _result = _QuantizedMatMulOutput._make(_result) return _result except _core._FallbackException: return quantized_mat_mul_eager_fallback( a, b, min_a, max_a, min_b, max_b, Toutput=Toutput, transpose_a=transpose_a, transpose_b=transpose_b, Tactivation=Tactivation, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def quantized_mat_mul_eager_fallback(a, b, min_a, max_a, min_b, max_b, Toutput=_dtypes.qint32, transpose_a=False, transpose_b=False, Tactivation=_dtypes.quint8, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_mat_mul """ _ctx = ctx if ctx else _context.context() if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") if Tactivation is None: Tactivation = _dtypes.quint8 Tactivation = _execute.make_type(Tactivation, "Tactivation") _attr_T1, (a,) = _execute.args_to_matching_eager([a], _ctx) _attr_T2, (b,) = _execute.args_to_matching_eager([b], _ctx) min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) _inputs_flat = [a, b, min_a, max_a, min_b, max_b] _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, "Tactivation", Tactivation) _result = _execute.execute(b"QuantizedMatMul", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedMatMul", _inputs_flat, _attrs, _result, name) _result = _QuantizedMatMulOutput._make(_result) return _result _quantized_mul_outputs = ["z", "min_z", "max_z"] _QuantizedMulOutput = _collections.namedtuple( "QuantizedMul", _quantized_mul_outputs) def quantized_mul(x, y, min_x, max_x, min_y, max_y, Toutput=_dtypes.qint32, name=None): r"""Returns x * y element-wise, working on quantized buffers. Args: x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. y: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. min_x: A `Tensor` of type `float32`. The float value that the lowest quantized `x` value represents. max_x: A `Tensor` of type `float32`. The float value that the highest quantized `x` value represents. min_y: A `Tensor` of type `float32`. The float value that the lowest quantized `y` value represents. max_y: A `Tensor` of type `float32`. The float value that the highest quantized `y` value represents. Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (z, min_z, max_z). z: A `Tensor` of type `Toutput`. min_z: A `Tensor` of type `float32`. max_z: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") _, _, _op = _op_def_lib._apply_op_helper( "QuantizedMul", x=x, y=y, min_x=min_x, max_x=max_x, min_y=min_y, max_y=max_y, Toutput=Toutput, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T1", _op.get_attr("T1"), "T2", _op.get_attr("T2"), "Toutput", _op.get_attr("Toutput")) _execute.record_gradient( "QuantizedMul", _inputs_flat, _attrs, _result, name) _result = _QuantizedMulOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedMul", name, _ctx._post_execution_callbacks, x, y, min_x, max_x, min_y, max_y, "Toutput", Toutput) _result = _QuantizedMulOutput._make(_result) return _result except _core._FallbackException: return quantized_mul_eager_fallback( x, y, min_x, max_x, min_y, max_y, Toutput=Toutput, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def quantized_mul_eager_fallback(x, y, min_x, max_x, min_y, max_y, Toutput=_dtypes.qint32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_mul """ _ctx = ctx if ctx else _context.context() if Toutput is None: Toutput = _dtypes.qint32 Toutput = _execute.make_type(Toutput, "Toutput") _attr_T1, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_T2, (y,) = _execute.args_to_matching_eager([y], _ctx) min_x = _ops.convert_to_tensor(min_x, _dtypes.float32) max_x = _ops.convert_to_tensor(max_x, _dtypes.float32) min_y = _ops.convert_to_tensor(min_y, _dtypes.float32) max_y = _ops.convert_to_tensor(max_y, _dtypes.float32) _inputs_flat = [x, y, min_x, max_x, min_y, max_y] _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput) _result = _execute.execute(b"QuantizedMul", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedMul", _inputs_flat, _attrs, _result, name) _result = _QuantizedMulOutput._make(_result) return _result def _range(start, limit, delta, name=None): r"""Creates a sequence of numbers. This operation creates a sequence of numbers that begins at `start` and extends by increments of `delta` up to but not including `limit`. For example: ``` # 'start' is 3 # 'limit' is 18 # 'delta' is 3 tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15] ``` Args: start: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `float64`, `int32`, `int64`. 0-D (scalar). First entry in the sequence. limit: A `Tensor`. Must have the same type as `start`. 0-D (scalar). Upper limit of sequence, exclusive. delta: A `Tensor`. Must have the same type as `start`. 0-D (scalar). Optional. Default is 1. Number that increments `start`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `start`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Range", start=start, limit=limit, delta=delta, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Range", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Range", name, _ctx._post_execution_callbacks, start, limit, delta) return _result except _core._FallbackException: return _range_eager_fallback( start, limit, delta, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _range_eager_fallback(start, limit, delta, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _range """ _ctx = ctx if ctx else _context.context() _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([start, limit, delta], _ctx, _dtypes.int32) (start, limit, delta) = _inputs_Tidx _inputs_flat = [start, limit, delta] _attrs = ("Tidx", _attr_Tidx) _result = _execute.execute(b"Range", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Range", _inputs_flat, _attrs, _result, name) _result, = _result return _result def real(input, Tout=_dtypes.float32, name=None): r"""Returns the real part of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of type `float` that is the real part of each element in `input`. All elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real part returned by this operation and *b* is the imaginary part. For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.real(input) ==> [-2.25, 3.25] ``` Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. name: A name for the operation (optional). Returns: A `Tensor` of type `Tout`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _, _, _op = _op_def_lib._apply_op_helper( "Real", input=input, Tout=Tout, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tout", _op.get_attr("Tout")) _execute.record_gradient( "Real", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Real", name, _ctx._post_execution_callbacks, input, "Tout", Tout) return _result except _core._FallbackException: return real_eager_fallback( input, Tout=Tout, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def real_eager_fallback(input, Tout=_dtypes.float32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function real """ _ctx = ctx if ctx else _context.context() if Tout is None: Tout = _dtypes.float32 Tout = _execute.make_type(Tout, "Tout") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx, _dtypes.complex64) _inputs_flat = [input] _attrs = ("T", _attr_T, "Tout", Tout) _result = _execute.execute(b"Real", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Real", _inputs_flat, _attrs, _result, name) _result, = _result return _result def real_div(x, y, name=None): r"""Returns x / y element-wise for real types. If `x` and `y` are reals, this will return the floating-point division. *NOTE*: `Div` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "RealDiv", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "RealDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "RealDiv", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return real_div_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def real_div_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function real_div """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"RealDiv", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "RealDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.reciprocal', 'reciprocal') def reciprocal(x, name=None): r"""Computes the reciprocal of x element-wise. I.e., \\(y = 1 / x\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Reciprocal", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Reciprocal", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Reciprocal", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return reciprocal_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def reciprocal_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reciprocal """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Reciprocal", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Reciprocal", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reciprocal_grad(y, dy, name=None): r"""Computes the gradient for the inverse of `x` wrt its input. Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "ReciprocalGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "ReciprocalGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ReciprocalGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return reciprocal_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def reciprocal_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reciprocal_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"ReciprocalGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ReciprocalGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result _requantization_range_outputs = ["output_min", "output_max"] _RequantizationRangeOutput = _collections.namedtuple( "RequantizationRange", _requantization_range_outputs) def requantization_range(input, input_min, input_max, name=None): r"""Given a quantized tensor described by (input, input_min, input_max), outputs a range that covers the actual values present in that tensor. This op is typically used to produce the requested_output_min and requested_output_max for Requantize. Args: input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. input_min: A `Tensor` of type `float32`. The float value that the minimum quantized input value represents. input_max: A `Tensor` of type `float32`. The float value that the maximum quantized input value represents. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output_min, output_max). output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "RequantizationRange", input=input, input_min=input_min, input_max=input_max, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tinput", _op.get_attr("Tinput")) _execute.record_gradient( "RequantizationRange", _inputs_flat, _attrs, _result, name) _result = _RequantizationRangeOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "RequantizationRange", name, _ctx._post_execution_callbacks, input, input_min, input_max) _result = _RequantizationRangeOutput._make(_result) return _result except _core._FallbackException: return requantization_range_eager_fallback( input, input_min, input_max, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def requantization_range_eager_fallback(input, input_min, input_max, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function requantization_range """ _ctx = ctx if ctx else _context.context() _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], _ctx) input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) _inputs_flat = [input, input_min, input_max] _attrs = ("Tinput", _attr_Tinput) _result = _execute.execute(b"RequantizationRange", 2, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "RequantizationRange", _inputs_flat, _attrs, _result, name) _result = _RequantizationRangeOutput._make(_result) return _result _requantize_outputs = ["output", "output_min", "output_max"] _RequantizeOutput = _collections.namedtuple( "Requantize", _requantize_outputs) def requantize(input, input_min, input_max, requested_output_min, requested_output_max, out_type, name=None): r"""Convert the quantized 'input' tensor into a lower-precision 'output', using the output range specified with 'requested_output_min' and 'requested_output_max'. [input_min, input_max] are scalar floats that specify the range for the float interpretation of the 'input' data. For example, if input_min is -1.0f and input_max is 1.0f, and we are dealing with quint16 quantized data, then a 0 value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. Args: input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. input_min: A `Tensor` of type `float32`. The float value that the minimum quantized input value represents. input_max: A `Tensor` of type `float32`. The float value that the maximum quantized input value represents. requested_output_min: A `Tensor` of type `float32`. The float value that the minimum quantized output value represents. requested_output_max: A `Tensor` of type `float32`. The float value that the maximum quantized output value represents. out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. The type of the output. Should be a lower bit depth than Tinput. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output, output_min, output_max). output: A `Tensor` of type `out_type`. output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "Requantize", input=input, input_min=input_min, input_max=input_max, requested_output_min=requested_output_min, requested_output_max=requested_output_max, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tinput", _op.get_attr("Tinput"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "Requantize", _inputs_flat, _attrs, _result, name) _result = _RequantizeOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Requantize", name, _ctx._post_execution_callbacks, input, input_min, input_max, requested_output_min, requested_output_max, "out_type", out_type) _result = _RequantizeOutput._make(_result) return _result except _core._FallbackException: return requantize_eager_fallback( input, input_min, input_max, requested_output_min, requested_output_max, out_type=out_type, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def requantize_eager_fallback(input, input_min, input_max, requested_output_min, requested_output_max, out_type, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function requantize """ _ctx = ctx if ctx else _context.context() out_type = _execute.make_type(out_type, "out_type") _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], _ctx) input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) requested_output_min = _ops.convert_to_tensor(requested_output_min, _dtypes.float32) requested_output_max = _ops.convert_to_tensor(requested_output_max, _dtypes.float32) _inputs_flat = [input, input_min, input_max, requested_output_min, requested_output_max] _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) _result = _execute.execute(b"Requantize", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Requantize", _inputs_flat, _attrs, _result, name) _result = _RequantizeOutput._make(_result) return _result @tf_export('math.rint', 'rint') def rint(x, name=None): r"""Returns element-wise integer closest to x. If the result is midway between two representable values, the even representable is chosen. For example: ``` rint(-1.5) ==> -2.0 rint(0.5000001) ==> 1.0 rint([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) ==> [-2., -2., -0., 0., 2., 2., 2.] ``` Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Rint", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Rint", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Rint", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return rint_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def rint_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function rint """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Rint", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Rint", _inputs_flat, _attrs, _result, name) _result, = _result return _result def round(x, name=None): r"""Rounds the values of a tensor to the nearest integer, element-wise. Rounds half to even. Also known as bankers rounding. If you want to round according to the current system rounding mode use std::cint. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Round", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Round", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Round", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return round_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def round_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function round """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Round", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Round", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.rsqrt', 'rsqrt') def rsqrt(x, name=None): r"""Computes reciprocal of square root of x element-wise. I.e., \\(y = 1 / \sqrt{x}\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Rsqrt", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Rsqrt", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Rsqrt", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return rsqrt_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def rsqrt_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function rsqrt """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Rsqrt", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Rsqrt", _inputs_flat, _attrs, _result, name) _result, = _result return _result def rsqrt_grad(y, dy, name=None): r"""Computes the gradient for the rsqrt of `x` wrt its input. Specifically, `grad = dy * -0.5 * y^3`, where `y = rsqrt(x)`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "RsqrtGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "RsqrtGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "RsqrtGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return rsqrt_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def rsqrt_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function rsqrt_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"RsqrtGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "RsqrtGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.segment_max', 'segment_max') def segment_max(data, segment_ids, name=None): r"""Computes the maximum along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output_i = \max_j(data_j)\\) where `max` is over `j` such that `segment_ids[j] == i`. If the max is empty for a given segment ID `i`, `output[i] = 0`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/SegmentMax.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SegmentMax", data=data, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "SegmentMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SegmentMax", name, _ctx._post_execution_callbacks, data, segment_ids) return _result except _core._FallbackException: return segment_max_eager_fallback( data, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def segment_max_eager_fallback(data, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function segment_max """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _inputs_flat = [data, segment_ids] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"SegmentMax", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SegmentMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.segment_mean', 'segment_mean') def segment_mean(data, segment_ids, name=None): r"""Computes the mean along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output_i = \frac{\sum_j data_j}{N}\\) where `mean` is over `j` such that `segment_ids[j] == i` and `N` is the total number of values summed. If the mean is empty for a given segment ID `i`, `output[i] = 0`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/SegmentMean.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SegmentMean", data=data, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "SegmentMean", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SegmentMean", name, _ctx._post_execution_callbacks, data, segment_ids) return _result except _core._FallbackException: return segment_mean_eager_fallback( data, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def segment_mean_eager_fallback(data, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function segment_mean """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _inputs_flat = [data, segment_ids] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"SegmentMean", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SegmentMean", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.segment_min', 'segment_min') def segment_min(data, segment_ids, name=None): r"""Computes the minimum along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output_i = \min_j(data_j)\\) where `min` is over `j` such that `segment_ids[j] == i`. If the min is empty for a given segment ID `i`, `output[i] = 0`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/SegmentMin.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SegmentMin", data=data, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "SegmentMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SegmentMin", name, _ctx._post_execution_callbacks, data, segment_ids) return _result except _core._FallbackException: return segment_min_eager_fallback( data, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def segment_min_eager_fallback(data, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function segment_min """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _inputs_flat = [data, segment_ids] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"SegmentMin", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SegmentMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.segment_prod', 'segment_prod') def segment_prod(data, segment_ids, name=None): r"""Computes the product along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output_i = \prod_j data_j\\) where the product is over `j` such that `segment_ids[j] == i`. If the product is empty for a given segment ID `i`, `output[i] = 1`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/SegmentProd.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SegmentProd", data=data, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "SegmentProd", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SegmentProd", name, _ctx._post_execution_callbacks, data, segment_ids) return _result except _core._FallbackException: return segment_prod_eager_fallback( data, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def segment_prod_eager_fallback(data, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function segment_prod """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _inputs_flat = [data, segment_ids] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"SegmentProd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SegmentProd", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.segment_sum', 'segment_sum') def segment_sum(data, segment_ids, name=None): r"""Computes the sum along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output_i = \sum_j data_j\\) where sum is over `j` such that `segment_ids[j] == i`. If the sum is empty for a given segment ID `i`, `output[i] = 0`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/SegmentSum.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SegmentSum", data=data, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "SegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SegmentSum", name, _ctx._post_execution_callbacks, data, segment_ids) return _result except _core._FallbackException: return segment_sum_eager_fallback( data, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def segment_sum_eager_fallback(data, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function segment_sum """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _inputs_flat = [data, segment_ids] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"SegmentSum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result def select(condition, x, y, name=None): r"""Selects elements from `x` or `y`, depending on `condition`. The `x`, and `y` tensors must all have the same shape, and the output will also have that shape. The `condition` tensor must be a scalar if `x` and `y` are scalars. If `x` and `y` are vectors or higher rank, then `condition` must be either a scalar, a vector with size matching the first dimension of `x`, or must have the same shape as `x`. The `condition` tensor acts as a mask that chooses, based on the value at each element, whether the corresponding element / row in the output should be taken from `x` (if true) or `y` (if false). If `condition` is a vector and `x` and `y` are higher rank matrices, then it chooses which row (outer dimension) to copy from `x` and `y`. If `condition` has the same shape as `x` and `y`, then it chooses which element to copy from `x` and `y`. For example: ```python # 'condition' tensor is [[True, False] # [False, True]] # 't' is [[1, 2], # [3, 4]] # 'e' is [[5, 6], # [7, 8]] select(condition, t, e) # => [[1, 6], [7, 4]] # 'condition' tensor is [True, False] # 't' is [[1, 2], # [3, 4]] # 'e' is [[5, 6], # [7, 8]] select(condition, t, e) ==> [[1, 2], [7, 8]] ``` Args: condition: A `Tensor` of type `bool`. x: A `Tensor` which may have the same shape as `condition`. If `condition` is rank 1, `x` may have higher rank, but its first dimension must match the size of `condition`. y: A `Tensor` with the same type and shape as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `t`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Select", condition=condition, t=x, e=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Select", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Select", name, _ctx._post_execution_callbacks, condition, x, y) return _result except _core._FallbackException: return select_eager_fallback( condition, x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def select_eager_fallback(condition, x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function select """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T condition = _ops.convert_to_tensor(condition, _dtypes.bool) _inputs_flat = [condition, x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Select", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Select", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sigmoid(x, name=None): r"""Computes sigmoid of `x` element-wise. Specifically, `y = 1 / (1 + exp(-x))`. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sigmoid", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sigmoid", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sigmoid", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return sigmoid_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sigmoid_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sigmoid """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sigmoid", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sigmoid", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sigmoid_grad(y, dy, name=None): r"""Computes the gradient of the sigmoid of `x` wrt its input. Specifically, `grad = dy * y * (1 - y)`, where `y = sigmoid(x)`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SigmoidGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "SigmoidGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SigmoidGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return sigmoid_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sigmoid_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sigmoid_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"SigmoidGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SigmoidGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sign(x, name=None): r"""Returns an element-wise indication of the sign of a number. `y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`. For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sign", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sign", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sign", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return sign_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sign_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sign """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sign", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sign", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.sin', 'sin') def sin(x, name=None): r"""Computes sin of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sin", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sin", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sin", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return sin_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sin_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sin """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sin", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sin", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.sinh', 'sinh') def sinh(x, name=None): r"""Computes hyperbolic sine of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sinh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sinh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sinh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return sinh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sinh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sinh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sinh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sinh", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_mat_mul(a, b, transpose_a=False, transpose_b=False, a_is_sparse=False, b_is_sparse=False, name=None): r"""Multiply matrix "a" by matrix "b". The inputs must be two-dimensional matrices and the inner dimension of "a" must match the outer dimension of "b". Both "a" and "b" must be `Tensor`s not `SparseTensor`s. This op is optimized for the case where at least one of "a" or "b" is sparse, in the sense that they have a large proportion of zero values. The breakeven for using this versus a dense matrix multiply on one platform was 30% zero values in the sparse matrix. The gradient computation of this operation will only take advantage of sparsity in the input gradient when that gradient comes from a Relu. Args: a: A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. b: A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. transpose_a: An optional `bool`. Defaults to `False`. transpose_b: An optional `bool`. Defaults to `False`. a_is_sparse: An optional `bool`. Defaults to `False`. b_is_sparse: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") if a_is_sparse is None: a_is_sparse = False a_is_sparse = _execute.make_bool(a_is_sparse, "a_is_sparse") if b_is_sparse is None: b_is_sparse = False b_is_sparse = _execute.make_bool(b_is_sparse, "b_is_sparse") _, _, _op = _op_def_lib._apply_op_helper( "SparseMatMul", a=a, b=b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("transpose_a", _op.get_attr("transpose_a"), "transpose_b", _op.get_attr("transpose_b"), "a_is_sparse", _op.get_attr("a_is_sparse"), "b_is_sparse", _op.get_attr("b_is_sparse"), "Ta", _op.get_attr("Ta"), "Tb", _op.get_attr("Tb")) _execute.record_gradient( "SparseMatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseMatMul", name, _ctx._post_execution_callbacks, a, b, "transpose_a", transpose_a, "transpose_b", transpose_b, "a_is_sparse", a_is_sparse, "b_is_sparse", b_is_sparse) return _result except _core._FallbackException: return sparse_mat_mul_eager_fallback( a, b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_mat_mul_eager_fallback(a, b, transpose_a=False, transpose_b=False, a_is_sparse=False, b_is_sparse=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_mat_mul """ _ctx = ctx if ctx else _context.context() if transpose_a is None: transpose_a = False transpose_a = _execute.make_bool(transpose_a, "transpose_a") if transpose_b is None: transpose_b = False transpose_b = _execute.make_bool(transpose_b, "transpose_b") if a_is_sparse is None: a_is_sparse = False a_is_sparse = _execute.make_bool(a_is_sparse, "a_is_sparse") if b_is_sparse is None: b_is_sparse = False b_is_sparse = _execute.make_bool(b_is_sparse, "b_is_sparse") _attr_Ta, (a,) = _execute.args_to_matching_eager([a], _ctx, _dtypes.float32) _attr_Tb, (b,) = _execute.args_to_matching_eager([b], _ctx, _dtypes.float32) _inputs_flat = [a, b] _attrs = ("transpose_a", transpose_a, "transpose_b", transpose_b, "a_is_sparse", a_is_sparse, "b_is_sparse", b_is_sparse, "Ta", _attr_Ta, "Tb", _attr_Tb) _result = _execute.execute(b"SparseMatMul", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseMatMul", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_mean(data, indices, segment_ids, name=None): r"""Computes the mean along sparse segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first dimension, selecting a subset of dimension 0, specified by `indices`. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentMean", data=data, indices=indices, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "SparseSegmentMean", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentMean", name, _ctx._post_execution_callbacks, data, indices, segment_ids) return _result except _core._FallbackException: return sparse_segment_mean_eager_fallback( data, indices, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_mean_eager_fallback(data, indices, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_mean """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"SparseSegmentMean", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentMean", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_mean_grad(grad, indices, segment_ids, output_dim0, name=None): r"""Computes gradients for SparseSegmentMean. Returns tensor "output" with same shape as grad, except for dimension 0 whose value is output_dim0. Args: grad: A `Tensor`. Must be one of the following types: `float32`, `float64`. gradient propagated to the SparseSegmentMean op. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. indices passed to the corresponding SparseSegmentMean op. segment_ids: A `Tensor` of type `int32`. segment_ids passed to the corresponding SparseSegmentMean op. output_dim0: A `Tensor` of type `int32`. dimension 0 of "data" passed to SparseSegmentMean op. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `grad`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentMeanGrad", grad=grad, indices=indices, segment_ids=segment_ids, output_dim0=output_dim0, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "SparseSegmentMeanGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentMeanGrad", name, _ctx._post_execution_callbacks, grad, indices, segment_ids, output_dim0) return _result except _core._FallbackException: return sparse_segment_mean_grad_eager_fallback( grad, indices, segment_ids, output_dim0, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_mean_grad_eager_fallback(grad, indices, segment_ids, output_dim0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_mean_grad """ _ctx = ctx if ctx else _context.context() _attr_T, (grad,) = _execute.args_to_matching_eager([grad], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) output_dim0 = _ops.convert_to_tensor(output_dim0, _dtypes.int32) _inputs_flat = [grad, indices, segment_ids, output_dim0] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"SparseSegmentMeanGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentMeanGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_mean_with_num_segments(data, indices, segment_ids, num_segments, name=None): r"""Computes the mean along sparse segments of a tensor. Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is misisng, the `output` tensor at that position will be zeroed. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. Should equal the number of distinct segment IDs. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentMeanWithNumSegments", data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "SparseSegmentMeanWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentMeanWithNumSegments", name, _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments) return _result except _core._FallbackException: return sparse_segment_mean_with_num_segments_eager_fallback( data, indices, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_mean_with_num_segments_eager_fallback(data, indices, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_mean_with_num_segments """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"SparseSegmentMeanWithNumSegments", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentMeanWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_sqrt_n(data, indices, segment_ids, name=None): r"""Computes the sum along sparse segments of a tensor divided by the sqrt of N. N is the size of the segment being reduced. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentSqrtN", data=data, indices=indices, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "SparseSegmentSqrtN", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentSqrtN", name, _ctx._post_execution_callbacks, data, indices, segment_ids) return _result except _core._FallbackException: return sparse_segment_sqrt_n_eager_fallback( data, indices, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_sqrt_n_eager_fallback(data, indices, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_sqrt_n """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"SparseSegmentSqrtN", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentSqrtN", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_sqrt_n_grad(grad, indices, segment_ids, output_dim0, name=None): r"""Computes gradients for SparseSegmentSqrtN. Returns tensor "output" with same shape as grad, except for dimension 0 whose value is output_dim0. Args: grad: A `Tensor`. Must be one of the following types: `float32`, `float64`. gradient propagated to the SparseSegmentSqrtN op. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. indices passed to the corresponding SparseSegmentSqrtN op. segment_ids: A `Tensor` of type `int32`. segment_ids passed to the corresponding SparseSegmentSqrtN op. output_dim0: A `Tensor` of type `int32`. dimension 0 of "data" passed to SparseSegmentSqrtN op. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `grad`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentSqrtNGrad", grad=grad, indices=indices, segment_ids=segment_ids, output_dim0=output_dim0, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "SparseSegmentSqrtNGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentSqrtNGrad", name, _ctx._post_execution_callbacks, grad, indices, segment_ids, output_dim0) return _result except _core._FallbackException: return sparse_segment_sqrt_n_grad_eager_fallback( grad, indices, segment_ids, output_dim0, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_sqrt_n_grad_eager_fallback(grad, indices, segment_ids, output_dim0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_sqrt_n_grad """ _ctx = ctx if ctx else _context.context() _attr_T, (grad,) = _execute.args_to_matching_eager([grad], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) output_dim0 = _ops.convert_to_tensor(output_dim0, _dtypes.int32) _inputs_flat = [grad, indices, segment_ids, output_dim0] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"SparseSegmentSqrtNGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentSqrtNGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_sqrt_n_with_num_segments(data, indices, segment_ids, num_segments, name=None): r"""Computes the sum along sparse segments of a tensor divided by the sqrt of N. N is the size of the segment being reduced. Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is misisng, the `output` tensor at that position will be zeroed. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. Should equal the number of distinct segment IDs. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentSqrtNWithNumSegments", data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "SparseSegmentSqrtNWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentSqrtNWithNumSegments", name, _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments) return _result except _core._FallbackException: return sparse_segment_sqrt_n_with_num_segments_eager_fallback( data, indices, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_sqrt_n_with_num_segments_eager_fallback(data, indices, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_sqrt_n_with_num_segments """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"SparseSegmentSqrtNWithNumSegments", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentSqrtNWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_sum(data, indices, segment_ids, name=None): r"""Computes the sum along sparse segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first dimension, selecting a subset of dimension 0, specified by `indices`. For example: ```python c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) # Select two rows, one segment. tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) # => [[0 0 0 0]] # Select two rows, two segment. tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) # => [[ 1 2 3 4] # [-1 -2 -3 -4]] # Select all rows, two segments. tf.sparse_segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) # => [[0 0 0 0] # [5 6 7 8]] # Which is equivalent to: tf.segment_sum(c, tf.constant([0, 0, 1])) ``` Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentSum", data=data, indices=indices, segment_ids=segment_ids, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "SparseSegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentSum", name, _ctx._post_execution_callbacks, data, indices, segment_ids) return _result except _core._FallbackException: return sparse_segment_sum_eager_fallback( data, indices, segment_ids, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_sum_eager_fallback(data, indices, segment_ids, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_sum """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"SparseSegmentSum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sparse_segment_sum_with_num_segments(data, indices, segment_ids, num_segments, name=None): r"""Computes the sum along sparse segments of a tensor. Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is misisng, the `output` tensor at that position will be zeroed. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. For example: ```python c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) tf.sparse_segment_sum_with_num_segments( c, tf.constant([0, 1]), tf.constant([0, 0]), num_segments=3) # => [[0 0 0 0] # [0 0 0 0] # [0 0 0 0]] tf.sparse_segment_sum_with_num_segments(c, tf.constant([0, 1]), tf.constant([0, 2], num_segments=4)) # => [[ 1 2 3 4] # [ 0 0 0 0] # [-1 -2 -3 -4] # [ 0 0 0 0]] ``` Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor. Has same rank as `segment_ids`. segment_ids: A `Tensor` of type `int32`. A 1-D tensor. Values should be sorted and can be repeated. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. Should equal the number of distinct segment IDs. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SparseSegmentSumWithNumSegments", data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "SparseSegmentSumWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SparseSegmentSumWithNumSegments", name, _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments) return _result except _core._FallbackException: return sparse_segment_sum_with_num_segments_eager_fallback( data, indices, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sparse_segment_sum_with_num_segments_eager_fallback(data, indices, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sparse_segment_sum_with_num_segments """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int32) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) segment_ids = _ops.convert_to_tensor(segment_ids, _dtypes.int32) _inputs_flat = [data, indices, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"SparseSegmentSumWithNumSegments", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SparseSegmentSumWithNumSegments", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sqrt(x, name=None): r"""Computes square root of x element-wise. I.e., \\(y = \sqrt{x} = x^{1/2}\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sqrt", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sqrt", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sqrt", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return sqrt_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sqrt_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sqrt """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sqrt", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sqrt", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sqrt_grad(y, dy, name=None): r"""Computes the gradient for the sqrt of `x` wrt its input. Specifically, `grad = dy * 0.5 / y`, where `y = sqrt(x)`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SqrtGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "SqrtGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SqrtGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return sqrt_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sqrt_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sqrt_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"SqrtGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SqrtGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def square(x, name=None): r"""Computes square of x element-wise. I.e., \\(y = x * x = x^2\\). Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Square", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Square", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Square", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return square_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def square_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function square """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Square", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Square", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.squared_difference', 'squared_difference') def squared_difference(x, y, name=None): r"""Returns (x - y)(x - y) element-wise. *NOTE*: `math.squared_difference` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "SquaredDifference", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "SquaredDifference", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SquaredDifference", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return squared_difference_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def squared_difference_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function squared_difference """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"SquaredDifference", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SquaredDifference", _inputs_flat, _attrs, _result, name) _result, = _result return _result def sub(x, y, name=None): r"""Returns x - y element-wise. *NOTE*: `Subtract` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Sub", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Sub", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sub", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return sub_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def sub_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function sub """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"Sub", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sub", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _sum(input, axis, keep_dims=False, name=None): r"""Computes the sum of elements across dimensions of a tensor. Reduces `input` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. The tensor to reduce. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The dimensions to reduce. Must be in the range `[-rank(input), rank(input))`. keep_dims: An optional `bool`. Defaults to `False`. If true, retain reduced dimensions with length 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _, _, _op = _op_def_lib._apply_op_helper( "Sum", input=input, reduction_indices=axis, keep_dims=keep_dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("keep_dims", _op.get_attr("keep_dims"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "Sum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Sum", name, _ctx._post_execution_callbacks, input, axis, "keep_dims", keep_dims) return _result except _core._FallbackException: return _sum_eager_fallback( input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def _sum_eager_fallback(input, axis, keep_dims=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _sum """ _ctx = ctx if ctx else _context.context() if keep_dims is None: keep_dims = False keep_dims = _execute.make_bool(keep_dims, "keep_dims") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"Sum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Sum", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.tan', 'tan') def tan(x, name=None): r"""Computes tan of x element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Tan", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Tan", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Tan", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return tan_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def tan_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tan """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Tan", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Tan", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tanh(x, name=None): r"""Computes hyperbolic tangent of `x` element-wise. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Tanh", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Tanh", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Tanh", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: return tanh_eager_fallback( x, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def tanh_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tanh """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"Tanh", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Tanh", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tanh_grad(y, dy, name=None): r"""Computes the gradient for the tanh of `x` wrt its input. Specifically, `grad = dy * (1 - y*y)`, where `y = tanh(x)`, and `dy` is the corresponding input gradient. Args: y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. dy: A `Tensor`. Must have the same type as `y`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `y`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "TanhGrad", y=y, dy=dy, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "TanhGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TanhGrad", name, _ctx._post_execution_callbacks, y, dy) return _result except _core._FallbackException: return tanh_grad_eager_fallback( y, dy, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def tanh_grad_eager_fallback(y, dy, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tanh_grad """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], _ctx) (y, dy) = _inputs_T _inputs_flat = [y, dy] _attrs = ("T", _attr_T) _result = _execute.execute(b"TanhGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TanhGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def truncate_div(x, y, name=None): r"""Returns x / y element-wise for integer types. Truncation designates that negative numbers will round fractional quantities toward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different than Python semantics. See `FloorDiv` for a division function that matches Python Semantics. *NOTE*: `TruncateDiv` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "TruncateDiv", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "TruncateDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TruncateDiv", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return truncate_div_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def truncate_div_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function truncate_div """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"TruncateDiv", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TruncateDiv", _inputs_flat, _attrs, _result, name) _result, = _result return _result def truncate_mod(x, y, name=None): r"""Returns element-wise remainder of division. This emulates C semantics in that the result here is consistent with a truncating divide. E.g. `truncate(x / y) * y + truncate_mod(x, y) = x`. *NOTE*: `TruncateMod` supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) Args: x: A `Tensor`. Must be one of the following types: `int32`, `int64`, `bfloat16`, `half`, `float32`, `float64`. y: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "TruncateMod", x=x, y=y, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "TruncateMod", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TruncateMod", name, _ctx._post_execution_callbacks, x, y) return _result except _core._FallbackException: return truncate_mod_eager_fallback( x, y, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def truncate_mod_eager_fallback(x, y, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function truncate_mod """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T) _result = _execute.execute(b"TruncateMod", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TruncateMod", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.unsorted_segment_max', 'unsorted_segment_max') def unsorted_segment_max(data, segment_ids, num_segments, name=None): r"""Computes the maximum along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. This operator is similar to the unsorted segment sum operator found [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). Instead of computing the sum over segments, it computes the maximum such that: \\(output_i = \max_j data_j\\) where max is over `j` such that `segment_ids[j] == i`. If the maximum is empty for a given segment ID `i`, it outputs the smallest possible value for the specific numeric type, `output[i] = numeric_limits<T>::lowest()`. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/UnsortedSegmentMax.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "UnsortedSegmentMax", data=data, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "UnsortedSegmentMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UnsortedSegmentMax", name, _ctx._post_execution_callbacks, data, segment_ids, num_segments) return _result except _core._FallbackException: return unsorted_segment_max_eager_fallback( data, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def unsorted_segment_max_eager_fallback(data, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unsorted_segment_max """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) _inputs_flat = [data, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"UnsortedSegmentMax", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UnsortedSegmentMax", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.unsorted_segment_min', 'unsorted_segment_min') def unsorted_segment_min(data, segment_ids, num_segments, name=None): r"""Computes the minimum along segments of a tensor. Read @{$math_ops#segmentation$the section on segmentation} for an explanation of segments. This operator is similar to the unsorted segment sum operator found [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). Instead of computing the sum over segments, it computes the minimum such that: \\(output_i = \min_j data_j\\) where min is over `j` such that `segment_ids[j] == i`. If the minimum is empty for a given segment ID `i`, it outputs the largest possible value for the specific numeric type, `output[i] = numeric_limits<T>::max()`. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "UnsortedSegmentMin", data=data, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "UnsortedSegmentMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UnsortedSegmentMin", name, _ctx._post_execution_callbacks, data, segment_ids, num_segments) return _result except _core._FallbackException: return unsorted_segment_min_eager_fallback( data, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def unsorted_segment_min_eager_fallback(data, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unsorted_segment_min """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) _inputs_flat = [data, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"UnsortedSegmentMin", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UnsortedSegmentMin", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.unsorted_segment_prod', 'unsorted_segment_prod') def unsorted_segment_prod(data, segment_ids, num_segments, name=None): r"""Computes the product along segments of a tensor. Read @{$math_ops#segmentation$the section on segmentation} for an explanation of segments. This operator is similar to the unsorted segment sum operator found [(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum). Instead of computing the sum over segments, it computes the product of all entries belonging to a segment such that: \\(output_i = \prod_j data_j\\) where the product is over `j` such that `segment_ids[j] == i`. If there is no entry for a given segment ID `i`, it outputs 1. Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A 1-D tensor whose rank is equal to the rank of `data`'s first dimension. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "UnsortedSegmentProd", data=data, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "UnsortedSegmentProd", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UnsortedSegmentProd", name, _ctx._post_execution_callbacks, data, segment_ids, num_segments) return _result except _core._FallbackException: return unsorted_segment_prod_eager_fallback( data, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def unsorted_segment_prod_eager_fallback(data, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unsorted_segment_prod """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) _inputs_flat = [data, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"UnsortedSegmentProd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UnsortedSegmentProd", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.unsorted_segment_sum', 'unsorted_segment_sum') def unsorted_segment_sum(data, segment_ids, num_segments, name=None): r"""Computes the sum along segments of a tensor. Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of segments. Computes a tensor such that \\(output[i] = sum_{j...} data[j...]\\) where the sum is over tuples `j...` such that `segment_ids[j...] == i`. Unlike `SegmentSum`, `segment_ids` need not be sorted and need not cover all values in the full range of valid values. If the sum is empty for a given segment ID `i`, `output[i] = 0`. If the given segment ID `i` is negative, the value is dropped and will not be added to the sum of the segment. `num_segments` should equal the number of distinct segment IDs. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/UnsortedSegmentSum.png" alt> </div> Args: data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor whose shape is a prefix of `data.shape`. num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `data`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "UnsortedSegmentSum", data=data, segment_ids=segment_ids, num_segments=num_segments, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices"), "Tnumsegments", _op.get_attr("Tnumsegments")) _execute.record_gradient( "UnsortedSegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UnsortedSegmentSum", name, _ctx._post_execution_callbacks, data, segment_ids, num_segments) return _result except _core._FallbackException: return unsorted_segment_sum_eager_fallback( data, segment_ids, num_segments, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def unsorted_segment_sum_eager_fallback(data, segment_ids, num_segments, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unsorted_segment_sum """ _ctx = ctx if ctx else _context.context() _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], _ctx) _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], _ctx, _dtypes.int32) _inputs_flat = [data, segment_ids, num_segments] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", _attr_Tnumsegments) _result = _execute.execute(b"UnsortedSegmentSum", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UnsortedSegmentSum", _inputs_flat, _attrs, _result, name) _result, = _result return _result @tf_export('math.zeta', 'zeta') def zeta(x, q, name=None): r"""Compute the Hurwitz zeta function \\(\zeta(x, q)\\). The Hurwitz zeta function is defined as: \\(\zeta(x, q) = \sum_{n=0}^{\infty} (q + n)^{-x}\\) Args: x: A `Tensor`. Must be one of the following types: `float32`, `float64`. q: A `Tensor`. Must have the same type as `x`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: _, _, _op = _op_def_lib._apply_op_helper( "Zeta", x=x, q=q, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Zeta", _inputs_flat, _attrs, _result, name) _result, = _result return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Zeta", name, _ctx._post_execution_callbacks, x, q) return _result except _core._FallbackException: return zeta_eager_fallback( x, q, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def zeta_eager_fallback(x, q, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function zeta """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, q], _ctx) (x, q) = _inputs_T _inputs_flat = [x, q] _attrs = ("T", _attr_T) _result = _execute.execute(b"Zeta", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Zeta", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _InitOpDefLibrary(op_list_proto_bytes): op_list = _op_def_pb2.OpList() op_list.ParseFromString(op_list_proto_bytes) _op_def_registry.register_op_list(op_list) op_def_lib = _op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib # op { # name: "Abs" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "AccumulateNV2" # input_arg { # name: "inputs" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "sum" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "shape" # type: "shape" # } # is_aggregate: true # is_commutative: true # } # op { # name: "Acos" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Acosh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Add" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_STRING # } # } # } # } # op { # name: "AddN" # input_arg { # name: "inputs" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "sum" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # type: DT_VARIANT # } # } # } # is_aggregate: true # is_commutative: true # } # op { # name: "AddV2" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # is_aggregate: true # is_commutative: true # } # op { # name: "All" # input_arg { # name: "input" # type: DT_BOOL # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type: DT_BOOL # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Angle" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "Tout" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # attr { # name: "Tout" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Any" # input_arg { # name: "input" # type: DT_BOOL # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type: DT_BOOL # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ApproximateEqual" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "tolerance" # type: "float" # default_value { # f: 1e-05 # } # } # is_commutative: true # } # op { # name: "ArgMax" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "dimension" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "output_type" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "output_type" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ArgMin" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "dimension" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "output_type" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "output_type" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Asin" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Asinh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Atan" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Atan2" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Atanh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "BatchMatMul" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # attr { # name: "adj_x" # type: "bool" # default_value { # b: false # } # } # attr { # name: "adj_y" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "BesselI0e" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "BesselI1e" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Betainc" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "b" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Bincount" # input_arg { # name: "arr" # type: DT_INT32 # } # input_arg { # name: "size" # type: DT_INT32 # } # input_arg { # name: "weights" # type_attr: "T" # } # output_arg { # name: "bins" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Bucketize" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type: DT_INT32 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "boundaries" # type: "list(float)" # } # } # op { # name: "Cast" # input_arg { # name: "x" # type_attr: "SrcT" # } # output_arg { # name: "y" # type_attr: "DstT" # } # attr { # name: "SrcT" # type: "type" # } # attr { # name: "DstT" # type: "type" # } # } # op { # name: "Ceil" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "ClipByValue" # input_arg { # name: "t" # type_attr: "T" # } # input_arg { # name: "clip_value_min" # type_attr: "T" # } # input_arg { # name: "clip_value_max" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "CompareAndBitpack" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "threshold" # type_attr: "T" # } # output_arg { # name: "output" # type: DT_UINT8 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BOOL # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT8 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Complex" # input_arg { # name: "real" # type_attr: "T" # } # input_arg { # name: "imag" # type_attr: "T" # } # output_arg { # name: "out" # type_attr: "Tout" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tout" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "ComplexAbs" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "Tout" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # attr { # name: "Tout" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Conj" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_VARIANT # } # } # } # } # op { # name: "Cos" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Cosh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Cross" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "b" # type_attr: "T" # } # output_arg { # name: "product" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "Cumprod" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "axis" # type_attr: "Tidx" # } # output_arg { # name: "out" # type_attr: "T" # } # attr { # name: "exclusive" # type: "bool" # default_value { # b: false # } # } # attr { # name: "reverse" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Cumsum" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "axis" # type_attr: "Tidx" # } # output_arg { # name: "out" # type_attr: "T" # } # attr { # name: "exclusive" # type: "bool" # default_value { # b: false # } # } # attr { # name: "reverse" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Digamma" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Div" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Equal" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_QUINT8 # type: DT_QINT8 # type: DT_QINT32 # type: DT_STRING # type: DT_BOOL # type: DT_COMPLEX128 # } # } # } # is_commutative: true # } # op { # name: "Erf" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Erfc" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Exp" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Expm1" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Floor" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "FloorDiv" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "FloorMod" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Greater" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "GreaterEqual" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "HistogramFixedWidth" # input_arg { # name: "values" # type_attr: "T" # } # input_arg { # name: "value_range" # type_attr: "T" # } # input_arg { # name: "nbins" # type: DT_INT32 # } # output_arg { # name: "out" # type_attr: "dtype" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "dtype" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Igamma" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "IgammaGradA" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Igammac" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Imag" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "Tout" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # attr { # name: "Tout" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Inv" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "InvGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "IsFinite" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "IsInf" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "IsNan" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Less" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "LessEqual" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # } # op { # name: "Lgamma" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "LinSpace" # input_arg { # name: "start" # type_attr: "T" # } # input_arg { # name: "stop" # type_attr: "T" # } # input_arg { # name: "num" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Log" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Log1p" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "LogicalAnd" # input_arg { # name: "x" # type: DT_BOOL # } # input_arg { # name: "y" # type: DT_BOOL # } # output_arg { # name: "z" # type: DT_BOOL # } # is_commutative: true # } # op { # name: "LogicalNot" # input_arg { # name: "x" # type: DT_BOOL # } # output_arg { # name: "y" # type: DT_BOOL # } # } # op { # name: "LogicalOr" # input_arg { # name: "x" # type: DT_BOOL # } # input_arg { # name: "y" # type: DT_BOOL # } # output_arg { # name: "z" # type: DT_BOOL # } # is_commutative: true # } # op { # name: "MatMul" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "b" # type_attr: "T" # } # output_arg { # name: "product" # type_attr: "T" # } # attr { # name: "transpose_a" # type: "bool" # default_value { # b: false # } # } # attr { # name: "transpose_b" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Max" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Maximum" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # is_commutative: true # } # op { # name: "Mean" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Min" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Minimum" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # is_commutative: true # } # op { # name: "Mod" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_HALF # type: DT_HALF # type: DT_BFLOAT16 # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Mul" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # is_commutative: true # } # op { # name: "Neg" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "NotEqual" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type: DT_BOOL # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_QUINT8 # type: DT_QINT8 # type: DT_QINT32 # type: DT_STRING # type: DT_BOOL # type: DT_COMPLEX128 # } # } # } # is_commutative: true # } # op { # name: "Polygamma" # input_arg { # name: "a" # type_attr: "T" # } # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Pow" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_FLOAT # type: DT_HALF # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Prod" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "QuantizeDownAndShrinkRange" # input_arg { # name: "input" # type_attr: "Tinput" # } # input_arg { # name: "input_min" # type: DT_FLOAT # } # input_arg { # name: "input_max" # type: DT_FLOAT # } # output_arg { # name: "output" # type_attr: "out_type" # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "Tinput" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "out_type" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # } # op { # name: "QuantizedAdd" # input_arg { # name: "x" # type_attr: "T1" # } # input_arg { # name: "y" # type_attr: "T2" # } # input_arg { # name: "min_x" # type: DT_FLOAT # } # input_arg { # name: "max_x" # type: DT_FLOAT # } # input_arg { # name: "min_y" # type: DT_FLOAT # } # input_arg { # name: "max_y" # type: DT_FLOAT # } # output_arg { # name: "z" # type_attr: "Toutput" # } # output_arg { # name: "min_z" # type: DT_FLOAT # } # output_arg { # name: "max_z" # type: DT_FLOAT # } # attr { # name: "T1" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "T2" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "Toutput" # type: "type" # default_value { # type: DT_QINT32 # } # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # is_commutative: true # } # op { # name: "QuantizedMatMul" # input_arg { # name: "a" # type_attr: "T1" # } # input_arg { # name: "b" # type_attr: "T2" # } # input_arg { # name: "min_a" # type: DT_FLOAT # } # input_arg { # name: "max_a" # type: DT_FLOAT # } # input_arg { # name: "min_b" # type: DT_FLOAT # } # input_arg { # name: "max_b" # type: DT_FLOAT # } # output_arg { # name: "out" # type_attr: "Toutput" # } # output_arg { # name: "min_out" # type: DT_FLOAT # } # output_arg { # name: "max_out" # type: DT_FLOAT # } # attr { # name: "T1" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "T2" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "Toutput" # type: "type" # default_value { # type: DT_QINT32 # } # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "transpose_a" # type: "bool" # default_value { # b: false # } # } # attr { # name: "transpose_b" # type: "bool" # default_value { # b: false # } # } # attr { # name: "Tactivation" # type: "type" # default_value { # type: DT_QUINT8 # } # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # } # op { # name: "QuantizedMul" # input_arg { # name: "x" # type_attr: "T1" # } # input_arg { # name: "y" # type_attr: "T2" # } # input_arg { # name: "min_x" # type: DT_FLOAT # } # input_arg { # name: "max_x" # type: DT_FLOAT # } # input_arg { # name: "min_y" # type: DT_FLOAT # } # input_arg { # name: "max_y" # type: DT_FLOAT # } # output_arg { # name: "z" # type_attr: "Toutput" # } # output_arg { # name: "min_z" # type: DT_FLOAT # } # output_arg { # name: "max_z" # type: DT_FLOAT # } # attr { # name: "T1" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "T2" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "Toutput" # type: "type" # default_value { # type: DT_QINT32 # } # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # is_commutative: true # } # op { # name: "Range" # input_arg { # name: "start" # type_attr: "Tidx" # } # input_arg { # name: "limit" # type_attr: "Tidx" # } # input_arg { # name: "delta" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "Tidx" # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Real" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "Tout" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_COMPLEX64 # } # allowed_values { # list { # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # attr { # name: "Tout" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "RealDiv" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Reciprocal" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "ReciprocalGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "RequantizationRange" # input_arg { # name: "input" # type_attr: "Tinput" # } # input_arg { # name: "input_min" # type: DT_FLOAT # } # input_arg { # name: "input_max" # type: DT_FLOAT # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "Tinput" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # } # op { # name: "Requantize" # input_arg { # name: "input" # type_attr: "Tinput" # } # input_arg { # name: "input_min" # type: DT_FLOAT # } # input_arg { # name: "input_max" # type: DT_FLOAT # } # input_arg { # name: "requested_output_min" # type: DT_FLOAT # } # input_arg { # name: "requested_output_max" # type: DT_FLOAT # } # output_arg { # name: "output" # type_attr: "out_type" # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "Tinput" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "out_type" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # } # op { # name: "Rint" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "Round" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Rsqrt" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "RsqrtGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "SegmentMax" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SegmentMean" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SegmentMin" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SegmentProd" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SegmentSum" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Select" # input_arg { # name: "condition" # type: DT_BOOL # } # input_arg { # name: "t" # type_attr: "T" # } # input_arg { # name: "e" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "Sigmoid" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "SigmoidGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Sign" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Sin" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Sinh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "SparseMatMul" # input_arg { # name: "a" # type_attr: "Ta" # } # input_arg { # name: "b" # type_attr: "Tb" # } # output_arg { # name: "product" # type: DT_FLOAT # } # attr { # name: "transpose_a" # type: "bool" # default_value { # b: false # } # } # attr { # name: "transpose_b" # type: "bool" # default_value { # b: false # } # } # attr { # name: "a_is_sparse" # type: "bool" # default_value { # b: false # } # } # attr { # name: "b_is_sparse" # type: "bool" # default_value { # b: false # } # } # attr { # name: "Ta" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_BFLOAT16 # } # } # } # attr { # name: "Tb" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_BFLOAT16 # } # } # } # } # op { # name: "SparseSegmentMean" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentMeanGrad" # input_arg { # name: "grad" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # input_arg { # name: "output_dim0" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentMeanWithNumSegments" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentSqrtN" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentSqrtNGrad" # input_arg { # name: "grad" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # input_arg { # name: "output_dim0" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentSqrtNWithNumSegments" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentSum" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SparseSegmentSumWithNumSegments" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "segment_ids" # type: DT_INT32 # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Sqrt" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "SqrtGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Square" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "SquaredDifference" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # is_commutative: true # } # op { # name: "Sub" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Sum" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "reduction_indices" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "keep_dims" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Tan" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "Tanh" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "TanhGrad" # input_arg { # name: "y" # type_attr: "T" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "TruncateDiv" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "TruncateMod" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "UnsortedSegmentMax" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UnsortedSegmentMin" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UnsortedSegmentProd" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UnsortedSegmentSum" # input_arg { # name: "data" # type_attr: "T" # } # input_arg { # name: "segment_ids" # type_attr: "Tindices" # } # input_arg { # name: "num_segments" # type_attr: "Tnumsegments" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tnumsegments" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Zeta" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "q" # type_attr: "T" # } # output_arg { # name: "z" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } _op_def_lib = _InitOpDefLibrary(b"\n,\n\003Abs\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\003\t\no\n\rAccumulateNV2\022\016\n\006inputs\"\001T*\001N\032\010\n\003sum\"\001T\"\014\n\001N\022\003int(\0010\001\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\016\n\005shape\022\005shape\200\001\001\220\001\001\n/\n\004Acos\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n.\n\005Acosh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n:\n\003Add\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\005\003\t\010\022\007\nW\n\004AddN\022\016\n\006inputs\"\001T*\001N\032\010\n\003sum\"\001T\"\014\n\001N\022\003int(\0010\001\"!\n\001T\022\004type:\026\n\0242\022\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\025\200\001\001\220\001\001\nA\n\005AddV2\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\032\n\001T\022\004type:\017\n\r2\013\016\023\001\002\004\006\005\003\t\010\022\200\001\001\220\001\001\nh\n\003All\022\t\n\005input\030\n\022\031\n\021reduction_indices\"\004Tidx\032\n\n\006output\030\n\"\025\n\tkeep_dims\022\004bool\032\002(\000\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\nT\n\005Angle\022\n\n\005input\"\001T\032\016\n\006output\"\004Tout\"\025\n\001T\022\004type\032\0020\010:\006\n\0042\002\010\022\"\030\n\004Tout\022\004type\032\0020\001:\006\n\0042\002\001\002\nh\n\003Any\022\t\n\005input\030\n\022\031\n\021reduction_indices\"\004Tidx\032\n\n\006output\030\n\"\025\n\tkeep_dims\022\004bool\032\002(\000\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\ni\n\020ApproximateEqual\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\031\n\ttolerance\022\005float\032\005%\254\305\'7\220\001\001\n\233\001\n\006ArgMax\022\n\n\005input\"\001T\022\021\n\tdimension\"\004Tidx\032\025\n\006output\"\013output_type\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\"\037\n\013output_type\022\004type\032\0020\t:\006\n\0042\002\003\t\n\233\001\n\006ArgMin\022\n\n\005input\"\001T\022\021\n\tdimension\"\004Tidx\032\025\n\006output\"\013output_type\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\"\037\n\013output_type\022\004type\032\0020\t:\006\n\0042\002\003\t\n/\n\004Asin\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n.\n\005Asinh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n/\n\004Atan\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n4\n\005Atan2\022\006\n\001y\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n.\n\005Atanh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\nh\n\013BatchMatMul\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\013\n\006output\"\001T\"\026\n\001T\022\004type:\013\n\t2\007\016\023\001\002\003\010\022\"\021\n\005adj_x\022\004bool\032\002(\000\"\021\n\005adj_y\022\004bool\032\002(\000\n0\n\tBesselI0e\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n0\n\tBesselI1e\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n<\n\007Betainc\022\006\n\001a\"\001T\022\006\n\001b\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\nK\n\010Bincount\022\007\n\003arr\030\003\022\010\n\004size\030\003\022\014\n\007weights\"\001T\032\t\n\004bins\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\003\t\001\002\nS\n\tBucketize\022\n\n\005input\"\001T\032\n\n\006output\030\003\"\023\n\001T\022\004type:\010\n\0062\004\003\t\001\002\"\031\n\nboundaries\022\013list(float)\n8\n\004Cast\022\t\n\001x\"\004SrcT\032\t\n\001y\"\004DstT\"\014\n\004SrcT\022\004type\"\014\n\004DstT\022\004type\n+\n\004Ceil\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\nn\n\013ClipByValue\022\006\n\001t\"\001T\022\023\n\016clip_value_min\"\001T\022\023\n\016clip_value_max\"\001T\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\nT\n\021CompareAndBitpack\022\n\n\005input\"\001T\022\016\n\tthreshold\"\001T\032\n\n\006output\030\004\"\027\n\001T\022\004type:\014\n\n2\010\n\023\001\002\006\005\003\t\n]\n\007Complex\022\t\n\004real\"\001T\022\t\n\004imag\"\001T\032\013\n\003out\"\004Tout\"\025\n\001T\022\004type\032\0020\001:\006\n\0042\002\001\002\"\030\n\004Tout\022\004type\032\0020\010:\006\n\0042\002\010\022\nP\n\nComplexAbs\022\006\n\001x\"\001T\032\t\n\001y\"\004Tout\"\025\n\001T\022\004type\032\0020\010:\006\n\0042\002\010\022\"\030\n\004Tout\022\004type\032\0020\001:\006\n\0042\002\001\002\n7\n\004Conj\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\026\n\001T\022\004type\032\0020\010:\007\n\0052\003\010\022\025\n,\n\003Cos\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n-\n\004Cosh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\nB\n\005Cross\022\006\n\001a\"\001T\022\006\n\001b\"\001T\032\014\n\007product\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\n\221\001\n\007Cumprod\022\006\n\001x\"\001T\022\014\n\004axis\"\004Tidx\032\010\n\003out\"\001T\"\025\n\texclusive\022\004bool\032\002(\000\"\023\n\007reverse\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\220\001\n\006Cumsum\022\006\n\001x\"\001T\022\014\n\004axis\"\004Tidx\032\010\n\003out\"\001T\"\025\n\texclusive\022\004bool\032\002(\000\"\023\n\007reverse\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n.\n\007Digamma\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n:\n\003Div\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\nB\n\005Equal\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\037\n\001T\022\004type:\024\n\0222\020\016\023\001\002\004\006\005\003\t\010\014\013\r\007\n\022\220\001\001\n*\n\003Erf\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n+\n\004Erfc\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n,\n\003Exp\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n.\n\005Expm1\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n,\n\005Floor\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n?\n\010FloorDiv\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\n9\n\010FloorMod\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\003\t\016\023\001\002\n=\n\007Greater\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\nB\n\014GreaterEqual\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\n}\n\023HistogramFixedWidth\022\013\n\006values\"\001T\022\020\n\013value_range\"\001T\022\t\n\005nbins\030\003\032\014\n\003out\"\005dtype\"\023\n\001T\022\004type:\010\n\0062\004\003\t\001\002\"\031\n\005dtype\022\004type\032\0020\003:\006\n\0042\002\003\t\n3\n\006Igamma\022\006\n\001a\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\n8\n\013IgammaGradA\022\006\n\001a\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\n4\n\007Igammac\022\006\n\001a\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\nS\n\004Imag\022\n\n\005input\"\001T\032\016\n\006output\"\004Tout\"\025\n\001T\022\004type\032\0020\010:\006\n\0042\002\010\022\"\030\n\004Tout\022\004type\032\0020\001:\006\n\0042\002\001\002\n.\n\003Inv\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n9\n\007InvGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n.\n\010IsFinite\022\006\n\001x\"\001T\032\005\n\001y\030\n\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n+\n\005IsInf\022\006\n\001x\"\001T\032\005\n\001y\030\n\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n+\n\005IsNan\022\006\n\001x\"\001T\032\005\n\001y\030\n\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n:\n\004Less\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\n?\n\tLessEqual\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\n-\n\006Lgamma\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\ni\n\010LinSpace\022\n\n\005start\"\001T\022\t\n\004stop\"\001T\022\013\n\003num\"\004Tidx\032\013\n\006output\"\001T\"\022\n\001T\022\004type:\007\n\0052\003\016\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n,\n\003Log\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n.\n\005Log1p\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n$\n\nLogicalAnd\022\005\n\001x\030\n\022\005\n\001y\030\n\032\005\n\001z\030\n\220\001\001\n\032\n\nLogicalNot\022\005\n\001x\030\n\032\005\n\001y\030\n\n#\n\tLogicalOr\022\005\n\001x\030\n\022\005\n\001y\030\n\032\005\n\001z\030\n\220\001\001\np\n\006MatMul\022\006\n\001a\"\001T\022\006\n\001b\"\001T\032\014\n\007product\"\001T\"\027\n\013transpose_a\022\004bool\032\002(\000\"\027\n\013transpose_b\022\004bool\032\002(\000\"\026\n\001T\022\004type:\013\n\t2\007\016\023\001\002\003\010\022\n\214\001\n\003Max\022\n\n\005input\"\001T\022\031\n\021reduction_indices\"\004Tidx\032\013\n\006output\"\001T\"\025\n\tkeep_dims\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n;\n\007Maximum\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\003\t\220\001\001\n\215\001\n\004Mean\022\n\n\005input\"\001T\022\031\n\021reduction_indices\"\004Tidx\032\013\n\006output\"\001T\"\025\n\tkeep_dims\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\214\001\n\003Min\022\n\n\005input\"\001T\022\031\n\021reduction_indices\"\004Tidx\032\013\n\006output\"\001T\"\025\n\tkeep_dims\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n;\n\007Minimum\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\003\t\220\001\001\n5\n\003Mod\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\026\n\001T\022\004type:\013\n\t2\007\003\t\023\023\016\001\002\n=\n\003Mul\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\220\001\001\n.\n\003Neg\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\nE\n\010NotEqual\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\005\n\001z\030\n\"\037\n\001T\022\004type:\024\n\0222\020\016\023\001\002\004\006\005\003\t\010\014\013\r\007\n\022\220\001\001\n6\n\tPolygamma\022\006\n\001a\"\001T\022\006\n\001x\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\n6\n\003Pow\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\001\023\002\003\t\010\022\n\215\001\n\004Prod\022\n\n\005input\"\001T\022\031\n\021reduction_indices\"\004Tidx\032\013\n\006output\"\001T\"\025\n\tkeep_dims\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\267\001\n\032QuantizeDownAndShrinkRange\022\017\n\005input\"\006Tinput\022\r\n\tinput_min\030\001\022\r\n\tinput_max\030\001\032\022\n\006output\"\010out_type\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\031\n\006Tinput\022\004type:\t\n\0072\005\013\014\r\017\020\"\033\n\010out_type\022\004type:\t\n\0072\005\013\014\r\017\020\n\301\001\n\014QuantizedAdd\022\007\n\001x\"\002T1\022\007\n\001y\"\002T2\022\t\n\005min_x\030\001\022\t\n\005max_x\030\001\022\t\n\005min_y\030\001\022\t\n\005max_y\030\001\032\014\n\001z\"\007Toutput\032\t\n\005min_z\030\001\032\t\n\005max_z\030\001\"\025\n\002T1\022\004type:\t\n\0072\005\013\014\r\017\020\"\025\n\002T2\022\004type:\t\n\0072\005\013\014\r\017\020\"\036\n\007Toutput\022\004type\032\0020\r:\t\n\0072\005\013\014\r\017\020\220\001\001\n\235\002\n\017QuantizedMatMul\022\007\n\001a\"\002T1\022\007\n\001b\"\002T2\022\t\n\005min_a\030\001\022\t\n\005max_a\030\001\022\t\n\005min_b\030\001\022\t\n\005max_b\030\001\032\016\n\003out\"\007Toutput\032\013\n\007min_out\030\001\032\013\n\007max_out\030\001\"\025\n\002T1\022\004type:\t\n\0072\005\013\014\r\017\020\"\025\n\002T2\022\004type:\t\n\0072\005\013\014\r\017\020\"\036\n\007Toutput\022\004type\032\0020\r:\t\n\0072\005\013\014\r\017\020\"\027\n\013transpose_a\022\004bool\032\002(\000\"\027\n\013transpose_b\022\004bool\032\002(\000\"\"\n\013Tactivation\022\004type\032\0020\014:\t\n\0072\005\013\014\r\017\020\n\301\001\n\014QuantizedMul\022\007\n\001x\"\002T1\022\007\n\001y\"\002T2\022\t\n\005min_x\030\001\022\t\n\005max_x\030\001\022\t\n\005min_y\030\001\022\t\n\005max_y\030\001\032\014\n\001z\"\007Toutput\032\t\n\005min_z\030\001\032\t\n\005max_z\030\001\"\025\n\002T1\022\004type:\t\n\0072\005\013\014\r\017\020\"\025\n\002T2\022\004type:\t\n\0072\005\013\014\r\017\020\"\036\n\007Toutput\022\004type\032\0020\r:\t\n\0072\005\013\014\r\017\020\220\001\001\na\n\005Range\022\r\n\005start\"\004Tidx\022\r\n\005limit\"\004Tidx\022\r\n\005delta\"\004Tidx\032\016\n\006output\"\004Tidx\"\033\n\004Tidx\022\004type\032\0020\003:\t\n\0072\005\016\001\002\003\t\nS\n\004Real\022\n\n\005input\"\001T\032\016\n\006output\"\004Tout\"\025\n\001T\022\004type\032\0020\010:\006\n\0042\002\010\022\"\030\n\004Tout\022\004type\032\0020\001:\006\n\0042\002\001\002\n>\n\007RealDiv\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\n5\n\nReciprocal\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n@\n\016ReciprocalGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n\177\n\023RequantizationRange\022\017\n\005input\"\006Tinput\022\r\n\tinput_min\030\001\022\r\n\tinput_max\030\001\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\031\n\006Tinput\022\004type:\t\n\0072\005\013\014\r\017\020\n\333\001\n\nRequantize\022\017\n\005input\"\006Tinput\022\r\n\tinput_min\030\001\022\r\n\tinput_max\030\001\022\030\n\024requested_output_min\030\001\022\030\n\024requested_output_max\030\001\032\022\n\006output\"\010out_type\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\031\n\006Tinput\022\004type:\t\n\0072\005\013\014\r\017\020\"\033\n\010out_type\022\004type:\t\n\0072\005\013\014\r\017\020\n+\n\004Rint\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n0\n\005Round\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n.\n\005Rsqrt\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n;\n\tRsqrtGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\nt\n\nSegmentMax\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nz\n\013SegmentMean\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nt\n\nSegmentMin\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nz\n\013SegmentProd\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\ny\n\nSegmentSum\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\n?\n\006Select\022\r\n\tcondition\030\n\022\006\n\001t\"\001T\022\006\n\001e\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n0\n\007Sigmoid\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n=\n\013SigmoidGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n/\n\004Sign\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n,\n\003Sin\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n-\n\004Sinh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n\301\001\n\014SparseMatMul\022\007\n\001a\"\002Ta\022\007\n\001b\"\002Tb\032\013\n\007product\030\001\"\027\n\013transpose_a\022\004bool\032\002(\000\"\027\n\013transpose_b\022\004bool\032\002(\000\"\027\n\013a_is_sparse\022\004bool\032\002(\000\"\027\n\013b_is_sparse\022\004bool\032\002(\000\"\026\n\002Ta\022\004type\032\0020\001:\006\n\0042\002\001\016\"\026\n\002Tb\022\004type\032\0020\001:\006\n\0042\002\001\016\nz\n\021SparseSegmentMean\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\217\001\n\025SparseSegmentMeanGrad\022\t\n\004grad\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\022\017\n\013output_dim0\030\003\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\311\001\n SparseSegmentMeanWithNumSegments\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n{\n\022SparseSegmentSqrtN\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\220\001\n\026SparseSegmentSqrtNGrad\022\t\n\004grad\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\022\017\n\013output_dim0\030\003\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\312\001\n!SparseSegmentSqrtNWithNumSegments\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n\203\001\n\020SparseSegmentSum\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\322\001\n\037SparseSegmentSumWithNumSegments\022\t\n\004data\"\001T\022\017\n\007indices\"\004Tidx\022\017\n\013segment_ids\030\003\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n-\n\004Sqrt\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n:\n\010SqrtGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n1\n\006Square\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\nG\n\021SquaredDifference\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\220\001\001\n:\n\003Sub\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\n\214\001\n\003Sum\022\n\n\005input\"\001T\022\031\n\021reduction_indices\"\004Tidx\032\013\n\006output\"\001T\"\025\n\tkeep_dims\022\004bool\032\002(\000\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n.\n\003Tan\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n-\n\004Tanh\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\n:\n\010TanhGrad\022\006\n\001y\"\001T\022\007\n\002dy\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\016\023\001\002\010\022\nB\n\013TruncateDiv\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\016\023\001\002\004\006\021\005\003\t\010\022\n<\n\013TruncateMod\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\006\n\001z\"\001T\"\025\n\001T\022\004type:\n\n\0102\006\003\t\016\023\001\002\n\274\001\n\022UnsortedSegmentMax\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n\274\001\n\022UnsortedSegmentMin\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n\302\001\n\023UnsortedSegmentProd\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n\301\001\n\022UnsortedSegmentSum\022\t\n\004data\"\001T\022\027\n\013segment_ids\"\010Tindices\022\034\n\014num_segments\"\014Tnumsegments\032\013\n\006output\"\001T\" \n\001T\022\004type:\025\n\0232\021\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\" \n\014Tnumsegments\022\004type\032\0020\003:\006\n\0042\002\003\t\n1\n\004Zeta\022\006\n\001x\"\001T\022\006\n\001q\"\001T\032\006\n\001z\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002")
[((167, 1, 167, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(167, 11, 167, 22): '"""math.acos"""', (167, 24, 167, 30): '"""acos"""'}, {}), "('math.acos', 'acos')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((223, 1, 223, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(223, 11, 223, 23): '"""math.acosh"""', (223, 25, 223, 32): '"""acosh"""'}, {}), "('math.acosh', 'acosh')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((279, 1, 279, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(279, 11, 279, 21): '"""math.add"""', (279, 23, 279, 28): '"""add"""'}, {}), "('math.add', 'add')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((903, 1, 903, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(903, 11, 903, 22): '"""math.asin"""', (903, 24, 903, 30): '"""asin"""'}, {}), "('math.asin', 'asin')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((959, 1, 959, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(959, 11, 959, 23): '"""math.asinh"""', (959, 25, 959, 32): '"""asinh"""'}, {}), "('math.asinh', 'asinh')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((1015, 1, 1015, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(1015, 11, 1015, 22): '"""math.atan"""', (1015, 24, 1015, 30): '"""atan"""'}, {}), "('math.atan', 'atan')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((1071, 1, 1071, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(1071, 11, 1071, 23): '"""math.atan2"""', (1071, 25, 1071, 32): '"""atan2"""'}, {}), "('math.atan2', 'atan2')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((1135, 1, 1135, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(1135, 11, 1135, 23): '"""math.atanh"""', (1135, 25, 1135, 32): '"""atanh"""'}, {}), "('math.atanh', 'atanh')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((1407, 1, 1407, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(1407, 11, 1407, 25): '"""math.betainc"""', (1407, 27, 1407, 36): '"""betainc"""'}, {}), "('math.betainc', 'betainc')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((1688, 1, 1688, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(1688, 11, 1688, 22): '"""math.ceil"""', (1688, 24, 1688, 30): '"""ceil"""'}, {}), "('math.ceil', 'ceil')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2113, 1, 2113, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2113, 11, 2113, 21): '"""math.cos"""', (2113, 23, 2113, 28): '"""cos"""'}, {}), "('math.cos', 'cos')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2169, 1, 2169, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2169, 11, 2169, 22): '"""math.cosh"""', (2169, 24, 2169, 30): '"""cosh"""'}, {}), "('math.cosh', 'cosh')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2225, 1, 2225, 35), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2225, 11, 2225, 25): '"""linalg.cross"""', (2225, 27, 2225, 34): '"""cross"""'}, {}), "('linalg.cross', 'cross')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2513, 1, 2513, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2513, 11, 2513, 25): '"""math.digamma"""', (2513, 27, 2513, 36): '"""digamma"""'}, {}), "('math.digamma', 'digamma')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2631, 1, 2631, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2631, 11, 2631, 23): '"""math.equal"""', (2631, 25, 2631, 32): '"""equal"""'}, {}), "('math.equal', 'equal')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2747, 1, 2747, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2747, 11, 2747, 22): '"""math.erfc"""', (2747, 24, 2747, 30): '"""erfc"""'}, {}), "('math.erfc', 'erfc')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2803, 1, 2803, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2803, 11, 2803, 21): '"""math.exp"""', (2803, 23, 2803, 28): '"""exp"""'}, {}), "('math.exp', 'exp')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2859, 1, 2859, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2859, 11, 2859, 23): '"""math.expm1"""', (2859, 25, 2859, 32): '"""expm1"""'}, {}), "('math.expm1', 'expm1')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((2917, 1, 2917, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(2917, 11, 2917, 23): '"""math.floor"""', (2917, 25, 2917, 32): '"""floor"""'}, {}), "('math.floor', 'floor')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3096, 1, 3096, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3096, 11, 3096, 25): '"""math.greater"""', (3096, 27, 3096, 36): '"""greater"""'}, {}), "('math.greater', 'greater')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3157, 1, 3157, 49), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3157, 11, 3157, 31): '"""math.greater_equal"""', (3157, 33, 3157, 48): '"""greater_equal"""'}, {}), "('math.greater_equal', 'greater_equal')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3307, 1, 3307, 35), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3307, 11, 3307, 24): '"""math.igamma"""', (3307, 26, 3307, 34): '"""igamma"""'}, {}), "('math.igamma', 'igamma')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3436, 1, 3436, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3436, 11, 3436, 25): '"""math.igammac"""', (3436, 27, 3436, 36): '"""igammac"""'}, {}), "('math.igammac', 'igammac')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3698, 1, 3698, 46), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3698, 11, 3698, 32): '"""debugging.is_finite"""', (3698, 34, 3698, 45): '"""is_finite"""'}, {}), "('debugging.is_finite', 'is_finite')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3758, 1, 3758, 40), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3758, 11, 3758, 29): '"""debugging.is_inf"""', (3758, 31, 3758, 39): '"""is_inf"""'}, {}), "('debugging.is_inf', 'is_inf')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3818, 1, 3818, 40), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3818, 11, 3818, 29): '"""debugging.is_nan"""', (3818, 31, 3818, 39): '"""is_nan"""'}, {}), "('debugging.is_nan', 'is_nan')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3878, 1, 3878, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3878, 11, 3878, 22): '"""math.less"""', (3878, 24, 3878, 30): '"""less"""'}, {}), "('math.less', 'less')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((3939, 1, 3939, 43), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(3939, 11, 3939, 28): '"""math.less_equal"""', (3939, 30, 3939, 42): '"""less_equal"""'}, {}), "('math.less_equal', 'less_equal')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4000, 1, 4000, 35), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4000, 11, 4000, 24): '"""math.lgamma"""', (4000, 26, 4000, 34): '"""lgamma"""'}, {}), "('math.lgamma', 'lgamma')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4056, 1, 4056, 35), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4056, 11, 4056, 22): '"""lin_space"""', (4056, 24, 4056, 34): '"""linspace"""'}, {}), "('lin_space', 'linspace')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4129, 1, 4129, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4129, 11, 4129, 21): '"""math.log"""', (4129, 23, 4129, 28): '"""log"""'}, {}), "('math.log', 'log')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4187, 1, 4187, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4187, 11, 4187, 23): '"""math.log1p"""', (4187, 25, 4187, 32): '"""log1p"""'}, {}), "('math.log1p', 'log1p')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4245, 1, 4245, 45), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4245, 11, 4245, 29): '"""math.logical_and"""', (4245, 31, 4245, 44): '"""logical_and"""'}, {}), "('math.logical_and', 'logical_and')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4306, 1, 4306, 45), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4306, 11, 4306, 29): '"""math.logical_not"""', (4306, 31, 4306, 44): '"""logical_not"""'}, {}), "('math.logical_not', 'logical_not')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4362, 1, 4362, 43), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4362, 11, 4362, 28): '"""math.logical_or"""', (4362, 30, 4362, 42): '"""logical_or"""'}, {}), "('math.logical_or', 'logical_or')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4584, 1, 4584, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4584, 11, 4584, 25): '"""math.maximum"""', (4584, 27, 4584, 36): '"""maximum"""'}, {}), "('math.maximum', 'maximum')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((4795, 1, 4795, 37), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(4795, 11, 4795, 25): '"""math.minimum"""', (4795, 27, 4795, 36): '"""minimum"""'}, {}), "('math.minimum', 'minimum')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((5036, 1, 5036, 41), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(5036, 11, 5036, 27): '"""math.not_equal"""', (5036, 29, 5036, 40): '"""not_equal"""'}, {}), "('math.not_equal', 'not_equal')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((5097, 1, 5097, 41), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(5097, 11, 5097, 27): '"""math.polygamma"""', (5097, 29, 5097, 40): '"""polygamma"""'}, {}), "('math.polygamma', 'polygamma')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((5305, 36, 5306, 74), 'collections.namedtuple', '_collections.namedtuple', ({(5306, 4, 5306, 32): '"""QuantizeDownAndShrinkRange"""', (5306, 34, 5306, 73): '_quantize_down_and_shrink_range_outputs'}, {}), "('QuantizeDownAndShrinkRange',\n _quantize_down_and_shrink_range_outputs)", True, 'import collections as _collections\n'), ((5407, 22, 5408, 43), 'collections.namedtuple', '_collections.namedtuple', ({(5408, 4, 5408, 18): '"""QuantizedAdd"""', (5408, 20, 5408, 42): '_quantized_add_outputs'}, {}), "('QuantizedAdd', _quantized_add_outputs)", True, 'import collections as _collections\n'), ((5497, 25, 5498, 50), 'collections.namedtuple', '_collections.namedtuple', ({(5498, 4, 5498, 21): '"""QuantizedMatMul"""', (5498, 23, 5498, 49): '_quantized_mat_mul_outputs'}, {}), "('QuantizedMatMul', _quantized_mat_mul_outputs)", True, 'import collections as _collections\n'), ((5626, 22, 5627, 43), 'collections.namedtuple', '_collections.namedtuple', ({(5627, 4, 5627, 18): '"""QuantizedMul"""', (5627, 20, 5627, 42): '_quantized_mul_outputs'}, {}), "('QuantizedMul', _quantized_mul_outputs)", True, 'import collections as _collections\n'), ((5924, 1, 5924, 43), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(5924, 11, 5924, 28): '"""math.reciprocal"""', (5924, 30, 5924, 42): '"""reciprocal"""'}, {}), "('math.reciprocal', 'reciprocal')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6043, 29, 6044, 57), 'collections.namedtuple', '_collections.namedtuple', ({(6044, 4, 6044, 25): '"""RequantizationRange"""', (6044, 27, 6044, 56): '_requantization_range_outputs'}, {}), "('RequantizationRange', _requantization_range_outputs)", True, 'import collections as _collections\n'), ((6119, 20, 6120, 38), 'collections.namedtuple', '_collections.namedtuple', ({(6120, 4, 6120, 16): '"""Requantize"""', (6120, 18, 6120, 37): '_requantize_outputs'}, {}), "('Requantize', _requantize_outputs)", True, 'import collections as _collections\n'), ((6212, 1, 6212, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6212, 11, 6212, 22): '"""math.rint"""', (6212, 24, 6212, 30): '"""rint"""'}, {}), "('math.rint', 'rint')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6336, 1, 6336, 33), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6336, 11, 6336, 23): '"""math.rsqrt"""', (6336, 25, 6336, 32): '"""rsqrt"""'}, {}), "('math.rsqrt', 'rsqrt')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6454, 1, 6454, 45), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6454, 11, 6454, 29): '"""math.segment_max"""', (6454, 31, 6454, 44): '"""segment_max"""'}, {}), "('math.segment_max', 'segment_max')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6527, 1, 6527, 47), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6527, 11, 6527, 30): '"""math.segment_mean"""', (6527, 32, 6527, 46): '"""segment_mean"""'}, {}), "('math.segment_mean', 'segment_mean')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6601, 1, 6601, 45), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6601, 11, 6601, 29): '"""math.segment_min"""', (6601, 31, 6601, 44): '"""segment_min"""'}, {}), "('math.segment_min', 'segment_min')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6674, 1, 6674, 47), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6674, 11, 6674, 30): '"""math.segment_prod"""', (6674, 32, 6674, 46): '"""segment_prod"""'}, {}), "('math.segment_prod', 'segment_prod')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((6747, 1, 6747, 45), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(6747, 11, 6747, 29): '"""math.segment_sum"""', (6747, 31, 6747, 44): '"""segment_sum"""'}, {}), "('math.segment_sum', 'segment_sum')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((7096, 1, 7096, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(7096, 11, 7096, 21): '"""math.sin"""', (7096, 23, 7096, 28): '"""sin"""'}, {}), "('math.sin', 'sin')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((7152, 1, 7152, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(7152, 11, 7152, 22): '"""math.sinh"""', (7152, 24, 7152, 30): '"""sinh"""'}, {}), "('math.sinh', 'sinh')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8110, 1, 8110, 59), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8110, 11, 8110, 36): '"""math.squared_difference"""', (8110, 38, 8110, 58): '"""squared_difference"""'}, {}), "('math.squared_difference', 'squared_difference')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8306, 1, 8306, 29), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8306, 11, 8306, 21): '"""math.tan"""', (8306, 23, 8306, 28): '"""tan"""'}, {}), "('math.tan', 'tan')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8605, 1, 8605, 63), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8605, 11, 8605, 38): '"""math.unsorted_segment_max"""', (8605, 40, 8605, 62): '"""unsorted_segment_max"""'}, {}), "('math.unsorted_segment_max', 'unsorted_segment_max')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8689, 1, 8689, 63), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8689, 11, 8689, 38): '"""math.unsorted_segment_min"""', (8689, 40, 8689, 62): '"""unsorted_segment_min"""'}, {}), "('math.unsorted_segment_min', 'unsorted_segment_min')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8769, 1, 8769, 65), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8769, 11, 8769, 39): '"""math.unsorted_segment_prod"""', (8769, 41, 8769, 64): '"""unsorted_segment_prod"""'}, {}), "('math.unsorted_segment_prod', 'unsorted_segment_prod')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8848, 1, 8848, 63), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8848, 11, 8848, 38): '"""math.unsorted_segment_sum"""', (8848, 40, 8848, 62): '"""unsorted_segment_sum"""'}, {}), "('math.unsorted_segment_sum', 'unsorted_segment_sum')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((8932, 1, 8932, 31), 'tensorflow.python.util.tf_export.tf_export', 'tf_export', ({(8932, 11, 8932, 22): '"""math.zeta"""', (8932, 24, 8932, 30): '"""zeta"""'}, {}), "('math.zeta', 'zeta')", False, 'from tensorflow.python.util.tf_export import tf_export\n'), ((75, 18, 75, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(75, 50, 75, 53): '[x]', (75, 55, 75, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((78, 12, 79, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((80, 2, 81, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(81, 6, 81, 11): '"""Abs"""', (81, 13, 81, 25): '_inputs_flat', (81, 27, 81, 33): '_attrs', (81, 35, 81, 42): '_result', (81, 44, 81, 48): 'name'}, {}), "('Abs', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((155, 10, 155, 45), 'tensorflow.python.eager.execute.make_shape', '_execute.make_shape', ({(155, 30, 155, 35): 'shape', (155, 37, 155, 44): '"""shape"""'}, {}), "(shape, 'shape')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((159, 12, 160, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((161, 2, 162, 59), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(162, 6, 162, 21): '"""AccumulateNV2"""', (162, 23, 162, 35): '_inputs_flat', (162, 37, 162, 43): '_attrs', (162, 45, 162, 52): '_result', (162, 54, 162, 58): 'name'}, {}), "('AccumulateNV2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((212, 18, 212, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(212, 50, 212, 53): '[x]', (212, 55, 212, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((215, 12, 216, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((217, 2, 218, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(218, 6, 218, 12): '"""Acos"""', (218, 14, 218, 26): '_inputs_flat', (218, 28, 218, 34): '_attrs', (218, 36, 218, 43): '_result', (218, 45, 218, 49): 'name'}, {}), "('Acos', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((268, 18, 268, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(268, 50, 268, 53): '[x]', (268, 55, 268, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((271, 12, 272, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((273, 2, 274, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(274, 6, 274, 13): '"""Acosh"""', (274, 15, 274, 27): '_inputs_flat', (274, 29, 274, 35): '_attrs', (274, 37, 274, 44): '_result', (274, 46, 274, 50): 'name'}, {}), "('Acosh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((328, 23, 328, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(328, 55, 328, 61): '[x, y]', (328, 63, 328, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((332, 12, 333, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((334, 2, 335, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(335, 6, 335, 11): '"""Add"""', (335, 13, 335, 25): '_inputs_flat', (335, 27, 335, 33): '_attrs', (335, 35, 335, 42): '_result', (335, 44, 335, 48): 'name'}, {}), "('Add', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((398, 12, 399, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((400, 2, 401, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(401, 6, 401, 12): '"""AddN"""', (401, 14, 401, 26): '_inputs_flat', (401, 28, 401, 34): '_attrs', (401, 36, 401, 43): '_result', (401, 45, 401, 49): 'name'}, {}), "('AddN', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((454, 23, 454, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(454, 55, 454, 61): '[x, y]', (454, 63, 454, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((458, 12, 459, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((460, 2, 461, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(461, 6, 461, 13): '"""AddV2"""', (461, 15, 461, 27): '_inputs_flat', (461, 29, 461, 35): '_attrs', (461, 37, 461, 44): '_result', (461, 46, 461, 50): 'name'}, {}), "('AddV2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((527, 14, 527, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(527, 33, 527, 42): 'keep_dims', (527, 44, 527, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((528, 24, 528, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(528, 56, 528, 62): '[axis]', (528, 64, 528, 68): '_ctx', (528, 70, 528, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((529, 10, 529, 53), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(529, 33, 529, 38): 'input', (529, 40, 529, 52): '_dtypes.bool'}, {}), '(input, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((532, 12, 533, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((534, 2, 535, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(535, 6, 535, 11): '"""All"""', (535, 13, 535, 25): '_inputs_flat', (535, 27, 535, 33): '_attrs', (535, 35, 535, 42): '_result', (535, 44, 535, 48): 'name'}, {}), "('All', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((608, 9, 608, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(608, 28, 608, 32): 'Tout', (608, 34, 608, 40): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((609, 22, 609, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(609, 54, 609, 61): '[input]', (609, 63, 609, 67): '_ctx', (609, 69, 609, 86): '_dtypes.complex64'}, {}), '([input], _ctx, _dtypes.complex64)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((612, 12, 613, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((614, 2, 615, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(615, 6, 615, 13): '"""Angle"""', (615, 15, 615, 27): '_inputs_flat', (615, 29, 615, 35): '_attrs', (615, 37, 615, 44): '_result', (615, 46, 615, 50): 'name'}, {}), "('Angle', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((681, 14, 681, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(681, 33, 681, 42): 'keep_dims', (681, 44, 681, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((682, 24, 682, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(682, 56, 682, 62): '[axis]', (682, 64, 682, 68): '_ctx', (682, 70, 682, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((683, 10, 683, 53), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(683, 33, 683, 38): 'input', (683, 40, 683, 52): '_dtypes.bool'}, {}), '(input, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((686, 12, 687, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((688, 2, 689, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(689, 6, 689, 11): '"""Any"""', (689, 13, 689, 25): '_inputs_flat', (689, 27, 689, 33): '_attrs', (689, 35, 689, 42): '_result', (689, 44, 689, 48): 'name'}, {}), "('Any', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((746, 14, 746, 57), 'tensorflow.python.eager.execute.make_float', '_execute.make_float', ({(746, 34, 746, 43): 'tolerance', (746, 45, 746, 56): '"""tolerance"""'}, {}), "(tolerance, 'tolerance')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((747, 23, 747, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(747, 55, 747, 61): '[x, y]', (747, 63, 747, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((751, 12, 752, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((753, 2, 754, 62), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(754, 6, 754, 24): '"""ApproximateEqual"""', (754, 26, 754, 38): '_inputs_flat', (754, 40, 754, 46): '_attrs', (754, 48, 754, 55): '_result', (754, 57, 754, 61): 'name'}, {}), "('ApproximateEqual', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((818, 16, 818, 62), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(818, 35, 818, 46): 'output_type', (818, 48, 818, 61): '"""output_type"""'}, {}), "(output_type, 'output_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((819, 22, 819, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(819, 54, 819, 61): '[input]', (819, 63, 819, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((820, 29, 820, 94), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(820, 61, 820, 72): '[dimension]', (820, 74, 820, 78): '_ctx', (820, 80, 820, 93): '_dtypes.int32'}, {}), '([dimension], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((823, 12, 824, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((825, 2, 826, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(826, 6, 826, 14): '"""ArgMax"""', (826, 16, 826, 28): '_inputs_flat', (826, 30, 826, 36): '_attrs', (826, 38, 826, 45): '_result', (826, 47, 826, 51): 'name'}, {}), "('ArgMax', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((890, 16, 890, 62), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(890, 35, 890, 46): 'output_type', (890, 48, 890, 61): '"""output_type"""'}, {}), "(output_type, 'output_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((891, 22, 891, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(891, 54, 891, 61): '[input]', (891, 63, 891, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((892, 29, 892, 94), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(892, 61, 892, 72): '[dimension]', (892, 74, 892, 78): '_ctx', (892, 80, 892, 93): '_dtypes.int32'}, {}), '([dimension], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((895, 12, 896, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((897, 2, 898, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(898, 6, 898, 14): '"""ArgMin"""', (898, 16, 898, 28): '_inputs_flat', (898, 30, 898, 36): '_attrs', (898, 38, 898, 45): '_result', (898, 47, 898, 51): 'name'}, {}), "('ArgMin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((948, 18, 948, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(948, 50, 948, 53): '[x]', (948, 55, 948, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((951, 12, 952, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((953, 2, 954, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(954, 6, 954, 12): '"""Asin"""', (954, 14, 954, 26): '_inputs_flat', (954, 28, 954, 34): '_attrs', (954, 36, 954, 43): '_result', (954, 45, 954, 49): 'name'}, {}), "('Asin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1004, 18, 1004, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1004, 50, 1004, 53): '[x]', (1004, 55, 1004, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1007, 12, 1008, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1009, 2, 1010, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1010, 6, 1010, 13): '"""Asinh"""', (1010, 15, 1010, 27): '_inputs_flat', (1010, 29, 1010, 35): '_attrs', (1010, 37, 1010, 44): '_result', (1010, 46, 1010, 50): 'name'}, {}), "('Asinh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1060, 18, 1060, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1060, 50, 1060, 53): '[x]', (1060, 55, 1060, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1063, 12, 1064, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1065, 2, 1066, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1066, 6, 1066, 12): '"""Atan"""', (1066, 14, 1066, 26): '_inputs_flat', (1066, 28, 1066, 34): '_attrs', (1066, 36, 1066, 43): '_result', (1066, 45, 1066, 49): 'name'}, {}), "('Atan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1123, 23, 1123, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1123, 55, 1123, 61): '[y, x]', (1123, 63, 1123, 67): '_ctx'}, {}), '([y, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1127, 12, 1128, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1129, 2, 1130, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1130, 6, 1130, 13): '"""Atan2"""', (1130, 15, 1130, 27): '_inputs_flat', (1130, 29, 1130, 35): '_attrs', (1130, 37, 1130, 44): '_result', (1130, 46, 1130, 50): 'name'}, {}), "('Atan2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1180, 18, 1180, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1180, 50, 1180, 53): '[x]', (1180, 55, 1180, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1183, 12, 1184, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1185, 2, 1186, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1186, 6, 1186, 13): '"""Atanh"""', (1186, 15, 1186, 27): '_inputs_flat', (1186, 29, 1186, 35): '_attrs', (1186, 37, 1186, 44): '_result', (1186, 46, 1186, 50): 'name'}, {}), "('Atanh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1271, 10, 1271, 44), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(1271, 29, 1271, 34): 'adj_x', (1271, 36, 1271, 43): '"""adj_x"""'}, {}), "(adj_x, 'adj_x')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1274, 10, 1274, 44), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(1274, 29, 1274, 34): 'adj_y', (1274, 36, 1274, 43): '"""adj_y"""'}, {}), "(adj_y, 'adj_y')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1275, 23, 1275, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1275, 55, 1275, 61): '[x, y]', (1275, 63, 1275, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1279, 12, 1280, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1281, 2, 1282, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1282, 6, 1282, 19): '"""BatchMatMul"""', (1282, 21, 1282, 33): '_inputs_flat', (1282, 35, 1282, 41): '_attrs', (1282, 43, 1282, 50): '_result', (1282, 52, 1282, 56): 'name'}, {}), "('BatchMatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1336, 18, 1336, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1336, 50, 1336, 53): '[x]', (1336, 55, 1336, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1339, 12, 1340, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1341, 2, 1342, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1342, 6, 1342, 17): '"""BesselI0e"""', (1342, 19, 1342, 31): '_inputs_flat', (1342, 33, 1342, 39): '_attrs', (1342, 41, 1342, 48): '_result', (1342, 50, 1342, 54): 'name'}, {}), "('BesselI0e', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1396, 18, 1396, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1396, 50, 1396, 53): '[x]', (1396, 55, 1396, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1399, 12, 1400, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1401, 2, 1402, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1402, 6, 1402, 17): '"""BesselI1e"""', (1402, 19, 1402, 31): '_inputs_flat', (1402, 33, 1402, 39): '_attrs', (1402, 41, 1402, 48): '_result', (1402, 50, 1402, 54): 'name'}, {}), "('BesselI1e', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1468, 23, 1468, 71), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1468, 55, 1468, 64): '[a, b, x]', (1468, 66, 1468, 70): '_ctx'}, {}), '([a, b, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1472, 12, 1473, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1474, 2, 1475, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1475, 6, 1475, 15): '"""Betainc"""', (1475, 17, 1475, 29): '_inputs_flat', (1475, 31, 1475, 37): '_attrs', (1475, 39, 1475, 46): '_result', (1475, 48, 1475, 52): 'name'}, {}), "('Betainc', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1537, 24, 1537, 72), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1537, 56, 1537, 65): '[weights]', (1537, 67, 1537, 71): '_ctx'}, {}), '([weights], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1538, 8, 1538, 50), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(1538, 31, 1538, 34): 'arr', (1538, 36, 1538, 49): '_dtypes.int32'}, {}), '(arr, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((1539, 9, 1539, 52), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(1539, 32, 1539, 36): 'size', (1539, 38, 1539, 51): '_dtypes.int32'}, {}), '(size, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((1542, 12, 1543, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1544, 2, 1545, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1545, 6, 1545, 16): '"""Bincount"""', (1545, 18, 1545, 30): '_inputs_flat', (1545, 32, 1545, 38): '_attrs', (1545, 40, 1545, 47): '_result', (1545, 49, 1545, 53): 'name'}, {}), "('Bincount', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1619, 22, 1619, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1619, 54, 1619, 61): '[input]', (1619, 63, 1619, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1622, 12, 1623, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1624, 2, 1625, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1625, 6, 1625, 17): '"""Bucketize"""', (1625, 19, 1625, 31): '_inputs_flat', (1625, 33, 1625, 39): '_attrs', (1625, 41, 1625, 48): '_result', (1625, 50, 1625, 54): 'name'}, {}), "('Bucketize', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1676, 9, 1676, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(1676, 28, 1676, 32): 'DstT', (1676, 34, 1676, 40): '"""DstT"""'}, {}), "(DstT, 'DstT')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1677, 21, 1677, 63), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1677, 53, 1677, 56): '[x]', (1677, 58, 1677, 62): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1680, 12, 1681, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1682, 2, 1683, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1683, 6, 1683, 12): '"""Cast"""', (1683, 14, 1683, 26): '_inputs_flat', (1683, 28, 1683, 34): '_attrs', (1683, 36, 1683, 43): '_result', (1683, 45, 1683, 49): 'name'}, {}), "('Cast', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1733, 18, 1733, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1733, 50, 1733, 53): '[x]', (1733, 55, 1733, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1736, 12, 1737, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1738, 2, 1739, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1739, 6, 1739, 12): '"""Ceil"""', (1739, 14, 1739, 26): '_inputs_flat', (1739, 28, 1739, 34): '_attrs', (1739, 36, 1739, 43): '_result', (1739, 45, 1739, 49): 'name'}, {}), "('Ceil', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1802, 23, 1802, 97), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1802, 55, 1802, 90): '[t, clip_value_min, clip_value_max]', (1802, 92, 1802, 96): '_ctx'}, {}), '([t, clip_value_min, clip_value_max], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1806, 12, 1807, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1808, 2, 1809, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1809, 6, 1809, 19): '"""ClipByValue"""', (1809, 21, 1809, 33): '_inputs_flat', (1809, 35, 1809, 41): '_attrs', (1809, 43, 1809, 50): '_result', (1809, 52, 1809, 56): 'name'}, {}), "('ClipByValue', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1886, 23, 1886, 80), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1886, 55, 1886, 73): '[input, threshold]', (1886, 75, 1886, 79): '_ctx'}, {}), '([input, threshold], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1890, 12, 1891, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1892, 2, 1893, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1893, 6, 1893, 25): '"""CompareAndBitpack"""', (1893, 27, 1893, 39): '_inputs_flat', (1893, 41, 1893, 47): '_attrs', (1893, 49, 1893, 56): '_result', (1893, 58, 1893, 62): 'name'}, {}), "('CompareAndBitpack', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1964, 9, 1964, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(1964, 28, 1964, 32): 'Tout', (1964, 34, 1964, 40): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1965, 23, 1965, 91), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(1965, 55, 1965, 67): '[real, imag]', (1965, 69, 1965, 73): '_ctx', (1965, 75, 1965, 90): '_dtypes.float32'}, {}), '([real, imag], _ctx, _dtypes.float32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1969, 12, 1970, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((1971, 2, 1972, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1972, 6, 1972, 15): '"""Complex"""', (1972, 17, 1972, 29): '_inputs_flat', (1972, 31, 1972, 37): '_attrs', (1972, 39, 1972, 46): '_result', (1972, 48, 1972, 52): 'name'}, {}), "('Complex', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2032, 9, 2032, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(2032, 28, 2032, 32): 'Tout', (2032, 34, 2032, 40): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2033, 18, 2033, 79), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2033, 50, 2033, 53): '[x]', (2033, 55, 2033, 59): '_ctx', (2033, 61, 2033, 78): '_dtypes.complex64'}, {}), '([x], _ctx, _dtypes.complex64)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2036, 12, 2037, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2038, 2, 2039, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2039, 6, 2039, 18): '"""ComplexAbs"""', (2039, 20, 2039, 32): '_inputs_flat', (2039, 34, 2039, 40): '_attrs', (2039, 42, 2039, 49): '_result', (2039, 51, 2039, 55): 'name'}, {}), "('ComplexAbs', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2102, 22, 2102, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2102, 54, 2102, 61): '[input]', (2102, 63, 2102, 67): '_ctx', (2102, 69, 2102, 86): '_dtypes.complex64'}, {}), '([input], _ctx, _dtypes.complex64)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2105, 12, 2106, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2107, 2, 2108, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2108, 6, 2108, 12): '"""Conj"""', (2108, 14, 2108, 26): '_inputs_flat', (2108, 28, 2108, 34): '_attrs', (2108, 36, 2108, 43): '_result', (2108, 45, 2108, 49): 'name'}, {}), "('Conj', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2158, 18, 2158, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2158, 50, 2158, 53): '[x]', (2158, 55, 2158, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2161, 12, 2162, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2163, 2, 2164, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2164, 6, 2164, 11): '"""Cos"""', (2164, 13, 2164, 25): '_inputs_flat', (2164, 27, 2164, 33): '_attrs', (2164, 35, 2164, 42): '_result', (2164, 44, 2164, 48): 'name'}, {}), "('Cos', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2214, 18, 2214, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2214, 50, 2214, 53): '[x]', (2214, 55, 2214, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2217, 12, 2218, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2219, 2, 2220, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2220, 6, 2220, 12): '"""Cosh"""', (2220, 14, 2220, 26): '_inputs_flat', (2220, 28, 2220, 34): '_attrs', (2220, 36, 2220, 43): '_result', (2220, 45, 2220, 49): 'name'}, {}), "('Cosh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2277, 23, 2277, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2277, 55, 2277, 61): '[a, b]', (2277, 63, 2277, 67): '_ctx'}, {}), '([a, b], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2281, 12, 2282, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2283, 2, 2284, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2284, 6, 2284, 13): '"""Cross"""', (2284, 15, 2284, 27): '_inputs_flat', (2284, 29, 2284, 35): '_attrs', (2284, 37, 2284, 44): '_result', (2284, 46, 2284, 50): 'name'}, {}), "('Cross', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2384, 14, 2384, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2384, 33, 2384, 42): 'exclusive', (2384, 44, 2384, 55): '"""exclusive"""'}, {}), "(exclusive, 'exclusive')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2387, 12, 2387, 50), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2387, 31, 2387, 38): 'reverse', (2387, 40, 2387, 49): '"""reverse"""'}, {}), "(reverse, 'reverse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2388, 18, 2388, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2388, 50, 2388, 53): '[x]', (2388, 55, 2388, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2389, 24, 2389, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2389, 56, 2389, 62): '[axis]', (2389, 64, 2389, 68): '_ctx', (2389, 70, 2389, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2393, 12, 2394, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2395, 2, 2396, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2396, 6, 2396, 15): '"""Cumprod"""', (2396, 17, 2396, 29): '_inputs_flat', (2396, 31, 2396, 37): '_attrs', (2396, 39, 2396, 46): '_result', (2396, 48, 2396, 52): 'name'}, {}), "('Cumprod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2496, 14, 2496, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2496, 33, 2496, 42): 'exclusive', (2496, 44, 2496, 55): '"""exclusive"""'}, {}), "(exclusive, 'exclusive')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2499, 12, 2499, 50), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2499, 31, 2499, 38): 'reverse', (2499, 40, 2499, 49): '"""reverse"""'}, {}), "(reverse, 'reverse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2500, 18, 2500, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2500, 50, 2500, 53): '[x]', (2500, 55, 2500, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2501, 24, 2501, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2501, 56, 2501, 62): '[axis]', (2501, 64, 2501, 68): '_ctx', (2501, 70, 2501, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2505, 12, 2506, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2507, 2, 2508, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2508, 6, 2508, 14): '"""Cumsum"""', (2508, 16, 2508, 28): '_inputs_flat', (2508, 30, 2508, 36): '_attrs', (2508, 38, 2508, 45): '_result', (2508, 47, 2508, 51): 'name'}, {}), "('Cumsum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2560, 18, 2560, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2560, 50, 2560, 53): '[x]', (2560, 55, 2560, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2563, 12, 2564, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2565, 2, 2566, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2566, 6, 2566, 15): '"""Digamma"""', (2566, 17, 2566, 29): '_inputs_flat', (2566, 31, 2566, 37): '_attrs', (2566, 39, 2566, 46): '_result', (2566, 48, 2566, 52): 'name'}, {}), "('Digamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2619, 23, 2619, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2619, 55, 2619, 61): '[x, y]', (2619, 63, 2619, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2623, 12, 2624, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2625, 2, 2626, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2626, 6, 2626, 11): '"""Div"""', (2626, 13, 2626, 25): '_inputs_flat', (2626, 27, 2626, 33): '_attrs', (2626, 35, 2626, 42): '_result', (2626, 44, 2626, 48): 'name'}, {}), "('Div', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2680, 23, 2680, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2680, 55, 2680, 61): '[x, y]', (2680, 63, 2680, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2684, 12, 2685, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2686, 2, 2687, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2687, 6, 2687, 13): '"""Equal"""', (2687, 15, 2687, 27): '_inputs_flat', (2687, 29, 2687, 35): '_attrs', (2687, 37, 2687, 44): '_result', (2687, 46, 2687, 50): 'name'}, {}), "('Equal', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2736, 18, 2736, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2736, 50, 2736, 53): '[x]', (2736, 55, 2736, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2739, 12, 2740, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2741, 2, 2742, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2742, 6, 2742, 11): '"""Erf"""', (2742, 13, 2742, 25): '_inputs_flat', (2742, 27, 2742, 33): '_attrs', (2742, 35, 2742, 42): '_result', (2742, 44, 2742, 48): 'name'}, {}), "('Erf', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2792, 18, 2792, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2792, 50, 2792, 53): '[x]', (2792, 55, 2792, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2795, 12, 2796, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2797, 2, 2798, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2798, 6, 2798, 12): '"""Erfc"""', (2798, 14, 2798, 26): '_inputs_flat', (2798, 28, 2798, 34): '_attrs', (2798, 36, 2798, 43): '_result', (2798, 45, 2798, 49): 'name'}, {}), "('Erfc', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2848, 18, 2848, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2848, 50, 2848, 53): '[x]', (2848, 55, 2848, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2851, 12, 2852, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2853, 2, 2854, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2854, 6, 2854, 11): '"""Exp"""', (2854, 13, 2854, 25): '_inputs_flat', (2854, 27, 2854, 33): '_attrs', (2854, 35, 2854, 42): '_result', (2854, 44, 2854, 48): 'name'}, {}), "('Exp', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2906, 18, 2906, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2906, 50, 2906, 53): '[x]', (2906, 55, 2906, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2909, 12, 2910, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2911, 2, 2912, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2912, 6, 2912, 13): '"""Expm1"""', (2912, 15, 2912, 27): '_inputs_flat', (2912, 29, 2912, 35): '_attrs', (2912, 37, 2912, 44): '_result', (2912, 46, 2912, 50): 'name'}, {}), "('Expm1', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2962, 18, 2962, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(2962, 50, 2962, 53): '[x]', (2962, 55, 2962, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2965, 12, 2966, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((2967, 2, 2968, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2968, 6, 2968, 13): '"""Floor"""', (2968, 15, 2968, 27): '_inputs_flat', (2968, 29, 2968, 35): '_attrs', (2968, 37, 2968, 44): '_result', (2968, 46, 2968, 50): 'name'}, {}), "('Floor', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3021, 23, 3021, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3021, 55, 3021, 61): '[x, y]', (3021, 63, 3021, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3025, 12, 3026, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3027, 2, 3028, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3028, 6, 3028, 16): '"""FloorDiv"""', (3028, 18, 3028, 30): '_inputs_flat', (3028, 32, 3028, 38): '_attrs', (3028, 40, 3028, 47): '_result', (3028, 49, 3028, 53): 'name'}, {}), "('FloorDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3084, 23, 3084, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3084, 55, 3084, 61): '[x, y]', (3084, 63, 3084, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3088, 12, 3089, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3090, 2, 3091, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3091, 6, 3091, 16): '"""FloorMod"""', (3091, 18, 3091, 30): '_inputs_flat', (3091, 32, 3091, 38): '_attrs', (3091, 40, 3091, 47): '_result', (3091, 49, 3091, 53): 'name'}, {}), "('FloorMod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3145, 23, 3145, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3145, 55, 3145, 61): '[x, y]', (3145, 63, 3145, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3149, 12, 3150, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3151, 2, 3152, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3152, 6, 3152, 15): '"""Greater"""', (3152, 17, 3152, 29): '_inputs_flat', (3152, 31, 3152, 37): '_attrs', (3152, 39, 3152, 46): '_result', (3152, 48, 3152, 52): 'name'}, {}), "('Greater', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3206, 23, 3206, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3206, 55, 3206, 61): '[x, y]', (3206, 63, 3206, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3210, 12, 3211, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3212, 2, 3213, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3213, 6, 3213, 20): '"""GreaterEqual"""', (3213, 22, 3213, 34): '_inputs_flat', (3213, 36, 3213, 42): '_attrs', (3213, 44, 3213, 51): '_result', (3213, 53, 3213, 57): 'name'}, {}), "('GreaterEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3293, 10, 3293, 44), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(3293, 29, 3293, 34): 'dtype', (3293, 36, 3293, 43): '"""dtype"""'}, {}), "(dtype, 'dtype')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3294, 23, 3294, 83), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3294, 55, 3294, 76): '[values, value_range]', (3294, 78, 3294, 82): '_ctx'}, {}), '([values, value_range], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3296, 10, 3296, 54), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(3296, 33, 3296, 38): 'nbins', (3296, 40, 3296, 53): '_dtypes.int32'}, {}), '(nbins, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((3299, 12, 3300, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3301, 2, 3302, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3302, 6, 3302, 27): '"""HistogramFixedWidth"""', (3302, 29, 3302, 41): '_inputs_flat', (3302, 43, 3302, 49): '_attrs', (3302, 51, 3302, 58): '_result', (3302, 60, 3302, 64): 'name'}, {}), "('HistogramFixedWidth', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3367, 23, 3367, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3367, 55, 3367, 61): '[a, x]', (3367, 63, 3367, 67): '_ctx'}, {}), '([a, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3371, 12, 3372, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3373, 2, 3374, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3374, 6, 3374, 14): '"""Igamma"""', (3374, 16, 3374, 28): '_inputs_flat', (3374, 30, 3374, 36): '_attrs', (3374, 38, 3374, 45): '_result', (3374, 47, 3374, 51): 'name'}, {}), "('Igamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3424, 23, 3424, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3424, 55, 3424, 61): '[a, x]', (3424, 63, 3424, 67): '_ctx'}, {}), '([a, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3428, 12, 3429, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3430, 2, 3431, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3431, 6, 3431, 19): '"""IgammaGradA"""', (3431, 21, 3431, 33): '_inputs_flat', (3431, 35, 3431, 41): '_attrs', (3431, 43, 3431, 50): '_result', (3431, 52, 3431, 56): 'name'}, {}), "('IgammaGradA', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3495, 23, 3495, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3495, 55, 3495, 61): '[a, x]', (3495, 63, 3495, 67): '_ctx'}, {}), '([a, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3499, 12, 3500, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3501, 2, 3502, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3502, 6, 3502, 15): '"""Igammac"""', (3502, 17, 3502, 29): '_inputs_flat', (3502, 31, 3502, 37): '_attrs', (3502, 39, 3502, 46): '_result', (3502, 48, 3502, 52): 'name'}, {}), "('Igammac', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3569, 9, 3569, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(3569, 28, 3569, 32): 'Tout', (3569, 34, 3569, 40): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3570, 22, 3570, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3570, 54, 3570, 61): '[input]', (3570, 63, 3570, 67): '_ctx', (3570, 69, 3570, 86): '_dtypes.complex64'}, {}), '([input], _ctx, _dtypes.complex64)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3573, 12, 3574, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3575, 2, 3576, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3576, 6, 3576, 12): '"""Imag"""', (3576, 14, 3576, 26): '_inputs_flat', (3576, 28, 3576, 34): '_attrs', (3576, 36, 3576, 43): '_result', (3576, 45, 3576, 49): 'name'}, {}), "('Imag', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3627, 18, 3627, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3627, 50, 3627, 53): '[x]', (3627, 55, 3627, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3630, 12, 3631, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3632, 2, 3633, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3633, 6, 3633, 11): '"""Inv"""', (3633, 13, 3633, 25): '_inputs_flat', (3633, 27, 3633, 33): '_attrs', (3633, 35, 3633, 42): '_result', (3633, 44, 3633, 48): 'name'}, {}), "('Inv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3686, 23, 3686, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3686, 55, 3686, 62): '[y, dy]', (3686, 64, 3686, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3690, 12, 3691, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3692, 2, 3693, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3693, 6, 3693, 15): '"""InvGrad"""', (3693, 17, 3693, 29): '_inputs_flat', (3693, 31, 3693, 37): '_attrs', (3693, 39, 3693, 46): '_result', (3693, 48, 3693, 52): 'name'}, {}), "('InvGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3747, 18, 3747, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3747, 50, 3747, 53): '[x]', (3747, 55, 3747, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3750, 12, 3751, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3752, 2, 3753, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3753, 6, 3753, 16): '"""IsFinite"""', (3753, 18, 3753, 30): '_inputs_flat', (3753, 32, 3753, 38): '_attrs', (3753, 40, 3753, 47): '_result', (3753, 49, 3753, 53): 'name'}, {}), "('IsFinite', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3807, 18, 3807, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3807, 50, 3807, 53): '[x]', (3807, 55, 3807, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3810, 12, 3811, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3812, 2, 3813, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3813, 6, 3813, 13): '"""IsInf"""', (3813, 15, 3813, 27): '_inputs_flat', (3813, 29, 3813, 35): '_attrs', (3813, 37, 3813, 44): '_result', (3813, 46, 3813, 50): 'name'}, {}), "('IsInf', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3867, 18, 3867, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3867, 50, 3867, 53): '[x]', (3867, 55, 3867, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3870, 12, 3871, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3872, 2, 3873, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3873, 6, 3873, 13): '"""IsNan"""', (3873, 15, 3873, 27): '_inputs_flat', (3873, 29, 3873, 35): '_attrs', (3873, 37, 3873, 44): '_result', (3873, 46, 3873, 50): 'name'}, {}), "('IsNan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3927, 23, 3927, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3927, 55, 3927, 61): '[x, y]', (3927, 63, 3927, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3931, 12, 3932, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3933, 2, 3934, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3934, 6, 3934, 12): '"""Less"""', (3934, 14, 3934, 26): '_inputs_flat', (3934, 28, 3934, 34): '_attrs', (3934, 36, 3934, 43): '_result', (3934, 45, 3934, 49): 'name'}, {}), "('Less', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3988, 23, 3988, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(3988, 55, 3988, 61): '[x, y]', (3988, 63, 3988, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3992, 12, 3993, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((3994, 2, 3995, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3995, 6, 3995, 17): '"""LessEqual"""', (3995, 19, 3995, 31): '_inputs_flat', (3995, 33, 3995, 39): '_attrs', (3995, 41, 3995, 48): '_result', (3995, 50, 3995, 54): 'name'}, {}), "('LessEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4045, 18, 4045, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4045, 50, 4045, 53): '[x]', (4045, 55, 4045, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4048, 12, 4049, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4050, 2, 4051, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4051, 6, 4051, 14): '"""Lgamma"""', (4051, 16, 4051, 28): '_inputs_flat', (4051, 30, 4051, 36): '_attrs', (4051, 38, 4051, 45): '_result', (4051, 47, 4051, 51): 'name'}, {}), "('Lgamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4116, 23, 4116, 75), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4116, 55, 4116, 68): '[start, stop]', (4116, 70, 4116, 74): '_ctx'}, {}), '([start, stop], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4118, 23, 4118, 82), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4118, 55, 4118, 60): '[num]', (4118, 62, 4118, 66): '_ctx', (4118, 68, 4118, 81): '_dtypes.int32'}, {}), '([num], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4121, 12, 4122, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4123, 2, 4124, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4124, 6, 4124, 16): '"""LinSpace"""', (4124, 18, 4124, 30): '_inputs_flat', (4124, 32, 4124, 38): '_attrs', (4124, 40, 4124, 47): '_result', (4124, 49, 4124, 53): 'name'}, {}), "('LinSpace', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4176, 18, 4176, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4176, 50, 4176, 53): '[x]', (4176, 55, 4176, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4179, 12, 4180, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4181, 2, 4182, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4182, 6, 4182, 11): '"""Log"""', (4182, 13, 4182, 25): '_inputs_flat', (4182, 27, 4182, 33): '_attrs', (4182, 35, 4182, 42): '_result', (4182, 44, 4182, 48): 'name'}, {}), "('Log', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4234, 18, 4234, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4234, 50, 4234, 53): '[x]', (4234, 55, 4234, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4237, 12, 4238, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4239, 2, 4240, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4240, 6, 4240, 13): '"""Log1p"""', (4240, 15, 4240, 27): '_inputs_flat', (4240, 29, 4240, 35): '_attrs', (4240, 37, 4240, 44): '_result', (4240, 46, 4240, 50): 'name'}, {}), "('Log1p', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4294, 6, 4294, 45), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(4294, 29, 4294, 30): 'x', (4294, 32, 4294, 44): '_dtypes.bool'}, {}), '(x, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((4295, 6, 4295, 45), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(4295, 29, 4295, 30): 'y', (4295, 32, 4295, 44): '_dtypes.bool'}, {}), '(y, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((4298, 12, 4299, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4300, 2, 4301, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4301, 6, 4301, 18): '"""LogicalAnd"""', (4301, 20, 4301, 32): '_inputs_flat', (4301, 34, 4301, 40): '_attrs', (4301, 42, 4301, 49): '_result', (4301, 51, 4301, 55): 'name'}, {}), "('LogicalAnd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4351, 6, 4351, 45), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(4351, 29, 4351, 30): 'x', (4351, 32, 4351, 44): '_dtypes.bool'}, {}), '(x, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((4354, 12, 4355, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4356, 2, 4357, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4357, 6, 4357, 18): '"""LogicalNot"""', (4357, 20, 4357, 32): '_inputs_flat', (4357, 34, 4357, 40): '_attrs', (4357, 42, 4357, 49): '_result', (4357, 51, 4357, 55): 'name'}, {}), "('LogicalNot', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4411, 6, 4411, 45), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(4411, 29, 4411, 30): 'x', (4411, 32, 4411, 44): '_dtypes.bool'}, {}), '(x, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((4412, 6, 4412, 45), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(4412, 29, 4412, 30): 'y', (4412, 32, 4412, 44): '_dtypes.bool'}, {}), '(y, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((4415, 12, 4416, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4417, 2, 4418, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4418, 6, 4418, 17): '"""LogicalOr"""', (4418, 19, 4418, 31): '_inputs_flat', (4418, 33, 4418, 39): '_attrs', (4418, 41, 4418, 48): '_result', (4418, 50, 4418, 54): 'name'}, {}), "('LogicalOr', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4492, 16, 4492, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4492, 35, 4492, 46): 'transpose_a', (4492, 48, 4492, 61): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4495, 16, 4495, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4495, 35, 4495, 46): 'transpose_b', (4495, 48, 4495, 61): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4496, 23, 4496, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4496, 55, 4496, 61): '[a, b]', (4496, 63, 4496, 67): '_ctx'}, {}), '([a, b], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4501, 12, 4502, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4503, 2, 4504, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4504, 6, 4504, 14): '"""MatMul"""', (4504, 16, 4504, 28): '_inputs_flat', (4504, 30, 4504, 36): '_attrs', (4504, 38, 4504, 45): '_result', (4504, 47, 4504, 51): 'name'}, {}), "('MatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4571, 14, 4571, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4571, 33, 4571, 42): 'keep_dims', (4571, 44, 4571, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4572, 22, 4572, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4572, 54, 4572, 61): '[input]', (4572, 63, 4572, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4573, 24, 4573, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4573, 56, 4573, 62): '[axis]', (4573, 64, 4573, 68): '_ctx', (4573, 70, 4573, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4576, 12, 4577, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4578, 2, 4579, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4579, 6, 4579, 11): '"""Max"""', (4579, 13, 4579, 25): '_inputs_flat', (4579, 27, 4579, 33): '_attrs', (4579, 35, 4579, 42): '_result', (4579, 44, 4579, 48): 'name'}, {}), "('Max', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4633, 23, 4633, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4633, 55, 4633, 61): '[x, y]', (4633, 63, 4633, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4637, 12, 4638, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4639, 2, 4640, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4640, 6, 4640, 15): '"""Maximum"""', (4640, 17, 4640, 29): '_inputs_flat', (4640, 31, 4640, 37): '_attrs', (4640, 39, 4640, 46): '_result', (4640, 48, 4640, 52): 'name'}, {}), "('Maximum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4707, 14, 4707, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4707, 33, 4707, 42): 'keep_dims', (4707, 44, 4707, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4708, 22, 4708, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4708, 54, 4708, 61): '[input]', (4708, 63, 4708, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4709, 24, 4709, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4709, 56, 4709, 62): '[axis]', (4709, 64, 4709, 68): '_ctx', (4709, 70, 4709, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4712, 12, 4713, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4714, 2, 4715, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4715, 6, 4715, 12): '"""Mean"""', (4715, 14, 4715, 26): '_inputs_flat', (4715, 28, 4715, 34): '_attrs', (4715, 36, 4715, 43): '_result', (4715, 45, 4715, 49): 'name'}, {}), "('Mean', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4782, 14, 4782, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4782, 33, 4782, 42): 'keep_dims', (4782, 44, 4782, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4783, 22, 4783, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4783, 54, 4783, 61): '[input]', (4783, 63, 4783, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4784, 24, 4784, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4784, 56, 4784, 62): '[axis]', (4784, 64, 4784, 68): '_ctx', (4784, 70, 4784, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4787, 12, 4788, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4789, 2, 4790, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4790, 6, 4790, 11): '"""Min"""', (4790, 13, 4790, 25): '_inputs_flat', (4790, 27, 4790, 33): '_attrs', (4790, 35, 4790, 42): '_result', (4790, 44, 4790, 48): 'name'}, {}), "('Min', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4844, 23, 4844, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4844, 55, 4844, 61): '[x, y]', (4844, 63, 4844, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4848, 12, 4849, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4850, 2, 4851, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4851, 6, 4851, 15): '"""Minimum"""', (4851, 17, 4851, 29): '_inputs_flat', (4851, 31, 4851, 37): '_attrs', (4851, 39, 4851, 46): '_result', (4851, 48, 4851, 52): 'name'}, {}), "('Minimum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4907, 23, 4907, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4907, 55, 4907, 61): '[x, y]', (4907, 63, 4907, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4911, 12, 4912, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4913, 2, 4914, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4914, 6, 4914, 11): '"""Mod"""', (4914, 13, 4914, 25): '_inputs_flat', (4914, 27, 4914, 33): '_attrs', (4914, 35, 4914, 42): '_result', (4914, 44, 4914, 48): 'name'}, {}), "('Mod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4967, 23, 4967, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(4967, 55, 4967, 61): '[x, y]', (4967, 63, 4967, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4971, 12, 4972, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((4973, 2, 4974, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4974, 6, 4974, 11): '"""Mul"""', (4974, 13, 4974, 25): '_inputs_flat', (4974, 27, 4974, 33): '_attrs', (4974, 35, 4974, 42): '_result', (4974, 44, 4974, 48): 'name'}, {}), "('Mul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5025, 18, 5025, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5025, 50, 5025, 53): '[x]', (5025, 55, 5025, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5028, 12, 5029, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5030, 2, 5031, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5031, 6, 5031, 11): '"""Neg"""', (5031, 13, 5031, 25): '_inputs_flat', (5031, 27, 5031, 33): '_attrs', (5031, 35, 5031, 42): '_result', (5031, 44, 5031, 48): 'name'}, {}), "('Neg', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5085, 23, 5085, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5085, 55, 5085, 61): '[x, y]', (5085, 63, 5085, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5089, 12, 5090, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5091, 2, 5092, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5092, 6, 5092, 16): '"""NotEqual"""', (5092, 18, 5092, 30): '_inputs_flat', (5092, 32, 5092, 38): '_attrs', (5092, 40, 5092, 47): '_result', (5092, 49, 5092, 53): 'name'}, {}), "('NotEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5150, 23, 5150, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5150, 55, 5150, 61): '[a, x]', (5150, 63, 5150, 67): '_ctx'}, {}), '([a, x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5154, 12, 5155, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5156, 2, 5157, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5157, 6, 5157, 17): '"""Polygamma"""', (5157, 19, 5157, 31): '_inputs_flat', (5157, 33, 5157, 39): '_attrs', (5157, 41, 5157, 48): '_result', (5157, 50, 5157, 54): 'name'}, {}), "('Polygamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5216, 23, 5216, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5216, 55, 5216, 61): '[x, y]', (5216, 63, 5216, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5220, 12, 5221, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5222, 2, 5223, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5223, 6, 5223, 11): '"""Pow"""', (5223, 13, 5223, 25): '_inputs_flat', (5223, 27, 5223, 33): '_attrs', (5223, 35, 5223, 42): '_result', (5223, 44, 5223, 48): 'name'}, {}), "('Pow', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5290, 14, 5290, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5290, 33, 5290, 42): 'keep_dims', (5290, 44, 5290, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5291, 22, 5291, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5291, 54, 5291, 61): '[input]', (5291, 63, 5291, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5292, 24, 5292, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5292, 56, 5292, 62): '[axis]', (5292, 64, 5292, 68): '_ctx', (5292, 70, 5292, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5295, 12, 5296, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5297, 2, 5298, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5298, 6, 5298, 12): '"""Prod"""', (5298, 14, 5298, 26): '_inputs_flat', (5298, 28, 5298, 34): '_attrs', (5298, 36, 5298, 43): '_result', (5298, 45, 5298, 49): 'name'}, {}), "('Prod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5391, 13, 5391, 53), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5391, 32, 5391, 40): 'out_type', (5391, 42, 5391, 52): '"""out_type"""'}, {}), "(out_type, 'out_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5392, 27, 5392, 73), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5392, 59, 5392, 66): '[input]', (5392, 68, 5392, 72): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5393, 14, 5393, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5393, 37, 5393, 46): 'input_min', (5393, 48, 5393, 63): '_dtypes.float32'}, {}), '(input_min, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5394, 14, 5394, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5394, 37, 5394, 46): 'input_max', (5394, 48, 5394, 63): '_dtypes.float32'}, {}), '(input_max, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5397, 12, 5399, 39), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5400, 2, 5401, 72), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5401, 6, 5401, 34): '"""QuantizeDownAndShrinkRange"""', (5401, 36, 5401, 48): '_inputs_flat', (5401, 50, 5401, 56): '_attrs', (5401, 58, 5401, 65): '_result', (5401, 67, 5401, 71): 'name'}, {}), "('QuantizeDownAndShrinkRange', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5479, 12, 5479, 50), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5479, 31, 5479, 38): 'Toutput', (5479, 40, 5479, 49): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5480, 19, 5480, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5480, 51, 5480, 54): '[x]', (5480, 56, 5480, 60): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5481, 19, 5481, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5481, 51, 5481, 54): '[y]', (5481, 56, 5481, 60): '_ctx'}, {}), '([y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5482, 10, 5482, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5482, 33, 5482, 38): 'min_x', (5482, 40, 5482, 55): '_dtypes.float32'}, {}), '(min_x, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5483, 10, 5483, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5483, 33, 5483, 38): 'max_x', (5483, 40, 5483, 55): '_dtypes.float32'}, {}), '(max_x, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5484, 10, 5484, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5484, 33, 5484, 38): 'min_y', (5484, 40, 5484, 55): '_dtypes.float32'}, {}), '(min_y, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5485, 10, 5485, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5485, 33, 5485, 38): 'max_y', (5485, 40, 5485, 55): '_dtypes.float32'}, {}), '(max_y, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5488, 12, 5489, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5490, 2, 5491, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5491, 6, 5491, 20): '"""QuantizedAdd"""', (5491, 22, 5491, 34): '_inputs_flat', (5491, 36, 5491, 42): '_attrs', (5491, 44, 5491, 51): '_result', (5491, 53, 5491, 57): 'name'}, {}), "('QuantizedAdd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5598, 12, 5598, 50), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5598, 31, 5598, 38): 'Toutput', (5598, 40, 5598, 49): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5601, 16, 5601, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5601, 35, 5601, 46): 'transpose_a', (5601, 48, 5601, 61): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5604, 16, 5604, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5604, 35, 5604, 46): 'transpose_b', (5604, 48, 5604, 61): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5607, 16, 5607, 62), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5607, 35, 5607, 46): 'Tactivation', (5607, 48, 5607, 61): '"""Tactivation"""'}, {}), "(Tactivation, 'Tactivation')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5608, 19, 5608, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5608, 51, 5608, 54): '[a]', (5608, 56, 5608, 60): '_ctx'}, {}), '([a], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5609, 19, 5609, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5609, 51, 5609, 54): '[b]', (5609, 56, 5609, 60): '_ctx'}, {}), '([b], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5610, 10, 5610, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5610, 33, 5610, 38): 'min_a', (5610, 40, 5610, 55): '_dtypes.float32'}, {}), '(min_a, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5611, 10, 5611, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5611, 33, 5611, 38): 'max_a', (5611, 40, 5611, 55): '_dtypes.float32'}, {}), '(max_a, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5612, 10, 5612, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5612, 33, 5612, 38): 'min_b', (5612, 40, 5612, 55): '_dtypes.float32'}, {}), '(min_b, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5613, 10, 5613, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5613, 33, 5613, 38): 'max_b', (5613, 40, 5613, 55): '_dtypes.float32'}, {}), '(max_b, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5617, 12, 5618, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5619, 2, 5620, 61), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5620, 6, 5620, 23): '"""QuantizedMatMul"""', (5620, 25, 5620, 37): '_inputs_flat', (5620, 39, 5620, 45): '_attrs', (5620, 47, 5620, 54): '_result', (5620, 56, 5620, 60): 'name'}, {}), "('QuantizedMatMul', _inputs_flat, _attrs, _result, name\n )", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5698, 12, 5698, 50), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5698, 31, 5698, 38): 'Toutput', (5698, 40, 5698, 49): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5699, 19, 5699, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5699, 51, 5699, 54): '[x]', (5699, 56, 5699, 60): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5700, 19, 5700, 61), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5700, 51, 5700, 54): '[y]', (5700, 56, 5700, 60): '_ctx'}, {}), '([y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5701, 10, 5701, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5701, 33, 5701, 38): 'min_x', (5701, 40, 5701, 55): '_dtypes.float32'}, {}), '(min_x, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5702, 10, 5702, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5702, 33, 5702, 38): 'max_x', (5702, 40, 5702, 55): '_dtypes.float32'}, {}), '(max_x, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5703, 10, 5703, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5703, 33, 5703, 38): 'min_y', (5703, 40, 5703, 55): '_dtypes.float32'}, {}), '(min_y, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5704, 10, 5704, 56), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(5704, 33, 5704, 38): 'max_y', (5704, 40, 5704, 55): '_dtypes.float32'}, {}), '(max_y, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((5707, 12, 5708, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5709, 2, 5710, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5710, 6, 5710, 20): '"""QuantizedMul"""', (5710, 22, 5710, 34): '_inputs_flat', (5710, 36, 5710, 42): '_attrs', (5710, 44, 5710, 51): '_result', (5710, 53, 5710, 57): 'name'}, {}), "('QuantizedMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5776, 29, 5776, 104), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5776, 61, 5776, 82): '[start, limit, delta]', (5776, 84, 5776, 88): '_ctx', (5776, 90, 5776, 103): '_dtypes.int32'}, {}), '([start, limit, delta], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5780, 12, 5781, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5782, 2, 5783, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5783, 6, 5783, 13): '"""Range"""', (5783, 15, 5783, 27): '_inputs_flat', (5783, 29, 5783, 35): '_attrs', (5783, 37, 5783, 44): '_result', (5783, 46, 5783, 50): 'name'}, {}), "('Range', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5850, 9, 5850, 41), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5850, 28, 5850, 32): 'Tout', (5850, 34, 5850, 40): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5851, 22, 5851, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5851, 54, 5851, 61): '[input]', (5851, 63, 5851, 67): '_ctx', (5851, 69, 5851, 86): '_dtypes.complex64'}, {}), '([input], _ctx, _dtypes.complex64)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5854, 12, 5855, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5856, 2, 5857, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5857, 6, 5857, 12): '"""Real"""', (5857, 14, 5857, 26): '_inputs_flat', (5857, 28, 5857, 34): '_attrs', (5857, 36, 5857, 43): '_result', (5857, 45, 5857, 49): 'name'}, {}), "('Real', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5912, 23, 5912, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5912, 55, 5912, 61): '[x, y]', (5912, 63, 5912, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5916, 12, 5917, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5918, 2, 5919, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5919, 6, 5919, 15): '"""RealDiv"""', (5919, 17, 5919, 29): '_inputs_flat', (5919, 31, 5919, 37): '_attrs', (5919, 39, 5919, 46): '_result', (5919, 48, 5919, 52): 'name'}, {}), "('RealDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5971, 18, 5971, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(5971, 50, 5971, 53): '[x]', (5971, 55, 5971, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5974, 12, 5975, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((5976, 2, 5977, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5977, 6, 5977, 18): '"""Reciprocal"""', (5977, 20, 5977, 32): '_inputs_flat', (5977, 34, 5977, 40): '_attrs', (5977, 42, 5977, 49): '_result', (5977, 51, 5977, 55): 'name'}, {}), "('Reciprocal', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6030, 23, 6030, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6030, 55, 6030, 62): '[y, dy]', (6030, 64, 6030, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6034, 12, 6035, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6036, 2, 6037, 60), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6037, 6, 6037, 22): '"""ReciprocalGrad"""', (6037, 24, 6037, 36): '_inputs_flat', (6037, 38, 6037, 44): '_attrs', (6037, 46, 6037, 53): '_result', (6037, 55, 6037, 59): 'name'}, {}), "('ReciprocalGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6105, 27, 6105, 73), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6105, 59, 6105, 66): '[input]', (6105, 68, 6105, 72): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6106, 14, 6106, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6106, 37, 6106, 46): 'input_min', (6106, 48, 6106, 63): '_dtypes.float32'}, {}), '(input_min, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6107, 14, 6107, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6107, 37, 6107, 46): 'input_max', (6107, 48, 6107, 63): '_dtypes.float32'}, {}), '(input_max, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6110, 12, 6111, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6112, 2, 6113, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6113, 6, 6113, 27): '"""RequantizationRange"""', (6113, 29, 6113, 41): '_inputs_flat', (6113, 43, 6113, 49): '_attrs', (6113, 51, 6113, 58): '_result', (6113, 60, 6113, 64): 'name'}, {}), "('RequantizationRange', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6196, 13, 6196, 53), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(6196, 32, 6196, 40): 'out_type', (6196, 42, 6196, 52): '"""out_type"""'}, {}), "(out_type, 'out_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6197, 27, 6197, 73), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6197, 59, 6197, 66): '[input]', (6197, 68, 6197, 72): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6198, 14, 6198, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6198, 37, 6198, 46): 'input_min', (6198, 48, 6198, 63): '_dtypes.float32'}, {}), '(input_min, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6199, 14, 6199, 64), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6199, 37, 6199, 46): 'input_max', (6199, 48, 6199, 63): '_dtypes.float32'}, {}), '(input_max, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6200, 25, 6200, 86), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6200, 48, 6200, 68): 'requested_output_min', (6200, 70, 6200, 85): '_dtypes.float32'}, {}), '(requested_output_min, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6201, 25, 6201, 86), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6201, 48, 6201, 68): 'requested_output_max', (6201, 70, 6201, 85): '_dtypes.float32'}, {}), '(requested_output_max, _dtypes.float32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6204, 12, 6205, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6206, 2, 6207, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6207, 6, 6207, 18): '"""Requantize"""', (6207, 20, 6207, 32): '_inputs_flat', (6207, 34, 6207, 40): '_attrs', (6207, 42, 6207, 49): '_result', (6207, 51, 6207, 55): 'name'}, {}), "('Requantize', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6267, 18, 6267, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6267, 50, 6267, 53): '[x]', (6267, 55, 6267, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6270, 12, 6271, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6272, 2, 6273, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6273, 6, 6273, 12): '"""Rint"""', (6273, 14, 6273, 26): '_inputs_flat', (6273, 28, 6273, 34): '_attrs', (6273, 36, 6273, 43): '_result', (6273, 45, 6273, 49): 'name'}, {}), "('Rint', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6325, 18, 6325, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6325, 50, 6325, 53): '[x]', (6325, 55, 6325, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6328, 12, 6329, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6330, 2, 6331, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6331, 6, 6331, 13): '"""Round"""', (6331, 15, 6331, 27): '_inputs_flat', (6331, 29, 6331, 35): '_attrs', (6331, 37, 6331, 44): '_result', (6331, 46, 6331, 50): 'name'}, {}), "('Round', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6383, 18, 6383, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6383, 50, 6383, 53): '[x]', (6383, 55, 6383, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6386, 12, 6387, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6388, 2, 6389, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6389, 6, 6389, 13): '"""Rsqrt"""', (6389, 15, 6389, 27): '_inputs_flat', (6389, 29, 6389, 35): '_attrs', (6389, 37, 6389, 44): '_result', (6389, 46, 6389, 50): 'name'}, {}), "('Rsqrt', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6442, 23, 6442, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6442, 55, 6442, 62): '[y, dy]', (6442, 64, 6442, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6446, 12, 6447, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6448, 2, 6449, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6449, 6, 6449, 17): '"""RsqrtGrad"""', (6449, 19, 6449, 31): '_inputs_flat', (6449, 33, 6449, 39): '_attrs', (6449, 41, 6449, 48): '_result', (6449, 50, 6449, 54): 'name'}, {}), "('RsqrtGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6515, 21, 6515, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6515, 53, 6515, 59): '[data]', (6515, 61, 6515, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6516, 35, 6516, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6516, 67, 6516, 80): '[segment_ids]', (6516, 82, 6516, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6519, 12, 6520, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6521, 2, 6522, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6522, 6, 6522, 18): '"""SegmentMax"""', (6522, 20, 6522, 32): '_inputs_flat', (6522, 34, 6522, 40): '_attrs', (6522, 42, 6522, 49): '_result', (6522, 51, 6522, 55): 'name'}, {}), "('SegmentMax', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6589, 21, 6589, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6589, 53, 6589, 59): '[data]', (6589, 61, 6589, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6590, 35, 6590, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6590, 67, 6590, 80): '[segment_ids]', (6590, 82, 6590, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6593, 12, 6594, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6595, 2, 6596, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6596, 6, 6596, 19): '"""SegmentMean"""', (6596, 21, 6596, 33): '_inputs_flat', (6596, 35, 6596, 41): '_attrs', (6596, 43, 6596, 50): '_result', (6596, 52, 6596, 56): 'name'}, {}), "('SegmentMean', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6662, 21, 6662, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6662, 53, 6662, 59): '[data]', (6662, 61, 6662, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6663, 35, 6663, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6663, 67, 6663, 80): '[segment_ids]', (6663, 82, 6663, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6666, 12, 6667, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6668, 2, 6669, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6669, 6, 6669, 18): '"""SegmentMin"""', (6669, 20, 6669, 32): '_inputs_flat', (6669, 34, 6669, 40): '_attrs', (6669, 42, 6669, 49): '_result', (6669, 51, 6669, 55): 'name'}, {}), "('SegmentMin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6735, 21, 6735, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6735, 53, 6735, 59): '[data]', (6735, 61, 6735, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6736, 35, 6736, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6736, 67, 6736, 80): '[segment_ids]', (6736, 82, 6736, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6739, 12, 6740, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6741, 2, 6742, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6742, 6, 6742, 19): '"""SegmentProd"""', (6742, 21, 6742, 33): '_inputs_flat', (6742, 35, 6742, 41): '_attrs', (6742, 43, 6742, 50): '_result', (6742, 52, 6742, 56): 'name'}, {}), "('SegmentProd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6808, 21, 6808, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6808, 53, 6808, 59): '[data]', (6808, 61, 6808, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6809, 35, 6809, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6809, 67, 6809, 80): '[segment_ids]', (6809, 82, 6809, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6812, 12, 6813, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6814, 2, 6815, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6815, 6, 6815, 18): '"""SegmentSum"""', (6815, 20, 6815, 32): '_inputs_flat', (6815, 34, 6815, 40): '_attrs', (6815, 42, 6815, 49): '_result', (6815, 51, 6815, 55): 'name'}, {}), "('SegmentSum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6907, 23, 6907, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6907, 55, 6907, 61): '[x, y]', (6907, 63, 6907, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6909, 14, 6909, 61), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(6909, 37, 6909, 46): 'condition', (6909, 48, 6909, 60): '_dtypes.bool'}, {}), '(condition, _dtypes.bool)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((6912, 12, 6913, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6914, 2, 6915, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6915, 6, 6915, 14): '"""Select"""', (6915, 16, 6915, 28): '_inputs_flat', (6915, 30, 6915, 36): '_attrs', (6915, 38, 6915, 45): '_result', (6915, 47, 6915, 51): 'name'}, {}), "('Select', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6966, 18, 6966, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(6966, 50, 6966, 53): '[x]', (6966, 55, 6966, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6969, 12, 6970, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((6971, 2, 6972, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6972, 6, 6972, 15): '"""Sigmoid"""', (6972, 17, 6972, 29): '_inputs_flat', (6972, 31, 6972, 37): '_attrs', (6972, 39, 6972, 46): '_result', (6972, 48, 6972, 52): 'name'}, {}), "('Sigmoid', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7025, 23, 7025, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7025, 55, 7025, 62): '[y, dy]', (7025, 64, 7025, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7029, 12, 7030, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7031, 2, 7032, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7032, 6, 7032, 19): '"""SigmoidGrad"""', (7032, 21, 7032, 33): '_inputs_flat', (7032, 35, 7032, 41): '_attrs', (7032, 43, 7032, 50): '_result', (7032, 52, 7032, 56): 'name'}, {}), "('SigmoidGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7085, 18, 7085, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7085, 50, 7085, 53): '[x]', (7085, 55, 7085, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7088, 12, 7089, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7090, 2, 7091, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7091, 6, 7091, 12): '"""Sign"""', (7091, 14, 7091, 26): '_inputs_flat', (7091, 28, 7091, 34): '_attrs', (7091, 36, 7091, 43): '_result', (7091, 45, 7091, 49): 'name'}, {}), "('Sign', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7141, 18, 7141, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7141, 50, 7141, 53): '[x]', (7141, 55, 7141, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7144, 12, 7145, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7146, 2, 7147, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7147, 6, 7147, 11): '"""Sin"""', (7147, 13, 7147, 25): '_inputs_flat', (7147, 27, 7147, 33): '_attrs', (7147, 35, 7147, 42): '_result', (7147, 44, 7147, 48): 'name'}, {}), "('Sin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7197, 18, 7197, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7197, 50, 7197, 53): '[x]', (7197, 55, 7197, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7200, 12, 7201, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7202, 2, 7203, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7203, 6, 7203, 12): '"""Sinh"""', (7203, 14, 7203, 26): '_inputs_flat', (7203, 28, 7203, 34): '_attrs', (7203, 36, 7203, 43): '_result', (7203, 45, 7203, 49): 'name'}, {}), "('Sinh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7291, 16, 7291, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7291, 35, 7291, 46): 'transpose_a', (7291, 48, 7291, 61): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7294, 16, 7294, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7294, 35, 7294, 46): 'transpose_b', (7294, 48, 7294, 61): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7297, 16, 7297, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7297, 35, 7297, 46): 'a_is_sparse', (7297, 48, 7297, 61): '"""a_is_sparse"""'}, {}), "(a_is_sparse, 'a_is_sparse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7300, 16, 7300, 62), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7300, 35, 7300, 46): 'b_is_sparse', (7300, 48, 7300, 61): '"""b_is_sparse"""'}, {}), "(b_is_sparse, 'b_is_sparse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7301, 19, 7301, 78), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7301, 51, 7301, 54): '[a]', (7301, 56, 7301, 60): '_ctx', (7301, 62, 7301, 77): '_dtypes.float32'}, {}), '([a], _ctx, _dtypes.float32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7302, 19, 7302, 78), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7302, 51, 7302, 54): '[b]', (7302, 56, 7302, 60): '_ctx', (7302, 62, 7302, 77): '_dtypes.float32'}, {}), '([b], _ctx, _dtypes.float32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7307, 12, 7308, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7309, 2, 7310, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7310, 6, 7310, 20): '"""SparseMatMul"""', (7310, 22, 7310, 34): '_inputs_flat', (7310, 36, 7310, 42): '_attrs', (7310, 44, 7310, 51): '_result', (7310, 53, 7310, 57): 'name'}, {}), "('SparseMatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7371, 21, 7371, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7371, 53, 7371, 59): '[data]', (7371, 61, 7371, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7372, 27, 7372, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7372, 59, 7372, 68): '[indices]', (7372, 70, 7372, 74): '_ctx', (7372, 76, 7372, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7373, 16, 7373, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7373, 39, 7373, 50): 'segment_ids', (7373, 52, 7373, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7376, 12, 7377, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7378, 2, 7379, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7379, 6, 7379, 25): '"""SparseSegmentMean"""', (7379, 27, 7379, 39): '_inputs_flat', (7379, 41, 7379, 47): '_attrs', (7379, 49, 7379, 56): '_result', (7379, 58, 7379, 62): 'name'}, {}), "('SparseSegmentMean', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7440, 21, 7440, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7440, 53, 7440, 59): '[grad]', (7440, 61, 7440, 65): '_ctx'}, {}), '([grad], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7441, 27, 7441, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7441, 59, 7441, 68): '[indices]', (7441, 70, 7441, 74): '_ctx', (7441, 76, 7441, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7442, 16, 7442, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7442, 39, 7442, 50): 'segment_ids', (7442, 52, 7442, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7443, 16, 7443, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7443, 39, 7443, 50): 'output_dim0', (7443, 52, 7443, 65): '_dtypes.int32'}, {}), '(output_dim0, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7446, 12, 7447, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7448, 2, 7449, 67), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7449, 6, 7449, 29): '"""SparseSegmentMeanGrad"""', (7449, 31, 7449, 43): '_inputs_flat', (7449, 45, 7449, 51): '_attrs', (7449, 53, 7449, 60): '_result', (7449, 62, 7449, 66): 'name'}, {}), "('SparseSegmentMeanGrad', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7514, 21, 7514, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7514, 53, 7514, 59): '[data]', (7514, 61, 7514, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7515, 27, 7515, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7515, 59, 7515, 68): '[indices]', (7515, 70, 7515, 74): '_ctx', (7515, 76, 7515, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7516, 40, 7516, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7516, 72, 7516, 86): '[num_segments]', (7516, 88, 7516, 92): '_ctx', (7516, 94, 7516, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7517, 16, 7517, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7517, 39, 7517, 50): 'segment_ids', (7517, 52, 7517, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7521, 12, 7523, 39), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7524, 2, 7525, 78), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7525, 6, 7525, 40): '"""SparseSegmentMeanWithNumSegments"""', (7525, 42, 7525, 54): '_inputs_flat', (7525, 56, 7525, 62): '_attrs', (7525, 64, 7525, 71): '_result', (7525, 73, 7525, 77): 'name'}, {}), "('SparseSegmentMeanWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7585, 21, 7585, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7585, 53, 7585, 59): '[data]', (7585, 61, 7585, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7586, 27, 7586, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7586, 59, 7586, 68): '[indices]', (7586, 70, 7586, 74): '_ctx', (7586, 76, 7586, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7587, 16, 7587, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7587, 39, 7587, 50): 'segment_ids', (7587, 52, 7587, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7590, 12, 7591, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7592, 2, 7593, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7593, 6, 7593, 26): '"""SparseSegmentSqrtN"""', (7593, 28, 7593, 40): '_inputs_flat', (7593, 42, 7593, 48): '_attrs', (7593, 50, 7593, 57): '_result', (7593, 59, 7593, 63): 'name'}, {}), "('SparseSegmentSqrtN', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7654, 21, 7654, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7654, 53, 7654, 59): '[grad]', (7654, 61, 7654, 65): '_ctx'}, {}), '([grad], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7655, 27, 7655, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7655, 59, 7655, 68): '[indices]', (7655, 70, 7655, 74): '_ctx', (7655, 76, 7655, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7656, 16, 7656, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7656, 39, 7656, 50): 'segment_ids', (7656, 52, 7656, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7657, 16, 7657, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7657, 39, 7657, 50): 'output_dim0', (7657, 52, 7657, 65): '_dtypes.int32'}, {}), '(output_dim0, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7660, 12, 7662, 39), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7663, 2, 7664, 68), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7664, 6, 7664, 30): '"""SparseSegmentSqrtNGrad"""', (7664, 32, 7664, 44): '_inputs_flat', (7664, 46, 7664, 52): '_attrs', (7664, 54, 7664, 61): '_result', (7664, 63, 7664, 67): 'name'}, {}), "('SparseSegmentSqrtNGrad', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7731, 21, 7731, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7731, 53, 7731, 59): '[data]', (7731, 61, 7731, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7732, 27, 7732, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7732, 59, 7732, 68): '[indices]', (7732, 70, 7732, 74): '_ctx', (7732, 76, 7732, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7733, 40, 7733, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7733, 72, 7733, 86): '[num_segments]', (7733, 88, 7733, 92): '_ctx', (7733, 94, 7733, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7734, 16, 7734, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7734, 39, 7734, 50): 'segment_ids', (7734, 52, 7734, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7738, 12, 7740, 39), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7741, 2, 7742, 79), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7742, 6, 7742, 41): '"""SparseSegmentSqrtNWithNumSegments"""', (7742, 43, 7742, 55): '_inputs_flat', (7742, 57, 7742, 63): '_attrs', (7742, 65, 7742, 72): '_result', (7742, 74, 7742, 78): 'name'}, {}), "('SparseSegmentSqrtNWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7826, 21, 7826, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7826, 53, 7826, 59): '[data]', (7826, 61, 7826, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7827, 27, 7827, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7827, 59, 7827, 68): '[indices]', (7827, 70, 7827, 74): '_ctx', (7827, 76, 7827, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7828, 16, 7828, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7828, 39, 7828, 50): 'segment_ids', (7828, 52, 7828, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7831, 12, 7832, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7833, 2, 7834, 62), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7834, 6, 7834, 24): '"""SparseSegmentSum"""', (7834, 26, 7834, 38): '_inputs_flat', (7834, 40, 7834, 46): '_attrs', (7834, 48, 7834, 55): '_result', (7834, 57, 7834, 61): 'name'}, {}), "('SparseSegmentSum', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7920, 21, 7920, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7920, 53, 7920, 59): '[data]', (7920, 61, 7920, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7921, 27, 7921, 90), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7921, 59, 7921, 68): '[indices]', (7921, 70, 7921, 74): '_ctx', (7921, 76, 7921, 89): '_dtypes.int32'}, {}), '([indices], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7922, 40, 7922, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7922, 72, 7922, 86): '[num_segments]', (7922, 88, 7922, 92): '_ctx', (7922, 94, 7922, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7923, 16, 7923, 66), 'tensorflow.python.framework.ops.convert_to_tensor', '_ops.convert_to_tensor', ({(7923, 39, 7923, 50): 'segment_ids', (7923, 52, 7923, 65): '_dtypes.int32'}, {}), '(segment_ids, _dtypes.int32)', True, 'from tensorflow.python.framework import ops as _ops\n'), ((7927, 12, 7929, 39), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7930, 2, 7931, 77), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7931, 6, 7931, 39): '"""SparseSegmentSumWithNumSegments"""', (7931, 41, 7931, 53): '_inputs_flat', (7931, 55, 7931, 61): '_attrs', (7931, 63, 7931, 70): '_result', (7931, 72, 7931, 76): 'name'}, {}), "('SparseSegmentSumWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7982, 18, 7982, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(7982, 50, 7982, 53): '[x]', (7982, 55, 7982, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7985, 12, 7986, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((7987, 2, 7988, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7988, 6, 7988, 12): '"""Sqrt"""', (7988, 14, 7988, 26): '_inputs_flat', (7988, 28, 7988, 34): '_attrs', (7988, 36, 7988, 43): '_result', (7988, 45, 7988, 49): 'name'}, {}), "('Sqrt', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8041, 23, 8041, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8041, 55, 8041, 62): '[y, dy]', (8041, 64, 8041, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8045, 12, 8046, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8047, 2, 8048, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8048, 6, 8048, 16): '"""SqrtGrad"""', (8048, 18, 8048, 30): '_inputs_flat', (8048, 32, 8048, 38): '_attrs', (8048, 40, 8048, 47): '_result', (8048, 49, 8048, 53): 'name'}, {}), "('SqrtGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8099, 18, 8099, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8099, 50, 8099, 53): '[x]', (8099, 55, 8099, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8102, 12, 8103, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8104, 2, 8105, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8105, 6, 8105, 14): '"""Square"""', (8105, 16, 8105, 28): '_inputs_flat', (8105, 30, 8105, 36): '_attrs', (8105, 38, 8105, 45): '_result', (8105, 47, 8105, 51): 'name'}, {}), "('Square', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8159, 23, 8159, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8159, 55, 8159, 61): '[x, y]', (8159, 63, 8159, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8163, 12, 8164, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8165, 2, 8166, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8166, 6, 8166, 25): '"""SquaredDifference"""', (8166, 27, 8166, 39): '_inputs_flat', (8166, 41, 8166, 47): '_attrs', (8166, 49, 8166, 56): '_result', (8166, 58, 8166, 62): 'name'}, {}), "('SquaredDifference', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8219, 23, 8219, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8219, 55, 8219, 61): '[x, y]', (8219, 63, 8219, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8223, 12, 8224, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8225, 2, 8226, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8226, 6, 8226, 11): '"""Sub"""', (8226, 13, 8226, 25): '_inputs_flat', (8226, 27, 8226, 33): '_attrs', (8226, 35, 8226, 42): '_result', (8226, 44, 8226, 48): 'name'}, {}), "('Sub', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8293, 14, 8293, 56), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(8293, 33, 8293, 42): 'keep_dims', (8293, 44, 8293, 55): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8294, 22, 8294, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8294, 54, 8294, 61): '[input]', (8294, 63, 8294, 67): '_ctx'}, {}), '([input], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8295, 24, 8295, 84), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8295, 56, 8295, 62): '[axis]', (8295, 64, 8295, 68): '_ctx', (8295, 70, 8295, 83): '_dtypes.int32'}, {}), '([axis], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8298, 12, 8299, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8300, 2, 8301, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8301, 6, 8301, 11): '"""Sum"""', (8301, 13, 8301, 25): '_inputs_flat', (8301, 27, 8301, 33): '_attrs', (8301, 35, 8301, 42): '_result', (8301, 44, 8301, 48): 'name'}, {}), "('Sum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8351, 18, 8351, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8351, 50, 8351, 53): '[x]', (8351, 55, 8351, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8354, 12, 8355, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8356, 2, 8357, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8357, 6, 8357, 11): '"""Tan"""', (8357, 13, 8357, 25): '_inputs_flat', (8357, 27, 8357, 33): '_attrs', (8357, 35, 8357, 42): '_result', (8357, 44, 8357, 48): 'name'}, {}), "('Tan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8406, 18, 8406, 60), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8406, 50, 8406, 53): '[x]', (8406, 55, 8406, 59): '_ctx'}, {}), '([x], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8409, 12, 8410, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8411, 2, 8412, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8412, 6, 8412, 12): '"""Tanh"""', (8412, 14, 8412, 26): '_inputs_flat', (8412, 28, 8412, 34): '_attrs', (8412, 36, 8412, 43): '_result', (8412, 45, 8412, 49): 'name'}, {}), "('Tanh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8465, 23, 8465, 69), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8465, 55, 8465, 62): '[y, dy]', (8465, 64, 8465, 68): '_ctx'}, {}), '([y, dy], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8469, 12, 8470, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8471, 2, 8472, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8472, 6, 8472, 16): '"""TanhGrad"""', (8472, 18, 8472, 30): '_inputs_flat', (8472, 32, 8472, 38): '_attrs', (8472, 40, 8472, 47): '_result', (8472, 49, 8472, 53): 'name'}, {}), "('TanhGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8530, 23, 8530, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8530, 55, 8530, 61): '[x, y]', (8530, 63, 8530, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8534, 12, 8535, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8536, 2, 8537, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8537, 6, 8537, 19): '"""TruncateDiv"""', (8537, 21, 8537, 33): '_inputs_flat', (8537, 35, 8537, 41): '_attrs', (8537, 43, 8537, 50): '_result', (8537, 52, 8537, 56): 'name'}, {}), "('TruncateDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8593, 23, 8593, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8593, 55, 8593, 61): '[x, y]', (8593, 63, 8593, 67): '_ctx'}, {}), '([x, y], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8597, 12, 8598, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8599, 2, 8600, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8600, 6, 8600, 19): '"""TruncateMod"""', (8600, 21, 8600, 33): '_inputs_flat', (8600, 35, 8600, 41): '_attrs', (8600, 43, 8600, 50): '_result', (8600, 52, 8600, 56): 'name'}, {}), "('TruncateMod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8675, 21, 8675, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8675, 53, 8675, 59): '[data]', (8675, 61, 8675, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8676, 35, 8676, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8676, 67, 8676, 80): '[segment_ids]', (8676, 82, 8676, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8677, 40, 8677, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8677, 72, 8677, 86): '[num_segments]', (8677, 88, 8677, 92): '_ctx', (8677, 94, 8677, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8681, 12, 8682, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8683, 2, 8684, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8684, 6, 8684, 26): '"""UnsortedSegmentMax"""', (8684, 28, 8684, 40): '_inputs_flat', (8684, 42, 8684, 48): '_attrs', (8684, 50, 8684, 57): '_result', (8684, 59, 8684, 63): 'name'}, {}), "('UnsortedSegmentMax', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8755, 21, 8755, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8755, 53, 8755, 59): '[data]', (8755, 61, 8755, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8756, 35, 8756, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8756, 67, 8756, 80): '[segment_ids]', (8756, 82, 8756, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8757, 40, 8757, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8757, 72, 8757, 86): '[num_segments]', (8757, 88, 8757, 92): '_ctx', (8757, 94, 8757, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8761, 12, 8762, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8763, 2, 8764, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8764, 6, 8764, 26): '"""UnsortedSegmentMin"""', (8764, 28, 8764, 40): '_inputs_flat', (8764, 42, 8764, 48): '_attrs', (8764, 50, 8764, 57): '_result', (8764, 59, 8764, 63): 'name'}, {}), "('UnsortedSegmentMin', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8834, 21, 8834, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8834, 53, 8834, 59): '[data]', (8834, 61, 8834, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8835, 35, 8835, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8835, 67, 8835, 80): '[segment_ids]', (8835, 82, 8835, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8836, 40, 8836, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8836, 72, 8836, 86): '[num_segments]', (8836, 88, 8836, 92): '_ctx', (8836, 94, 8836, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8840, 12, 8841, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8842, 2, 8843, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8843, 6, 8843, 27): '"""UnsortedSegmentProd"""', (8843, 29, 8843, 41): '_inputs_flat', (8843, 43, 8843, 49): '_attrs', (8843, 51, 8843, 58): '_result', (8843, 60, 8843, 64): 'name'}, {}), "('UnsortedSegmentProd', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8918, 21, 8918, 66), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8918, 53, 8918, 59): '[data]', (8918, 61, 8918, 65): '_ctx'}, {}), '([data], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8919, 35, 8919, 87), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8919, 67, 8919, 80): '[segment_ids]', (8919, 82, 8919, 86): '_ctx'}, {}), '([segment_ids], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8920, 40, 8920, 108), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8920, 72, 8920, 86): '[num_segments]', (8920, 88, 8920, 92): '_ctx', (8920, 94, 8920, 107): '_dtypes.int32'}, {}), '([num_segments], _ctx, _dtypes.int32)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8924, 12, 8925, 63), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8926, 2, 8927, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8927, 6, 8927, 26): '"""UnsortedSegmentSum"""', (8927, 28, 8927, 40): '_inputs_flat', (8927, 42, 8927, 48): '_attrs', (8927, 50, 8927, 57): '_result', (8927, 59, 8927, 63): 'name'}, {}), "('UnsortedSegmentSum', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8983, 23, 8983, 68), 'tensorflow.python.eager.execute.args_to_matching_eager', '_execute.args_to_matching_eager', ({(8983, 55, 8983, 61): '[x, q]', (8983, 63, 8983, 67): '_ctx'}, {}), '([x, q], _ctx)', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8987, 12, 8988, 49), 'tensorflow.python.eager.execute.execute', '_execute.execute', (), '', True, 'from tensorflow.python.eager import execute as _execute\n'), ((8989, 2, 8990, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8990, 6, 8990, 12): '"""Zeta"""', (8990, 14, 8990, 26): '_inputs_flat', (8990, 28, 8990, 34): '_attrs', (8990, 36, 8990, 43): '_result', (8990, 45, 8990, 49): 'name'}, {}), "('Zeta', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8995, 12, 8995, 32), 'tensorflow.core.framework.op_def_pb2.OpList', '_op_def_pb2.OpList', ({}, {}), '()', True, 'from tensorflow.core.framework import op_def_pb2 as _op_def_pb2\n'), ((8997, 2, 8997, 44), 'tensorflow.python.framework.op_def_registry.register_op_list', '_op_def_registry.register_op_list', ({(8997, 36, 8997, 43): 'op_list'}, {}), '(op_list)', True, 'from tensorflow.python.framework import op_def_registry as _op_def_registry\n'), ((8998, 15, 8998, 45), 'tensorflow.python.framework.op_def_library.OpDefLibrary', '_op_def_library.OpDefLibrary', ({}, {}), '()', True, 'from tensorflow.python.framework import op_def_library as _op_def_library\n'), ((48, 4, 49, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(49, 6, 49, 11): '"""Abs"""', (49, 13, 49, 25): '_inputs_flat', (49, 27, 49, 33): '_attrs', (49, 35, 49, 42): '_result', (49, 44, 49, 48): 'name'}, {}), "('Abs', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((74, 25, 74, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((115, 12, 115, 47), 'tensorflow.python.eager.execute.make_shape', '_execute.make_shape', ({(115, 32, 115, 37): 'shape', (115, 39, 115, 46): '"""shape"""'}, {}), "(shape, 'shape')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((122, 4, 123, 59), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(123, 6, 123, 21): '"""AccumulateNV2"""', (123, 23, 123, 35): '_inputs_flat', (123, 37, 123, 43): '_attrs', (123, 45, 123, 52): '_result', (123, 54, 123, 58): 'name'}, {}), "('AccumulateNV2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((149, 25, 149, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((185, 4, 186, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(186, 6, 186, 12): '"""Acos"""', (186, 14, 186, 26): '_inputs_flat', (186, 28, 186, 34): '_attrs', (186, 36, 186, 43): '_result', (186, 45, 186, 49): 'name'}, {}), "('Acos', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((211, 25, 211, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((241, 4, 242, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(242, 6, 242, 13): '"""Acosh"""', (242, 15, 242, 27): '_inputs_flat', (242, 29, 242, 35): '_attrs', (242, 37, 242, 44): '_result', (242, 46, 242, 50): 'name'}, {}), "('Acosh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((267, 25, 267, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((301, 4, 302, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(302, 6, 302, 11): '"""Add"""', (302, 13, 302, 25): '_inputs_flat', (302, 27, 302, 33): '_attrs', (302, 35, 302, 42): '_result', (302, 44, 302, 48): 'name'}, {}), "('Add', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((327, 25, 327, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((363, 4, 364, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(364, 6, 364, 12): '"""AddN"""', (364, 14, 364, 26): '_inputs_flat', (364, 28, 364, 34): '_attrs', (364, 36, 364, 43): '_result', (364, 45, 364, 49): 'name'}, {}), "('AddN', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((389, 25, 389, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((427, 4, 428, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(428, 6, 428, 13): '"""AddV2"""', (428, 15, 428, 27): '_inputs_flat', (428, 29, 428, 35): '_attrs', (428, 37, 428, 44): '_result', (428, 46, 428, 50): 'name'}, {}), "('AddV2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((453, 25, 453, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((490, 16, 490, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(490, 35, 490, 44): 'keep_dims', (490, 46, 490, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((498, 4, 499, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(499, 6, 499, 11): '"""All"""', (499, 13, 499, 25): '_inputs_flat', (499, 27, 499, 33): '_attrs', (499, 35, 499, 42): '_result', (499, 44, 499, 48): 'name'}, {}), "('All', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((524, 25, 524, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((573, 11, 573, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(573, 30, 573, 34): 'Tout', (573, 36, 573, 42): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((579, 4, 580, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(580, 6, 580, 13): '"""Angle"""', (580, 15, 580, 27): '_inputs_flat', (580, 29, 580, 35): '_attrs', (580, 37, 580, 44): '_result', (580, 46, 580, 50): 'name'}, {}), "('Angle', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((605, 25, 605, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((644, 16, 644, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(644, 35, 644, 44): 'keep_dims', (644, 46, 644, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((652, 4, 653, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(653, 6, 653, 11): '"""Any"""', (653, 13, 653, 25): '_inputs_flat', (653, 27, 653, 33): '_attrs', (653, 35, 653, 42): '_result', (653, 44, 653, 48): 'name'}, {}), "('Any', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((678, 25, 678, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((710, 16, 710, 59), 'tensorflow.python.eager.execute.make_float', '_execute.make_float', ({(710, 36, 710, 45): 'tolerance', (710, 47, 710, 58): '"""tolerance"""'}, {}), "(tolerance, 'tolerance')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((716, 4, 717, 62), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(717, 6, 717, 24): '"""ApproximateEqual"""', (717, 26, 717, 38): '_inputs_flat', (717, 40, 717, 46): '_attrs', (717, 48, 717, 55): '_result', (717, 57, 717, 61): 'name'}, {}), "('ApproximateEqual', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((743, 25, 743, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((780, 18, 780, 64), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(780, 37, 780, 48): 'output_type', (780, 50, 780, 63): '"""output_type"""'}, {}), "(output_type, 'output_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((788, 4, 789, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(789, 6, 789, 14): '"""ArgMax"""', (789, 16, 789, 28): '_inputs_flat', (789, 30, 789, 36): '_attrs', (789, 38, 789, 45): '_result', (789, 47, 789, 51): 'name'}, {}), "('ArgMax', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((815, 25, 815, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((852, 18, 852, 64), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(852, 37, 852, 48): 'output_type', (852, 50, 852, 63): '"""output_type"""'}, {}), "(output_type, 'output_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((860, 4, 861, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(861, 6, 861, 14): '"""ArgMin"""', (861, 16, 861, 28): '_inputs_flat', (861, 30, 861, 36): '_attrs', (861, 38, 861, 45): '_result', (861, 47, 861, 51): 'name'}, {}), "('ArgMin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((887, 25, 887, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((921, 4, 922, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(922, 6, 922, 12): '"""Asin"""', (922, 14, 922, 26): '_inputs_flat', (922, 28, 922, 34): '_attrs', (922, 36, 922, 43): '_result', (922, 45, 922, 49): 'name'}, {}), "('Asin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((947, 25, 947, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((977, 4, 978, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(978, 6, 978, 13): '"""Asinh"""', (978, 15, 978, 27): '_inputs_flat', (978, 29, 978, 35): '_attrs', (978, 37, 978, 44): '_result', (978, 46, 978, 50): 'name'}, {}), "('Asinh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1003, 25, 1003, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1033, 4, 1034, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1034, 6, 1034, 12): '"""Atan"""', (1034, 14, 1034, 26): '_inputs_flat', (1034, 28, 1034, 34): '_attrs', (1034, 36, 1034, 43): '_result', (1034, 45, 1034, 49): 'name'}, {}), "('Atan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1059, 25, 1059, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1096, 4, 1097, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1097, 6, 1097, 13): '"""Atan2"""', (1097, 15, 1097, 27): '_inputs_flat', (1097, 29, 1097, 35): '_attrs', (1097, 37, 1097, 44): '_result', (1097, 46, 1097, 50): 'name'}, {}), "('Atan2', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1122, 25, 1122, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1153, 4, 1154, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1154, 6, 1154, 13): '"""Atanh"""', (1154, 15, 1154, 27): '_inputs_flat', (1154, 29, 1154, 35): '_attrs', (1154, 37, 1154, 44): '_result', (1154, 46, 1154, 50): 'name'}, {}), "('Atanh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1179, 25, 1179, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1231, 12, 1231, 46), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(1231, 31, 1231, 36): 'adj_x', (1231, 38, 1231, 45): '"""adj_x"""'}, {}), "(adj_x, 'adj_x')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1234, 12, 1234, 46), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(1234, 31, 1234, 36): 'adj_y', (1234, 38, 1234, 45): '"""adj_y"""'}, {}), "(adj_y, 'adj_y')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1241, 4, 1242, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1242, 6, 1242, 19): '"""BatchMatMul"""', (1242, 21, 1242, 33): '_inputs_flat', (1242, 35, 1242, 41): '_attrs', (1242, 43, 1242, 50): '_result', (1242, 52, 1242, 56): 'name'}, {}), "('BatchMatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1268, 25, 1268, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1309, 4, 1310, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1310, 6, 1310, 17): '"""BesselI0e"""', (1310, 19, 1310, 31): '_inputs_flat', (1310, 33, 1310, 39): '_attrs', (1310, 41, 1310, 48): '_result', (1310, 50, 1310, 54): 'name'}, {}), "('BesselI0e', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1335, 25, 1335, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1369, 4, 1370, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1370, 6, 1370, 17): '"""BesselI1e"""', (1370, 19, 1370, 31): '_inputs_flat', (1370, 33, 1370, 39): '_attrs', (1370, 41, 1370, 48): '_result', (1370, 50, 1370, 54): 'name'}, {}), "('BesselI1e', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1395, 25, 1395, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1441, 4, 1442, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1442, 6, 1442, 15): '"""Betainc"""', (1442, 17, 1442, 29): '_inputs_flat', (1442, 31, 1442, 37): '_attrs', (1442, 39, 1442, 46): '_result', (1442, 48, 1442, 52): 'name'}, {}), "('Betainc', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1467, 25, 1467, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1510, 4, 1511, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1511, 6, 1511, 16): '"""Bincount"""', (1511, 18, 1511, 30): '_inputs_flat', (1511, 32, 1511, 38): '_attrs', (1511, 40, 1511, 47): '_result', (1511, 49, 1511, 53): 'name'}, {}), "('Bincount', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1536, 25, 1536, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1587, 4, 1588, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1588, 6, 1588, 17): '"""Bucketize"""', (1588, 19, 1588, 31): '_inputs_flat', (1588, 33, 1588, 39): '_attrs', (1588, 41, 1588, 48): '_result', (1588, 50, 1588, 54): 'name'}, {}), "('Bucketize', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1613, 25, 1613, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1618, 16, 1618, 53), 'tensorflow.python.eager.execute.make_float', '_execute.make_float', ({(1618, 36, 1618, 38): '_f', (1618, 40, 1618, 52): '"""boundaries"""'}, {}), "(_f, 'boundaries')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1643, 11, 1643, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(1643, 30, 1643, 34): 'DstT', (1643, 36, 1643, 42): '"""DstT"""'}, {}), "(DstT, 'DstT')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1649, 4, 1650, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1650, 6, 1650, 12): '"""Cast"""', (1650, 14, 1650, 26): '_inputs_flat', (1650, 28, 1650, 34): '_attrs', (1650, 36, 1650, 43): '_result', (1650, 45, 1650, 49): 'name'}, {}), "('Cast', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1675, 25, 1675, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1706, 4, 1707, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1707, 6, 1707, 12): '"""Ceil"""', (1707, 14, 1707, 26): '_inputs_flat', (1707, 28, 1707, 34): '_attrs', (1707, 36, 1707, 43): '_result', (1707, 45, 1707, 49): 'name'}, {}), "('Ceil', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1732, 25, 1732, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1774, 4, 1775, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1775, 6, 1775, 19): '"""ClipByValue"""', (1775, 21, 1775, 33): '_inputs_flat', (1775, 35, 1775, 41): '_attrs', (1775, 43, 1775, 50): '_result', (1775, 52, 1775, 56): 'name'}, {}), "('ClipByValue', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1801, 25, 1801, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1858, 4, 1859, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1859, 6, 1859, 25): '"""CompareAndBitpack"""', (1859, 27, 1859, 39): '_inputs_flat', (1859, 41, 1859, 47): '_attrs', (1859, 49, 1859, 56): '_result', (1859, 58, 1859, 62): 'name'}, {}), "('CompareAndBitpack', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1885, 25, 1885, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1929, 11, 1929, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(1929, 30, 1929, 34): 'Tout', (1929, 36, 1929, 42): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1935, 4, 1936, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(1936, 6, 1936, 15): '"""Complex"""', (1936, 17, 1936, 29): '_inputs_flat', (1936, 31, 1936, 37): '_attrs', (1936, 39, 1936, 46): '_result', (1936, 48, 1936, 52): 'name'}, {}), "('Complex', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1961, 25, 1961, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((1997, 11, 1997, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(1997, 30, 1997, 34): 'Tout', (1997, 36, 1997, 42): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2003, 4, 2004, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2004, 6, 2004, 18): '"""ComplexAbs"""', (2004, 20, 2004, 32): '_inputs_flat', (2004, 34, 2004, 40): '_attrs', (2004, 42, 2004, 49): '_result', (2004, 51, 2004, 55): 'name'}, {}), "('ComplexAbs', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2029, 25, 2029, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2075, 4, 2076, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2076, 6, 2076, 12): '"""Conj"""', (2076, 14, 2076, 26): '_inputs_flat', (2076, 28, 2076, 34): '_attrs', (2076, 36, 2076, 43): '_result', (2076, 45, 2076, 49): 'name'}, {}), "('Conj', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2101, 25, 2101, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2131, 4, 2132, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2132, 6, 2132, 11): '"""Cos"""', (2132, 13, 2132, 25): '_inputs_flat', (2132, 27, 2132, 33): '_attrs', (2132, 35, 2132, 42): '_result', (2132, 44, 2132, 48): 'name'}, {}), "('Cos', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2157, 25, 2157, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2187, 4, 2188, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2188, 6, 2188, 12): '"""Cosh"""', (2188, 14, 2188, 26): '_inputs_flat', (2188, 28, 2188, 34): '_attrs', (2188, 36, 2188, 43): '_result', (2188, 45, 2188, 49): 'name'}, {}), "('Cosh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2213, 25, 2213, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2250, 4, 2251, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2251, 6, 2251, 13): '"""Cross"""', (2251, 15, 2251, 27): '_inputs_flat', (2251, 29, 2251, 35): '_attrs', (2251, 37, 2251, 44): '_result', (2251, 46, 2251, 50): 'name'}, {}), "('Cross', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2276, 25, 2276, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2342, 16, 2342, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2342, 35, 2342, 44): 'exclusive', (2342, 46, 2342, 57): '"""exclusive"""'}, {}), "(exclusive, 'exclusive')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2345, 14, 2345, 52), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2345, 33, 2345, 40): 'reverse', (2345, 42, 2345, 51): '"""reverse"""'}, {}), "(reverse, 'reverse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2354, 4, 2355, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2355, 6, 2355, 15): '"""Cumprod"""', (2355, 17, 2355, 29): '_inputs_flat', (2355, 31, 2355, 37): '_attrs', (2355, 39, 2355, 46): '_result', (2355, 48, 2355, 52): 'name'}, {}), "('Cumprod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2381, 25, 2381, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2454, 16, 2454, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2454, 35, 2454, 44): 'exclusive', (2454, 46, 2454, 57): '"""exclusive"""'}, {}), "(exclusive, 'exclusive')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2457, 14, 2457, 52), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(2457, 33, 2457, 40): 'reverse', (2457, 42, 2457, 51): '"""reverse"""'}, {}), "(reverse, 'reverse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2466, 4, 2467, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2467, 6, 2467, 14): '"""Cumsum"""', (2467, 16, 2467, 28): '_inputs_flat', (2467, 30, 2467, 36): '_attrs', (2467, 38, 2467, 45): '_result', (2467, 47, 2467, 51): 'name'}, {}), "('Cumsum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2493, 25, 2493, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2533, 4, 2534, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2534, 6, 2534, 15): '"""Digamma"""', (2534, 17, 2534, 29): '_inputs_flat', (2534, 31, 2534, 37): '_attrs', (2534, 39, 2534, 46): '_result', (2534, 48, 2534, 52): 'name'}, {}), "('Digamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2559, 25, 2559, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2592, 4, 2593, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2593, 6, 2593, 11): '"""Div"""', (2593, 13, 2593, 25): '_inputs_flat', (2593, 27, 2593, 33): '_attrs', (2593, 35, 2593, 42): '_result', (2593, 44, 2593, 48): 'name'}, {}), "('Div', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2618, 25, 2618, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2653, 4, 2654, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2654, 6, 2654, 13): '"""Equal"""', (2654, 15, 2654, 27): '_inputs_flat', (2654, 29, 2654, 35): '_attrs', (2654, 37, 2654, 44): '_result', (2654, 46, 2654, 50): 'name'}, {}), "('Equal', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2679, 25, 2679, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2709, 4, 2710, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2710, 6, 2710, 11): '"""Erf"""', (2710, 13, 2710, 25): '_inputs_flat', (2710, 27, 2710, 33): '_attrs', (2710, 35, 2710, 42): '_result', (2710, 44, 2710, 48): 'name'}, {}), "('Erf', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2735, 25, 2735, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2765, 4, 2766, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2766, 6, 2766, 12): '"""Erfc"""', (2766, 14, 2766, 26): '_inputs_flat', (2766, 28, 2766, 34): '_attrs', (2766, 36, 2766, 43): '_result', (2766, 45, 2766, 49): 'name'}, {}), "('Erfc', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2791, 25, 2791, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2821, 4, 2822, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2822, 6, 2822, 11): '"""Exp"""', (2822, 13, 2822, 25): '_inputs_flat', (2822, 27, 2822, 33): '_attrs', (2822, 35, 2822, 42): '_result', (2822, 44, 2822, 48): 'name'}, {}), "('Exp', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2847, 25, 2847, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2879, 4, 2880, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2880, 6, 2880, 13): '"""Expm1"""', (2880, 15, 2880, 27): '_inputs_flat', (2880, 29, 2880, 35): '_attrs', (2880, 37, 2880, 44): '_result', (2880, 46, 2880, 50): 'name'}, {}), "('Expm1', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2905, 25, 2905, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2935, 4, 2936, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2936, 6, 2936, 13): '"""Floor"""', (2936, 15, 2936, 27): '_inputs_flat', (2936, 29, 2936, 35): '_attrs', (2936, 37, 2936, 44): '_result', (2936, 46, 2936, 50): 'name'}, {}), "('Floor', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((2961, 25, 2961, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((2994, 4, 2995, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(2995, 6, 2995, 16): '"""FloorDiv"""', (2995, 18, 2995, 30): '_inputs_flat', (2995, 32, 2995, 38): '_attrs', (2995, 40, 2995, 47): '_result', (2995, 49, 2995, 53): 'name'}, {}), "('FloorDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3020, 25, 3020, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3057, 4, 3058, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3058, 6, 3058, 16): '"""FloorMod"""', (3058, 18, 3058, 30): '_inputs_flat', (3058, 32, 3058, 38): '_attrs', (3058, 40, 3058, 47): '_result', (3058, 49, 3058, 53): 'name'}, {}), "('FloorMod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3083, 25, 3083, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3118, 4, 3119, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3119, 6, 3119, 15): '"""Greater"""', (3119, 17, 3119, 29): '_inputs_flat', (3119, 31, 3119, 37): '_attrs', (3119, 39, 3119, 46): '_result', (3119, 48, 3119, 52): 'name'}, {}), "('Greater', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3144, 25, 3144, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3179, 4, 3180, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3180, 6, 3180, 20): '"""GreaterEqual"""', (3180, 22, 3180, 34): '_inputs_flat', (3180, 36, 3180, 42): '_attrs', (3180, 44, 3180, 51): '_result', (3180, 53, 3180, 57): 'name'}, {}), "('GreaterEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3205, 25, 3205, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3256, 12, 3256, 46), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(3256, 31, 3256, 36): 'dtype', (3256, 38, 3256, 45): '"""dtype"""'}, {}), "(dtype, 'dtype')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3263, 4, 3264, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3264, 6, 3264, 27): '"""HistogramFixedWidth"""', (3264, 29, 3264, 41): '_inputs_flat', (3264, 43, 3264, 49): '_attrs', (3264, 51, 3264, 58): '_result', (3264, 60, 3264, 64): 'name'}, {}), "('HistogramFixedWidth', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3290, 25, 3290, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3340, 4, 3341, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3341, 6, 3341, 14): '"""Igamma"""', (3341, 16, 3341, 28): '_inputs_flat', (3341, 30, 3341, 36): '_attrs', (3341, 38, 3341, 45): '_result', (3341, 47, 3341, 51): 'name'}, {}), "('Igamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3366, 25, 3366, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3397, 4, 3398, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3398, 6, 3398, 19): '"""IgammaGradA"""', (3398, 21, 3398, 33): '_inputs_flat', (3398, 35, 3398, 41): '_attrs', (3398, 43, 3398, 50): '_result', (3398, 52, 3398, 56): 'name'}, {}), "('IgammaGradA', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3423, 25, 3423, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3468, 4, 3469, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3469, 6, 3469, 15): '"""Igammac"""', (3469, 17, 3469, 29): '_inputs_flat', (3469, 31, 3469, 37): '_attrs', (3469, 39, 3469, 46): '_result', (3469, 48, 3469, 52): 'name'}, {}), "('Igammac', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3494, 25, 3494, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3534, 11, 3534, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(3534, 30, 3534, 34): 'Tout', (3534, 36, 3534, 42): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3540, 4, 3541, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3541, 6, 3541, 12): '"""Imag"""', (3541, 14, 3541, 26): '_inputs_flat', (3541, 28, 3541, 34): '_attrs', (3541, 36, 3541, 43): '_result', (3541, 45, 3541, 49): 'name'}, {}), "('Imag', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3566, 25, 3566, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3600, 4, 3601, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3601, 6, 3601, 11): '"""Inv"""', (3601, 13, 3601, 25): '_inputs_flat', (3601, 27, 3601, 33): '_attrs', (3601, 35, 3601, 42): '_result', (3601, 44, 3601, 48): 'name'}, {}), "('Inv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3626, 25, 3626, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3659, 4, 3660, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3660, 6, 3660, 15): '"""InvGrad"""', (3660, 17, 3660, 29): '_inputs_flat', (3660, 31, 3660, 37): '_attrs', (3660, 39, 3660, 46): '_result', (3660, 48, 3660, 52): 'name'}, {}), "('InvGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3685, 25, 3685, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3720, 4, 3721, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3721, 6, 3721, 16): '"""IsFinite"""', (3721, 18, 3721, 30): '_inputs_flat', (3721, 32, 3721, 38): '_attrs', (3721, 40, 3721, 47): '_result', (3721, 49, 3721, 53): 'name'}, {}), "('IsFinite', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3746, 25, 3746, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3780, 4, 3781, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3781, 6, 3781, 13): '"""IsInf"""', (3781, 15, 3781, 27): '_inputs_flat', (3781, 29, 3781, 35): '_attrs', (3781, 37, 3781, 44): '_result', (3781, 46, 3781, 50): 'name'}, {}), "('IsInf', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3806, 25, 3806, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3840, 4, 3841, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3841, 6, 3841, 13): '"""IsNan"""', (3841, 15, 3841, 27): '_inputs_flat', (3841, 29, 3841, 35): '_attrs', (3841, 37, 3841, 44): '_result', (3841, 46, 3841, 50): 'name'}, {}), "('IsNan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3866, 25, 3866, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3900, 4, 3901, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3901, 6, 3901, 12): '"""Less"""', (3901, 14, 3901, 26): '_inputs_flat', (3901, 28, 3901, 34): '_attrs', (3901, 36, 3901, 43): '_result', (3901, 45, 3901, 49): 'name'}, {}), "('Less', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3926, 25, 3926, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((3961, 4, 3962, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(3962, 6, 3962, 17): '"""LessEqual"""', (3962, 19, 3962, 31): '_inputs_flat', (3962, 33, 3962, 39): '_attrs', (3962, 41, 3962, 48): '_result', (3962, 50, 3962, 54): 'name'}, {}), "('LessEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((3987, 25, 3987, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4018, 4, 4019, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4019, 6, 4019, 14): '"""Lgamma"""', (4019, 16, 4019, 28): '_inputs_flat', (4019, 30, 4019, 36): '_attrs', (4019, 38, 4019, 45): '_result', (4019, 47, 4019, 51): 'name'}, {}), "('Lgamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4044, 25, 4044, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4089, 4, 4090, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4090, 6, 4090, 16): '"""LinSpace"""', (4090, 18, 4090, 30): '_inputs_flat', (4090, 32, 4090, 38): '_attrs', (4090, 40, 4090, 47): '_result', (4090, 49, 4090, 53): 'name'}, {}), "('LinSpace', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4115, 25, 4115, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4149, 4, 4150, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4150, 6, 4150, 11): '"""Log"""', (4150, 13, 4150, 25): '_inputs_flat', (4150, 27, 4150, 33): '_attrs', (4150, 35, 4150, 42): '_result', (4150, 44, 4150, 48): 'name'}, {}), "('Log', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4175, 25, 4175, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4207, 4, 4208, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4208, 6, 4208, 13): '"""Log1p"""', (4208, 15, 4208, 27): '_inputs_flat', (4208, 29, 4208, 35): '_attrs', (4208, 37, 4208, 44): '_result', (4208, 46, 4208, 50): 'name'}, {}), "('Log1p', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4233, 25, 4233, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4267, 4, 4268, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4268, 6, 4268, 18): '"""LogicalAnd"""', (4268, 20, 4268, 32): '_inputs_flat', (4268, 34, 4268, 40): '_attrs', (4268, 42, 4268, 49): '_result', (4268, 51, 4268, 55): 'name'}, {}), "('LogicalAnd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4293, 25, 4293, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4324, 4, 4325, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4325, 6, 4325, 18): '"""LogicalNot"""', (4325, 20, 4325, 32): '_inputs_flat', (4325, 34, 4325, 40): '_attrs', (4325, 42, 4325, 49): '_result', (4325, 51, 4325, 55): 'name'}, {}), "('LogicalNot', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4350, 25, 4350, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4384, 4, 4385, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4385, 6, 4385, 17): '"""LogicalOr"""', (4385, 19, 4385, 31): '_inputs_flat', (4385, 33, 4385, 39): '_attrs', (4385, 41, 4385, 48): '_result', (4385, 50, 4385, 54): 'name'}, {}), "('LogicalOr', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4410, 25, 4410, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4450, 18, 4450, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4450, 37, 4450, 48): 'transpose_a', (4450, 50, 4450, 63): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4453, 18, 4453, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4453, 37, 4453, 48): 'transpose_b', (4453, 50, 4453, 63): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4461, 4, 4462, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4462, 6, 4462, 14): '"""MatMul"""', (4462, 16, 4462, 28): '_inputs_flat', (4462, 30, 4462, 36): '_attrs', (4462, 38, 4462, 45): '_result', (4462, 47, 4462, 51): 'name'}, {}), "('MatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4489, 25, 4489, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4534, 16, 4534, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4534, 35, 4534, 44): 'keep_dims', (4534, 46, 4534, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4542, 4, 4543, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4543, 6, 4543, 11): '"""Max"""', (4543, 13, 4543, 25): '_inputs_flat', (4543, 27, 4543, 33): '_attrs', (4543, 35, 4543, 42): '_result', (4543, 44, 4543, 48): 'name'}, {}), "('Max', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4568, 25, 4568, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4606, 4, 4607, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4607, 6, 4607, 15): '"""Maximum"""', (4607, 17, 4607, 29): '_inputs_flat', (4607, 31, 4607, 37): '_attrs', (4607, 39, 4607, 46): '_result', (4607, 48, 4607, 52): 'name'}, {}), "('Maximum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4632, 25, 4632, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4670, 16, 4670, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4670, 35, 4670, 44): 'keep_dims', (4670, 46, 4670, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4678, 4, 4679, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4679, 6, 4679, 12): '"""Mean"""', (4679, 14, 4679, 26): '_inputs_flat', (4679, 28, 4679, 34): '_attrs', (4679, 36, 4679, 43): '_result', (4679, 45, 4679, 49): 'name'}, {}), "('Mean', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4704, 25, 4704, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4745, 16, 4745, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(4745, 35, 4745, 44): 'keep_dims', (4745, 46, 4745, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4753, 4, 4754, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4754, 6, 4754, 11): '"""Min"""', (4754, 13, 4754, 25): '_inputs_flat', (4754, 27, 4754, 33): '_attrs', (4754, 35, 4754, 42): '_result', (4754, 44, 4754, 48): 'name'}, {}), "('Min', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4779, 25, 4779, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4817, 4, 4818, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4818, 6, 4818, 15): '"""Minimum"""', (4818, 17, 4818, 29): '_inputs_flat', (4818, 31, 4818, 37): '_attrs', (4818, 39, 4818, 46): '_result', (4818, 48, 4818, 52): 'name'}, {}), "('Minimum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4843, 25, 4843, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4880, 4, 4881, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4881, 6, 4881, 11): '"""Mod"""', (4881, 13, 4881, 25): '_inputs_flat', (4881, 27, 4881, 33): '_attrs', (4881, 35, 4881, 42): '_result', (4881, 44, 4881, 48): 'name'}, {}), "('Mod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4906, 25, 4906, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4940, 4, 4941, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4941, 6, 4941, 11): '"""Mul"""', (4941, 13, 4941, 25): '_inputs_flat', (4941, 27, 4941, 33): '_attrs', (4941, 35, 4941, 42): '_result', (4941, 44, 4941, 48): 'name'}, {}), "('Mul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((4966, 25, 4966, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((4998, 4, 4999, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(4999, 6, 4999, 11): '"""Neg"""', (4999, 13, 4999, 25): '_inputs_flat', (4999, 27, 4999, 33): '_attrs', (4999, 35, 4999, 42): '_result', (4999, 44, 4999, 48): 'name'}, {}), "('Neg', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5024, 25, 5024, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5058, 4, 5059, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5059, 6, 5059, 16): '"""NotEqual"""', (5059, 18, 5059, 30): '_inputs_flat', (5059, 32, 5059, 38): '_attrs', (5059, 40, 5059, 47): '_result', (5059, 49, 5059, 53): 'name'}, {}), "('NotEqual', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5084, 25, 5084, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5123, 4, 5124, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5124, 6, 5124, 17): '"""Polygamma"""', (5124, 19, 5124, 31): '_inputs_flat', (5124, 33, 5124, 39): '_attrs', (5124, 41, 5124, 48): '_result', (5124, 50, 5124, 54): 'name'}, {}), "('Polygamma', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5149, 25, 5149, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5189, 4, 5190, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5190, 6, 5190, 11): '"""Pow"""', (5190, 13, 5190, 25): '_inputs_flat', (5190, 27, 5190, 33): '_attrs', (5190, 35, 5190, 42): '_result', (5190, 44, 5190, 48): 'name'}, {}), "('Pow', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5215, 25, 5215, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5253, 16, 5253, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5253, 35, 5253, 44): 'keep_dims', (5253, 46, 5253, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5261, 4, 5262, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5262, 6, 5262, 12): '"""Prod"""', (5262, 14, 5262, 26): '_inputs_flat', (5262, 28, 5262, 34): '_attrs', (5262, 36, 5262, 43): '_result', (5262, 45, 5262, 49): 'name'}, {}), "('Prod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5287, 25, 5287, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5354, 15, 5354, 55), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5354, 34, 5354, 42): 'out_type', (5354, 44, 5354, 54): '"""out_type"""'}, {}), "(out_type, 'out_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5362, 4, 5363, 72), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5363, 6, 5363, 34): '"""QuantizeDownAndShrinkRange"""', (5363, 36, 5363, 48): '_inputs_flat', (5363, 50, 5363, 56): '_attrs', (5363, 58, 5363, 65): '_result', (5363, 67, 5363, 71): 'name'}, {}), "('QuantizeDownAndShrinkRange', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5390, 25, 5390, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5439, 14, 5439, 52), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5439, 33, 5439, 40): 'Toutput', (5439, 42, 5439, 51): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5447, 4, 5448, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5448, 6, 5448, 20): '"""QuantizedAdd"""', (5448, 22, 5448, 34): '_inputs_flat', (5448, 36, 5448, 42): '_attrs', (5448, 44, 5448, 51): '_result', (5448, 53, 5448, 57): 'name'}, {}), "('QuantizedAdd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5476, 25, 5476, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5543, 14, 5543, 52), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5543, 33, 5543, 40): 'Toutput', (5543, 42, 5543, 51): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5546, 18, 5546, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5546, 37, 5546, 48): 'transpose_a', (5546, 50, 5546, 63): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5549, 18, 5549, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(5549, 37, 5549, 48): 'transpose_b', (5549, 50, 5549, 63): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5552, 18, 5552, 64), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5552, 37, 5552, 48): 'Tactivation', (5552, 50, 5552, 63): '"""Tactivation"""'}, {}), "(Tactivation, 'Tactivation')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5564, 4, 5565, 61), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5565, 6, 5565, 23): '"""QuantizedMatMul"""', (5565, 25, 5565, 37): '_inputs_flat', (5565, 39, 5565, 45): '_attrs', (5565, 47, 5565, 54): '_result', (5565, 56, 5565, 60): 'name'}, {}), "('QuantizedMatMul', _inputs_flat, _attrs, _result, name\n )", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5595, 25, 5595, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5658, 14, 5658, 52), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5658, 33, 5658, 40): 'Toutput', (5658, 42, 5658, 51): '"""Toutput"""'}, {}), "(Toutput, 'Toutput')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5666, 4, 5667, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5667, 6, 5667, 20): '"""QuantizedMul"""', (5667, 22, 5667, 34): '_inputs_flat', (5667, 36, 5667, 42): '_attrs', (5667, 44, 5667, 51): '_result', (5667, 53, 5667, 57): 'name'}, {}), "('QuantizedMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5695, 25, 5695, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5749, 4, 5750, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5750, 6, 5750, 13): '"""Range"""', (5750, 15, 5750, 27): '_inputs_flat', (5750, 29, 5750, 35): '_attrs', (5750, 37, 5750, 44): '_result', (5750, 46, 5750, 50): 'name'}, {}), "('Range', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5775, 25, 5775, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5815, 11, 5815, 43), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(5815, 30, 5815, 34): 'Tout', (5815, 36, 5815, 42): '"""Tout"""'}, {}), "(Tout, 'Tout')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5821, 4, 5822, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5822, 6, 5822, 12): '"""Real"""', (5822, 14, 5822, 26): '_inputs_flat', (5822, 28, 5822, 34): '_attrs', (5822, 36, 5822, 43): '_result', (5822, 45, 5822, 49): 'name'}, {}), "('Real', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5847, 25, 5847, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5885, 4, 5886, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5886, 6, 5886, 15): '"""RealDiv"""', (5886, 17, 5886, 29): '_inputs_flat', (5886, 31, 5886, 37): '_attrs', (5886, 39, 5886, 46): '_result', (5886, 48, 5886, 52): 'name'}, {}), "('RealDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5911, 25, 5911, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((5944, 4, 5945, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(5945, 6, 5945, 18): '"""Reciprocal"""', (5945, 20, 5945, 32): '_inputs_flat', (5945, 34, 5945, 40): '_attrs', (5945, 42, 5945, 49): '_result', (5945, 51, 5945, 55): 'name'}, {}), "('Reciprocal', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((5970, 25, 5970, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6003, 4, 6004, 60), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6004, 6, 6004, 22): '"""ReciprocalGrad"""', (6004, 24, 6004, 36): '_inputs_flat', (6004, 38, 6004, 44): '_attrs', (6004, 46, 6004, 53): '_result', (6004, 55, 6004, 59): 'name'}, {}), "('ReciprocalGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6029, 25, 6029, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6076, 4, 6077, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6077, 6, 6077, 27): '"""RequantizationRange"""', (6077, 29, 6077, 41): '_inputs_flat', (6077, 43, 6077, 49): '_attrs', (6077, 51, 6077, 58): '_result', (6077, 60, 6077, 64): 'name'}, {}), "('RequantizationRange', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6104, 25, 6104, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6156, 15, 6156, 55), 'tensorflow.python.eager.execute.make_type', '_execute.make_type', ({(6156, 34, 6156, 42): 'out_type', (6156, 44, 6156, 54): '"""out_type"""'}, {}), "(out_type, 'out_type')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6166, 4, 6167, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6167, 6, 6167, 18): '"""Requantize"""', (6167, 20, 6167, 32): '_inputs_flat', (6167, 34, 6167, 40): '_attrs', (6167, 42, 6167, 49): '_result', (6167, 51, 6167, 55): 'name'}, {}), "('Requantize', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6195, 25, 6195, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6240, 4, 6241, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6241, 6, 6241, 12): '"""Rint"""', (6241, 14, 6241, 26): '_inputs_flat', (6241, 28, 6241, 34): '_attrs', (6241, 36, 6241, 43): '_result', (6241, 45, 6241, 49): 'name'}, {}), "('Rint', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6266, 25, 6266, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6298, 4, 6299, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6299, 6, 6299, 13): '"""Round"""', (6299, 15, 6299, 27): '_inputs_flat', (6299, 29, 6299, 35): '_attrs', (6299, 37, 6299, 44): '_result', (6299, 46, 6299, 50): 'name'}, {}), "('Round', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6324, 25, 6324, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6356, 4, 6357, 51), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6357, 6, 6357, 13): '"""Rsqrt"""', (6357, 15, 6357, 27): '_inputs_flat', (6357, 29, 6357, 35): '_attrs', (6357, 37, 6357, 44): '_result', (6357, 46, 6357, 50): 'name'}, {}), "('Rsqrt', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6382, 25, 6382, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6415, 4, 6416, 55), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6416, 6, 6416, 17): '"""RsqrtGrad"""', (6416, 19, 6416, 31): '_inputs_flat', (6416, 33, 6416, 39): '_attrs', (6416, 41, 6416, 48): '_result', (6416, 50, 6416, 54): 'name'}, {}), "('RsqrtGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6441, 25, 6441, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6488, 4, 6489, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6489, 6, 6489, 18): '"""SegmentMax"""', (6489, 20, 6489, 32): '_inputs_flat', (6489, 34, 6489, 40): '_attrs', (6489, 42, 6489, 49): '_result', (6489, 51, 6489, 55): 'name'}, {}), "('SegmentMax', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6514, 25, 6514, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6562, 4, 6563, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6563, 6, 6563, 19): '"""SegmentMean"""', (6563, 21, 6563, 33): '_inputs_flat', (6563, 35, 6563, 41): '_attrs', (6563, 43, 6563, 50): '_result', (6563, 52, 6563, 56): 'name'}, {}), "('SegmentMean', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6588, 25, 6588, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6635, 4, 6636, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6636, 6, 6636, 18): '"""SegmentMin"""', (6636, 20, 6636, 32): '_inputs_flat', (6636, 34, 6636, 40): '_attrs', (6636, 42, 6636, 49): '_result', (6636, 51, 6636, 55): 'name'}, {}), "('SegmentMin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6661, 25, 6661, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6708, 4, 6709, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6709, 6, 6709, 19): '"""SegmentProd"""', (6709, 21, 6709, 33): '_inputs_flat', (6709, 35, 6709, 41): '_attrs', (6709, 43, 6709, 50): '_result', (6709, 52, 6709, 56): 'name'}, {}), "('SegmentProd', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6734, 25, 6734, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6781, 4, 6782, 56), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6782, 6, 6782, 18): '"""SegmentSum"""', (6782, 20, 6782, 32): '_inputs_flat', (6782, 34, 6782, 40): '_attrs', (6782, 42, 6782, 49): '_result', (6782, 51, 6782, 55): 'name'}, {}), "('SegmentSum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6807, 25, 6807, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6880, 4, 6881, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6881, 6, 6881, 14): '"""Select"""', (6881, 16, 6881, 28): '_inputs_flat', (6881, 30, 6881, 36): '_attrs', (6881, 38, 6881, 45): '_result', (6881, 47, 6881, 51): 'name'}, {}), "('Select', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6906, 25, 6906, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6939, 4, 6940, 53), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6940, 6, 6940, 15): '"""Sigmoid"""', (6940, 17, 6940, 29): '_inputs_flat', (6940, 31, 6940, 37): '_attrs', (6940, 39, 6940, 46): '_result', (6940, 48, 6940, 52): 'name'}, {}), "('Sigmoid', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((6965, 25, 6965, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((6998, 4, 6999, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(6999, 6, 6999, 19): '"""SigmoidGrad"""', (6999, 21, 6999, 33): '_inputs_flat', (6999, 35, 6999, 41): '_attrs', (6999, 43, 6999, 50): '_result', (6999, 52, 6999, 56): 'name'}, {}), "('SigmoidGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7024, 25, 7024, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7058, 4, 7059, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7059, 6, 7059, 12): '"""Sign"""', (7059, 14, 7059, 26): '_inputs_flat', (7059, 28, 7059, 34): '_attrs', (7059, 36, 7059, 43): '_result', (7059, 45, 7059, 49): 'name'}, {}), "('Sign', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7084, 25, 7084, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7114, 4, 7115, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7115, 6, 7115, 11): '"""Sin"""', (7115, 13, 7115, 25): '_inputs_flat', (7115, 27, 7115, 33): '_attrs', (7115, 35, 7115, 42): '_result', (7115, 44, 7115, 48): 'name'}, {}), "('Sin', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7140, 25, 7140, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7170, 4, 7171, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7171, 6, 7171, 12): '"""Sinh"""', (7171, 14, 7171, 26): '_inputs_flat', (7171, 28, 7171, 34): '_attrs', (7171, 36, 7171, 43): '_result', (7171, 45, 7171, 49): 'name'}, {}), "('Sinh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7196, 25, 7196, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7237, 18, 7237, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7237, 37, 7237, 48): 'transpose_a', (7237, 50, 7237, 63): '"""transpose_a"""'}, {}), "(transpose_a, 'transpose_a')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7240, 18, 7240, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7240, 37, 7240, 48): 'transpose_b', (7240, 50, 7240, 63): '"""transpose_b"""'}, {}), "(transpose_b, 'transpose_b')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7243, 18, 7243, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7243, 37, 7243, 48): 'a_is_sparse', (7243, 50, 7243, 63): '"""a_is_sparse"""'}, {}), "(a_is_sparse, 'a_is_sparse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7246, 18, 7246, 64), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(7246, 37, 7246, 48): 'b_is_sparse', (7246, 50, 7246, 63): '"""b_is_sparse"""'}, {}), "(b_is_sparse, 'b_is_sparse')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7258, 4, 7259, 58), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7259, 6, 7259, 20): '"""SparseMatMul"""', (7259, 22, 7259, 34): '_inputs_flat', (7259, 36, 7259, 42): '_attrs', (7259, 44, 7259, 51): '_result', (7259, 53, 7259, 57): 'name'}, {}), "('SparseMatMul', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7288, 25, 7288, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7343, 4, 7344, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7344, 6, 7344, 25): '"""SparseSegmentMean"""', (7344, 27, 7344, 39): '_inputs_flat', (7344, 41, 7344, 47): '_attrs', (7344, 49, 7344, 56): '_result', (7344, 58, 7344, 62): 'name'}, {}), "('SparseSegmentMean', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7370, 25, 7370, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7412, 4, 7413, 67), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7413, 6, 7413, 29): '"""SparseSegmentMeanGrad"""', (7413, 31, 7413, 43): '_inputs_flat', (7413, 45, 7413, 51): '_attrs', (7413, 53, 7413, 60): '_result', (7413, 62, 7413, 66): 'name'}, {}), "('SparseSegmentMeanGrad', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7439, 25, 7439, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7485, 4, 7486, 78), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7486, 6, 7486, 40): '"""SparseSegmentMeanWithNumSegments"""', (7486, 42, 7486, 54): '_inputs_flat', (7486, 56, 7486, 62): '_attrs', (7486, 64, 7486, 71): '_result', (7486, 73, 7486, 77): 'name'}, {}), "('SparseSegmentMeanWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7513, 25, 7513, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7557, 4, 7558, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7558, 6, 7558, 26): '"""SparseSegmentSqrtN"""', (7558, 28, 7558, 40): '_inputs_flat', (7558, 42, 7558, 48): '_attrs', (7558, 50, 7558, 57): '_result', (7558, 59, 7558, 63): 'name'}, {}), "('SparseSegmentSqrtN', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7584, 25, 7584, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7626, 4, 7627, 68), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7627, 6, 7627, 30): '"""SparseSegmentSqrtNGrad"""', (7627, 32, 7627, 44): '_inputs_flat', (7627, 46, 7627, 52): '_attrs', (7627, 54, 7627, 61): '_result', (7627, 63, 7627, 67): 'name'}, {}), "('SparseSegmentSqrtNGrad', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7653, 25, 7653, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7702, 4, 7703, 79), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7703, 6, 7703, 41): '"""SparseSegmentSqrtNWithNumSegments"""', (7703, 43, 7703, 55): '_inputs_flat', (7703, 57, 7703, 63): '_attrs', (7703, 65, 7703, 72): '_result', (7703, 74, 7703, 78): 'name'}, {}), "('SparseSegmentSqrtNWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7730, 25, 7730, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7798, 4, 7799, 62), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7799, 6, 7799, 24): '"""SparseSegmentSum"""', (7799, 26, 7799, 38): '_inputs_flat', (7799, 40, 7799, 46): '_attrs', (7799, 48, 7799, 55): '_result', (7799, 57, 7799, 61): 'name'}, {}), "('SparseSegmentSum', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7825, 25, 7825, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7891, 4, 7892, 77), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7892, 6, 7892, 39): '"""SparseSegmentSumWithNumSegments"""', (7892, 41, 7892, 53): '_inputs_flat', (7892, 55, 7892, 61): '_attrs', (7892, 63, 7892, 70): '_result', (7892, 72, 7892, 76): 'name'}, {}), "('SparseSegmentSumWithNumSegments', _inputs_flat,\n _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7919, 25, 7919, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((7955, 4, 7956, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(7956, 6, 7956, 12): '"""Sqrt"""', (7956, 14, 7956, 26): '_inputs_flat', (7956, 28, 7956, 34): '_attrs', (7956, 36, 7956, 43): '_result', (7956, 45, 7956, 49): 'name'}, {}), "('Sqrt', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((7981, 25, 7981, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8014, 4, 8015, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8015, 6, 8015, 16): '"""SqrtGrad"""', (8015, 18, 8015, 30): '_inputs_flat', (8015, 32, 8015, 38): '_attrs', (8015, 40, 8015, 47): '_result', (8015, 49, 8015, 53): 'name'}, {}), "('SqrtGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8040, 25, 8040, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8072, 4, 8073, 52), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8073, 6, 8073, 14): '"""Square"""', (8073, 16, 8073, 28): '_inputs_flat', (8073, 30, 8073, 36): '_attrs', (8073, 38, 8073, 45): '_result', (8073, 47, 8073, 51): 'name'}, {}), "('Square', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8098, 25, 8098, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8132, 4, 8133, 63), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8133, 6, 8133, 25): '"""SquaredDifference"""', (8133, 27, 8133, 39): '_inputs_flat', (8133, 41, 8133, 47): '_attrs', (8133, 49, 8133, 56): '_result', (8133, 58, 8133, 62): 'name'}, {}), "('SquaredDifference', _inputs_flat, _attrs, _result,\n name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8158, 25, 8158, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8192, 4, 8193, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8193, 6, 8193, 11): '"""Sub"""', (8193, 13, 8193, 25): '_inputs_flat', (8193, 27, 8193, 33): '_attrs', (8193, 35, 8193, 42): '_result', (8193, 44, 8193, 48): 'name'}, {}), "('Sub', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8218, 25, 8218, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8256, 16, 8256, 58), 'tensorflow.python.eager.execute.make_bool', '_execute.make_bool', ({(8256, 35, 8256, 44): 'keep_dims', (8256, 46, 8256, 57): '"""keep_dims"""'}, {}), "(keep_dims, 'keep_dims')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8264, 4, 8265, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8265, 6, 8265, 11): '"""Sum"""', (8265, 13, 8265, 25): '_inputs_flat', (8265, 27, 8265, 33): '_attrs', (8265, 35, 8265, 42): '_result', (8265, 44, 8265, 48): 'name'}, {}), "('Sum', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8290, 25, 8290, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8324, 4, 8325, 49), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8325, 6, 8325, 11): '"""Tan"""', (8325, 13, 8325, 25): '_inputs_flat', (8325, 27, 8325, 33): '_attrs', (8325, 35, 8325, 42): '_result', (8325, 44, 8325, 48): 'name'}, {}), "('Tan', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8350, 25, 8350, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8379, 4, 8380, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8380, 6, 8380, 12): '"""Tanh"""', (8380, 14, 8380, 26): '_inputs_flat', (8380, 28, 8380, 34): '_attrs', (8380, 36, 8380, 43): '_result', (8380, 45, 8380, 49): 'name'}, {}), "('Tanh', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8405, 25, 8405, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8438, 4, 8439, 54), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8439, 6, 8439, 16): '"""TanhGrad"""', (8439, 18, 8439, 30): '_inputs_flat', (8439, 32, 8439, 38): '_attrs', (8439, 40, 8439, 47): '_result', (8439, 49, 8439, 53): 'name'}, {}), "('TanhGrad', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8464, 25, 8464, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8503, 4, 8504, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8504, 6, 8504, 19): '"""TruncateDiv"""', (8504, 21, 8504, 33): '_inputs_flat', (8504, 35, 8504, 41): '_attrs', (8504, 43, 8504, 50): '_result', (8504, 52, 8504, 56): 'name'}, {}), "('TruncateDiv', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8529, 25, 8529, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8566, 4, 8567, 57), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8567, 6, 8567, 19): '"""TruncateMod"""', (8567, 21, 8567, 33): '_inputs_flat', (8567, 35, 8567, 41): '_attrs', (8567, 43, 8567, 50): '_result', (8567, 52, 8567, 56): 'name'}, {}), "('TruncateMod', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8592, 25, 8592, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8647, 4, 8648, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8648, 6, 8648, 26): '"""UnsortedSegmentMax"""', (8648, 28, 8648, 40): '_inputs_flat', (8648, 42, 8648, 48): '_attrs', (8648, 50, 8648, 57): '_result', (8648, 59, 8648, 63): 'name'}, {}), "('UnsortedSegmentMax', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8674, 25, 8674, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8727, 4, 8728, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8728, 6, 8728, 26): '"""UnsortedSegmentMin"""', (8728, 28, 8728, 40): '_inputs_flat', (8728, 42, 8728, 48): '_attrs', (8728, 50, 8728, 57): '_result', (8728, 59, 8728, 63): 'name'}, {}), "('UnsortedSegmentMin', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8754, 25, 8754, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8806, 4, 8807, 65), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8807, 6, 8807, 27): '"""UnsortedSegmentProd"""', (8807, 29, 8807, 41): '_inputs_flat', (8807, 43, 8807, 49): '_attrs', (8807, 51, 8807, 58): '_result', (8807, 60, 8807, 64): 'name'}, {}), "('UnsortedSegmentProd', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8833, 25, 8833, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8890, 4, 8891, 64), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8891, 6, 8891, 26): '"""UnsortedSegmentSum"""', (8891, 28, 8891, 40): '_inputs_flat', (8891, 42, 8891, 48): '_attrs', (8891, 50, 8891, 57): '_result', (8891, 59, 8891, 63): 'name'}, {}), "('UnsortedSegmentSum', _inputs_flat, _attrs,\n _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8917, 25, 8917, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((8956, 4, 8957, 50), 'tensorflow.python.eager.execute.record_gradient', '_execute.record_gradient', ({(8957, 6, 8957, 12): '"""Zeta"""', (8957, 14, 8957, 26): '_inputs_flat', (8957, 28, 8957, 34): '_attrs', (8957, 36, 8957, 43): '_result', (8957, 45, 8957, 49): 'name'}, {}), "('Zeta', _inputs_flat, _attrs, _result, name)", True, 'from tensorflow.python.eager import execute as _execute\n'), ((8982, 25, 8982, 43), 'tensorflow.python.eager.context.context', '_context.context', ({}, {}), '()', True, 'from tensorflow.python.eager import context as _context\n'), ((55, 16, 57, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(56, 8, 56, 28): '_ctx._context_handle', (56, 30, 56, 61): '_ctx._eager_context.device_name', (56, 63, 56, 68): '"""Abs"""', (56, 70, 56, 74): 'name', (57, 8, 57, 38): '_ctx._post_execution_callbacks', (57, 40, 57, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Abs', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((129, 16, 132, 23), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(130, 8, 130, 28): '_ctx._context_handle', (130, 30, 130, 61): '_ctx._eager_context.device_name', (131, 8, 131, 23): '"""AccumulateNV2"""', (131, 25, 131, 29): 'name', (131, 31, 131, 61): '_ctx._post_execution_callbacks', (131, 63, 131, 69): 'inputs', (132, 8, 132, 15): '"""shape"""', (132, 17, 132, 22): 'shape'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'AccumulateNV2', name, _ctx.\n _post_execution_callbacks, inputs, 'shape', shape)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((192, 16, 194, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(193, 8, 193, 28): '_ctx._context_handle', (193, 30, 193, 61): '_ctx._eager_context.device_name', (193, 63, 193, 69): '"""Acos"""', (193, 71, 193, 75): 'name', (194, 8, 194, 38): '_ctx._post_execution_callbacks', (194, 40, 194, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Acos', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((248, 16, 250, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(249, 8, 249, 28): '_ctx._context_handle', (249, 30, 249, 61): '_ctx._eager_context.device_name', (249, 63, 249, 70): '"""Acosh"""', (249, 72, 249, 76): 'name', (250, 8, 250, 38): '_ctx._post_execution_callbacks', (250, 40, 250, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Acosh', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((308, 16, 310, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(309, 8, 309, 28): '_ctx._context_handle', (309, 30, 309, 61): '_ctx._eager_context.device_name', (309, 63, 309, 68): '"""Add"""', (309, 70, 309, 74): 'name', (310, 8, 310, 38): '_ctx._post_execution_callbacks', (310, 40, 310, 41): 'x', (310, 43, 310, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Add', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((370, 16, 372, 47), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(371, 8, 371, 28): '_ctx._context_handle', (371, 30, 371, 61): '_ctx._eager_context.device_name', (371, 63, 371, 69): '"""AddN"""', (371, 71, 371, 75): 'name', (372, 8, 372, 38): '_ctx._post_execution_callbacks', (372, 40, 372, 46): 'inputs'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'AddN', name, _ctx.\n _post_execution_callbacks, inputs)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((434, 16, 436, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(435, 8, 435, 28): '_ctx._context_handle', (435, 30, 435, 61): '_ctx._eager_context.device_name', (435, 63, 435, 70): '"""AddV2"""', (435, 72, 435, 76): 'name', (436, 8, 436, 38): '_ctx._post_execution_callbacks', (436, 40, 436, 41): 'x', (436, 43, 436, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'AddV2', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((505, 16, 507, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(506, 8, 506, 28): '_ctx._context_handle', (506, 30, 506, 61): '_ctx._eager_context.device_name', (506, 63, 506, 68): '"""All"""', (506, 70, 506, 74): 'name', (507, 8, 507, 38): '_ctx._post_execution_callbacks', (507, 40, 507, 45): 'input', (507, 47, 507, 51): 'axis', (507, 53, 507, 64): '"""keep_dims"""', (507, 66, 507, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'All', name, _ctx._post_execution_callbacks,\n input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((586, 16, 588, 60), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(587, 8, 587, 28): '_ctx._context_handle', (587, 30, 587, 61): '_ctx._eager_context.device_name', (587, 63, 587, 70): '"""Angle"""', (587, 72, 587, 76): 'name', (588, 8, 588, 38): '_ctx._post_execution_callbacks', (588, 40, 588, 45): 'input', (588, 47, 588, 53): '"""Tout"""', (588, 55, 588, 59): 'Tout'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Angle', name, _ctx.\n _post_execution_callbacks, input, 'Tout', Tout)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((659, 16, 661, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(660, 8, 660, 28): '_ctx._context_handle', (660, 30, 660, 61): '_ctx._eager_context.device_name', (660, 63, 660, 68): '"""Any"""', (660, 70, 660, 74): 'name', (661, 8, 661, 38): '_ctx._post_execution_callbacks', (661, 40, 661, 45): 'input', (661, 47, 661, 51): 'axis', (661, 53, 661, 64): '"""keep_dims"""', (661, 66, 661, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Any', name, _ctx._post_execution_callbacks,\n input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((723, 16, 726, 31), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(724, 8, 724, 28): '_ctx._context_handle', (724, 30, 724, 61): '_ctx._eager_context.device_name', (725, 8, 725, 26): '"""ApproximateEqual"""', (725, 28, 725, 32): 'name', (725, 34, 725, 64): '_ctx._post_execution_callbacks', (725, 66, 725, 67): 'x', (725, 69, 725, 70): 'y', (726, 8, 726, 19): '"""tolerance"""', (726, 21, 726, 30): 'tolerance'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ApproximateEqual', name, _ctx.\n _post_execution_callbacks, x, y, 'tolerance', tolerance)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((795, 16, 798, 20), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(796, 8, 796, 28): '_ctx._context_handle', (796, 30, 796, 61): '_ctx._eager_context.device_name', (796, 63, 796, 71): '"""ArgMax"""', (796, 73, 796, 77): 'name', (797, 8, 797, 38): '_ctx._post_execution_callbacks', (797, 40, 797, 45): 'input', (797, 47, 797, 56): 'dimension', (797, 58, 797, 71): '"""output_type"""', (798, 8, 798, 19): 'output_type'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ArgMax', name, _ctx.\n _post_execution_callbacks, input, dimension, 'output_type', output_type)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((867, 16, 870, 20), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(868, 8, 868, 28): '_ctx._context_handle', (868, 30, 868, 61): '_ctx._eager_context.device_name', (868, 63, 868, 71): '"""ArgMin"""', (868, 73, 868, 77): 'name', (869, 8, 869, 38): '_ctx._post_execution_callbacks', (869, 40, 869, 45): 'input', (869, 47, 869, 56): 'dimension', (869, 58, 869, 71): '"""output_type"""', (870, 8, 870, 19): 'output_type'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ArgMin', name, _ctx.\n _post_execution_callbacks, input, dimension, 'output_type', output_type)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((928, 16, 930, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(929, 8, 929, 28): '_ctx._context_handle', (929, 30, 929, 61): '_ctx._eager_context.device_name', (929, 63, 929, 69): '"""Asin"""', (929, 71, 929, 75): 'name', (930, 8, 930, 38): '_ctx._post_execution_callbacks', (930, 40, 930, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Asin', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((984, 16, 986, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(985, 8, 985, 28): '_ctx._context_handle', (985, 30, 985, 61): '_ctx._eager_context.device_name', (985, 63, 985, 70): '"""Asinh"""', (985, 72, 985, 76): 'name', (986, 8, 986, 38): '_ctx._post_execution_callbacks', (986, 40, 986, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Asinh', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1040, 16, 1042, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1041, 8, 1041, 28): '_ctx._context_handle', (1041, 30, 1041, 61): '_ctx._eager_context.device_name', (1041, 63, 1041, 69): '"""Atan"""', (1041, 71, 1041, 75): 'name', (1042, 8, 1042, 38): '_ctx._post_execution_callbacks', (1042, 40, 1042, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Atan', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1103, 16, 1105, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1104, 8, 1104, 28): '_ctx._context_handle', (1104, 30, 1104, 61): '_ctx._eager_context.device_name', (1104, 63, 1104, 70): '"""Atan2"""', (1104, 72, 1104, 76): 'name', (1105, 8, 1105, 38): '_ctx._post_execution_callbacks', (1105, 40, 1105, 41): 'y', (1105, 43, 1105, 44): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Atan2', name, _ctx.\n _post_execution_callbacks, y, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1160, 16, 1162, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1161, 8, 1161, 28): '_ctx._context_handle', (1161, 30, 1161, 61): '_ctx._eager_context.device_name', (1161, 63, 1161, 70): '"""Atanh"""', (1161, 72, 1161, 76): 'name', (1162, 8, 1162, 38): '_ctx._post_execution_callbacks', (1162, 40, 1162, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Atanh', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1248, 16, 1251, 14), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1249, 8, 1249, 28): '_ctx._context_handle', (1249, 30, 1249, 61): '_ctx._eager_context.device_name', (1249, 63, 1249, 76): '"""BatchMatMul"""', (1250, 8, 1250, 12): 'name', (1250, 14, 1250, 44): '_ctx._post_execution_callbacks', (1250, 46, 1250, 47): 'x', (1250, 49, 1250, 50): 'y', (1250, 52, 1250, 59): '"""adj_x"""', (1250, 61, 1250, 66): 'adj_x', (1250, 68, 1250, 75): '"""adj_y"""', (1251, 8, 1251, 13): 'adj_y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'BatchMatMul', name, _ctx.\n _post_execution_callbacks, x, y, 'adj_x', adj_x, 'adj_y', adj_y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1316, 16, 1318, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1317, 8, 1317, 28): '_ctx._context_handle', (1317, 30, 1317, 61): '_ctx._eager_context.device_name', (1317, 63, 1317, 74): '"""BesselI0e"""', (1318, 8, 1318, 12): 'name', (1318, 14, 1318, 44): '_ctx._post_execution_callbacks', (1318, 46, 1318, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'BesselI0e', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1376, 16, 1378, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1377, 8, 1377, 28): '_ctx._context_handle', (1377, 30, 1377, 61): '_ctx._eager_context.device_name', (1377, 63, 1377, 74): '"""BesselI1e"""', (1378, 8, 1378, 12): 'name', (1378, 14, 1378, 44): '_ctx._post_execution_callbacks', (1378, 46, 1378, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'BesselI1e', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1448, 16, 1450, 54), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1449, 8, 1449, 28): '_ctx._context_handle', (1449, 30, 1449, 61): '_ctx._eager_context.device_name', (1449, 63, 1449, 72): '"""Betainc"""', (1450, 8, 1450, 12): 'name', (1450, 14, 1450, 44): '_ctx._post_execution_callbacks', (1450, 46, 1450, 47): 'a', (1450, 49, 1450, 50): 'b', (1450, 52, 1450, 53): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Betainc', name, _ctx.\n _post_execution_callbacks, a, b, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1517, 16, 1519, 65), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1518, 8, 1518, 28): '_ctx._context_handle', (1518, 30, 1518, 61): '_ctx._eager_context.device_name', (1518, 63, 1518, 73): '"""Bincount"""', (1519, 8, 1519, 12): 'name', (1519, 14, 1519, 44): '_ctx._post_execution_callbacks', (1519, 46, 1519, 49): 'arr', (1519, 51, 1519, 55): 'size', (1519, 57, 1519, 64): 'weights'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Bincount', name, _ctx.\n _post_execution_callbacks, arr, size, weights)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1580, 18, 1580, 55), 'tensorflow.python.eager.execute.make_float', '_execute.make_float', ({(1580, 38, 1580, 40): '_f', (1580, 42, 1580, 54): '"""boundaries"""'}, {}), "(_f, 'boundaries')", True, 'from tensorflow.python.eager import execute as _execute\n'), ((1594, 16, 1596, 78), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1595, 8, 1595, 28): '_ctx._context_handle', (1595, 30, 1595, 61): '_ctx._eager_context.device_name', (1595, 63, 1595, 74): '"""Bucketize"""', (1596, 8, 1596, 12): 'name', (1596, 14, 1596, 44): '_ctx._post_execution_callbacks', (1596, 46, 1596, 51): 'input', (1596, 53, 1596, 65): '"""boundaries"""', (1596, 67, 1596, 77): 'boundaries'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Bucketize', name, _ctx.\n _post_execution_callbacks, input, 'boundaries', boundaries)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1656, 16, 1658, 56), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1657, 8, 1657, 28): '_ctx._context_handle', (1657, 30, 1657, 61): '_ctx._eager_context.device_name', (1657, 63, 1657, 69): '"""Cast"""', (1657, 71, 1657, 75): 'name', (1658, 8, 1658, 38): '_ctx._post_execution_callbacks', (1658, 40, 1658, 41): 'x', (1658, 43, 1658, 49): '"""DstT"""', (1658, 51, 1658, 55): 'DstT'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cast', name, _ctx.\n _post_execution_callbacks, x, 'DstT', DstT)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1713, 16, 1715, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1714, 8, 1714, 28): '_ctx._context_handle', (1714, 30, 1714, 61): '_ctx._eager_context.device_name', (1714, 63, 1714, 69): '"""Ceil"""', (1714, 71, 1714, 75): 'name', (1715, 8, 1715, 38): '_ctx._post_execution_callbacks', (1715, 40, 1715, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Ceil', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1781, 16, 1784, 23), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1782, 8, 1782, 28): '_ctx._context_handle', (1782, 30, 1782, 61): '_ctx._eager_context.device_name', (1782, 63, 1782, 76): '"""ClipByValue"""', (1783, 8, 1783, 12): 'name', (1783, 14, 1783, 44): '_ctx._post_execution_callbacks', (1783, 46, 1783, 47): 't', (1783, 49, 1783, 63): 'clip_value_min', (1784, 8, 1784, 22): 'clip_value_max'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ClipByValue', name, _ctx.\n _post_execution_callbacks, t, clip_value_min, clip_value_max)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1865, 16, 1868, 18), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1866, 8, 1866, 28): '_ctx._context_handle', (1866, 30, 1866, 61): '_ctx._eager_context.device_name', (1867, 8, 1867, 27): '"""CompareAndBitpack"""', (1867, 29, 1867, 33): 'name', (1867, 35, 1867, 65): '_ctx._post_execution_callbacks', (1867, 67, 1867, 72): 'input', (1868, 8, 1868, 17): 'threshold'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'CompareAndBitpack', name, _ctx.\n _post_execution_callbacks, input, threshold)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((1942, 16, 1944, 71), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(1943, 8, 1943, 28): '_ctx._context_handle', (1943, 30, 1943, 61): '_ctx._eager_context.device_name', (1943, 63, 1943, 72): '"""Complex"""', (1944, 8, 1944, 12): 'name', (1944, 14, 1944, 44): '_ctx._post_execution_callbacks', (1944, 46, 1944, 50): 'real', (1944, 52, 1944, 56): 'imag', (1944, 58, 1944, 64): '"""Tout"""', (1944, 66, 1944, 70): 'Tout'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Complex', name, _ctx.\n _post_execution_callbacks, real, imag, 'Tout', Tout)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2010, 16, 2012, 62), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2011, 8, 2011, 28): '_ctx._context_handle', (2011, 30, 2011, 61): '_ctx._eager_context.device_name', (2011, 63, 2011, 75): '"""ComplexAbs"""', (2012, 8, 2012, 12): 'name', (2012, 14, 2012, 44): '_ctx._post_execution_callbacks', (2012, 46, 2012, 47): 'x', (2012, 49, 2012, 55): '"""Tout"""', (2012, 57, 2012, 61): 'Tout'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ComplexAbs', name, _ctx.\n _post_execution_callbacks, x, 'Tout', Tout)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2082, 16, 2084, 46), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2083, 8, 2083, 28): '_ctx._context_handle', (2083, 30, 2083, 61): '_ctx._eager_context.device_name', (2083, 63, 2083, 69): '"""Conj"""', (2083, 71, 2083, 75): 'name', (2084, 8, 2084, 38): '_ctx._post_execution_callbacks', (2084, 40, 2084, 45): 'input'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Conj', name, _ctx.\n _post_execution_callbacks, input)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2138, 16, 2140, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2139, 8, 2139, 28): '_ctx._context_handle', (2139, 30, 2139, 61): '_ctx._eager_context.device_name', (2139, 63, 2139, 68): '"""Cos"""', (2139, 70, 2139, 74): 'name', (2140, 8, 2140, 38): '_ctx._post_execution_callbacks', (2140, 40, 2140, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cos', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2194, 16, 2196, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2195, 8, 2195, 28): '_ctx._context_handle', (2195, 30, 2195, 61): '_ctx._eager_context.device_name', (2195, 63, 2195, 69): '"""Cosh"""', (2195, 71, 2195, 75): 'name', (2196, 8, 2196, 38): '_ctx._post_execution_callbacks', (2196, 40, 2196, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cosh', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2257, 16, 2259, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2258, 8, 2258, 28): '_ctx._context_handle', (2258, 30, 2258, 61): '_ctx._eager_context.device_name', (2258, 63, 2258, 70): '"""Cross"""', (2258, 72, 2258, 76): 'name', (2259, 8, 2259, 38): '_ctx._post_execution_callbacks', (2259, 40, 2259, 41): 'a', (2259, 43, 2259, 44): 'b'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cross', name, _ctx.\n _post_execution_callbacks, a, b)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2361, 16, 2364, 27), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2362, 8, 2362, 28): '_ctx._context_handle', (2362, 30, 2362, 61): '_ctx._eager_context.device_name', (2362, 63, 2362, 72): '"""Cumprod"""', (2363, 8, 2363, 12): 'name', (2363, 14, 2363, 44): '_ctx._post_execution_callbacks', (2363, 46, 2363, 47): 'x', (2363, 49, 2363, 53): 'axis', (2363, 55, 2363, 66): '"""exclusive"""', (2363, 68, 2363, 77): 'exclusive', (2364, 8, 2364, 17): '"""reverse"""', (2364, 19, 2364, 26): 'reverse'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cumprod', name, _ctx.\n _post_execution_callbacks, x, axis, 'exclusive', exclusive, 'reverse',\n reverse)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2473, 16, 2476, 27), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2474, 8, 2474, 28): '_ctx._context_handle', (2474, 30, 2474, 61): '_ctx._eager_context.device_name', (2474, 63, 2474, 71): '"""Cumsum"""', (2474, 73, 2474, 77): 'name', (2475, 8, 2475, 38): '_ctx._post_execution_callbacks', (2475, 40, 2475, 41): 'x', (2475, 43, 2475, 47): 'axis', (2475, 49, 2475, 60): '"""exclusive"""', (2475, 62, 2475, 71): 'exclusive', (2476, 8, 2476, 17): '"""reverse"""', (2476, 19, 2476, 26): 'reverse'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Cumsum', name, _ctx.\n _post_execution_callbacks, x, axis, 'exclusive', exclusive, 'reverse',\n reverse)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2540, 16, 2542, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2541, 8, 2541, 28): '_ctx._context_handle', (2541, 30, 2541, 61): '_ctx._eager_context.device_name', (2541, 63, 2541, 72): '"""Digamma"""', (2542, 8, 2542, 12): 'name', (2542, 14, 2542, 44): '_ctx._post_execution_callbacks', (2542, 46, 2542, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Digamma', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2599, 16, 2601, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2600, 8, 2600, 28): '_ctx._context_handle', (2600, 30, 2600, 61): '_ctx._eager_context.device_name', (2600, 63, 2600, 68): '"""Div"""', (2600, 70, 2600, 74): 'name', (2601, 8, 2601, 38): '_ctx._post_execution_callbacks', (2601, 40, 2601, 41): 'x', (2601, 43, 2601, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Div', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2660, 16, 2662, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2661, 8, 2661, 28): '_ctx._context_handle', (2661, 30, 2661, 61): '_ctx._eager_context.device_name', (2661, 63, 2661, 70): '"""Equal"""', (2661, 72, 2661, 76): 'name', (2662, 8, 2662, 38): '_ctx._post_execution_callbacks', (2662, 40, 2662, 41): 'x', (2662, 43, 2662, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Equal', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2716, 16, 2718, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2717, 8, 2717, 28): '_ctx._context_handle', (2717, 30, 2717, 61): '_ctx._eager_context.device_name', (2717, 63, 2717, 68): '"""Erf"""', (2717, 70, 2717, 74): 'name', (2718, 8, 2718, 38): '_ctx._post_execution_callbacks', (2718, 40, 2718, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Erf', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2772, 16, 2774, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2773, 8, 2773, 28): '_ctx._context_handle', (2773, 30, 2773, 61): '_ctx._eager_context.device_name', (2773, 63, 2773, 69): '"""Erfc"""', (2773, 71, 2773, 75): 'name', (2774, 8, 2774, 38): '_ctx._post_execution_callbacks', (2774, 40, 2774, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Erfc', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2828, 16, 2830, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2829, 8, 2829, 28): '_ctx._context_handle', (2829, 30, 2829, 61): '_ctx._eager_context.device_name', (2829, 63, 2829, 68): '"""Exp"""', (2829, 70, 2829, 74): 'name', (2830, 8, 2830, 38): '_ctx._post_execution_callbacks', (2830, 40, 2830, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Exp', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2886, 16, 2888, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2887, 8, 2887, 28): '_ctx._context_handle', (2887, 30, 2887, 61): '_ctx._eager_context.device_name', (2887, 63, 2887, 70): '"""Expm1"""', (2887, 72, 2887, 76): 'name', (2888, 8, 2888, 38): '_ctx._post_execution_callbacks', (2888, 40, 2888, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Expm1', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((2942, 16, 2944, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(2943, 8, 2943, 28): '_ctx._context_handle', (2943, 30, 2943, 61): '_ctx._eager_context.device_name', (2943, 63, 2943, 70): '"""Floor"""', (2943, 72, 2943, 76): 'name', (2944, 8, 2944, 38): '_ctx._post_execution_callbacks', (2944, 40, 2944, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Floor', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3001, 16, 3003, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3002, 8, 3002, 28): '_ctx._context_handle', (3002, 30, 3002, 61): '_ctx._eager_context.device_name', (3002, 63, 3002, 73): '"""FloorDiv"""', (3003, 8, 3003, 12): 'name', (3003, 14, 3003, 44): '_ctx._post_execution_callbacks', (3003, 46, 3003, 47): 'x', (3003, 49, 3003, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'FloorDiv', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3064, 16, 3066, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3065, 8, 3065, 28): '_ctx._context_handle', (3065, 30, 3065, 61): '_ctx._eager_context.device_name', (3065, 63, 3065, 73): '"""FloorMod"""', (3066, 8, 3066, 12): 'name', (3066, 14, 3066, 44): '_ctx._post_execution_callbacks', (3066, 46, 3066, 47): 'x', (3066, 49, 3066, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'FloorMod', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3125, 16, 3127, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3126, 8, 3126, 28): '_ctx._context_handle', (3126, 30, 3126, 61): '_ctx._eager_context.device_name', (3126, 63, 3126, 72): '"""Greater"""', (3127, 8, 3127, 12): 'name', (3127, 14, 3127, 44): '_ctx._post_execution_callbacks', (3127, 46, 3127, 47): 'x', (3127, 49, 3127, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Greater', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3186, 16, 3188, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3187, 8, 3187, 28): '_ctx._context_handle', (3187, 30, 3187, 61): '_ctx._eager_context.device_name', (3187, 63, 3187, 77): '"""GreaterEqual"""', (3188, 8, 3188, 12): 'name', (3188, 14, 3188, 44): '_ctx._post_execution_callbacks', (3188, 46, 3188, 47): 'x', (3188, 49, 3188, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'GreaterEqual', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3270, 16, 3273, 43), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3271, 8, 3271, 28): '_ctx._context_handle', (3271, 30, 3271, 61): '_ctx._eager_context.device_name', (3272, 8, 3272, 29): '"""HistogramFixedWidth"""', (3272, 31, 3272, 35): 'name', (3272, 37, 3272, 67): '_ctx._post_execution_callbacks', (3272, 69, 3272, 75): 'values', (3273, 8, 3273, 19): 'value_range', (3273, 21, 3273, 26): 'nbins', (3273, 28, 3273, 35): '"""dtype"""', (3273, 37, 3273, 42): 'dtype'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'HistogramFixedWidth', name, _ctx.\n _post_execution_callbacks, values, value_range, nbins, 'dtype', dtype)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3347, 16, 3349, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3348, 8, 3348, 28): '_ctx._context_handle', (3348, 30, 3348, 61): '_ctx._eager_context.device_name', (3348, 63, 3348, 71): '"""Igamma"""', (3348, 73, 3348, 77): 'name', (3349, 8, 3349, 38): '_ctx._post_execution_callbacks', (3349, 40, 3349, 41): 'a', (3349, 43, 3349, 44): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Igamma', name, _ctx.\n _post_execution_callbacks, a, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3404, 16, 3406, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3405, 8, 3405, 28): '_ctx._context_handle', (3405, 30, 3405, 61): '_ctx._eager_context.device_name', (3405, 63, 3405, 76): '"""IgammaGradA"""', (3406, 8, 3406, 12): 'name', (3406, 14, 3406, 44): '_ctx._post_execution_callbacks', (3406, 46, 3406, 47): 'a', (3406, 49, 3406, 50): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'IgammaGradA', name, _ctx.\n _post_execution_callbacks, a, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3475, 16, 3477, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3476, 8, 3476, 28): '_ctx._context_handle', (3476, 30, 3476, 61): '_ctx._eager_context.device_name', (3476, 63, 3476, 72): '"""Igammac"""', (3477, 8, 3477, 12): 'name', (3477, 14, 3477, 44): '_ctx._post_execution_callbacks', (3477, 46, 3477, 47): 'a', (3477, 49, 3477, 50): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Igammac', name, _ctx.\n _post_execution_callbacks, a, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3547, 16, 3549, 60), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3548, 8, 3548, 28): '_ctx._context_handle', (3548, 30, 3548, 61): '_ctx._eager_context.device_name', (3548, 63, 3548, 69): '"""Imag"""', (3548, 71, 3548, 75): 'name', (3549, 8, 3549, 38): '_ctx._post_execution_callbacks', (3549, 40, 3549, 45): 'input', (3549, 47, 3549, 53): '"""Tout"""', (3549, 55, 3549, 59): 'Tout'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Imag', name, _ctx.\n _post_execution_callbacks, input, 'Tout', Tout)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3607, 16, 3609, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3608, 8, 3608, 28): '_ctx._context_handle', (3608, 30, 3608, 61): '_ctx._eager_context.device_name', (3608, 63, 3608, 68): '"""Inv"""', (3608, 70, 3608, 74): 'name', (3609, 8, 3609, 38): '_ctx._post_execution_callbacks', (3609, 40, 3609, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Inv', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3666, 16, 3668, 52), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3667, 8, 3667, 28): '_ctx._context_handle', (3667, 30, 3667, 61): '_ctx._eager_context.device_name', (3667, 63, 3667, 72): '"""InvGrad"""', (3668, 8, 3668, 12): 'name', (3668, 14, 3668, 44): '_ctx._post_execution_callbacks', (3668, 46, 3668, 47): 'y', (3668, 49, 3668, 51): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'InvGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3727, 16, 3729, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3728, 8, 3728, 28): '_ctx._context_handle', (3728, 30, 3728, 61): '_ctx._eager_context.device_name', (3728, 63, 3728, 73): '"""IsFinite"""', (3729, 8, 3729, 12): 'name', (3729, 14, 3729, 44): '_ctx._post_execution_callbacks', (3729, 46, 3729, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'IsFinite', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3787, 16, 3789, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3788, 8, 3788, 28): '_ctx._context_handle', (3788, 30, 3788, 61): '_ctx._eager_context.device_name', (3788, 63, 3788, 70): '"""IsInf"""', (3788, 72, 3788, 76): 'name', (3789, 8, 3789, 38): '_ctx._post_execution_callbacks', (3789, 40, 3789, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'IsInf', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3847, 16, 3849, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3848, 8, 3848, 28): '_ctx._context_handle', (3848, 30, 3848, 61): '_ctx._eager_context.device_name', (3848, 63, 3848, 70): '"""IsNan"""', (3848, 72, 3848, 76): 'name', (3849, 8, 3849, 38): '_ctx._post_execution_callbacks', (3849, 40, 3849, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'IsNan', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3907, 16, 3909, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3908, 8, 3908, 28): '_ctx._context_handle', (3908, 30, 3908, 61): '_ctx._eager_context.device_name', (3908, 63, 3908, 69): '"""Less"""', (3908, 71, 3908, 75): 'name', (3909, 8, 3909, 38): '_ctx._post_execution_callbacks', (3909, 40, 3909, 41): 'x', (3909, 43, 3909, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Less', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((3968, 16, 3970, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(3969, 8, 3969, 28): '_ctx._context_handle', (3969, 30, 3969, 61): '_ctx._eager_context.device_name', (3969, 63, 3969, 74): '"""LessEqual"""', (3970, 8, 3970, 12): 'name', (3970, 14, 3970, 44): '_ctx._post_execution_callbacks', (3970, 46, 3970, 47): 'x', (3970, 49, 3970, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'LessEqual', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4025, 16, 4027, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4026, 8, 4026, 28): '_ctx._context_handle', (4026, 30, 4026, 61): '_ctx._eager_context.device_name', (4026, 63, 4026, 71): '"""Lgamma"""', (4026, 73, 4026, 77): 'name', (4027, 8, 4027, 38): '_ctx._post_execution_callbacks', (4027, 40, 4027, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Lgamma', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4096, 16, 4098, 63), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4097, 8, 4097, 28): '_ctx._context_handle', (4097, 30, 4097, 61): '_ctx._eager_context.device_name', (4097, 63, 4097, 73): '"""LinSpace"""', (4098, 8, 4098, 12): 'name', (4098, 14, 4098, 44): '_ctx._post_execution_callbacks', (4098, 46, 4098, 51): 'start', (4098, 53, 4098, 57): 'stop', (4098, 59, 4098, 62): 'num'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'LinSpace', name, _ctx.\n _post_execution_callbacks, start, stop, num)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4156, 16, 4158, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4157, 8, 4157, 28): '_ctx._context_handle', (4157, 30, 4157, 61): '_ctx._eager_context.device_name', (4157, 63, 4157, 68): '"""Log"""', (4157, 70, 4157, 74): 'name', (4158, 8, 4158, 38): '_ctx._post_execution_callbacks', (4158, 40, 4158, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Log', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4214, 16, 4216, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4215, 8, 4215, 28): '_ctx._context_handle', (4215, 30, 4215, 61): '_ctx._eager_context.device_name', (4215, 63, 4215, 70): '"""Log1p"""', (4215, 72, 4215, 76): 'name', (4216, 8, 4216, 38): '_ctx._post_execution_callbacks', (4216, 40, 4216, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Log1p', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4274, 16, 4276, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4275, 8, 4275, 28): '_ctx._context_handle', (4275, 30, 4275, 61): '_ctx._eager_context.device_name', (4275, 63, 4275, 75): '"""LogicalAnd"""', (4276, 8, 4276, 12): 'name', (4276, 14, 4276, 44): '_ctx._post_execution_callbacks', (4276, 46, 4276, 47): 'x', (4276, 49, 4276, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'LogicalAnd', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4331, 16, 4333, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4332, 8, 4332, 28): '_ctx._context_handle', (4332, 30, 4332, 61): '_ctx._eager_context.device_name', (4332, 63, 4332, 75): '"""LogicalNot"""', (4333, 8, 4333, 12): 'name', (4333, 14, 4333, 44): '_ctx._post_execution_callbacks', (4333, 46, 4333, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'LogicalNot', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4391, 16, 4393, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4392, 8, 4392, 28): '_ctx._context_handle', (4392, 30, 4392, 61): '_ctx._eager_context.device_name', (4392, 63, 4392, 74): '"""LogicalOr"""', (4393, 8, 4393, 12): 'name', (4393, 14, 4393, 44): '_ctx._post_execution_callbacks', (4393, 46, 4393, 47): 'x', (4393, 49, 4393, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'LogicalOr', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4468, 16, 4471, 35), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4469, 8, 4469, 28): '_ctx._context_handle', (4469, 30, 4469, 61): '_ctx._eager_context.device_name', (4469, 63, 4469, 71): '"""MatMul"""', (4469, 73, 4469, 77): 'name', (4470, 8, 4470, 38): '_ctx._post_execution_callbacks', (4470, 40, 4470, 41): 'a', (4470, 43, 4470, 44): 'b', (4470, 46, 4470, 59): '"""transpose_a"""', (4470, 61, 4470, 72): 'transpose_a', (4471, 8, 4471, 21): '"""transpose_b"""', (4471, 23, 4471, 34): 'transpose_b'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'MatMul', name, _ctx.\n _post_execution_callbacks, a, b, 'transpose_a', transpose_a,\n 'transpose_b', transpose_b)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4549, 16, 4551, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4550, 8, 4550, 28): '_ctx._context_handle', (4550, 30, 4550, 61): '_ctx._eager_context.device_name', (4550, 63, 4550, 68): '"""Max"""', (4550, 70, 4550, 74): 'name', (4551, 8, 4551, 38): '_ctx._post_execution_callbacks', (4551, 40, 4551, 45): 'input', (4551, 47, 4551, 51): 'axis', (4551, 53, 4551, 64): '"""keep_dims"""', (4551, 66, 4551, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Max', name, _ctx._post_execution_callbacks,\n input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4613, 16, 4615, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4614, 8, 4614, 28): '_ctx._context_handle', (4614, 30, 4614, 61): '_ctx._eager_context.device_name', (4614, 63, 4614, 72): '"""Maximum"""', (4615, 8, 4615, 12): 'name', (4615, 14, 4615, 44): '_ctx._post_execution_callbacks', (4615, 46, 4615, 47): 'x', (4615, 49, 4615, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Maximum', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4685, 16, 4687, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4686, 8, 4686, 28): '_ctx._context_handle', (4686, 30, 4686, 61): '_ctx._eager_context.device_name', (4686, 63, 4686, 69): '"""Mean"""', (4686, 71, 4686, 75): 'name', (4687, 8, 4687, 38): '_ctx._post_execution_callbacks', (4687, 40, 4687, 45): 'input', (4687, 47, 4687, 51): 'axis', (4687, 53, 4687, 64): '"""keep_dims"""', (4687, 66, 4687, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Mean', name, _ctx.\n _post_execution_callbacks, input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4760, 16, 4762, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4761, 8, 4761, 28): '_ctx._context_handle', (4761, 30, 4761, 61): '_ctx._eager_context.device_name', (4761, 63, 4761, 68): '"""Min"""', (4761, 70, 4761, 74): 'name', (4762, 8, 4762, 38): '_ctx._post_execution_callbacks', (4762, 40, 4762, 45): 'input', (4762, 47, 4762, 51): 'axis', (4762, 53, 4762, 64): '"""keep_dims"""', (4762, 66, 4762, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Min', name, _ctx._post_execution_callbacks,\n input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4824, 16, 4826, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4825, 8, 4825, 28): '_ctx._context_handle', (4825, 30, 4825, 61): '_ctx._eager_context.device_name', (4825, 63, 4825, 72): '"""Minimum"""', (4826, 8, 4826, 12): 'name', (4826, 14, 4826, 44): '_ctx._post_execution_callbacks', (4826, 46, 4826, 47): 'x', (4826, 49, 4826, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Minimum', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4887, 16, 4889, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4888, 8, 4888, 28): '_ctx._context_handle', (4888, 30, 4888, 61): '_ctx._eager_context.device_name', (4888, 63, 4888, 68): '"""Mod"""', (4888, 70, 4888, 74): 'name', (4889, 8, 4889, 38): '_ctx._post_execution_callbacks', (4889, 40, 4889, 41): 'x', (4889, 43, 4889, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Mod', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((4947, 16, 4949, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(4948, 8, 4948, 28): '_ctx._context_handle', (4948, 30, 4948, 61): '_ctx._eager_context.device_name', (4948, 63, 4948, 68): '"""Mul"""', (4948, 70, 4948, 74): 'name', (4949, 8, 4949, 38): '_ctx._post_execution_callbacks', (4949, 40, 4949, 41): 'x', (4949, 43, 4949, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Mul', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5005, 16, 5007, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5006, 8, 5006, 28): '_ctx._context_handle', (5006, 30, 5006, 61): '_ctx._eager_context.device_name', (5006, 63, 5006, 68): '"""Neg"""', (5006, 70, 5006, 74): 'name', (5007, 8, 5007, 38): '_ctx._post_execution_callbacks', (5007, 40, 5007, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Neg', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5065, 16, 5067, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5066, 8, 5066, 28): '_ctx._context_handle', (5066, 30, 5066, 61): '_ctx._eager_context.device_name', (5066, 63, 5066, 73): '"""NotEqual"""', (5067, 8, 5067, 12): 'name', (5067, 14, 5067, 44): '_ctx._post_execution_callbacks', (5067, 46, 5067, 47): 'x', (5067, 49, 5067, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'NotEqual', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5130, 16, 5132, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5131, 8, 5131, 28): '_ctx._context_handle', (5131, 30, 5131, 61): '_ctx._eager_context.device_name', (5131, 63, 5131, 74): '"""Polygamma"""', (5132, 8, 5132, 12): 'name', (5132, 14, 5132, 44): '_ctx._post_execution_callbacks', (5132, 46, 5132, 47): 'a', (5132, 49, 5132, 50): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Polygamma', name, _ctx.\n _post_execution_callbacks, a, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5196, 16, 5198, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5197, 8, 5197, 28): '_ctx._context_handle', (5197, 30, 5197, 61): '_ctx._eager_context.device_name', (5197, 63, 5197, 68): '"""Pow"""', (5197, 70, 5197, 74): 'name', (5198, 8, 5198, 38): '_ctx._post_execution_callbacks', (5198, 40, 5198, 41): 'x', (5198, 43, 5198, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Pow', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5268, 16, 5270, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5269, 8, 5269, 28): '_ctx._context_handle', (5269, 30, 5269, 61): '_ctx._eager_context.device_name', (5269, 63, 5269, 69): '"""Prod"""', (5269, 71, 5269, 75): 'name', (5270, 8, 5270, 38): '_ctx._post_execution_callbacks', (5270, 40, 5270, 45): 'input', (5270, 47, 5270, 51): 'axis', (5270, 53, 5270, 64): '"""keep_dims"""', (5270, 66, 5270, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Prod', name, _ctx.\n _post_execution_callbacks, input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5369, 16, 5372, 58), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5370, 8, 5370, 28): '_ctx._context_handle', (5370, 30, 5370, 61): '_ctx._eager_context.device_name', (5371, 8, 5371, 36): '"""QuantizeDownAndShrinkRange"""', (5371, 38, 5371, 42): 'name', (5371, 44, 5371, 74): '_ctx._post_execution_callbacks', (5372, 8, 5372, 13): 'input', (5372, 15, 5372, 24): 'input_min', (5372, 26, 5372, 35): 'input_max', (5372, 37, 5372, 47): '"""out_type"""', (5372, 49, 5372, 57): 'out_type'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'QuantizeDownAndShrinkRange', name, _ctx.\n _post_execution_callbacks, input, input_min, input_max, 'out_type',\n out_type)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5454, 16, 5457, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5455, 8, 5455, 28): '_ctx._context_handle', (5455, 30, 5455, 61): '_ctx._eager_context.device_name', (5455, 63, 5455, 77): '"""QuantizedAdd"""', (5456, 8, 5456, 12): 'name', (5456, 14, 5456, 44): '_ctx._post_execution_callbacks', (5456, 46, 5456, 47): 'x', (5456, 49, 5456, 50): 'y', (5456, 52, 5456, 57): 'min_x', (5456, 59, 5456, 64): 'max_x', (5456, 66, 5456, 71): 'min_y', (5457, 8, 5457, 13): 'max_y', (5457, 15, 5457, 24): '"""Toutput"""', (5457, 26, 5457, 33): 'Toutput'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'QuantizedAdd', name, _ctx.\n _post_execution_callbacks, x, y, min_x, max_x, min_y, max_y, 'Toutput',\n Toutput)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5571, 16, 5575, 63), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5572, 8, 5572, 28): '_ctx._context_handle', (5572, 30, 5572, 61): '_ctx._eager_context.device_name', (5573, 8, 5573, 25): '"""QuantizedMatMul"""', (5573, 27, 5573, 31): 'name', (5573, 33, 5573, 63): '_ctx._post_execution_callbacks', (5573, 65, 5573, 66): 'a', (5573, 68, 5573, 69): 'b', (5573, 71, 5573, 76): 'min_a', (5574, 8, 5574, 13): 'max_a', (5574, 15, 5574, 20): 'min_b', (5574, 22, 5574, 27): 'max_b', (5574, 29, 5574, 38): '"""Toutput"""', (5574, 40, 5574, 47): 'Toutput', (5574, 49, 5574, 62): '"""transpose_a"""', (5574, 64, 5574, 75): 'transpose_a', (5575, 8, 5575, 21): '"""transpose_b"""', (5575, 23, 5575, 34): 'transpose_b', (5575, 36, 5575, 49): '"""Tactivation"""', (5575, 51, 5575, 62): 'Tactivation'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'QuantizedMatMul', name, _ctx.\n _post_execution_callbacks, a, b, min_a, max_a, min_b, max_b, 'Toutput',\n Toutput, 'transpose_a', transpose_a, 'transpose_b', transpose_b,\n 'Tactivation', Tactivation)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5673, 16, 5676, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5674, 8, 5674, 28): '_ctx._context_handle', (5674, 30, 5674, 61): '_ctx._eager_context.device_name', (5674, 63, 5674, 77): '"""QuantizedMul"""', (5675, 8, 5675, 12): 'name', (5675, 14, 5675, 44): '_ctx._post_execution_callbacks', (5675, 46, 5675, 47): 'x', (5675, 49, 5675, 50): 'y', (5675, 52, 5675, 57): 'min_x', (5675, 59, 5675, 64): 'max_x', (5675, 66, 5675, 71): 'min_y', (5676, 8, 5676, 13): 'max_y', (5676, 15, 5676, 24): '"""Toutput"""', (5676, 26, 5676, 33): 'Toutput'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'QuantizedMul', name, _ctx.\n _post_execution_callbacks, x, y, min_x, max_x, min_y, max_y, 'Toutput',\n Toutput)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5756, 16, 5758, 60), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5757, 8, 5757, 28): '_ctx._context_handle', (5757, 30, 5757, 61): '_ctx._eager_context.device_name', (5757, 63, 5757, 70): '"""Range"""', (5757, 72, 5757, 76): 'name', (5758, 8, 5758, 38): '_ctx._post_execution_callbacks', (5758, 40, 5758, 45): 'start', (5758, 47, 5758, 52): 'limit', (5758, 54, 5758, 59): 'delta'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Range', name, _ctx.\n _post_execution_callbacks, start, limit, delta)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5828, 16, 5830, 60), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5829, 8, 5829, 28): '_ctx._context_handle', (5829, 30, 5829, 61): '_ctx._eager_context.device_name', (5829, 63, 5829, 69): '"""Real"""', (5829, 71, 5829, 75): 'name', (5830, 8, 5830, 38): '_ctx._post_execution_callbacks', (5830, 40, 5830, 45): 'input', (5830, 47, 5830, 53): '"""Tout"""', (5830, 55, 5830, 59): 'Tout'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Real', name, _ctx.\n _post_execution_callbacks, input, 'Tout', Tout)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5892, 16, 5894, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5893, 8, 5893, 28): '_ctx._context_handle', (5893, 30, 5893, 61): '_ctx._eager_context.device_name', (5893, 63, 5893, 72): '"""RealDiv"""', (5894, 8, 5894, 12): 'name', (5894, 14, 5894, 44): '_ctx._post_execution_callbacks', (5894, 46, 5894, 47): 'x', (5894, 49, 5894, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'RealDiv', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((5951, 16, 5953, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(5952, 8, 5952, 28): '_ctx._context_handle', (5952, 30, 5952, 61): '_ctx._eager_context.device_name', (5952, 63, 5952, 75): '"""Reciprocal"""', (5953, 8, 5953, 12): 'name', (5953, 14, 5953, 44): '_ctx._post_execution_callbacks', (5953, 46, 5953, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Reciprocal', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6010, 16, 6012, 70), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6011, 8, 6011, 28): '_ctx._context_handle', (6011, 30, 6011, 61): '_ctx._eager_context.device_name', (6012, 8, 6012, 24): '"""ReciprocalGrad"""', (6012, 26, 6012, 30): 'name', (6012, 32, 6012, 62): '_ctx._post_execution_callbacks', (6012, 64, 6012, 65): 'y', (6012, 67, 6012, 69): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'ReciprocalGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6083, 16, 6086, 29), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6084, 8, 6084, 28): '_ctx._context_handle', (6084, 30, 6084, 61): '_ctx._eager_context.device_name', (6085, 8, 6085, 29): '"""RequantizationRange"""', (6085, 31, 6085, 35): 'name', (6085, 37, 6085, 67): '_ctx._post_execution_callbacks', (6085, 69, 6085, 74): 'input', (6086, 8, 6086, 17): 'input_min', (6086, 19, 6086, 28): 'input_max'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'RequantizationRange', name, _ctx.\n _post_execution_callbacks, input, input_min, input_max)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6173, 16, 6176, 73), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6174, 8, 6174, 28): '_ctx._context_handle', (6174, 30, 6174, 61): '_ctx._eager_context.device_name', (6174, 63, 6174, 75): '"""Requantize"""', (6175, 8, 6175, 12): 'name', (6175, 14, 6175, 44): '_ctx._post_execution_callbacks', (6175, 46, 6175, 51): 'input', (6175, 53, 6175, 62): 'input_min', (6175, 64, 6175, 73): 'input_max', (6176, 8, 6176, 28): 'requested_output_min', (6176, 30, 6176, 50): 'requested_output_max', (6176, 52, 6176, 62): '"""out_type"""', (6176, 64, 6176, 72): 'out_type'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Requantize', name, _ctx.\n _post_execution_callbacks, input, input_min, input_max,\n requested_output_min, requested_output_max, 'out_type', out_type)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6247, 16, 6249, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6248, 8, 6248, 28): '_ctx._context_handle', (6248, 30, 6248, 61): '_ctx._eager_context.device_name', (6248, 63, 6248, 69): '"""Rint"""', (6248, 71, 6248, 75): 'name', (6249, 8, 6249, 38): '_ctx._post_execution_callbacks', (6249, 40, 6249, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Rint', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6305, 16, 6307, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6306, 8, 6306, 28): '_ctx._context_handle', (6306, 30, 6306, 61): '_ctx._eager_context.device_name', (6306, 63, 6306, 70): '"""Round"""', (6306, 72, 6306, 76): 'name', (6307, 8, 6307, 38): '_ctx._post_execution_callbacks', (6307, 40, 6307, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Round', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6363, 16, 6365, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6364, 8, 6364, 28): '_ctx._context_handle', (6364, 30, 6364, 61): '_ctx._eager_context.device_name', (6364, 63, 6364, 70): '"""Rsqrt"""', (6364, 72, 6364, 76): 'name', (6365, 8, 6365, 38): '_ctx._post_execution_callbacks', (6365, 40, 6365, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Rsqrt', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6422, 16, 6424, 52), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6423, 8, 6423, 28): '_ctx._context_handle', (6423, 30, 6423, 61): '_ctx._eager_context.device_name', (6423, 63, 6423, 74): '"""RsqrtGrad"""', (6424, 8, 6424, 12): 'name', (6424, 14, 6424, 44): '_ctx._post_execution_callbacks', (6424, 46, 6424, 47): 'y', (6424, 49, 6424, 51): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'RsqrtGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6495, 16, 6497, 64), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6496, 8, 6496, 28): '_ctx._context_handle', (6496, 30, 6496, 61): '_ctx._eager_context.device_name', (6496, 63, 6496, 75): '"""SegmentMax"""', (6497, 8, 6497, 12): 'name', (6497, 14, 6497, 44): '_ctx._post_execution_callbacks', (6497, 46, 6497, 50): 'data', (6497, 52, 6497, 63): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SegmentMax', name, _ctx.\n _post_execution_callbacks, data, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6569, 16, 6571, 64), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6570, 8, 6570, 28): '_ctx._context_handle', (6570, 30, 6570, 61): '_ctx._eager_context.device_name', (6570, 63, 6570, 76): '"""SegmentMean"""', (6571, 8, 6571, 12): 'name', (6571, 14, 6571, 44): '_ctx._post_execution_callbacks', (6571, 46, 6571, 50): 'data', (6571, 52, 6571, 63): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SegmentMean', name, _ctx.\n _post_execution_callbacks, data, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6642, 16, 6644, 64), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6643, 8, 6643, 28): '_ctx._context_handle', (6643, 30, 6643, 61): '_ctx._eager_context.device_name', (6643, 63, 6643, 75): '"""SegmentMin"""', (6644, 8, 6644, 12): 'name', (6644, 14, 6644, 44): '_ctx._post_execution_callbacks', (6644, 46, 6644, 50): 'data', (6644, 52, 6644, 63): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SegmentMin', name, _ctx.\n _post_execution_callbacks, data, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6715, 16, 6717, 64), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6716, 8, 6716, 28): '_ctx._context_handle', (6716, 30, 6716, 61): '_ctx._eager_context.device_name', (6716, 63, 6716, 76): '"""SegmentProd"""', (6717, 8, 6717, 12): 'name', (6717, 14, 6717, 44): '_ctx._post_execution_callbacks', (6717, 46, 6717, 50): 'data', (6717, 52, 6717, 63): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SegmentProd', name, _ctx.\n _post_execution_callbacks, data, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6788, 16, 6790, 64), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6789, 8, 6789, 28): '_ctx._context_handle', (6789, 30, 6789, 61): '_ctx._eager_context.device_name', (6789, 63, 6789, 75): '"""SegmentSum"""', (6790, 8, 6790, 12): 'name', (6790, 14, 6790, 44): '_ctx._post_execution_callbacks', (6790, 46, 6790, 50): 'data', (6790, 52, 6790, 63): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SegmentSum', name, _ctx.\n _post_execution_callbacks, data, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6887, 16, 6889, 56), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6888, 8, 6888, 28): '_ctx._context_handle', (6888, 30, 6888, 61): '_ctx._eager_context.device_name', (6888, 63, 6888, 71): '"""Select"""', (6888, 73, 6888, 77): 'name', (6889, 8, 6889, 38): '_ctx._post_execution_callbacks', (6889, 40, 6889, 49): 'condition', (6889, 51, 6889, 52): 'x', (6889, 54, 6889, 55): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Select', name, _ctx.\n _post_execution_callbacks, condition, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((6946, 16, 6948, 48), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(6947, 8, 6947, 28): '_ctx._context_handle', (6947, 30, 6947, 61): '_ctx._eager_context.device_name', (6947, 63, 6947, 72): '"""Sigmoid"""', (6948, 8, 6948, 12): 'name', (6948, 14, 6948, 44): '_ctx._post_execution_callbacks', (6948, 46, 6948, 47): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sigmoid', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7005, 16, 7007, 52), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7006, 8, 7006, 28): '_ctx._context_handle', (7006, 30, 7006, 61): '_ctx._eager_context.device_name', (7006, 63, 7006, 76): '"""SigmoidGrad"""', (7007, 8, 7007, 12): 'name', (7007, 14, 7007, 44): '_ctx._post_execution_callbacks', (7007, 46, 7007, 47): 'y', (7007, 49, 7007, 51): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SigmoidGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7065, 16, 7067, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7066, 8, 7066, 28): '_ctx._context_handle', (7066, 30, 7066, 61): '_ctx._eager_context.device_name', (7066, 63, 7066, 69): '"""Sign"""', (7066, 71, 7066, 75): 'name', (7067, 8, 7067, 38): '_ctx._post_execution_callbacks', (7067, 40, 7067, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sign', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7121, 16, 7123, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7122, 8, 7122, 28): '_ctx._context_handle', (7122, 30, 7122, 61): '_ctx._eager_context.device_name', (7122, 63, 7122, 68): '"""Sin"""', (7122, 70, 7122, 74): 'name', (7123, 8, 7123, 38): '_ctx._post_execution_callbacks', (7123, 40, 7123, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sin', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7177, 16, 7179, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7178, 8, 7178, 28): '_ctx._context_handle', (7178, 30, 7178, 61): '_ctx._eager_context.device_name', (7178, 63, 7178, 69): '"""Sinh"""', (7178, 71, 7178, 75): 'name', (7179, 8, 7179, 38): '_ctx._post_execution_callbacks', (7179, 40, 7179, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sinh', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7265, 16, 7269, 35), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7266, 8, 7266, 28): '_ctx._context_handle', (7266, 30, 7266, 61): '_ctx._eager_context.device_name', (7266, 63, 7266, 77): '"""SparseMatMul"""', (7267, 8, 7267, 12): 'name', (7267, 14, 7267, 44): '_ctx._post_execution_callbacks', (7267, 46, 7267, 47): 'a', (7267, 49, 7267, 50): 'b', (7267, 52, 7267, 65): '"""transpose_a"""', (7268, 8, 7268, 19): 'transpose_a', (7268, 21, 7268, 34): '"""transpose_b"""', (7268, 36, 7268, 47): 'transpose_b', (7268, 49, 7268, 62): '"""a_is_sparse"""', (7268, 64, 7268, 75): 'a_is_sparse', (7269, 8, 7269, 21): '"""b_is_sparse"""', (7269, 23, 7269, 34): 'b_is_sparse'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseMatMul', name, _ctx.\n _post_execution_callbacks, a, b, 'transpose_a', transpose_a,\n 'transpose_b', transpose_b, 'a_is_sparse', a_is_sparse, 'b_is_sparse',\n b_is_sparse)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7350, 16, 7353, 29), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7351, 8, 7351, 28): '_ctx._context_handle', (7351, 30, 7351, 61): '_ctx._eager_context.device_name', (7352, 8, 7352, 27): '"""SparseSegmentMean"""', (7352, 29, 7352, 33): 'name', (7352, 35, 7352, 65): '_ctx._post_execution_callbacks', (7352, 67, 7352, 71): 'data', (7353, 8, 7353, 15): 'indices', (7353, 17, 7353, 28): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentMean', name, _ctx.\n _post_execution_callbacks, data, indices, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7419, 16, 7422, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7420, 8, 7420, 28): '_ctx._context_handle', (7420, 30, 7420, 61): '_ctx._eager_context.device_name', (7421, 8, 7421, 31): '"""SparseSegmentMeanGrad"""', (7421, 33, 7421, 37): 'name', (7421, 39, 7421, 69): '_ctx._post_execution_callbacks', (7421, 71, 7421, 75): 'grad', (7422, 8, 7422, 15): 'indices', (7422, 17, 7422, 28): 'segment_ids', (7422, 30, 7422, 41): 'output_dim0'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentMeanGrad', name, _ctx.\n _post_execution_callbacks, grad, indices, segment_ids, output_dim0)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7492, 16, 7496, 21), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7493, 8, 7493, 28): '_ctx._context_handle', (7493, 30, 7493, 61): '_ctx._eager_context.device_name', (7494, 8, 7494, 42): '"""SparseSegmentMeanWithNumSegments"""', (7494, 44, 7494, 48): 'name', (7495, 8, 7495, 38): '_ctx._post_execution_callbacks', (7495, 40, 7495, 44): 'data', (7495, 46, 7495, 53): 'indices', (7495, 55, 7495, 66): 'segment_ids', (7496, 8, 7496, 20): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentMeanWithNumSegments', name,\n _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7564, 16, 7567, 29), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7565, 8, 7565, 28): '_ctx._context_handle', (7565, 30, 7565, 61): '_ctx._eager_context.device_name', (7566, 8, 7566, 28): '"""SparseSegmentSqrtN"""', (7566, 30, 7566, 34): 'name', (7566, 36, 7566, 66): '_ctx._post_execution_callbacks', (7566, 68, 7566, 72): 'data', (7567, 8, 7567, 15): 'indices', (7567, 17, 7567, 28): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentSqrtN', name, _ctx.\n _post_execution_callbacks, data, indices, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7633, 16, 7636, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7634, 8, 7634, 28): '_ctx._context_handle', (7634, 30, 7634, 61): '_ctx._eager_context.device_name', (7635, 8, 7635, 32): '"""SparseSegmentSqrtNGrad"""', (7635, 34, 7635, 38): 'name', (7635, 40, 7635, 70): '_ctx._post_execution_callbacks', (7635, 72, 7635, 76): 'grad', (7636, 8, 7636, 15): 'indices', (7636, 17, 7636, 28): 'segment_ids', (7636, 30, 7636, 41): 'output_dim0'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentSqrtNGrad', name, _ctx.\n _post_execution_callbacks, grad, indices, segment_ids, output_dim0)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7709, 16, 7713, 21), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7710, 8, 7710, 28): '_ctx._context_handle', (7710, 30, 7710, 61): '_ctx._eager_context.device_name', (7711, 8, 7711, 43): '"""SparseSegmentSqrtNWithNumSegments"""', (7711, 45, 7711, 49): 'name', (7712, 8, 7712, 38): '_ctx._post_execution_callbacks', (7712, 40, 7712, 44): 'data', (7712, 46, 7712, 53): 'indices', (7712, 55, 7712, 66): 'segment_ids', (7713, 8, 7713, 20): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentSqrtNWithNumSegments', name,\n _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7805, 16, 7808, 29), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7806, 8, 7806, 28): '_ctx._context_handle', (7806, 30, 7806, 61): '_ctx._eager_context.device_name', (7807, 8, 7807, 26): '"""SparseSegmentSum"""', (7807, 28, 7807, 32): 'name', (7807, 34, 7807, 64): '_ctx._post_execution_callbacks', (7807, 66, 7807, 70): 'data', (7808, 8, 7808, 15): 'indices', (7808, 17, 7808, 28): 'segment_ids'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentSum', name, _ctx.\n _post_execution_callbacks, data, indices, segment_ids)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7898, 16, 7902, 21), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7899, 8, 7899, 28): '_ctx._context_handle', (7899, 30, 7899, 61): '_ctx._eager_context.device_name', (7900, 8, 7900, 41): '"""SparseSegmentSumWithNumSegments"""', (7900, 43, 7900, 47): 'name', (7901, 8, 7901, 38): '_ctx._post_execution_callbacks', (7901, 40, 7901, 44): 'data', (7901, 46, 7901, 53): 'indices', (7901, 55, 7901, 66): 'segment_ids', (7902, 8, 7902, 20): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SparseSegmentSumWithNumSegments', name,\n _ctx._post_execution_callbacks, data, indices, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((7962, 16, 7964, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(7963, 8, 7963, 28): '_ctx._context_handle', (7963, 30, 7963, 61): '_ctx._eager_context.device_name', (7963, 63, 7963, 69): '"""Sqrt"""', (7963, 71, 7963, 75): 'name', (7964, 8, 7964, 38): '_ctx._post_execution_callbacks', (7964, 40, 7964, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sqrt', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8021, 16, 8023, 52), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8022, 8, 8022, 28): '_ctx._context_handle', (8022, 30, 8022, 61): '_ctx._eager_context.device_name', (8022, 63, 8022, 73): '"""SqrtGrad"""', (8023, 8, 8023, 12): 'name', (8023, 14, 8023, 44): '_ctx._post_execution_callbacks', (8023, 46, 8023, 47): 'y', (8023, 49, 8023, 51): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SqrtGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8079, 16, 8081, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8080, 8, 8080, 28): '_ctx._context_handle', (8080, 30, 8080, 61): '_ctx._eager_context.device_name', (8080, 63, 8080, 71): '"""Square"""', (8080, 73, 8080, 77): 'name', (8081, 8, 8081, 38): '_ctx._post_execution_callbacks', (8081, 40, 8081, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Square', name, _ctx.\n _post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8139, 16, 8141, 72), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8140, 8, 8140, 28): '_ctx._context_handle', (8140, 30, 8140, 61): '_ctx._eager_context.device_name', (8141, 8, 8141, 27): '"""SquaredDifference"""', (8141, 29, 8141, 33): 'name', (8141, 35, 8141, 65): '_ctx._post_execution_callbacks', (8141, 67, 8141, 68): 'x', (8141, 70, 8141, 71): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'SquaredDifference', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8199, 16, 8201, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8200, 8, 8200, 28): '_ctx._context_handle', (8200, 30, 8200, 61): '_ctx._eager_context.device_name', (8200, 63, 8200, 68): '"""Sub"""', (8200, 70, 8200, 74): 'name', (8201, 8, 8201, 38): '_ctx._post_execution_callbacks', (8201, 40, 8201, 41): 'x', (8201, 43, 8201, 44): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sub', name, _ctx._post_execution_callbacks,\n x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8271, 16, 8273, 76), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8272, 8, 8272, 28): '_ctx._context_handle', (8272, 30, 8272, 61): '_ctx._eager_context.device_name', (8272, 63, 8272, 68): '"""Sum"""', (8272, 70, 8272, 74): 'name', (8273, 8, 8273, 38): '_ctx._post_execution_callbacks', (8273, 40, 8273, 45): 'input', (8273, 47, 8273, 51): 'axis', (8273, 53, 8273, 64): '"""keep_dims"""', (8273, 66, 8273, 75): 'keep_dims'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Sum', name, _ctx._post_execution_callbacks,\n input, axis, 'keep_dims', keep_dims)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8331, 16, 8333, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8332, 8, 8332, 28): '_ctx._context_handle', (8332, 30, 8332, 61): '_ctx._eager_context.device_name', (8332, 63, 8332, 68): '"""Tan"""', (8332, 70, 8332, 74): 'name', (8333, 8, 8333, 38): '_ctx._post_execution_callbacks', (8333, 40, 8333, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Tan', name, _ctx._post_execution_callbacks, x)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8386, 16, 8388, 42), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8387, 8, 8387, 28): '_ctx._context_handle', (8387, 30, 8387, 61): '_ctx._eager_context.device_name', (8387, 63, 8387, 69): '"""Tanh"""', (8387, 71, 8387, 75): 'name', (8388, 8, 8388, 38): '_ctx._post_execution_callbacks', (8388, 40, 8388, 41): 'x'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Tanh', name, _ctx._post_execution_callbacks, x\n )", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8445, 16, 8447, 52), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8446, 8, 8446, 28): '_ctx._context_handle', (8446, 30, 8446, 61): '_ctx._eager_context.device_name', (8446, 63, 8446, 73): '"""TanhGrad"""', (8447, 8, 8447, 12): 'name', (8447, 14, 8447, 44): '_ctx._post_execution_callbacks', (8447, 46, 8447, 47): 'y', (8447, 49, 8447, 51): 'dy'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'TanhGrad', name, _ctx.\n _post_execution_callbacks, y, dy)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8510, 16, 8512, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8511, 8, 8511, 28): '_ctx._context_handle', (8511, 30, 8511, 61): '_ctx._eager_context.device_name', (8511, 63, 8511, 76): '"""TruncateDiv"""', (8512, 8, 8512, 12): 'name', (8512, 14, 8512, 44): '_ctx._post_execution_callbacks', (8512, 46, 8512, 47): 'x', (8512, 49, 8512, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'TruncateDiv', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8573, 16, 8575, 51), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8574, 8, 8574, 28): '_ctx._context_handle', (8574, 30, 8574, 61): '_ctx._eager_context.device_name', (8574, 63, 8574, 76): '"""TruncateMod"""', (8575, 8, 8575, 12): 'name', (8575, 14, 8575, 44): '_ctx._post_execution_callbacks', (8575, 46, 8575, 47): 'x', (8575, 49, 8575, 50): 'y'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'TruncateMod', name, _ctx.\n _post_execution_callbacks, x, y)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8654, 16, 8657, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8655, 8, 8655, 28): '_ctx._context_handle', (8655, 30, 8655, 61): '_ctx._eager_context.device_name', (8656, 8, 8656, 28): '"""UnsortedSegmentMax"""', (8656, 30, 8656, 34): 'name', (8656, 36, 8656, 66): '_ctx._post_execution_callbacks', (8656, 68, 8656, 72): 'data', (8657, 8, 8657, 19): 'segment_ids', (8657, 21, 8657, 33): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'UnsortedSegmentMax', name, _ctx.\n _post_execution_callbacks, data, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8734, 16, 8737, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8735, 8, 8735, 28): '_ctx._context_handle', (8735, 30, 8735, 61): '_ctx._eager_context.device_name', (8736, 8, 8736, 28): '"""UnsortedSegmentMin"""', (8736, 30, 8736, 34): 'name', (8736, 36, 8736, 66): '_ctx._post_execution_callbacks', (8736, 68, 8736, 72): 'data', (8737, 8, 8737, 19): 'segment_ids', (8737, 21, 8737, 33): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'UnsortedSegmentMin', name, _ctx.\n _post_execution_callbacks, data, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8813, 16, 8816, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8814, 8, 8814, 28): '_ctx._context_handle', (8814, 30, 8814, 61): '_ctx._eager_context.device_name', (8815, 8, 8815, 29): '"""UnsortedSegmentProd"""', (8815, 31, 8815, 35): 'name', (8815, 37, 8815, 67): '_ctx._post_execution_callbacks', (8815, 69, 8815, 73): 'data', (8816, 8, 8816, 19): 'segment_ids', (8816, 21, 8816, 33): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'UnsortedSegmentProd', name, _ctx.\n _post_execution_callbacks, data, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8897, 16, 8900, 34), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8898, 8, 8898, 28): '_ctx._context_handle', (8898, 30, 8898, 61): '_ctx._eager_context.device_name', (8899, 8, 8899, 28): '"""UnsortedSegmentSum"""', (8899, 30, 8899, 34): 'name', (8899, 36, 8899, 66): '_ctx._post_execution_callbacks', (8899, 68, 8899, 72): 'data', (8900, 8, 8900, 19): 'segment_ids', (8900, 21, 8900, 33): 'num_segments'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'UnsortedSegmentSum', name, _ctx.\n _post_execution_callbacks, data, segment_ids, num_segments)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((8963, 16, 8965, 45), 'tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute', '_pywrap_tensorflow.TFE_Py_FastPathExecute', ({(8964, 8, 8964, 28): '_ctx._context_handle', (8964, 30, 8964, 61): '_ctx._eager_context.device_name', (8964, 63, 8964, 69): '"""Zeta"""', (8964, 71, 8964, 75): 'name', (8965, 8, 8965, 38): '_ctx._post_execution_callbacks', (8965, 40, 8965, 41): 'x', (8965, 43, 8965, 44): 'q'}, {}), "(_ctx._context_handle, _ctx.\n _eager_context.device_name, 'Zeta', name, _ctx.\n _post_execution_callbacks, x, q)", True, 'from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\n'), ((67, 22, 67, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(67, 49, 67, 55): 'e.code', (67, 57, 67, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((142, 22, 142, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(142, 49, 142, 55): 'e.code', (142, 57, 142, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((204, 22, 204, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(204, 49, 204, 55): 'e.code', (204, 57, 204, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((260, 22, 260, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(260, 49, 260, 55): 'e.code', (260, 57, 260, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((320, 22, 320, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(320, 49, 320, 55): 'e.code', (320, 57, 320, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((382, 22, 382, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(382, 49, 382, 55): 'e.code', (382, 57, 382, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((446, 22, 446, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(446, 49, 446, 55): 'e.code', (446, 57, 446, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((517, 22, 517, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(517, 49, 517, 55): 'e.code', (517, 57, 517, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((598, 22, 598, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(598, 49, 598, 55): 'e.code', (598, 57, 598, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((671, 22, 671, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(671, 49, 671, 55): 'e.code', (671, 57, 671, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((736, 22, 736, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(736, 49, 736, 55): 'e.code', (736, 57, 736, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((808, 22, 808, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(808, 49, 808, 55): 'e.code', (808, 57, 808, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((880, 22, 880, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(880, 49, 880, 55): 'e.code', (880, 57, 880, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((940, 22, 940, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(940, 49, 940, 55): 'e.code', (940, 57, 940, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((996, 22, 996, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(996, 49, 996, 55): 'e.code', (996, 57, 996, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1052, 22, 1052, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1052, 49, 1052, 55): 'e.code', (1052, 57, 1052, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1115, 22, 1115, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1115, 49, 1115, 55): 'e.code', (1115, 57, 1115, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1172, 22, 1172, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1172, 49, 1172, 55): 'e.code', (1172, 57, 1172, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1261, 22, 1261, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1261, 49, 1261, 55): 'e.code', (1261, 57, 1261, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1328, 22, 1328, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1328, 49, 1328, 55): 'e.code', (1328, 57, 1328, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1388, 22, 1388, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1388, 49, 1388, 55): 'e.code', (1388, 57, 1388, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1460, 22, 1460, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1460, 49, 1460, 55): 'e.code', (1460, 57, 1460, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1529, 22, 1529, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1529, 49, 1529, 55): 'e.code', (1529, 57, 1529, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1606, 22, 1606, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1606, 49, 1606, 55): 'e.code', (1606, 57, 1606, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1668, 22, 1668, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1668, 49, 1668, 55): 'e.code', (1668, 57, 1668, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1725, 22, 1725, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1725, 49, 1725, 55): 'e.code', (1725, 57, 1725, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1794, 22, 1794, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1794, 49, 1794, 55): 'e.code', (1794, 57, 1794, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1878, 22, 1878, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1878, 49, 1878, 55): 'e.code', (1878, 57, 1878, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((1954, 22, 1954, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(1954, 49, 1954, 55): 'e.code', (1954, 57, 1954, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2022, 22, 2022, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2022, 49, 2022, 55): 'e.code', (2022, 57, 2022, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2094, 22, 2094, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2094, 49, 2094, 55): 'e.code', (2094, 57, 2094, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2150, 22, 2150, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2150, 49, 2150, 55): 'e.code', (2150, 57, 2150, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2206, 22, 2206, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2206, 49, 2206, 55): 'e.code', (2206, 57, 2206, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2269, 22, 2269, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2269, 49, 2269, 55): 'e.code', (2269, 57, 2269, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2374, 22, 2374, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2374, 49, 2374, 55): 'e.code', (2374, 57, 2374, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2486, 22, 2486, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2486, 49, 2486, 55): 'e.code', (2486, 57, 2486, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2552, 22, 2552, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2552, 49, 2552, 55): 'e.code', (2552, 57, 2552, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2611, 22, 2611, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2611, 49, 2611, 55): 'e.code', (2611, 57, 2611, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2672, 22, 2672, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2672, 49, 2672, 55): 'e.code', (2672, 57, 2672, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2728, 22, 2728, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2728, 49, 2728, 55): 'e.code', (2728, 57, 2728, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2784, 22, 2784, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2784, 49, 2784, 55): 'e.code', (2784, 57, 2784, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2840, 22, 2840, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2840, 49, 2840, 55): 'e.code', (2840, 57, 2840, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2898, 22, 2898, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2898, 49, 2898, 55): 'e.code', (2898, 57, 2898, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((2954, 22, 2954, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(2954, 49, 2954, 55): 'e.code', (2954, 57, 2954, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3013, 22, 3013, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3013, 49, 3013, 55): 'e.code', (3013, 57, 3013, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3076, 22, 3076, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3076, 49, 3076, 55): 'e.code', (3076, 57, 3076, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3137, 22, 3137, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3137, 49, 3137, 55): 'e.code', (3137, 57, 3137, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3198, 22, 3198, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3198, 49, 3198, 55): 'e.code', (3198, 57, 3198, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3283, 22, 3283, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3283, 49, 3283, 55): 'e.code', (3283, 57, 3283, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3359, 22, 3359, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3359, 49, 3359, 55): 'e.code', (3359, 57, 3359, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3416, 22, 3416, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3416, 49, 3416, 55): 'e.code', (3416, 57, 3416, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3487, 22, 3487, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3487, 49, 3487, 55): 'e.code', (3487, 57, 3487, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3559, 22, 3559, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3559, 49, 3559, 55): 'e.code', (3559, 57, 3559, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3619, 22, 3619, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3619, 49, 3619, 55): 'e.code', (3619, 57, 3619, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3678, 22, 3678, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3678, 49, 3678, 55): 'e.code', (3678, 57, 3678, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3739, 22, 3739, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3739, 49, 3739, 55): 'e.code', (3739, 57, 3739, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3799, 22, 3799, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3799, 49, 3799, 55): 'e.code', (3799, 57, 3799, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3859, 22, 3859, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3859, 49, 3859, 55): 'e.code', (3859, 57, 3859, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3919, 22, 3919, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3919, 49, 3919, 55): 'e.code', (3919, 57, 3919, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((3980, 22, 3980, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(3980, 49, 3980, 55): 'e.code', (3980, 57, 3980, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4037, 22, 4037, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4037, 49, 4037, 55): 'e.code', (4037, 57, 4037, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4108, 22, 4108, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4108, 49, 4108, 55): 'e.code', (4108, 57, 4108, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4168, 22, 4168, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4168, 49, 4168, 55): 'e.code', (4168, 57, 4168, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4226, 22, 4226, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4226, 49, 4226, 55): 'e.code', (4226, 57, 4226, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4286, 22, 4286, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4286, 49, 4286, 55): 'e.code', (4286, 57, 4286, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4343, 22, 4343, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4343, 49, 4343, 55): 'e.code', (4343, 57, 4343, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4403, 22, 4403, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4403, 49, 4403, 55): 'e.code', (4403, 57, 4403, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4482, 22, 4482, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4482, 49, 4482, 55): 'e.code', (4482, 57, 4482, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4561, 22, 4561, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4561, 49, 4561, 55): 'e.code', (4561, 57, 4561, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4625, 22, 4625, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4625, 49, 4625, 55): 'e.code', (4625, 57, 4625, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4697, 22, 4697, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4697, 49, 4697, 55): 'e.code', (4697, 57, 4697, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4772, 22, 4772, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4772, 49, 4772, 55): 'e.code', (4772, 57, 4772, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4836, 22, 4836, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4836, 49, 4836, 55): 'e.code', (4836, 57, 4836, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4899, 22, 4899, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4899, 49, 4899, 55): 'e.code', (4899, 57, 4899, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((4959, 22, 4959, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(4959, 49, 4959, 55): 'e.code', (4959, 57, 4959, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5017, 22, 5017, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5017, 49, 5017, 55): 'e.code', (5017, 57, 5017, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5077, 22, 5077, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5077, 49, 5077, 55): 'e.code', (5077, 57, 5077, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5142, 22, 5142, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5142, 49, 5142, 55): 'e.code', (5142, 57, 5142, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5208, 22, 5208, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5208, 49, 5208, 55): 'e.code', (5208, 57, 5208, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5280, 22, 5280, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5280, 49, 5280, 55): 'e.code', (5280, 57, 5280, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5383, 22, 5383, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5383, 49, 5383, 55): 'e.code', (5383, 57, 5383, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5469, 22, 5469, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5469, 49, 5469, 55): 'e.code', (5469, 57, 5469, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5588, 22, 5588, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5588, 49, 5588, 55): 'e.code', (5588, 57, 5588, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5688, 22, 5688, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5688, 49, 5688, 55): 'e.code', (5688, 57, 5688, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5768, 22, 5768, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5768, 49, 5768, 55): 'e.code', (5768, 57, 5768, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5840, 22, 5840, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5840, 49, 5840, 55): 'e.code', (5840, 57, 5840, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5904, 22, 5904, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5904, 49, 5904, 55): 'e.code', (5904, 57, 5904, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((5963, 22, 5963, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(5963, 49, 5963, 55): 'e.code', (5963, 57, 5963, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6022, 22, 6022, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6022, 49, 6022, 55): 'e.code', (6022, 57, 6022, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6097, 22, 6097, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6097, 49, 6097, 55): 'e.code', (6097, 57, 6097, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6188, 22, 6188, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6188, 49, 6188, 55): 'e.code', (6188, 57, 6188, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6259, 22, 6259, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6259, 49, 6259, 55): 'e.code', (6259, 57, 6259, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6317, 22, 6317, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6317, 49, 6317, 55): 'e.code', (6317, 57, 6317, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6375, 22, 6375, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6375, 49, 6375, 55): 'e.code', (6375, 57, 6375, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6434, 22, 6434, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6434, 49, 6434, 55): 'e.code', (6434, 57, 6434, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6507, 22, 6507, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6507, 49, 6507, 55): 'e.code', (6507, 57, 6507, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6581, 22, 6581, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6581, 49, 6581, 55): 'e.code', (6581, 57, 6581, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6654, 22, 6654, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6654, 49, 6654, 55): 'e.code', (6654, 57, 6654, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6727, 22, 6727, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6727, 49, 6727, 55): 'e.code', (6727, 57, 6727, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6800, 22, 6800, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6800, 49, 6800, 55): 'e.code', (6800, 57, 6800, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6899, 22, 6899, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6899, 49, 6899, 55): 'e.code', (6899, 57, 6899, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((6958, 22, 6958, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(6958, 49, 6958, 55): 'e.code', (6958, 57, 6958, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7017, 22, 7017, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7017, 49, 7017, 55): 'e.code', (7017, 57, 7017, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7077, 22, 7077, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7077, 49, 7077, 55): 'e.code', (7077, 57, 7077, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7133, 22, 7133, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7133, 49, 7133, 55): 'e.code', (7133, 57, 7133, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7189, 22, 7189, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7189, 49, 7189, 55): 'e.code', (7189, 57, 7189, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7281, 22, 7281, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7281, 49, 7281, 55): 'e.code', (7281, 57, 7281, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7363, 22, 7363, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7363, 49, 7363, 55): 'e.code', (7363, 57, 7363, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7432, 22, 7432, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7432, 49, 7432, 55): 'e.code', (7432, 57, 7432, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7506, 22, 7506, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7506, 49, 7506, 55): 'e.code', (7506, 57, 7506, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7577, 22, 7577, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7577, 49, 7577, 55): 'e.code', (7577, 57, 7577, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7646, 22, 7646, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7646, 49, 7646, 55): 'e.code', (7646, 57, 7646, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7723, 22, 7723, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7723, 49, 7723, 55): 'e.code', (7723, 57, 7723, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7818, 22, 7818, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7818, 49, 7818, 55): 'e.code', (7818, 57, 7818, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7912, 22, 7912, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7912, 49, 7912, 55): 'e.code', (7912, 57, 7912, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((7974, 22, 7974, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(7974, 49, 7974, 55): 'e.code', (7974, 57, 7974, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8033, 22, 8033, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8033, 49, 8033, 55): 'e.code', (8033, 57, 8033, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8091, 22, 8091, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8091, 49, 8091, 55): 'e.code', (8091, 57, 8091, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8151, 22, 8151, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8151, 49, 8151, 55): 'e.code', (8151, 57, 8151, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8211, 22, 8211, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8211, 49, 8211, 55): 'e.code', (8211, 57, 8211, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8283, 22, 8283, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8283, 49, 8283, 55): 'e.code', (8283, 57, 8283, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8343, 22, 8343, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8343, 49, 8343, 55): 'e.code', (8343, 57, 8343, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8398, 22, 8398, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8398, 49, 8398, 55): 'e.code', (8398, 57, 8398, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8457, 22, 8457, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8457, 49, 8457, 55): 'e.code', (8457, 57, 8457, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8522, 22, 8522, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8522, 49, 8522, 55): 'e.code', (8522, 57, 8522, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8585, 22, 8585, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8585, 49, 8585, 55): 'e.code', (8585, 57, 8585, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8667, 22, 8667, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8667, 49, 8667, 55): 'e.code', (8667, 57, 8667, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8747, 22, 8747, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8747, 49, 8747, 55): 'e.code', (8747, 57, 8747, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8826, 22, 8826, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8826, 49, 8826, 55): 'e.code', (8826, 57, 8826, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8910, 22, 8910, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8910, 49, 8910, 55): 'e.code', (8910, 57, 8910, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n'), ((8975, 22, 8975, 65), 'tensorflow.python.eager.core._status_to_exception', '_core._status_to_exception', ({(8975, 49, 8975, 55): 'e.code', (8975, 57, 8975, 64): 'message'}, {}), '(e.code, message)', True, 'from tensorflow.python.eager import core as _core\n')]
yamiacat/indico
indico/modules/oauth/models/applications.py
754c02cd7cd25bf1eab0ca5f497eb24b135dd51c
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from uuid import uuid4 from sqlalchemy.dialects.postgresql import ARRAY, UUID from sqlalchemy.ext.declarative import declared_attr from werkzeug.urls import url_parse from indico.core.db import db from indico.core.db.sqlalchemy import PyIntEnum from indico.modules.oauth import logger from indico.util.i18n import _ from indico.util.struct.enum import IndicoEnum SCOPES = {'read:user': _("User information (read only)"), 'read:legacy_api': _('Legacy API (read only)'), 'write:legacy_api': _('Legacy API (write only)'), 'registrants': _('Event registrants')} class SystemAppType(int, IndicoEnum): none = 0 checkin = 1 flower = 2 __enforced_data__ = { checkin: {'default_scopes': {'registrants'}, 'redirect_uris': ['http://localhost'], 'is_enabled': True}, flower: {'default_scopes': {'read:user'}, 'is_enabled': True} } __default_data__ = { checkin: {'is_trusted': True, 'name': 'Checkin App', 'description': 'The checkin app for mobile devices allows scanning ticket QR codes and ' 'checking-in event participants.'}, flower: {'is_trusted': True, 'name': 'Flower', 'description': 'Flower allows monitoring Celery tasks. If flower is installed, this app is used to ' 'restrict access to Indico administrators.'} } @property def enforced_data(self): return self.__enforced_data__.get(self, {}) @property def default_data(self): return dict(self.__default_data__.get(self, {}), **self.enforced_data) class OAuthApplication(db.Model): """OAuth applications registered in Indico.""" __tablename__ = 'applications' @declared_attr def __table_args__(cls): return (db.Index('ix_uq_applications_name_lower', db.func.lower(cls.name), unique=True), db.Index(None, cls.system_app_type, unique=True, postgresql_where=db.text(f'system_app_type != {SystemAppType.none.value}')), {'schema': 'oauth'}) #: the unique id of the application id = db.Column( db.Integer, primary_key=True ) #: human readable name name = db.Column( db.String, nullable=False ) #: human readable description description = db.Column( db.Text, nullable=False, default='' ) #: the OAuth client_id client_id = db.Column( UUID, unique=True, nullable=False, default=lambda: str(uuid4()) ) #: the OAuth client_secret client_secret = db.Column( UUID, nullable=False, default=lambda: str(uuid4()) ) #: the OAuth default scopes the application may request access to default_scopes = db.Column( ARRAY(db.String), nullable=False ) #: the OAuth absolute URIs that a application may use to redirect to after authorization redirect_uris = db.Column( ARRAY(db.String), nullable=False, default=[] ) #: whether the application is enabled or disabled is_enabled = db.Column( db.Boolean, nullable=False, default=True ) #: whether the application can access user data without asking for permission is_trusted = db.Column( db.Boolean, nullable=False, default=False ) #: the type of system app (if any). system apps cannot be deleted system_app_type = db.Column( PyIntEnum(SystemAppType), nullable=False, default=SystemAppType.none ) # relationship backrefs: # - tokens (OAuthToken.application) @property def client_type(self): return 'public' @property def default_redirect_uri(self): return self.redirect_uris[0] if self.redirect_uris else None @property def locator(self): return {'id': self.id} def __repr__(self): # pragma: no cover return f'<OAuthApplication({self.id}, {self.name}, {self.client_id})>' def reset_client_secret(self): self.client_secret = str(uuid4()) logger.info("Client secret for %s has been reset.", self) def validate_redirect_uri(self, redirect_uri): """Called by flask-oauthlib to validate the redirect_uri. Uses a logic similar to the one at GitHub, i.e. protocol and host/port must match exactly and if there is a path in the whitelisted URL, the path of the redirect_uri must start with that path. """ uri_data = url_parse(redirect_uri) for valid_uri_data in map(url_parse, self.redirect_uris): if (uri_data.scheme == valid_uri_data.scheme and uri_data.netloc == valid_uri_data.netloc and uri_data.path.startswith(valid_uri_data.path)): return True return False
[((21, 23, 21, 56), 'indico.util.i18n._', '_', ({(21, 25, 21, 55): '"""User information (read only)"""'}, {}), "('User information (read only)')", False, 'from indico.util.i18n import _\n'), ((22, 29, 22, 56), 'indico.util.i18n._', '_', ({(22, 31, 22, 55): '"""Legacy API (read only)"""'}, {}), "('Legacy API (read only)')", False, 'from indico.util.i18n import _\n'), ((23, 30, 23, 58), 'indico.util.i18n._', '_', ({(23, 32, 23, 57): '"""Legacy API (write only)"""'}, {}), "('Legacy API (write only)')", False, 'from indico.util.i18n import _\n'), ((24, 25, 24, 47), 'indico.util.i18n._', '_', ({(24, 27, 24, 46): '"""Event registrants"""'}, {}), "('Event registrants')", False, 'from indico.util.i18n import _\n'), ((73, 9, 76, 5), 'indico.core.db.db.Column', 'db.Column', (), '', False, 'from indico.core.db import db\n'), ((78, 11, 81, 5), 'indico.core.db.db.Column', 'db.Column', (), '', False, 'from indico.core.db import db\n'), ((83, 18, 87, 5), 'indico.core.db.db.Column', 'db.Column', (), '', False, 'from indico.core.db import db\n'), ((113, 17, 117, 5), 'indico.core.db.db.Column', 'db.Column', (), '', False, 'from indico.core.db import db\n'), ((119, 17, 123, 5), 'indico.core.db.db.Column', 'db.Column', (), '', False, 'from indico.core.db import db\n'), ((103, 8, 103, 24), 'sqlalchemy.dialects.postgresql.ARRAY', 'ARRAY', ({(103, 14, 103, 23): 'db.String'}, {}), '(db.String)', False, 'from sqlalchemy.dialects.postgresql import ARRAY, UUID\n'), ((108, 8, 108, 24), 'sqlalchemy.dialects.postgresql.ARRAY', 'ARRAY', ({(108, 14, 108, 23): 'db.String'}, {}), '(db.String)', False, 'from sqlalchemy.dialects.postgresql import ARRAY, UUID\n'), ((126, 8, 126, 32), 'indico.core.db.sqlalchemy.PyIntEnum', 'PyIntEnum', ({(126, 18, 126, 31): 'SystemAppType'}, {}), '(SystemAppType)', False, 'from indico.core.db.sqlalchemy import PyIntEnum\n'), ((151, 8, 151, 65), 'indico.modules.oauth.logger.info', 'logger.info', ({(151, 20, 151, 58): '"""Client secret for %s has been reset."""', (151, 60, 151, 64): 'self'}, {}), "('Client secret for %s has been reset.', self)", False, 'from indico.modules.oauth import logger\n'), ((161, 19, 161, 42), 'werkzeug.urls.url_parse', 'url_parse', ({(161, 29, 161, 41): 'redirect_uri'}, {}), '(redirect_uri)', False, 'from werkzeug.urls import url_parse\n'), ((150, 33, 150, 40), 'uuid.uuid4', 'uuid4', ({}, {}), '()', False, 'from uuid import uuid4\n'), ((67, 58, 67, 81), 'indico.core.db.db.func.lower', 'db.func.lower', ({(67, 72, 67, 80): 'cls.name'}, {}), '(cls.name)', False, 'from indico.core.db import db\n'), ((69, 42, 69, 99), 'indico.core.db.db.text', 'db.text', ({(69, 50, 69, 98): 'f"""system_app_type != {SystemAppType.none.value}"""'}, {}), "(f'system_app_type != {SystemAppType.none.value}')", False, 'from indico.core.db import db\n'), ((93, 28, 93, 35), 'uuid.uuid4', 'uuid4', ({}, {}), '()', False, 'from uuid import uuid4\n'), ((99, 28, 99, 35), 'uuid.uuid4', 'uuid4', ({}, {}), '()', False, 'from uuid import uuid4\n')]
FrancisLiang/models-1
PaddleNLP/unarchived/deep_attention_matching_net/utils/layers.py
e14d5bc1ab36d0dd11977f27cff54605bf99c945
import paddle.fluid as fluid def loss(x, y, clip_value=10.0): """Calculate the sigmoid cross entropy with logits for input(x). Args: x: Variable with shape with shape [batch, dim] y: Input label Returns: loss: cross entropy logits: prediction """ logits = fluid.layers.fc( input=x, size=1, bias_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(0.))) loss = fluid.layers.sigmoid_cross_entropy_with_logits(x=logits, label=y) loss = fluid.layers.reduce_mean( fluid.layers.clip( loss, min=-clip_value, max=clip_value)) return loss, logits def ffn(input, d_inner_hid, d_hid, name=None): """Position-wise Feed-Forward Network """ hidden = fluid.layers.fc(input=input, size=d_inner_hid, num_flatten_dims=2, param_attr=fluid.ParamAttr(name=name + '_fc.w_0'), bias_attr=fluid.ParamAttr( name=name + '_fc.b_0', initializer=fluid.initializer.Constant(0.)), act="relu") out = fluid.layers.fc(input=hidden, size=d_hid, num_flatten_dims=2, param_attr=fluid.ParamAttr(name=name + '_fc.w_1'), bias_attr=fluid.ParamAttr( name=name + '_fc.b_1', initializer=fluid.initializer.Constant(0.))) return out def dot_product_attention(query, key, value, d_key, q_mask=None, k_mask=None, dropout_rate=None, mask_cache=None): """Dot product layer. Args: query: a tensor with shape [batch, Q_time, Q_dimension] key: a tensor with shape [batch, time, K_dimension] value: a tensor with shape [batch, time, V_dimension] q_lengths: a tensor with shape [batch] k_lengths: a tensor with shape [batch] Returns: a tensor with shape [batch, query_time, value_dimension] Raises: AssertionError: if Q_dimension not equal to K_dimension when attention type is dot. """ logits = fluid.layers.matmul( x=query, y=key, transpose_y=True, alpha=d_key**(-0.5)) if (q_mask is not None) and (k_mask is not None): if mask_cache is not None and q_mask.name in mask_cache and k_mask.name in mask_cache[ q_mask.name]: mask, another_mask = mask_cache[q_mask.name][k_mask.name] else: mask = fluid.layers.matmul(x=q_mask, y=k_mask, transpose_y=True) another_mask = fluid.layers.scale( mask, scale=float(2**32 - 1), bias=float(-1), bias_after_scale=False) if mask_cache is not None: if q_mask.name not in mask_cache: mask_cache[q_mask.name] = dict() mask_cache[q_mask.name][k_mask.name] = [mask, another_mask] logits = mask * logits + another_mask attention = fluid.layers.softmax(logits) if dropout_rate: attention = fluid.layers.dropout( input=attention, dropout_prob=dropout_rate, is_test=False, seed=2) atten_out = fluid.layers.matmul(x=attention, y=value) return atten_out def block(name, query, key, value, d_key, q_mask=None, k_mask=None, is_layer_norm=True, dropout_rate=None, mask_cache=None): """ """ att_out = dot_product_attention( query, key, value, d_key, q_mask, k_mask, dropout_rate, mask_cache=mask_cache) y = query + att_out if is_layer_norm: y = fluid.layers.layer_norm( input=y, begin_norm_axis=len(y.shape) - 1, param_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(1.), name=name + '_layer_norm.w_0'), bias_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(0.), name=name + '_layer_norm.b_0')) z = ffn(y, d_key, d_key, name) w = y + z if is_layer_norm: w = fluid.layers.layer_norm( input=w, begin_norm_axis=len(w.shape) - 1, param_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(1.), name=name + '_layer_norm.w_1'), bias_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(0.), name=name + '_layer_norm.b_1')) return w def cnn_3d(input, out_channels_0, out_channels_1, add_relu=True): # same padding conv_0 = fluid.layers.conv3d( name="conv3d_0", input=input, num_filters=out_channels_0, filter_size=[3, 3, 3], padding=[1, 1, 1], act="elu" if add_relu else None, param_attr=fluid.ParamAttr(initializer=fluid.initializer.Uniform( low=-0.01, high=0.01)), bias_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.0))) # same padding pooling_0 = fluid.layers.pool3d( input=conv_0, pool_type="max", pool_size=3, pool_padding=1, pool_stride=3) conv_1 = fluid.layers.conv3d( name="conv3d_1", input=pooling_0, num_filters=out_channels_1, filter_size=[3, 3, 3], padding=[1, 1, 1], act="elu" if add_relu else None, param_attr=fluid.ParamAttr(initializer=fluid.initializer.Uniform( low=-0.01, high=0.01)), bias_attr=fluid.ParamAttr( initializer=fluid.initializer.Constant(value=0.0))) # same padding pooling_1 = fluid.layers.pool3d( input=conv_1, pool_type="max", pool_size=3, pool_padding=1, pool_stride=3) return pooling_1
[((20, 11, 20, 76), 'paddle.fluid.layers.sigmoid_cross_entropy_with_logits', 'fluid.layers.sigmoid_cross_entropy_with_logits', (), '', True, 'import paddle.fluid as fluid\n'), ((75, 13, 76, 62), 'paddle.fluid.layers.matmul', 'fluid.layers.matmul', (), '', True, 'import paddle.fluid as fluid\n'), ((97, 16, 97, 44), 'paddle.fluid.layers.softmax', 'fluid.layers.softmax', ({(97, 37, 97, 43): 'logits'}, {}), '(logits)', True, 'import paddle.fluid as fluid\n'), ((102, 16, 102, 57), 'paddle.fluid.layers.matmul', 'fluid.layers.matmul', (), '', True, 'import paddle.fluid as fluid\n'), ((173, 16, 178, 22), 'paddle.fluid.layers.pool3d', 'fluid.layers.pool3d', (), '', True, 'import paddle.fluid as fluid\n'), ((193, 16, 198, 22), 'paddle.fluid.layers.pool3d', 'fluid.layers.pool3d', (), '', True, 'import paddle.fluid as fluid\n'), ((22, 8, 23, 50), 'paddle.fluid.layers.clip', 'fluid.layers.clip', (), '', True, 'import paddle.fluid as fluid\n'), ((99, 20, 100, 78), 'paddle.fluid.layers.dropout', 'fluid.layers.dropout', (), '', True, 'import paddle.fluid as fluid\n'), ((34, 40, 34, 78), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', (), '', True, 'import paddle.fluid as fluid\n'), ((42, 37, 42, 75), 'paddle.fluid.ParamAttr', 'fluid.ParamAttr', (), '', True, 'import paddle.fluid as fluid\n'), ((83, 19, 83, 76), 'paddle.fluid.layers.matmul', 'fluid.layers.matmul', (), '', True, 'import paddle.fluid as fluid\n'), ((19, 46, 19, 76), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(19, 73, 19, 75): '0.0'}, {}), '(0.0)', True, 'import paddle.fluid as fluid\n'), ((37, 45, 37, 75), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(37, 72, 37, 74): '0.0'}, {}), '(0.0)', True, 'import paddle.fluid as fluid\n'), ((45, 42, 45, 72), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(45, 69, 45, 71): '0.0'}, {}), '(0.0)', True, 'import paddle.fluid as fluid\n'), ((167, 47, 168, 33), 'paddle.fluid.initializer.Uniform', 'fluid.initializer.Uniform', (), '', True, 'import paddle.fluid as fluid\n'), ((170, 24, 170, 61), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', (), '', True, 'import paddle.fluid as fluid\n'), ((187, 47, 188, 33), 'paddle.fluid.initializer.Uniform', 'fluid.initializer.Uniform', (), '', True, 'import paddle.fluid as fluid\n'), ((190, 24, 190, 61), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', (), '', True, 'import paddle.fluid as fluid\n'), ((136, 28, 136, 58), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(136, 55, 136, 57): '1.0'}, {}), '(1.0)', True, 'import paddle.fluid as fluid\n'), ((139, 28, 139, 58), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(139, 55, 139, 57): '0.0'}, {}), '(0.0)', True, 'import paddle.fluid as fluid\n'), ((149, 28, 149, 58), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(149, 55, 149, 57): '1.0'}, {}), '(1.0)', True, 'import paddle.fluid as fluid\n'), ((152, 28, 152, 58), 'paddle.fluid.initializer.Constant', 'fluid.initializer.Constant', ({(152, 55, 152, 57): '0.0'}, {}), '(0.0)', True, 'import paddle.fluid as fluid\n')]
TheWardoctor/wardoctors-repo
plugin.video.saltsrd.lite/js2py/translators/jsregexps.py
893f646d9e27251ffc00ca5f918e4eb859a5c8f0
from salts_lib.pyjsparser.pyjsparserdata import * REGEXP_SPECIAL_SINGLE = {'\\', '^', '$', '*', '+', '?', '.'} NOT_PATTERN_CHARS = {'^', '$', '\\', '.', '*', '+', '?', '(', ')', '[', ']', '|'} # what about '{', '}', ??? CHAR_CLASS_ESCAPE = {'d', 'D', 's', 'S', 'w', 'W'} CONTROL_ESCAPE_CHARS = {'f', 'n', 'r', 't', 'v'} CONTROL_LETTERS = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'} def SpecialChar(char): return {'type': 'SpecialChar', 'content': char} def isPatternCharacter(char): return char not in NOT_PATTERN_CHARS class JsRegExpParser: def __init__(self, source, flags): self.source = source self.flags = flags self.index = 0 self.length = len(source) self.lineNumber = 0 self.lineStart = 0 def parsePattern(self): '''Perform sctring escape - for regexp literals''' return {'type': 'Pattern', 'contents': self.parseDisjunction()} def parseDisjunction(self): alternatives = [] while True: alternatives.append(self.parseAlternative()) if not self.isEOF(): self.expect_character('|') else: break return {'type': 'Disjunction', 'contents': alternatives} def isEOF(self): if self.index>=self.length: return True return False def expect_character(self, character): if self.source[self.index]!=character: self.throwUnexpected(character) self.index += 1 def parseAlternative(self): contents = [] while not self.isEOF() and self.source[self.index]!='|': contents.append(self.parseTerm()) return {'type': 'Alternative', 'contents': contents} def follows(self, chars): for i, c in enumerate(chars): if self.index+i>=self.length or self.source[self.index+i] != c: return False return True def parseTerm(self): assertion = self.parseAssertion() if assertion: return assertion else: return {'type': 'Term', 'contents': self.parseAtom()} # quantifier will go inside atom! def parseAssertion(self): if self.follows('$'): content = SpecialChar('$') self.index += 1 elif self.follows('^'): content = SpecialChar('^') self.index += 1 elif self.follows('\\b'): content = SpecialChar('\\b') self.index += 2 elif self.follows('\\B'): content = SpecialChar('\\B') self.index += 2 elif self.follows('(?='): self.index += 3 dis = self.parseDisjunction() self.expect_character(')') content = {'type': 'Lookached', 'contents': dis, 'negated': False} elif self.follows('(?!'): self.index += 3 dis = self.parseDisjunction() self.expect_character(')') content = {'type': 'Lookached', 'contents': dis, 'negated': True} else: return None return {'type': 'Assertion', 'content': content} def parseAtom(self): if self.follows('.'): content = SpecialChar('.') self.index += 1 elif self.follows('\\'): self.index += 1 content = self.parseAtomEscape() elif self.follows('['): content = self.parseCharacterClass() elif self.follows('(?:'): self.index += 3 dis = self.parseDisjunction() self.expect_character(')') content = 'idk' elif self.follows('('): self.index += 1 dis = self.parseDisjunction() self.expect_character(')') content = 'idk' elif isPatternCharacter(self.source[self.index]): content = self.source[self.index] self.index += 1 else: return None quantifier = self.parseQuantifier() return {'type': 'Atom', 'content': content, 'quantifier': quantifier} def parseQuantifier(self): prefix = self.parseQuantifierPrefix() if not prefix: return None greedy = True if self.follows('?'): self.index += 1 greedy = False return {'type': 'Quantifier', 'contents': prefix, 'greedy': greedy} def parseQuantifierPrefix(self): if self.isEOF(): return None if self.follows('+'): content = '+' self.index += 1 elif self.follows('?'): content = '?' self.index += 1 elif self.follows('*'): content = '*' self.index += 1 elif self.follows('{'): # try matching otherwise return None and restore the state i = self.index self.index += 1 digs1 = self.scanDecimalDigs() # if no minimal number of digs provided then return no quantifier if not digs1: self.index = i return None # scan char limit if provided if self.follows(','): self.index += 1 digs2 = self.scanDecimalDigs() else: digs2 = '' # must be valid! if not self.follows('}'): self.index = i return None else: self.expect_character('}') content = int(digs1), int(digs2) if digs2 else None else: return None return content def parseAtomEscape(self): ch = self.source[self.index] if isDecimalDigit(ch) and ch!=0: digs = self.scanDecimalDigs() elif ch in CHAR_CLASS_ESCAPE: self.index += 1 return SpecialChar('\\' + ch) else: return self.parseCharacterEscape() def parseCharacterEscape(self): ch = self.source[self.index] if ch in CONTROL_ESCAPE_CHARS: return SpecialChar('\\' + ch) if ch=='c': 'ok, fuck this shit.' def scanDecimalDigs(self): s = self.index while not self.isEOF() and isDecimalDigit(self.source[self.index]): self.index += 1 return self.source[s:self.index] a = JsRegExpParser('a(?=x)', '') print(a.parsePattern())
[]
yixinliao/pytorch_connectomics
connectomics/model/block/squeeze_excitation.py
0f6de546e6da1e0f3258b2c84f7e16b3a993c70c
import torch.nn as nn from .basic import * class squeeze_excitation_2d(nn.Module): """Squeeze-and-Excitation Block 2D Args: channel (int): number of input channels. channel_reduction (int): channel squeezing factor. spatial_reduction (int): pooling factor for x,y axes. """ def __init__(self, channel, channel_reduction=4, spatial_reduction=4, norm_mode='bn', act_mode='elu'): super(squeeze_excitation_2d, self).__init__() self.pool_size = (spatial_reduction, spatial_reduction) layers = [nn.AvgPool2d(kernel_size=self.pool_size, stride=self.pool_size)] layers += conv2d_norm_act(channel, channel // channel_reduction, kernel_size=1, padding=0, norm_mode=norm_mode, act_mode=act_mode, return_list=True) layers += conv2d_norm_act(channel // channel_reduction, channel, kernel_size=1, padding=0, norm_mode=norm_mode, return_list=True) layers = [nn.Sigmoid(), nn.Upsample(scale_factor=self.pool_size, mode='trilinear', align_corners=False)] self.se = nn.Sequential(*layers) def forward(self, x): y = self.se(x) z = x + y*x return z class squeeze_excitation_3d(nn.Module): """Squeeze-and-Excitation Block 3D Args: channel (int): number of input channels. channel_reduction (int): channel squeezing factor. spatial_reduction (int): pooling factor for x,y axes. z_reduction (int): pooling factor for z axis. """ def __init__(self, channel, channel_reduction=4, spatial_reduction=4, z_reduction=1, norm_mode='bn', act_mode='elu'): super(squeeze_excitation_3d, self).__init__() self.pool_size = (z_reduction, spatial_reduction, spatial_reduction) layers = [nn.AvgPool3d(kernel_size=self.pool_size, stride=self.pool_size)] layers += conv3d_norm_act(channel, channel//channel_reduction, kernel_size=1, padding=0, norm_mode=norm_mode, act_mode=act_mode, return_list=True) layers += conv3d_norm_act(channel//channel_reduction, channel, kernel_size=1, padding=0, norm_mode=norm_mode, return_list=True) layers += [nn.Sigmoid(), nn.Upsample(scale_factor=self.pool_size, mode='trilinear', align_corners=False)] self.se = nn.Sequential(*layers) def forward(self, x): y = self.se(x) z = x + y*x return z
[((20, 18, 20, 40), 'torch.nn.Sequential', 'nn.Sequential', ({(20, 32, 20, 39): '*layers'}, {}), '(*layers)', True, 'import torch.nn as nn\n'), ((45, 18, 45, 40), 'torch.nn.Sequential', 'nn.Sequential', ({(45, 32, 45, 39): '*layers'}, {}), '(*layers)', True, 'import torch.nn as nn\n'), ((15, 18, 15, 81), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (), '', True, 'import torch.nn as nn\n'), ((18, 18, 18, 30), 'torch.nn.Sigmoid', 'nn.Sigmoid', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((19, 16, 19, 95), 'torch.nn.Upsample', 'nn.Upsample', (), '', True, 'import torch.nn as nn\n'), ((40, 18, 40, 81), 'torch.nn.AvgPool3d', 'nn.AvgPool3d', (), '', True, 'import torch.nn as nn\n'), ((43, 19, 43, 31), 'torch.nn.Sigmoid', 'nn.Sigmoid', ({}, {}), '()', True, 'import torch.nn as nn\n'), ((44, 16, 44, 95), 'torch.nn.Upsample', 'nn.Upsample', (), '', True, 'import torch.nn as nn\n')]
blueshed/duckdown
duckdown/handlers/site_handler.py
e6d0e62d378bd2d9ed0cd5ce4bc7ab3476b86020
# pylint: disable=W0201, E1101 """ handle request for markdown pages """ import logging import os import importlib from tornado.web import RequestHandler, HTTPError from tornado.escape import url_escape from ..utils.converter_mixin import ConverterMixin from .access_control import UserMixin from ..utils.nav import nav LOGGER = logging.getLogger(__name__) EMPTY_TOC = '<div class="toc">\n<ul></ul>\n</div>\n' class SiteHandler( UserMixin, ConverterMixin, RequestHandler ): # pylint: disable=W0223 """ inline transform request for markdown pages """ def initialize(self, pages): """ setup init properties """ self.pages = pages self.meta = None self.nav = None self.site_nav = None self.site = None def create_template_loader(self, template_path): """ if we have one, us it """ if self.site.template_loader: return self.site.template_loader return super().create_template_loader(template_path) @property def has_toc(self): """ determin if toc is empty """ return self.meta.toc != EMPTY_TOC def meta_value(self, name, default=None): """ return markdown meta value """ return self.meta.Meta.get(name, [default]) def one_meta_value(self, name, default=None): """ return markdown meta value """ result = self.meta_value(name, default) return result[0] if result else None def load_site_nav(self, site, path): """ set the handler site_nav attribute """ menu = nav(site, root=self.pages, path=path) if menu: self.site_nav = "\n".join(menu) def load_dir_nav(self, site, path): """ load nav section if it exist """ folder = os.path.dirname(path) if folder: LOGGER.info(" -- folder: %s", folder) nav_path = os.path.join(folder, "-nav.md") _, content = site.get_file(nav_path) if content: content = content.decode("utf-8") LOGGER.info(" -- nav: %s", nav_path) content = self.meta.convert(content) self.nav = self.convert_images(content) def run_script( self, site, script_name, path ): # pylint: disable=unused-argument """ load a module and call module.main """ name = f"{self.settings['script_path']}.{script_name}" script_module = importlib.import_module(name) return script_module.main(path) async def get(self, path): """ handle get """ path = path if path else "index.html" file, ext = os.path.splitext(path) doc = os.path.join(self.pages, f"{file}.md") self.site = self.get_site(path) _, content = self.site.get_file(doc) if content is None: raise HTTPError(404) if content: content = content.decode("utf-8") self.meta = self.markdown self.load_dir_nav(self.site, doc) self.load_site_nav(self.site, path) file_path = os.path.split(file)[0] # load theme theme_file = os.path.join(self.pages, file_path, "-theme.css") _, theme_css = self.site.get_file(theme_file) if theme_css: LOGGER.info(" -- theme.css") theme_css = theme_css.decode("utf-8") edit_path = "/edit" if file: edit_path = f"/edit?path={ url_escape(file) }.md" LOGGER.info(" -- ext: %s", ext) if ext == ".html": content = self.meta.convert(content) LOGGER.info(" -- meta: %s", self.meta.Meta) template = self.one_meta_value("template", "site") LOGGER.info(" -- tmpl: %s", template) for key in self.meta.Meta: if key.startswith("x-script-"): outcome = self.run_script( self.site, self.meta.Meta[key][0], path ) self.meta.Meta[key] = [outcome] self.render( f"{template}_tmpl.html", content=self.convert_images(content), edit_path=edit_path, theme_css=theme_css, ) else: self.write(self.convert_images(content))
[((13, 9, 13, 36), 'logging.getLogger', 'logging.getLogger', ({(13, 27, 13, 35): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((58, 17, 58, 38), 'os.path.dirname', 'os.path.dirname', ({(58, 33, 58, 37): 'path'}, {}), '(path)', False, 'import os\n'), ((74, 24, 74, 53), 'importlib.import_module', 'importlib.import_module', ({(74, 48, 74, 52): 'name'}, {}), '(name)', False, 'import importlib\n'), ((82, 20, 82, 42), 'os.path.splitext', 'os.path.splitext', ({(82, 37, 82, 41): 'path'}, {}), '(path)', False, 'import os\n'), ((84, 14, 84, 52), 'os.path.join', 'os.path.join', ({(84, 27, 84, 37): 'self.pages', (84, 39, 84, 51): 'f"""{file}.md"""'}, {}), "(self.pages, f'{file}.md')", False, 'import os\n'), ((99, 21, 99, 70), 'os.path.join', 'os.path.join', ({(99, 34, 99, 44): 'self.pages', (99, 46, 99, 55): 'file_path', (99, 57, 99, 69): '"""-theme.css"""'}, {}), "(self.pages, file_path, '-theme.css')", False, 'import os\n'), ((61, 23, 61, 54), 'os.path.join', 'os.path.join', ({(61, 36, 61, 42): 'folder', (61, 44, 61, 53): '"""-nav.md"""'}, {}), "(folder, '-nav.md')", False, 'import os\n'), ((88, 18, 88, 32), 'tornado.web.HTTPError', 'HTTPError', ({(88, 28, 88, 31): '(404)'}, {}), '(404)', False, 'from tornado.web import RequestHandler, HTTPError\n'), ((96, 20, 96, 39), 'os.path.split', 'os.path.split', ({(96, 34, 96, 38): 'file'}, {}), '(file)', False, 'import os\n'), ((107, 39, 107, 55), 'tornado.escape.url_escape', 'url_escape', ({(107, 50, 107, 54): 'file'}, {}), '(file)', False, 'from tornado.escape import url_escape\n')]
KivenCkl/LeetCode
Problemset/binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.py
fcc97c66f8154a5d20c2aca86120cb37b9d2d83d
# @Title: 从二叉搜索树到更大和树 (Binary Search Tree to Greater Sum Tree) # @Author: KivenC # @Date: 2019-05-15 19:52:08 # @Runtime: 48 ms # @Memory: 13 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.sum_value = 0 def bstToGst(self, root: TreeNode) -> TreeNode: if not root: return self.bstToGst(root.right) root.val = self.sum_value = self.sum_value + root.val self.bstToGst(root.left) return root
[]
robinson96/GRAPE
vine/clone.py
f6404ae6ee2933647e515a9480077ab01fb2c430
import os import option import utility import grapeMenu import grapeGit as git import grapeConfig class Clone(option.Option): """ grape-clone Clones a git repo and configures it for use with git. Usage: grape-clone <url> <path> [--recursive] [--allNested] Arguments: <url> The URL of the remote repository <path> The directory where you want to clone the repo to. Options: --recursive Recursively clone submodules. --allNested Get all nested subprojects. """ def __init__(self): super(Clone, self).__init__() self._key = "clone" self._section = "Getting Started" #Clones the default repo into a new local repo def description(self): return "Clone a repo and configure it for grape" def execute(self, args): remotepath = args["<url>"] destpath = args["<path>"] rstr = "--recursive" if args["--recursive"] else "" utility.printMsg("Cloning %s into %s %s" % (remotepath, destpath, "recursively" if args["--recursive"] else "")) git.clone(" %s %s %s" % (rstr, remotepath, destpath)) utility.printMsg("Clone succeeded!") os.chdir(destpath) grapeConfig.read() # ensure you start on a reasonable publish branch menu = grapeMenu.menu() config = grapeConfig.grapeConfig() publicBranches = config.getPublicBranchList() if publicBranches: if "develop" in publicBranches: initialBranch = "develop" elif "master" in publicBranches: initialBranch = "master" else: initialBranch = publicBranches[0] menu.applyMenuChoice("checkout", args=[initialBranch]) if args["--allNested"]: configArgs = ["--uv","--uvArg=--allNestedSubprojects"] else: configArgs = [] return menu.applyMenuChoice("config", configArgs) def setDefaultConfig(self, config): pass
[((38, 8, 38, 120), 'utility.printMsg', 'utility.printMsg', ({(38, 25, 38, 119): "('Cloning %s into %s %s' % (remotepath, destpath, 'recursively' if args[\n '--recursive'] else ''))"}, {}), "('Cloning %s into %s %s' % (remotepath, destpath, \n 'recursively' if args['--recursive'] else ''))", False, 'import utility\n'), ((39, 8, 39, 61), 'grapeGit.clone', 'git.clone', ({(39, 18, 39, 60): "(' %s %s %s' % (rstr, remotepath, destpath))"}, {}), "(' %s %s %s' % (rstr, remotepath, destpath))", True, 'import grapeGit as git\n'), ((40, 8, 40, 44), 'utility.printMsg', 'utility.printMsg', ({(40, 25, 40, 43): '"""Clone succeeded!"""'}, {}), "('Clone succeeded!')", False, 'import utility\n'), ((41, 8, 41, 26), 'os.chdir', 'os.chdir', ({(41, 17, 41, 25): 'destpath'}, {}), '(destpath)', False, 'import os\n'), ((42, 8, 42, 26), 'grapeConfig.read', 'grapeConfig.read', ({}, {}), '()', False, 'import grapeConfig\n'), ((44, 15, 44, 31), 'grapeMenu.menu', 'grapeMenu.menu', ({}, {}), '()', False, 'import grapeMenu\n'), ((45, 17, 45, 42), 'grapeConfig.grapeConfig', 'grapeConfig.grapeConfig', ({}, {}), '()', False, 'import grapeConfig\n')]
pearsonlab/python-neo
neo/test/iotest/test_nixio.py
8915dfe9e55fd3a36be83d820bdd83ab085e9402
# -*- coding: utf-8 -*- # Copyright (c) 2016, German Neuroinformatics Node (G-Node) # Achilleas Koutsou <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. """ Tests for neo.io.nixio """ import os from datetime import datetime try: import unittest2 as unittest except ImportError: import unittest try: from unittest import mock except ImportError: import mock import string import itertools from six import string_types import numpy as np import quantities as pq from neo.core import (Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch) from neo.test.iotest.common_io_test import BaseTestIO try: import nixio HAVE_NIX = True except ImportError: HAVE_NIX = False from neo.io.nixio import NixIO from neo.io.nixio import nixtypes @unittest.skipUnless(HAVE_NIX, "Requires NIX") class NixIOTest(unittest.TestCase): filename = None io = None def compare_blocks(self, neoblocks, nixblocks): for neoblock, nixblock in zip(neoblocks, nixblocks): self.compare_attr(neoblock, nixblock) self.assertEqual(len(neoblock.segments), len(nixblock.groups)) for idx, neoseg in enumerate(neoblock.segments): nixgrp = nixblock.groups[neoseg.name] self.compare_segment_group(neoseg, nixgrp) for idx, neochx in enumerate(neoblock.channel_indexes): if neochx.name: nixsrc = nixblock.sources[neochx.name] else: nixsrc = nixblock.sources[idx] self.compare_chx_source(neochx, nixsrc) self.check_refs(neoblock, nixblock) def compare_chx_source(self, neochx, nixsrc): self.compare_attr(neochx, nixsrc) nix_channels = list(src for src in nixsrc.sources if src.type == "neo.channelindex") self.assertEqual(len(neochx.index), len(nix_channels)) for nixchan in nix_channels: nixchanidx = nixchan.metadata["index"] try: neochanpos = list(neochx.index).index(nixchanidx) except ValueError: self.fail("Channel indexes do not match.") if len(neochx.channel_names): neochanname = neochx.channel_names[neochanpos] if ((not isinstance(neochanname, str)) and isinstance(neochanname, bytes)): neochanname = neochanname.decode() nixchanname = nixchan.name self.assertEqual(neochanname, nixchanname) nix_units = list(src for src in nixsrc.sources if src.type == "neo.unit") self.assertEqual(len(neochx.units), len(nix_units)) for neounit in neochx.units: nixunit = nixsrc.sources[neounit.name] self.compare_attr(neounit, nixunit) def check_refs(self, neoblock, nixblock): """ Checks whether the references between objects that are not nested are mapped correctly (e.g., SpikeTrains referenced by a Unit). :param neoblock: A Neo block :param nixblock: The corresponding NIX block """ for idx, neochx in enumerate(neoblock.channel_indexes): if neochx.name: nixchx = nixblock.sources[neochx.name] else: nixchx = nixblock.sources[idx] # AnalogSignals referencing CHX neoasigs = list(sig.name for sig in neochx.analogsignals) nixasigs = list(set(da.metadata.name for da in nixblock.data_arrays if da.type == "neo.analogsignal" and nixchx in da.sources)) self.assertEqual(len(neoasigs), len(nixasigs)) # IrregularlySampledSignals referencing CHX neoisigs = list(sig.name for sig in neochx.irregularlysampledsignals) nixisigs = list(set(da.metadata.name for da in nixblock.data_arrays if da.type == "neo.irregularlysampledsignal" and nixchx in da.sources)) self.assertEqual(len(neoisigs), len(nixisigs)) # SpikeTrains referencing CHX and Units for sidx, neounit in enumerate(neochx.units): if neounit.name: nixunit = nixchx.sources[neounit.name] else: nixunit = nixchx.sources[sidx] neosts = list(st.name for st in neounit.spiketrains) nixsts = list(mt for mt in nixblock.multi_tags if mt.type == "neo.spiketrain" and nixunit.name in mt.sources) # SpikeTrains must also reference CHX for nixst in nixsts: self.assertIn(nixchx.name, nixst.sources) nixsts = list(st.name for st in nixsts) self.assertEqual(len(neosts), len(nixsts)) for neoname in neosts: if neoname: self.assertIn(neoname, nixsts) # Events and Epochs must reference all Signals in the Group (NIX only) for nixgroup in nixblock.groups: nixevep = list(mt for mt in nixgroup.multi_tags if mt.type in ["neo.event", "neo.epoch"]) nixsigs = list(da.name for da in nixgroup.data_arrays if da.type in ["neo.analogsignal", "neo.irregularlysampledsignal"]) for nee in nixevep: for ns in nixsigs: self.assertIn(ns, nee.references) def compare_segment_group(self, neoseg, nixgroup): self.compare_attr(neoseg, nixgroup) neo_signals = neoseg.analogsignals + neoseg.irregularlysampledsignals self.compare_signals_das(neo_signals, nixgroup.data_arrays) neo_eests = neoseg.epochs + neoseg.events + neoseg.spiketrains self.compare_eests_mtags(neo_eests, nixgroup.multi_tags) def compare_signals_das(self, neosignals, data_arrays): for sig in neosignals: if self.io._find_lazy_loaded(sig) is not None: sig = self.io.load_lazy_object(sig) dalist = list() for idx in itertools.count(): nixname = "{}.{}".format(sig.name, idx) if nixname in data_arrays: dalist.append(data_arrays[nixname]) else: break _, nsig = np.shape(sig) self.assertEqual(nsig, len(dalist)) self.compare_signal_dalist(sig, dalist) def compare_signal_dalist(self, neosig, nixdalist): """ Check if a Neo Analog or IrregularlySampledSignal matches a list of NIX DataArrays. :param neosig: Neo Analog or IrregularlySampledSignal :param nixdalist: List of DataArrays """ nixmd = nixdalist[0].metadata self.assertTrue(all(nixmd == da.metadata for da in nixdalist)) neounit = str(neosig.dimensionality) for sig, da in zip(np.transpose(neosig), sorted(nixdalist, key=lambda d: d.name)): self.compare_attr(neosig, da) np.testing.assert_almost_equal(sig.magnitude, da) self.assertEqual(neounit, da.unit) timedim = da.dimensions[0] if isinstance(neosig, AnalogSignal): self.assertIsInstance(timedim, nixtypes["SampledDimension"]) self.assertEqual( pq.Quantity(timedim.sampling_interval, timedim.unit), neosig.sampling_period ) self.assertEqual(timedim.offset, neosig.t_start.magnitude) if "t_start.units" in da.metadata.props: self.assertEqual(da.metadata["t_start.units"], str(neosig.t_start.dimensionality)) elif isinstance(neosig, IrregularlySampledSignal): self.assertIsInstance(timedim, nixtypes["RangeDimension"]) np.testing.assert_almost_equal(neosig.times.magnitude, timedim.ticks) self.assertEqual(timedim.unit, str(neosig.times.dimensionality)) def compare_eests_mtags(self, eestlist, mtaglist): self.assertEqual(len(eestlist), len(mtaglist)) for eest in eestlist: if self.io._find_lazy_loaded(eest) is not None: eest = self.io.load_lazy_object(eest) mtag = mtaglist[eest.name] if isinstance(eest, Epoch): self.compare_epoch_mtag(eest, mtag) elif isinstance(eest, Event): self.compare_event_mtag(eest, mtag) elif isinstance(eest, SpikeTrain): self.compare_spiketrain_mtag(eest, mtag) def compare_epoch_mtag(self, epoch, mtag): self.assertEqual(mtag.type, "neo.epoch") self.compare_attr(epoch, mtag) np.testing.assert_almost_equal(epoch.times.magnitude, mtag.positions) np.testing.assert_almost_equal(epoch.durations.magnitude, mtag.extents) self.assertEqual(mtag.positions.unit, str(epoch.times.units.dimensionality)) self.assertEqual(mtag.extents.unit, str(epoch.durations.units.dimensionality)) for neol, nixl in zip(epoch.labels, mtag.positions.dimensions[0].labels): # Dirty. Should find the root cause instead if isinstance(neol, bytes): neol = neol.decode() if isinstance(nixl, bytes): nixl = nixl.decode() self.assertEqual(neol, nixl) def compare_event_mtag(self, event, mtag): self.assertEqual(mtag.type, "neo.event") self.compare_attr(event, mtag) np.testing.assert_almost_equal(event.times.magnitude, mtag.positions) self.assertEqual(mtag.positions.unit, str(event.units.dimensionality)) for neol, nixl in zip(event.labels, mtag.positions.dimensions[0].labels): # Dirty. Should find the root cause instead # Only happens in 3.2 if isinstance(neol, bytes): neol = neol.decode() if isinstance(nixl, bytes): nixl = nixl.decode() self.assertEqual(neol, nixl) def compare_spiketrain_mtag(self, spiketrain, mtag): self.assertEqual(mtag.type, "neo.spiketrain") self.compare_attr(spiketrain, mtag) np.testing.assert_almost_equal(spiketrain.times.magnitude, mtag.positions) if len(mtag.features): neowf = spiketrain.waveforms nixwf = mtag.features[0].data self.assertEqual(np.shape(neowf), np.shape(nixwf)) self.assertEqual(nixwf.unit, str(neowf.units.dimensionality)) np.testing.assert_almost_equal(neowf.magnitude, nixwf) self.assertIsInstance(nixwf.dimensions[0], nixtypes["SetDimension"]) self.assertIsInstance(nixwf.dimensions[1], nixtypes["SetDimension"]) self.assertIsInstance(nixwf.dimensions[2], nixtypes["SampledDimension"]) def compare_attr(self, neoobj, nixobj): if neoobj.name: if isinstance(neoobj, (AnalogSignal, IrregularlySampledSignal)): nix_name = ".".join(nixobj.name.split(".")[:-1]) else: nix_name = nixobj.name self.assertEqual(neoobj.name, nix_name) self.assertEqual(neoobj.description, nixobj.definition) if hasattr(neoobj, "rec_datetime") and neoobj.rec_datetime: self.assertEqual(neoobj.rec_datetime, datetime.fromtimestamp(nixobj.created_at)) if hasattr(neoobj, "file_datetime") and neoobj.file_datetime: self.assertEqual(neoobj.file_datetime, datetime.fromtimestamp( nixobj.metadata["file_datetime"])) if neoobj.annotations: nixmd = nixobj.metadata for k, v, in neoobj.annotations.items(): if isinstance(v, pq.Quantity): self.assertEqual(nixmd.props[str(k)].unit, str(v.dimensionality)) np.testing.assert_almost_equal(nixmd[str(k)], v.magnitude) else: self.assertEqual(nixmd[str(k)], v) @classmethod def create_full_nix_file(cls, filename): nixfile = nixio.File.open(filename, nixio.FileMode.Overwrite) nix_block_a = nixfile.create_block(cls.rword(10), "neo.block") nix_block_a.definition = cls.rsentence(5, 10) nix_block_b = nixfile.create_block(cls.rword(10), "neo.block") nix_block_b.definition = cls.rsentence(3, 3) nix_block_a.metadata = nixfile.create_section( nix_block_a.name, nix_block_a.name+".metadata" ) nix_block_b.metadata = nixfile.create_section( nix_block_b.name, nix_block_b.name+".metadata" ) nix_blocks = [nix_block_a, nix_block_b] for blk in nix_blocks: for ind in range(3): group = blk.create_group(cls.rword(), "neo.segment") group.definition = cls.rsentence(10, 15) group_md = blk.metadata.create_section(group.name, group.name+".metadata") group.metadata = group_md blk = nix_blocks[0] group = blk.groups[0] allspiketrains = list() allsignalgroups = list() # analogsignals for n in range(3): siggroup = list() asig_name = "{}_asig{}".format(cls.rword(10), n) asig_definition = cls.rsentence(5, 5) asig_md = group.metadata.create_section(asig_name, asig_name+".metadata") for idx in range(3): da_asig = blk.create_data_array( "{}.{}".format(asig_name, idx), "neo.analogsignal", data=cls.rquant(100, 1) ) da_asig.definition = asig_definition da_asig.unit = "mV" da_asig.metadata = asig_md timedim = da_asig.append_sampled_dimension(0.01) timedim.unit = "ms" timedim.label = "time" timedim.offset = 10 da_asig.append_set_dimension() group.data_arrays.append(da_asig) siggroup.append(da_asig) allsignalgroups.append(siggroup) # irregularlysampledsignals for n in range(2): siggroup = list() isig_name = "{}_isig{}".format(cls.rword(10), n) isig_definition = cls.rsentence(12, 12) isig_md = group.metadata.create_section(isig_name, isig_name+".metadata") isig_times = cls.rquant(200, 1, True) for idx in range(10): da_isig = blk.create_data_array( "{}.{}".format(isig_name, idx), "neo.irregularlysampledsignal", data=cls.rquant(200, 1) ) da_isig.definition = isig_definition da_isig.unit = "mV" da_isig.metadata = isig_md timedim = da_isig.append_range_dimension(isig_times) timedim.unit = "s" timedim.label = "time" da_isig.append_set_dimension() group.data_arrays.append(da_isig) siggroup.append(da_isig) allsignalgroups.append(siggroup) # SpikeTrains with Waveforms for n in range(4): stname = "{}-st{}".format(cls.rword(20), n) times = cls.rquant(400, 1, True) times_da = blk.create_data_array( "{}.times".format(stname), "neo.spiketrain.times", data=times ) times_da.unit = "ms" mtag_st = blk.create_multi_tag(stname, "neo.spiketrain", times_da) group.multi_tags.append(mtag_st) mtag_st.definition = cls.rsentence(20, 30) mtag_st_md = group.metadata.create_section( mtag_st.name, mtag_st.name+".metadata" ) mtag_st.metadata = mtag_st_md mtag_st_md.create_property( "t_stop", nixio.Value(max(times_da).item()+1) ) waveforms = cls.rquant((10, 8, 5), 1) wfname = "{}.waveforms".format(mtag_st.name) wfda = blk.create_data_array(wfname, "neo.waveforms", data=waveforms) wfda.unit = "mV" mtag_st.create_feature(wfda, nixio.LinkType.Indexed) wfda.append_set_dimension() # spike dimension wfda.append_set_dimension() # channel dimension wftimedim = wfda.append_sampled_dimension(0.1) wftimedim.unit = "ms" wftimedim.label = "time" wfda.metadata = mtag_st_md.create_section( wfname, "neo.waveforms.metadata" ) wfda.metadata.create_property("left_sweep", [nixio.Value(20)]*5) allspiketrains.append(mtag_st) # Epochs for n in range(3): epname = "{}-ep{}".format(cls.rword(5), n) times = cls.rquant(5, 1, True) times_da = blk.create_data_array( "{}.times".format(epname), "neo.epoch.times", data=times ) times_da.unit = "s" extents = cls.rquant(5, 1) extents_da = blk.create_data_array( "{}.durations".format(epname), "neo.epoch.durations", data=extents ) extents_da.unit = "s" mtag_ep = blk.create_multi_tag( epname, "neo.epoch", times_da ) group.multi_tags.append(mtag_ep) mtag_ep.definition = cls.rsentence(2) mtag_ep.extents = extents_da label_dim = mtag_ep.positions.append_set_dimension() label_dim.labels = cls.rsentence(5).split(" ") # reference all signals in the group for siggroup in allsignalgroups: mtag_ep.references.extend(siggroup) # Events for n in range(2): evname = "{}-ev{}".format(cls.rword(5), n) times = cls.rquant(5, 1, True) times_da = blk.create_data_array( "{}.times".format(evname), "neo.event.times", data=times ) times_da.unit = "s" mtag_ev = blk.create_multi_tag( evname, "neo.event", times_da ) group.multi_tags.append(mtag_ev) mtag_ev.definition = cls.rsentence(2) label_dim = mtag_ev.positions.append_set_dimension() label_dim.labels = cls.rsentence(5).split(" ") # reference all signals in the group for siggroup in allsignalgroups: mtag_ev.references.extend(siggroup) # CHX nixchx = blk.create_source(cls.rword(10), "neo.channelindex") nixchx.metadata = nix_blocks[0].metadata.create_section( nixchx.name, "neo.channelindex.metadata" ) chantype = "neo.channelindex" # 3 channels for idx in [2, 5, 9]: channame = cls.rword(20) nixrc = nixchx.create_source(channame, chantype) nixrc.definition = cls.rsentence(13) nixrc.metadata = nixchx.metadata.create_section( nixrc.name, "neo.channelindex.metadata" ) nixrc.metadata.create_property("index", nixio.Value(idx)) dims = tuple(map(nixio.Value, cls.rquant(3, 1))) nixrc.metadata.create_property("coordinates", dims) nixrc.metadata.create_property("coordinates.units", nixio.Value("um")) nunits = 1 stsperunit = np.array_split(allspiketrains, nunits) for idx in range(nunits): unitname = "{}-unit{}".format(cls.rword(5), idx) nixunit = nixchx.create_source(unitname, "neo.unit") nixunit.definition = cls.rsentence(4, 10) for st in stsperunit[idx]: st.sources.append(nixchx) st.sources.append(nixunit) # pick a few signal groups to reference this CHX randsiggroups = np.random.choice(allsignalgroups, 5, False) for siggroup in randsiggroups: for sig in siggroup: sig.sources.append(nixchx) return nixfile @staticmethod def rdate(): return datetime(year=np.random.randint(1980, 2020), month=np.random.randint(1, 13), day=np.random.randint(1, 29)) @classmethod def populate_dates(cls, obj): obj.file_datetime = cls.rdate() obj.rec_datetime = cls.rdate() @staticmethod def rword(n=10): return "".join(np.random.choice(list(string.ascii_letters), n)) @classmethod def rsentence(cls, n=3, maxwl=10): return " ".join(cls.rword(np.random.randint(1, maxwl)) for _ in range(n)) @classmethod def rdict(cls, nitems): rd = dict() for _ in range(nitems): key = cls.rword() value = cls.rword() if np.random.choice((0, 1)) \ else np.random.uniform() rd[key] = value return rd @staticmethod def rquant(shape, unit, incr=False): try: dim = len(shape) except TypeError: dim = 1 if incr and dim > 1: raise TypeError("Shape of quantity array may only be " "one-dimensional when incremental values are " "requested.") arr = np.random.random(shape) if incr: arr = np.array(np.cumsum(arr)) return arr*unit @classmethod def create_all_annotated(cls): times = cls.rquant(1, pq.s) signal = cls.rquant(1, pq.V) blk = Block() blk.annotate(**cls.rdict(3)) seg = Segment() seg.annotate(**cls.rdict(4)) blk.segments.append(seg) asig = AnalogSignal(signal=signal, sampling_rate=pq.Hz) asig.annotate(**cls.rdict(2)) seg.analogsignals.append(asig) isig = IrregularlySampledSignal(times=times, signal=signal, time_units=pq.s) isig.annotate(**cls.rdict(2)) seg.irregularlysampledsignals.append(isig) epoch = Epoch(times=times, durations=times) epoch.annotate(**cls.rdict(4)) seg.epochs.append(epoch) event = Event(times=times) event.annotate(**cls.rdict(4)) seg.events.append(event) spiketrain = SpikeTrain(times=times, t_stop=pq.s, units=pq.s) d = cls.rdict(6) d["quantity"] = pq.Quantity(10, "mV") d["qarray"] = pq.Quantity(range(10), "mA") spiketrain.annotate(**d) seg.spiketrains.append(spiketrain) chx = ChannelIndex(name="achx", index=[1, 2]) chx.annotate(**cls.rdict(5)) blk.channel_indexes.append(chx) unit = Unit() unit.annotate(**cls.rdict(2)) chx.units.append(unit) return blk class NixIOWriteTest(NixIOTest): def setUp(self): self.filename = "nixio_testfile_write.h5" self.writer = NixIO(self.filename, "ow") self.io = self.writer self.reader = nixio.File.open(self.filename, nixio.FileMode.ReadOnly) def tearDown(self): del self.writer self.reader.close() os.remove(self.filename) def write_and_compare(self, blocks): self.writer.write_all_blocks(blocks) self.compare_blocks(self.writer.read_all_blocks(), self.reader.blocks) def test_block_write(self): block = Block(name=self.rword(), description=self.rsentence()) self.write_and_compare([block]) block.annotate(**self.rdict(5)) self.write_and_compare([block]) def test_segment_write(self): block = Block(name=self.rword()) segment = Segment(name=self.rword(), description=self.rword()) block.segments.append(segment) self.write_and_compare([block]) segment.annotate(**self.rdict(2)) self.write_and_compare([block]) def test_channel_index_write(self): block = Block(name=self.rword()) chx = ChannelIndex(name=self.rword(), description=self.rsentence(), index=[1, 2, 3, 5, 8, 13]) block.channel_indexes.append(chx) self.write_and_compare([block]) chx.annotate(**self.rdict(3)) self.write_and_compare([block]) def test_signals_write(self): block = Block() seg = Segment() block.segments.append(seg) asig = AnalogSignal(signal=self.rquant((10, 3), pq.mV), sampling_rate=pq.Quantity(10, "Hz")) seg.analogsignals.append(asig) self.write_and_compare([block]) anotherblock = Block("ir signal block") seg = Segment("ir signal seg") anotherblock.segments.append(seg) irsig = IrregularlySampledSignal( signal=np.random.random((20, 3)), times=self.rquant(20, pq.ms, True), units=pq.A ) seg.irregularlysampledsignals.append(irsig) self.write_and_compare([anotherblock]) block.segments[0].analogsignals.append( AnalogSignal(signal=[10.0, 1.0, 3.0], units=pq.S, sampling_period=pq.Quantity(3, "s"), dtype=np.double, name="signal42", description="this is an analogsignal", t_start=45 * pq.ms), ) self.write_and_compare([block, anotherblock]) block.segments[0].irregularlysampledsignals.append( IrregularlySampledSignal(times=np.random.random(10), signal=np.random.random((10, 3)), units="mV", time_units="s", dtype=np.float, name="some sort of signal", description="the signal is described") ) self.write_and_compare([block, anotherblock]) def test_epoch_write(self): block = Block() seg = Segment() block.segments.append(seg) epoch = Epoch(times=[1, 1, 10, 3]*pq.ms, durations=[3, 3, 3, 1]*pq.ms, labels=np.array(["one", "two", "three", "four"]), name="test epoch", description="an epoch for testing") seg.epochs.append(epoch) self.write_and_compare([block]) def test_event_write(self): block = Block() seg = Segment() block.segments.append(seg) event = Event(times=np.arange(0, 30, 10)*pq.s, labels=np.array(["0", "1", "2"]), name="event name", description="event description") seg.events.append(event) self.write_and_compare([block]) def test_spiketrain_write(self): block = Block() seg = Segment() block.segments.append(seg) spiketrain = SpikeTrain(times=[3, 4, 5]*pq.s, t_stop=10.0, name="spikes!", description="sssssspikes") seg.spiketrains.append(spiketrain) self.write_and_compare([block]) waveforms = self.rquant((20, 5, 10), pq.mV) spiketrain = SpikeTrain(times=[1, 1.1, 1.2]*pq.ms, t_stop=1.5*pq.s, name="spikes with wf", description="spikes for waveform test", waveforms=waveforms) seg.spiketrains.append(spiketrain) self.write_and_compare([block]) spiketrain.left_sweep = np.random.random(10)*pq.ms self.write_and_compare([block]) def test_metadata_structure_write(self): neoblk = self.create_all_annotated() self.io.write_block(neoblk) blk = self.io.nix_file.blocks[0] blkmd = blk.metadata self.assertEqual(blk.name, blkmd.name) grp = blk.groups[0] # segment self.assertIn(grp.name, blkmd.sections) grpmd = blkmd.sections[grp.name] for da in grp.data_arrays: # signals name = ".".join(da.name.split(".")[:-1]) self.assertIn(name, grpmd.sections) for mtag in grp.multi_tags: # spiketrains, events, and epochs self.assertIn(mtag.name, grpmd.sections) srcchx = blk.sources[0] # chx self.assertIn(srcchx.name, blkmd.sections) for srcunit in blk.sources: # units self.assertIn(srcunit.name, blkmd.sections) self.write_and_compare([neoblk]) def test_anonymous_objects_write(self): nblocks = 2 nsegs = 2 nanasig = 4 nirrseg = 2 nepochs = 3 nevents = 4 nspiketrains = 3 nchx = 5 nunits = 10 times = self.rquant(1, pq.s) signal = self.rquant(1, pq.V) blocks = [] for blkidx in range(nblocks): blk = Block() blocks.append(blk) for segidx in range(nsegs): seg = Segment() blk.segments.append(seg) for anaidx in range(nanasig): seg.analogsignals.append(AnalogSignal(signal=signal, sampling_rate=pq.Hz)) for irridx in range(nirrseg): seg.irregularlysampledsignals.append( IrregularlySampledSignal(times=times, signal=signal, time_units=pq.s) ) for epidx in range(nepochs): seg.epochs.append(Epoch(times=times, durations=times)) for evidx in range(nevents): seg.events.append(Event(times=times)) for stidx in range(nspiketrains): seg.spiketrains.append(SpikeTrain(times=times, t_stop=pq.s, units=pq.s)) for chidx in range(nchx): chx = ChannelIndex(name="chx{}".format(chidx), index=[1, 2]) blk.channel_indexes.append(chx) for unidx in range(nunits): unit = Unit() chx.units.append(unit) self.writer.write_all_blocks(blocks) self.compare_blocks(blocks, self.reader.blocks) def test_to_value(self): section = self.io.nix_file.create_section("Metadata value test", "Test") writeprop = self.io._write_property # quantity qvalue = pq.Quantity(10, "mV") writeprop(section, "qvalue", qvalue) self.assertEqual(section["qvalue"], 10) self.assertEqual(section.props["qvalue"].unit, "mV") # datetime dt = self.rdate() writeprop(section, "dt", dt) self.assertEqual(datetime.fromtimestamp(section["dt"]), dt) # string randstr = self.rsentence() writeprop(section, "randstr", randstr) self.assertEqual(section["randstr"], randstr) # bytes bytestring = b"bytestring" writeprop(section, "randbytes", bytestring) self.assertEqual(section["randbytes"], bytestring.decode()) # iterables randlist = np.random.random(10).tolist() writeprop(section, "randlist", randlist) self.assertEqual(randlist, section["randlist"]) randarray = np.random.random(10) writeprop(section, "randarray", randarray) np.testing.assert_almost_equal(randarray, section["randarray"]) # numpy item npval = np.float64(2398) writeprop(section, "npval", npval) self.assertEqual(npval, section["npval"]) # number val = 42 writeprop(section, "val", val) self.assertEqual(val, section["val"]) # multi-dimensional data -- UNSUPORTED # mdlist = [[1, 2, 3], [4, 5, 6]] # writeprop(section, "mdlist", mdlist) # mdarray = np.random.random((10, 3)) # writeprop(section, "mdarray", mdarray) class NixIOReadTest(NixIOTest): filename = "testfile_readtest.h5" nixfile = None nix_blocks = None original_methods = dict() @classmethod def setUpClass(cls): if HAVE_NIX: cls.nixfile = cls.create_full_nix_file(cls.filename) def setUp(self): self.io = NixIO(self.filename, "ro") self.original_methods["_read_cascade"] = self.io._read_cascade self.original_methods["_update_maps"] = self.io._update_maps @classmethod def tearDownClass(cls): if HAVE_NIX: cls.nixfile.close() def tearDown(self): del self.io def test_all_read(self): neo_blocks = self.io.read_all_blocks(cascade=True, lazy=False) nix_blocks = self.io.nix_file.blocks self.compare_blocks(neo_blocks, nix_blocks) def test_lazyload_fullcascade_read(self): neo_blocks = self.io.read_all_blocks(cascade=True, lazy=True) nix_blocks = self.io.nix_file.blocks # data objects should be empty for block in neo_blocks: for seg in block.segments: for asig in seg.analogsignals: self.assertEqual(len(asig), 0) for isig in seg.irregularlysampledsignals: self.assertEqual(len(isig), 0) for epoch in seg.epochs: self.assertEqual(len(epoch), 0) for event in seg.events: self.assertEqual(len(event), 0) for st in seg.spiketrains: self.assertEqual(len(st), 0) self.compare_blocks(neo_blocks, nix_blocks) def test_lazyload_lazycascade_read(self): neo_blocks = self.io.read_all_blocks(cascade="lazy", lazy=True) nix_blocks = self.io.nix_file.blocks self.compare_blocks(neo_blocks, nix_blocks) def test_lazycascade_read(self): def getitem(self, index): return self._data.__getitem__(index) from neo.io.nixio import LazyList getitem_original = LazyList.__getitem__ LazyList.__getitem__ = getitem neo_blocks = self.io.read_all_blocks(cascade="lazy", lazy=False) for block in neo_blocks: self.assertIsInstance(block.segments, LazyList) self.assertIsInstance(block.channel_indexes, LazyList) for seg in block.segments: self.assertIsInstance(seg, string_types) for chx in block.channel_indexes: self.assertIsInstance(chx, string_types) LazyList.__getitem__ = getitem_original def test_load_lazy_cascade(self): from neo.io.nixio import LazyList neo_blocks = self.io.read_all_blocks(cascade="lazy", lazy=False) for block in neo_blocks: self.assertIsInstance(block.segments, LazyList) self.assertIsInstance(block.channel_indexes, LazyList) name = block.name block = self.io.load_lazy_cascade("/" + name, lazy=False) self.assertIsInstance(block.segments, list) self.assertIsInstance(block.channel_indexes, list) for seg in block.segments: self.assertIsInstance(seg.analogsignals, list) self.assertIsInstance(seg.irregularlysampledsignals, list) self.assertIsInstance(seg.epochs, list) self.assertIsInstance(seg.events, list) self.assertIsInstance(seg.spiketrains, list) def test_nocascade_read(self): self.io._read_cascade = mock.Mock() neo_blocks = self.io.read_all_blocks(cascade=False) self.io._read_cascade.assert_not_called() for block in neo_blocks: self.assertEqual(len(block.segments), 0) nix_block = self.io.nix_file.blocks[block.name] self.compare_attr(block, nix_block) def test_lazy_load_subschema(self): blk = self.io.nix_file.blocks[0] segpath = "/" + blk.name + "/segments/" + blk.groups[0].name segment = self.io.load_lazy_cascade(segpath, lazy=True) self.assertIsInstance(segment, Segment) self.assertEqual(segment.name, blk.groups[0].name) self.assertIs(segment.block, None) self.assertEqual(len(segment.analogsignals[0]), 0) segment = self.io.load_lazy_cascade(segpath, lazy=False) self.assertEqual(np.shape(segment.analogsignals[0]), (100, 3)) class NixIOHashTest(NixIOTest): def setUp(self): self.hash = NixIO._hash_object def _hash_test(self, objtype, argfuncs): attr = {} for arg, func in argfuncs.items(): attr[arg] = func() obj_one = objtype(**attr) obj_two = objtype(**attr) hash_one = self.hash(obj_one) hash_two = self.hash(obj_two) self.assertEqual(hash_one, hash_two) for arg, func in argfuncs.items(): chattr = attr.copy() chattr[arg] = func() obj_two = objtype(**chattr) hash_two = self.hash(obj_two) self.assertNotEqual( hash_one, hash_two, "Hash test failed with different '{}'".format(arg) ) def test_block_seg_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "rec_datetime": self.rdate, "file_datetime": self.rdate, # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(Block, argfuncs) self._hash_test(Segment, argfuncs) self._hash_test(Unit, argfuncs) def test_chx_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "index": lambda: np.random.random(10).tolist(), "channel_names": lambda: self.rsentence(10).split(" "), "coordinates": lambda: [(np.random.random() * pq.cm, np.random.random() * pq.cm, np.random.random() * pq.cm)]*10, # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(ChannelIndex, argfuncs) def test_analogsignal_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "signal": lambda: self.rquant((10, 10), pq.mV), "sampling_rate": lambda: np.random.random() * pq.Hz, "t_start": lambda: np.random.random() * pq.sec, "t_stop": lambda: np.random.random() * pq.sec, # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(AnalogSignal, argfuncs) def test_irregularsignal_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "signal": lambda: self.rquant((10, 10), pq.mV), "times": lambda: self.rquant(10, pq.ms, True), # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(IrregularlySampledSignal, argfuncs) def test_event_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "times": lambda: self.rquant(10, pq.ms), "durations": lambda: self.rquant(10, pq.ms), "labels": lambda: self.rsentence(10).split(" "), # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(Event, argfuncs) self._hash_test(Epoch, argfuncs) def test_spiketrain_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, "times": lambda: self.rquant(10, pq.ms, True), "t_start": lambda: -np.random.random() * pq.sec, "t_stop": lambda: np.random.random() * 100 * pq.sec, "waveforms": lambda: self.rquant((10, 10, 20), pq.mV), # annotations self.rword(): self.rword, self.rword(): lambda: self.rquant((10, 10), pq.mV)} self._hash_test(SpikeTrain, argfuncs) class NixIOPartialWriteTest(NixIOTest): filename = "testfile_partialwrite.h5" nixfile = None neo_blocks = None original_methods = dict() @classmethod def setUpClass(cls): if HAVE_NIX: cls.nixfile = cls.create_full_nix_file(cls.filename) def setUp(self): self.io = NixIO(self.filename, "rw") self.neo_blocks = self.io.read_all_blocks() self.original_methods["_write_attr_annotations"] =\ self.io._write_attr_annotations @classmethod def tearDownClass(cls): if HAVE_NIX: cls.nixfile.close() def tearDown(self): self.restore_methods() del self.io def restore_methods(self): for name, method in self.original_methods.items(): setattr(self.io, name, self.original_methods[name]) def _mock_write_attr(self, objclass): typestr = str(objclass.__name__).lower() self.io._write_attr_annotations = mock.Mock( wraps=self.io._write_attr_annotations, side_effect=self.check_obj_type("neo.{}".format(typestr)) ) neo_blocks = self.neo_blocks self.modify_objects(neo_blocks, excludes=[objclass]) self.io.write_all_blocks(neo_blocks) self.restore_methods() def check_obj_type(self, typestring): neq = self.assertNotEqual def side_effect_func(*args, **kwargs): obj = kwargs.get("nixobj", args[0]) if isinstance(obj, list): for sig in obj: neq(sig.type, typestring) else: neq(obj.type, typestring) return side_effect_func @classmethod def modify_objects(cls, objs, excludes=()): excludes = tuple(excludes) for obj in objs: if not (excludes and isinstance(obj, excludes)): obj.description = cls.rsentence() for container in getattr(obj, "_child_containers", []): children = getattr(obj, container) cls.modify_objects(children, excludes) def test_partial(self): for objclass in NixIO.supported_objects: self._mock_write_attr(objclass) self.compare_blocks(self.neo_blocks, self.io.nix_file.blocks) def test_no_modifications(self): self.io._write_attr_annotations = mock.Mock() self.io.write_all_blocks(self.neo_blocks) self.io._write_attr_annotations.assert_not_called() self.compare_blocks(self.neo_blocks, self.io.nix_file.blocks) # clearing hashes and checking again for k in self.io._object_hashes.keys(): self.io._object_hashes[k] = None self.io.write_all_blocks(self.neo_blocks) self.io._write_attr_annotations.assert_not_called() # changing hashes to force rewrite for k in self.io._object_hashes.keys(): self.io._object_hashes[k] = "_" self.io.write_all_blocks(self.neo_blocks) callcount = self.io._write_attr_annotations.call_count self.assertEqual(callcount, len(self.io._object_hashes)) self.compare_blocks(self.neo_blocks, self.io.nix_file.blocks) @unittest.skipUnless(HAVE_NIX, "Requires NIX") class CommonTests(BaseTestIO, unittest.TestCase): ioclass = NixIO
[((47, 1, 47, 46), 'unittest.skipUnless', 'unittest.skipUnless', ({(47, 21, 47, 29): 'HAVE_NIX', (47, 31, 47, 45): '"""Requires NIX"""'}, {}), "(HAVE_NIX, 'Requires NIX')", False, 'import unittest\n'), ((1160, 1, 1160, 46), 'unittest.skipUnless', 'unittest.skipUnless', ({(1160, 21, 1160, 29): 'HAVE_NIX', (1160, 31, 1160, 45): '"""Requires NIX"""'}, {}), "(HAVE_NIX, 'Requires NIX')", False, 'import unittest\n'), ((222, 8, 222, 77), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(222, 39, 222, 60): 'epoch.times.magnitude', (222, 62, 222, 76): 'mtag.positions'}, {}), '(epoch.times.magnitude, mtag.positions)', True, 'import numpy as np\n'), ((224, 8, 224, 79), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(224, 39, 224, 64): 'epoch.durations.magnitude', (224, 66, 224, 78): 'mtag.extents'}, {}), '(epoch.durations.magnitude, mtag.extents)', True, 'import numpy as np\n'), ((241, 8, 241, 77), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(241, 39, 241, 60): 'event.times.magnitude', (241, 62, 241, 76): 'mtag.positions'}, {}), '(event.times.magnitude, mtag.positions)', True, 'import numpy as np\n'), ((256, 8, 257, 54), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(256, 39, 256, 65): 'spiketrain.times.magnitude', (257, 39, 257, 53): 'mtag.positions'}, {}), '(spiketrain.times.magnitude, mtag.positions)', True, 'import numpy as np\n'), ((297, 18, 297, 69), 'nixio.File.open', 'nixio.File.open', ({(297, 34, 297, 42): 'filename', (297, 44, 297, 68): 'nixio.FileMode.Overwrite'}, {}), '(filename, nixio.FileMode.Overwrite)', False, 'import nixio\n'), ((499, 21, 499, 59), 'numpy.array_split', 'np.array_split', ({(499, 36, 499, 50): 'allspiketrains', (499, 52, 499, 58): 'nunits'}, {}), '(allspiketrains, nunits)', True, 'import numpy as np\n'), ((509, 24, 509, 67), 'numpy.random.choice', 'np.random.choice', ({(509, 41, 509, 56): 'allsignalgroups', (509, 58, 509, 59): '5', (509, 61, 509, 66): 'False'}, {}), '(allsignalgroups, 5, False)', True, 'import numpy as np\n'), ((556, 14, 556, 37), 'numpy.random.random', 'np.random.random', ({(556, 31, 556, 36): 'shape'}, {}), '(shape)', True, 'import numpy as np\n'), ((565, 14, 565, 21), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((568, 14, 568, 23), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((572, 15, 572, 63), 'neo.core.AnalogSignal', 'AnalogSignal', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((576, 15, 577, 56), 'neo.core.IrregularlySampledSignal', 'IrregularlySampledSignal', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((581, 16, 581, 51), 'neo.core.Epoch', 'Epoch', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((585, 16, 585, 34), 'neo.core.Event', 'Event', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((589, 21, 589, 69), 'neo.core.SpikeTrain', 'SpikeTrain', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((591, 24, 591, 45), 'quantities.Quantity', 'pq.Quantity', ({(591, 36, 591, 38): '10', (591, 40, 591, 44): '"""mV"""'}, {}), "(10, 'mV')", True, 'import quantities as pq\n'), ((596, 14, 596, 53), 'neo.core.ChannelIndex', 'ChannelIndex', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((600, 15, 600, 21), 'neo.core.Unit', 'Unit', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((611, 22, 611, 48), 'neo.io.nixio.NixIO', 'NixIO', ({(611, 28, 611, 41): 'self.filename', (611, 43, 611, 47): '"""ow"""'}, {}), "(self.filename, 'ow')", False, 'from neo.io.nixio import NixIO\n'), ((613, 22, 614, 62), 'nixio.File.open', 'nixio.File.open', ({(613, 38, 613, 51): 'self.filename', (614, 38, 614, 61): 'nixio.FileMode.ReadOnly'}, {}), '(self.filename, nixio.FileMode.ReadOnly)', False, 'import nixio\n'), ((619, 8, 619, 32), 'os.remove', 'os.remove', ({(619, 18, 619, 31): 'self.filename'}, {}), '(self.filename)', False, 'import os\n'), ((654, 16, 654, 23), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((655, 14, 655, 23), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((663, 23, 663, 47), 'neo.core.Block', 'Block', ({(663, 29, 663, 46): '"""ir signal block"""'}, {}), "('ir signal block')", False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((664, 14, 664, 38), 'neo.core.Segment', 'Segment', ({(664, 22, 664, 37): '"""ir signal seg"""'}, {}), "('ir signal seg')", False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((694, 16, 694, 23), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((695, 14, 695, 23), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((706, 16, 706, 23), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((707, 14, 707, 23), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((718, 16, 718, 23), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((719, 14, 719, 23), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((722, 21, 723, 74), 'neo.core.SpikeTrain', 'SpikeTrain', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((728, 21, 731, 52), 'neo.core.SpikeTrain', 'SpikeTrain', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((816, 17, 816, 38), 'quantities.Quantity', 'pq.Quantity', ({(816, 29, 816, 31): '10', (816, 33, 816, 37): '"""mV"""'}, {}), "(10, 'mV')", True, 'import quantities as pq\n'), ((841, 20, 841, 40), 'numpy.random.random', 'np.random.random', ({(841, 37, 841, 39): '10'}, {}), '(10)', True, 'import numpy as np\n'), ((843, 8, 843, 71), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(843, 39, 843, 48): 'randarray', (843, 50, 843, 70): "section['randarray']"}, {}), "(randarray, section['randarray'])", True, 'import numpy as np\n'), ((846, 16, 846, 32), 'numpy.float64', 'np.float64', ({(846, 27, 846, 31): '2398'}, {}), '(2398)', True, 'import numpy as np\n'), ((877, 18, 877, 44), 'neo.io.nixio.NixIO', 'NixIO', ({(877, 24, 877, 37): 'self.filename', (877, 39, 877, 43): '"""ro"""'}, {}), "(self.filename, 'ro')", False, 'from neo.io.nixio import NixIO\n'), ((951, 32, 951, 43), 'mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'import mock\n'), ((1082, 18, 1082, 44), 'neo.io.nixio.NixIO', 'NixIO', ({(1082, 24, 1082, 37): 'self.filename', (1082, 39, 1082, 43): '"""rw"""'}, {}), "(self.filename, 'rw')", False, 'from neo.io.nixio import NixIO\n'), ((1139, 42, 1139, 53), 'mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'import mock\n'), ((162, 23, 162, 40), 'itertools.count', 'itertools.count', ({}, {}), '()', False, 'import itertools\n'), ((168, 22, 168, 35), 'numpy.shape', 'np.shape', ({(168, 31, 168, 34): 'sig'}, {}), '(sig)', True, 'import numpy as np\n'), ((183, 27, 183, 47), 'numpy.transpose', 'np.transpose', ({(183, 40, 183, 46): 'neosig'}, {}), '(neosig)', True, 'import numpy as np\n'), ((186, 12, 186, 61), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(186, 43, 186, 56): 'sig.magnitude', (186, 58, 186, 60): 'da'}, {}), '(sig.magnitude, da)', True, 'import numpy as np\n'), ((263, 12, 263, 66), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(263, 43, 263, 58): 'neowf.magnitude', (263, 60, 263, 65): 'nixwf'}, {}), '(neowf.magnitude, nixwf)', True, 'import numpy as np\n'), ((736, 32, 736, 52), 'numpy.random.random', 'np.random.random', ({(736, 49, 736, 51): '(10)'}, {}), '(10)', True, 'import numpy as np\n'), ((780, 18, 780, 25), 'neo.core.Block', 'Block', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((824, 25, 824, 62), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', ({(824, 48, 824, 61): "section['dt']"}, {}), "(section['dt'])", False, 'from datetime import datetime\n'), ((968, 25, 968, 59), 'numpy.shape', 'np.shape', ({(968, 34, 968, 58): 'segment.analogsignals[0]'}, {}), '(segment.analogsignals[0])', True, 'import numpy as np\n'), ((261, 29, 261, 44), 'numpy.shape', 'np.shape', ({(261, 38, 261, 43): 'neowf'}, {}), '(neowf)', True, 'import numpy as np\n'), ((261, 46, 261, 61), 'numpy.shape', 'np.shape', ({(261, 55, 261, 60): 'nixwf'}, {}), '(nixwf)', True, 'import numpy as np\n'), ((279, 29, 279, 70), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', ({(279, 52, 279, 69): 'nixobj.created_at'}, {}), '(nixobj.created_at)', False, 'from datetime import datetime\n'), ((282, 29, 283, 66), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', ({(283, 33, 283, 65): "nixobj.metadata['file_datetime']"}, {}), "(nixobj.metadata['file_datetime'])", False, 'from datetime import datetime\n'), ((492, 52, 492, 68), 'nixio.Value', 'nixio.Value', ({(492, 64, 492, 67): 'idx'}, {}), '(idx)', False, 'import nixio\n'), ((496, 43, 496, 60), 'nixio.Value', 'nixio.Value', ({(496, 55, 496, 59): '"""um"""'}, {}), "('um')", False, 'import nixio\n'), ((518, 29, 518, 58), 'numpy.random.randint', 'np.random.randint', ({(518, 47, 518, 51): '(1980)', (518, 53, 518, 57): '(2020)'}, {}), '(1980, 2020)', True, 'import numpy as np\n'), ((519, 30, 519, 54), 'numpy.random.randint', 'np.random.randint', ({(519, 48, 519, 49): '(1)', (519, 51, 519, 53): '(13)'}, {}), '(1, 13)', True, 'import numpy as np\n'), ((520, 28, 520, 52), 'numpy.random.randint', 'np.random.randint', ({(520, 46, 520, 47): '(1)', (520, 49, 520, 51): '(29)'}, {}), '(1, 29)', True, 'import numpy as np\n'), ((541, 35, 541, 59), 'numpy.random.choice', 'np.random.choice', ({(541, 52, 541, 58): '(0, 1)'}, {}), '((0, 1))', True, 'import numpy as np\n'), ((542, 21, 542, 40), 'numpy.random.uniform', 'np.random.uniform', ({}, {}), '()', True, 'import numpy as np\n'), ((558, 27, 558, 41), 'numpy.cumsum', 'np.cumsum', ({(558, 37, 558, 40): 'arr'}, {}), '(arr)', True, 'import numpy as np\n'), ((659, 42, 659, 63), 'quantities.Quantity', 'pq.Quantity', ({(659, 54, 659, 56): '10', (659, 58, 659, 62): '"""Hz"""'}, {}), "(10, 'Hz')", True, 'import quantities as pq\n'), ((667, 19, 667, 44), 'numpy.random.random', 'np.random.random', ({(667, 36, 667, 43): '(20, 3)'}, {}), '((20, 3))', True, 'import numpy as np\n'), ((699, 29, 699, 70), 'numpy.array', 'np.array', ({(699, 38, 699, 69): "['one', 'two', 'three', 'four']"}, {}), "(['one', 'two', 'three', 'four'])", True, 'import numpy as np\n'), ((711, 29, 711, 54), 'numpy.array', 'np.array', ({(711, 38, 711, 53): "['0', '1', '2']"}, {}), "(['0', '1', '2'])", True, 'import numpy as np\n'), ((783, 22, 783, 31), 'neo.core.Segment', 'Segment', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((837, 19, 837, 39), 'numpy.random.random', 'np.random.random', ({(837, 36, 837, 38): '10'}, {}), '(10)', True, 'import numpy as np\n'), ((192, 20, 192, 72), 'quantities.Quantity', 'pq.Quantity', ({(192, 32, 192, 57): 'timedim.sampling_interval', (192, 59, 192, 71): 'timedim.unit'}, {}), '(timedim.sampling_interval, timedim.unit)', True, 'import quantities as pq\n'), ((201, 16, 202, 61), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', ({(201, 47, 201, 69): 'neosig.times.magnitude', (202, 47, 202, 60): 'timedim.ticks'}, {}), '(neosig.times.magnitude, timedim.ticks)', True, 'import numpy as np\n'), ((533, 34, 533, 61), 'numpy.random.randint', 'np.random.randint', ({(533, 52, 533, 53): '(1)', (533, 55, 533, 60): 'maxwl'}, {}), '(1, maxwl)', True, 'import numpy as np\n'), ((676, 41, 676, 60), 'quantities.Quantity', 'pq.Quantity', ({(676, 53, 676, 54): '(3)', (676, 56, 676, 59): '"""s"""'}, {}), "(3, 's')", True, 'import quantities as pq\n'), ((684, 43, 684, 63), 'numpy.random.random', 'np.random.random', ({(684, 60, 684, 62): '(10)'}, {}), '(10)', True, 'import numpy as np\n'), ((685, 44, 685, 69), 'numpy.random.random', 'np.random.random', ({(685, 61, 685, 68): '(10, 3)'}, {}), '((10, 3))', True, 'import numpy as np\n'), ((710, 28, 710, 48), 'numpy.arange', 'np.arange', ({(710, 38, 710, 39): '0', (710, 41, 710, 43): '30', (710, 45, 710, 47): '10'}, {}), '(0, 30, 10)', True, 'import numpy as np\n'), ((806, 27, 806, 33), 'neo.core.Unit', 'Unit', ({}, {}), '()', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((1026, 45, 1026, 63), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1027, 39, 1027, 57), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1028, 38, 1028, 56), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((420, 43, 420, 58), 'nixio.Value', 'nixio.Value', ({(420, 55, 420, 57): '(20)'}, {}), '(20)', False, 'import nixio\n'), ((786, 45, 787, 78), 'neo.core.AnalogSignal', 'AnalogSignal', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((790, 24, 792, 65), 'neo.core.IrregularlySampledSignal', 'IrregularlySampledSignal', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((795, 38, 795, 73), 'neo.core.Epoch', 'Epoch', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((797, 38, 797, 56), 'neo.core.Event', 'Event', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((799, 43, 800, 65), 'neo.core.SpikeTrain', 'SpikeTrain', (), '', False, 'from neo.core import Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch\n'), ((1012, 37, 1012, 57), 'numpy.random.random', 'np.random.random', ({(1012, 54, 1012, 56): '(10)'}, {}), '(10)', True, 'import numpy as np\n'), ((1060, 40, 1060, 58), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1061, 38, 1061, 56), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1014, 45, 1014, 63), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1015, 45, 1015, 63), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n'), ((1016, 45, 1016, 63), 'numpy.random.random', 'np.random.random', ({}, {}), '()', True, 'import numpy as np\n')]
taudata-indonesia/elearning
lib/taudataNlpTm.py
6f9db8b829357cde1ae678255cc251629dfc25d2
# -*- coding: utf-8 -*- """ Created on Wed Mar 28 11:25:43 2019 @author: Taufik Sutanto [email protected] https://tau-data.id ~~Perjanjian Penggunaan Materi & Codes (PPMC) - License:~~ * Modul Python dan gambar-gambar (images) yang digunakan adalah milik dari berbagai sumber sebagaimana yang telah dicantumkan dalam masing-masing license modul, caption atau watermark. * Materi & Codes diluar point (1) (i.e. code ini & semua slide ".ipynb)) yang digunakan di tau-data dapat digunakan untuk keperluan akademis dan kegiatan non-komersil lainnya. * Untuk keperluan diluar point (2), maka dibutuhkan izin tertulis dari Taufik Edy Sutanto (selanjutnya disebut sebagai pengarang). * Materi & Codes tidak boleh dipublikasikan tanpa izin dari pengarang. * Materi & codes diberikan "as-is", tanpa warranty. Pengarang tidak bertanggung jawab atas penggunaannya diluar kegiatan resmi yang dilaksanakan pengarang. * Dengan menggunakan materi dan codes ini berarti pengguna telah menyetujui PPMC ini. """ import re, numpy as np import itertools, nltk from collections import Counter from nltk.corpus import wordnet as wn from nltk.stem import PorterStemmer;ps = PorterStemmer() from itertools import chain import warnings; warnings.simplefilter('ignore') def lesk_wsd(sentence, ambiguous_word, pos=None, stem=True, hyperhypo=True): # https://en.wikipedia.org/wiki/Lesk_algorithm # https://stackoverflow.com/questions/20896278/word-sense-disambiguation-algorithm-in-python max_overlaps = 0; lesk_sense = None context_sentence = sentence.split() for ss in wn.synsets(ambiguous_word): #break if pos and ss.pos is not pos: # If POS is specified. continue lesk_dictionary = [] lesk_dictionary+= ss.definition().replace('(','').replace(')','').split() # Includes definition. lesk_dictionary+= ss.lemma_names() # Includes lemma_names. # Optional: includes lemma_names of hypernyms and hyponyms. if hyperhypo == True: lesk_dictionary+= list(chain(*[i.lemma_names() for i in ss.hypernyms()+ss.hyponyms()])) if stem == True: # Matching exact words causes sparsity, so lets match stems. lesk_dictionary = [ps.stem(i) for i in lesk_dictionary] context_sentence = [ps.stem(i) for i in context_sentence] overlaps = set(lesk_dictionary).intersection(context_sentence) if len(overlaps) > max_overlaps: lesk_sense = ss max_overlaps = len(overlaps) return lesk_sense.name() def words(text): return re.findall(r'\w+', text.lower()) corpus = 'data/corpus_sederhana.txt' WORDS = Counter(words(open(corpus).read())) def P(word): "Probability of `word`." N=sum(WORDS.values()) return WORDS[word] / N def correction(word): "Most probable spelling correction for word." return max(candidates(word), key=P) def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word]) def known(words): "The subset of `words` that appear in the dictionary of WORDS." return set(w for w in words if w in WORDS) def edits1(word): "All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) def edits2(word): "All edits that are two edits away from `word`." return (e2 for e1 in edits1(word) for e2 in edits1(e1)) def get_nMax(arr, n): indices = arr.ravel().argsort()[-n:] indices = (np.unravel_index(i, arr.shape) for i in indices) return [(arr[i], i) for i in indices] def filter_for_tags(tagged, tags=['NN', 'JJ', 'NNP']): return [item for item in tagged if item[1] in tags] def normalize(tagged): return [(item[0].replace('.', ''), item[1]) for item in tagged] def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in itertools.ifilterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element def lDistance(firstString, secondString): "Function to find the Levenshtein distance between two words/sentences - gotten from http://rosettacode.org/wiki/Levenshtein_distance#Python" if len(firstString) > len(secondString): firstString, secondString = secondString, firstString distances = range(len(firstString) + 1) for index2, char2 in enumerate(secondString): newDistances = [index2 + 1] for index1, char1 in enumerate(firstString): if char1 == char2: newDistances.append(distances[index1]) else: newDistances.append(1 + min((distances[index1], distances[index1+1], newDistances[-1]))) distances = newDistances return distances[-1]
[((21, 41, 21, 56), 'nltk.stem.PorterStemmer', 'PorterStemmer', ({}, {}), '()', False, 'from nltk.stem import PorterStemmer\n'), ((23, 17, 23, 48), 'warnings.simplefilter', 'warnings.simplefilter', ({(23, 39, 23, 47): '"""ignore"""'}, {}), "('ignore')", False, 'import warnings\n'), ((30, 14, 30, 40), 'nltk.corpus.wordnet.synsets', 'wn.synsets', ({(30, 25, 30, 39): 'ambiguous_word'}, {}), '(ambiguous_word)', True, 'from nltk.corpus import wordnet as wn\n'), ((90, 15, 90, 45), 'numpy.unravel_index', 'np.unravel_index', ({(90, 32, 90, 33): 'i', (90, 35, 90, 44): 'arr.shape'}, {}), '(i, arr.shape)', True, 'import re, numpy as np\n'), ((106, 23, 106, 74), 'itertools.ifilterfalse', 'itertools.ifilterfalse', ({(106, 46, 106, 63): 'seen.__contains__', (106, 65, 106, 73): 'iterable'}, {}), '(seen.__contains__, iterable)', False, 'import itertools, nltk\n')]
Eve-ning/reamber_base_py
reamber/base/MapSet.py
6d19c84f2c110b60e633b82b73e0516396466f56
from __future__ import annotations from copy import deepcopy from dataclasses import dataclass, field from typing import List, Iterator, TypeVar, Union, Any, Generic import pandas as pd from pandas.core.indexing import _LocIndexer from reamber.base.Map import Map from reamber.base.Property import stack_props NoteListT = TypeVar('NoteListT') HitListT = TypeVar('HitListT') HoldListT = TypeVar('HoldListT') BpmListT = TypeVar('BpmListT') MapT = TypeVar('MapT') @dataclass class MapSet(Generic[NoteListT, HitListT, HoldListT, BpmListT, MapT]): maps: List[MapT[NoteListT, HitListT, HoldListT, BpmListT]] = field(default_factory=lambda: []) def __init__(self, maps: List[MapT[NoteListT, HitListT, HoldListT, BpmListT]]): self.maps = maps def __iter__(self) -> Iterator[MapT]: for m in self.maps: yield m def items(self): for m in self.maps: yield m.__class__, m def __getitem__(self, item: Union[Any, type]): if isinstance(item, type): # We want to index by type. return [m[item][0] for m in self.maps] else: # We want to index by slice/int/etc. return self.maps[item] def __setitem__(self, key: Union[Any, type], value): this = self[key] assert len(this) == len(value), "The lengths of the set and get must be the same." for i in range(len(this)): this[i] = value[i] def deepcopy(self): """ Returns a deep copy of itself """ return deepcopy(self) def describe(self, rounding: int = 2, unicode: bool = False) -> List[str]: """ Describes the map's attributes as a short summary :param rounding: The decimal rounding :param unicode: Whether to attempt to get the non-unicode or unicode. \ Doesn't attempt to translate. """ return [m.describe(rounding=rounding, unicode=unicode, s=self) for m in self] def rate(self, by: float) -> MapSet: """ Changes the rate of the map. Note that you need to do rate on the mapset to affect BPM. :param by: The value to rate it by. 1.1x speeds up the song by 10%. Hence 10/11 of the length. """ copy = self.deepcopy() copy.maps = [m.rate(by=by) for m in copy.maps] return copy # noinspection DuplicatedCode,PyUnresolvedReferences @stack_props() class Stacker: """ This purpose of this class is to provide unnamed access to the lists. This can make code much shorter as we don't have to deal with keyed dicts. For example, >>> m = Map.stack() >>> m.offset *= 2 Or if you do it inline, >>> m.stack().lengths *= 2 This will change the offsets of all lists that have the offset property. This will change the map itself, as stack is a reference This also is a "naive" system, so if the property, like column, doesn't exist for Bpms, it will not break it. However, all properties must exist at least once. If the property isn't listed here, you can do string indexing For example, >>> m = Map.stack() >>> m.other_property *= 2 """ """ How does this work? Firstly, if you concat a list of dfs, pd will always make a copy, so you have to preserve the original dfs and also the stacked. LISTS ---STACK---> COPY ---> STACKED +---------- REFERENCE ---> UNSTACKED The reason for stacking is so that we don't have to loop through all dfs to mutate. If we did loop through the dfs, we have to stack them anyways, so it's as efficient. However, it's just easier, by my eyes, to stack then attempt to mutate. So, we keep 2 things in check, the unstacked, and the stacked. However, we only can mutate the stacked one, then convert to the unstacked, because the unstacked is the referenced. Hence, we keep track of what partitions of the unstacked are each of the stacked. IXS | | | | | UNSTACKED [........] [........] [..] [....] STACKED [...............................] That's where ixs come in to help in converting the stacked values to unstacked. So the workflow is that when we retrieve a value, it's always from the stacked. Then, when it's mutated, it can be set and it will always call the _update to update the referenced unstacked. """ stackers: List[Map.Stacker] # noinspection PyProtectedMember def __init__(self, stackers: List[Map.Stacker]): self.stackers = stackers def __getitem__(self, item): return pd.DataFrame([i[item] for i in self.stackers]) def __setitem__(self, key, value): for s, i in zip(self.stackers, value.iloc): s[key] = i _props = ['offset', 'column', 'length', 'bpm', 'metronome'] def stack(self, include: List[str] = None): """ This creates a mutator for this instance, see Mutator for details. """ return self.Stacker([_.stack(include) for _ in self])
[((13, 12, 13, 32), 'typing.TypeVar', 'TypeVar', ({(13, 20, 13, 31): '"""NoteListT"""'}, {}), "('NoteListT')", False, 'from typing import List, Iterator, TypeVar, Union, Any, Generic\n'), ((14, 11, 14, 30), 'typing.TypeVar', 'TypeVar', ({(14, 19, 14, 29): '"""HitListT"""'}, {}), "('HitListT')", False, 'from typing import List, Iterator, TypeVar, Union, Any, Generic\n'), ((15, 12, 15, 32), 'typing.TypeVar', 'TypeVar', ({(15, 20, 15, 31): '"""HoldListT"""'}, {}), "('HoldListT')", False, 'from typing import List, Iterator, TypeVar, Union, Any, Generic\n'), ((16, 11, 16, 30), 'typing.TypeVar', 'TypeVar', ({(16, 19, 16, 29): '"""BpmListT"""'}, {}), "('BpmListT')", False, 'from typing import List, Iterator, TypeVar, Union, Any, Generic\n'), ((17, 7, 17, 22), 'typing.TypeVar', 'TypeVar', ({(17, 15, 17, 21): '"""MapT"""'}, {}), "('MapT')", False, 'from typing import List, Iterator, TypeVar, Union, Any, Generic\n'), ((23, 65, 23, 98), 'dataclasses.field', 'field', (), '', False, 'from dataclasses import dataclass, field\n'), ((73, 5, 73, 18), 'reamber.base.Property.stack_props', 'stack_props', ({}, {}), '()', False, 'from reamber.base.Property import stack_props\n'), ((51, 15, 51, 29), 'copy.deepcopy', 'deepcopy', ({(51, 24, 51, 28): 'self'}, {}), '(self)', False, 'from copy import deepcopy\n'), ((142, 19, 142, 65), 'pandas.DataFrame', 'pd.DataFrame', ({(142, 32, 142, 64): '[i[item] for i in self.stackers]'}, {}), '([i[item] for i in self.stackers])', True, 'import pandas as pd\n')]
uwmisl/poretitioner
src/poretitioner/utils/filtering.py
0ff9f67a3b25fdcb460b11c970b2ed366da07da7
""" ========= filtering.py ========= This module provides more granular filtering for captures. You can customize your own filters too. """ from __future__ import annotations import re from abc import ABC, ABCMeta, abstractmethod from dataclasses import dataclass from json import JSONEncoder from pathlib import PosixPath from typing import ( Any, Dict, Iterable, Mapping, NewType, Optional, Protocol, Type, TypedDict, Union, ) import h5py import numpy as np from h5py import File as Fast5File from ..hdf5 import ( HasFast5, HDF5_Group, HDF5_GroupSerialableDataclass, HDF5_GroupSerializable, HDF5_GroupSerializing, IsAttr, ) from ..logger import Logger, getLogger from ..signals import Capture from .core import NumpyArrayLike, PathLikeOrString, ReadId, stripped_by_keys from .plugin import Plugin CaptureOrTimeSeries = Union[Capture, NumpyArrayLike] # Unique identifier for a collection of filters (e.g. "ProfJeffsAwesomeFilters") FilterSetId = NewType("FilterSetId", str) # Unique identifier for an individual filter (e.g. "min_frac") FilterName = NewType("FilterName", str) __all__ = [ "does_pass_filters", "get_filters", "FilterName", "FilterSetId", "FilterConfig", "Filter", "Filters", "DEFAULT_FILTER_PLUGINS", "FilterSet", "FilterConfigs", "FilterPlugin", "PATH", ] @dataclass(frozen=True) class FILTER_PATH: ROOT = f"/Filter/" @classmethod def filter_set_path(cls, filter_set_id: FilterSetId) -> str: filter_path = str(PosixPath(FILTER_PATH.ROOT, filter_set_id)) return filter_path @classmethod def filter_set_pass_path(cls, filter_set_id: FilterSetId) -> str: pass_path = str(PosixPath(FILTER_PATH.filter_set_path(filter_set_id), "pass")) return pass_path @classmethod def filter_set_pass_path_for_read_id(cls, filter_set_id: FilterSetId, read_id: ReadId) -> str: pass_path = str(PosixPath(FILTER_PATH.filter_set_pass_path(filter_set_id), read_id)) return pass_path class FilterConfig(TypedDict): """A blueprint for how to construct a FilterPlugin. Contains a name, and any number of other attributes Note on terminology: - FilterConfig: A high-level description of a filter. - FilterPlugin: An actual, callable, implementation of a FilterConfig. For custom plugins, make sure "filepath" is an attribute that points to the file to laod """ # Mapping of a FilterName to filter configurations. FilterConfigs = NewType("FilterConfigs", Dict[FilterName, FilterConfig]) # TODO: Filter Plugin should check that name is unique. https://github.com/uwmisl/poretitioner/issues/91 class FilterPlugin(Plugin): """ Abstract class for Filter plugins. To write your own filter, subclass this abstract class and implement the `apply` method and `name` property. """ @classmethod @abstractmethod def name(cls) -> str: """Unique name for this filter. Make sure it doesn't conflict with any existing names. Returns ------- str The unique name for this filter (e.g. "fourier_transform"). Raises ------ NotImplementedError Raised if this filter is called without this name method being implemented. """ raise NotImplementedError( "'name' class method not implemented for filter. This class method should return a unique name for this filter." ) @abstractmethod def apply(self, capture: CaptureOrTimeSeries) -> bool: """Returns True if a capture passes a given filter criteria. For instance, a range filter would check that a capture's summary statistsics lie within a given range. Parameters ---------- capture : np.typing.ArrayLike Time series capture to filter. Returns ------- bool Whether this capture passes the filter. Raises ------ NotImplementedError Raised when the filter method isn't implemented by the consuming Filter class """ raise NotImplementedError( "'apply' method not implemented for filter. This method should return True if and only if applied to a capture that meets the filter criterion. For instance, " ) def __call__(self, capture: CaptureOrTimeSeries) -> bool: """Apply the filter. Defining `__call__` lets us do nice things like: class MyCustomFilter(FilterPlugin): def apply(capture): # ... pass # Later in code where filtering is done.... valid_captures = [] filters = [ MyCustomFilter(), AnotherCustomFilter(), ... ] valid_captures = [capture for capture in captures if all([filt(capture) for filt in filters])] for capture in captures: # You'd want to parallelize this in a real life example... for filt in filters: filtered_captures = filt(capture). Parameters ---------- capture : CaptureOrTimeSeries Capture to filter. Returns ------- bool Whether this capture passes the filter. """ result = self.apply(capture) return result RANGE_FILTER_DEFAULT_MINIMUM: float = -np.inf RANGE_FILTER_DEFAULT_MAXIMUM: float = np.inf class RangeFilter(FilterPlugin): def __init__(self, minimum: Optional[float] = None, maximum: Optional[float] = None): """A filter that filters based on whether a signal falls between a maximum and a minimum. Parameters ---------- minimum : float, optional The smallest value this signal should be allowed to take (inclusive), by default RangeFilter.DEFAULT_MINIMUM maximum : float, optional The largest value this signal should be allowed to take (inclusive), by default RangeFilter.DEFAULT_MAXIMUM """ self.minimum = minimum if minimum is not None else RANGE_FILTER_DEFAULT_MINIMUM self.maximum = maximum if maximum is not None else RANGE_FILTER_DEFAULT_MAXIMUM def extract(self, capture: CaptureOrTimeSeries) -> NumpyArrayLike: """Extracts a summary statistic from the capture (e.g. mean, length, standard deviation). Identity operation by default (just returns the capture). You can use this function to transform the data in a useful way before processing it (e.g. getting the mean value of a capture before filtering based on that mean.) Note: If we picture the filtering workflow as an ETL (Extract-Transform-Load) pipeline, this would be the "transform" (take data, modify it for a later purpose), but I feel that "transform" is perhaps a misleading function name in this context. Parameters ---------- capture : CaptureOrTimeSeries Capture from which to extract data. """ try: signal = capture.fractionalized() except AttributeError: signal = capture else: signal = capture return signal # signal = getattr(capture, Capture.fractionalized.__name__, capture) def is_in_range(self, value: Union[NumpyArrayLike, float]) -> bool: try: # If the value is just a float, we can use this handy syntax: return self.minimum <= value <= self.maximum except ValueError: # But we're not allowed to use that syntax on numpy arrays. return all(np.logical_and(self.minimum <= value, value <= self.maximum)) def apply(self, signal): value = self.extract(signal) return self.is_in_range(value) class StandardDeviationFilter(RangeFilter): """Filters for captures with standard deviations in some range.""" @classmethod def name(cls) -> str: return "stdv" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return np.std(signal) class MeanFilter(RangeFilter): """Filters for captures with an arithmetic mean within a range.""" @classmethod def name(cls) -> str: return "mean" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return np.mean(signal) class MedianFilter(RangeFilter): """Filters for captures with a median within a range.""" @classmethod def name(cls) -> str: return "median" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return np.median(signal) class MinimumFilter(RangeFilter): """Filters for captures with a minimum within a range.""" @classmethod def name(cls) -> str: return "min" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return np.min(signal) class MaximumFilter(RangeFilter): """Filters for captures with a maximum within a range.""" @classmethod def name(cls) -> str: return "max" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return np.max(signal) class LengthFilter(RangeFilter): """Filters captures based on their length.""" @classmethod def name(cls) -> str: return "length" def extract(self, capture: CaptureOrTimeSeries): signal = super().extract(capture) return len(signal) class EjectedFilter(FilterPlugin): """Filters captures based on whether they were ejected from the pore.""" @classmethod def name(cls) -> str: return "ejected" def extract(self, capture: Capture): return capture.ejected """ How to Create Your Own Custom Filter: Need more advanced filtering than what we provide out of the box? No problem. Create your own custom filter by inheriting from the FilterPlugin class. For this example, let's do something complex. Say you only want to examine captures that have more than 5 samples with a hyperbolic tangent greater than some threshold. That means our custom filter's `apply` function should return True if and only if the signal has more than 5 samples greater than the threshold, after taking the hyperbolic tangent in `extract`. """ class MyCustomFilter(FilterPlugin): threshold: float = 0.5 # Totally arbitrary. def name(self): return "foo" def extract(self, capture): # Do the transformations here, or pre-process it before the filter. # Gets the hyperbolic tangent of the signal. extracted = np.tanh(capture.signal) return extracted def apply(self, signal): # Only return true if more than 5 samples have a square root greater than 2.0 (arbitrary) extracted = self.extract(signal) # If we want to filter out signals with fewer than 5 matching samples, then we # should retrun True when there are 5 or more matching samples. n_meeting_threshold = len( extracted[extracted > self.threshold] ) # Number of samples greater than the threshold meets_criteria = ( n_meeting_threshold >= 5 ) # Are there at least 5 samples meeting this threshold? return meets_criteria def apply_feature_filters(capture: CaptureOrTimeSeries, filters: List[FilterPlugin]) -> bool: """ Check whether an array of current values (i.e. a single nanopore capture) passes a set of filters. Filters can be based on summary statistics (e.g., mean) and/or a range of allowed values. Notes on filter behavior: If the filters list is empty, there are no filters and the capture passes. Parameters ---------- capture : CaptureOrTimeSeries | NumpyArrayLike Capture containing time series of nanopore current values for a single capture, or the signal itself. filters : List[FilterPlugin] List of FilterPlugin instances. Write your own filter by subclassing FilterPlugin. Returns ------- boolean True if capture passes all filters; False otherwise. """ if filters is None: filters = [] # TODO: Parallelize? https://github.com/uwmisl/poretitioner/issues/67 filtered = [filter_out(capture) for filter_out in filters] print(filtered) # Did this signal pass all filters? all_passed = all(filtered) return all_passed def check_capture_ejection_by_read(f5, read_id): """Checks whether the current capture was in the pore until the voltage was reversed. Parameters ---------- f5 : h5py.File object (open for reading or more) Capture fast5 file read_id : TODO Returns ------- boolean True if the end of the capture coincides with the end of a voltage window. """ try: ejected = f5.get(f"/read_{read_id}/Signal").attrs["ejected"] except AttributeError: raise ValueError(f"path /read_{read_id} does not exist in the fast5 file.") return ejected def check_capture_ejection(end_capture, voltage_ends, tol_obs=20): """Checks whether the current capture was in the pore until the voltage was reversed. Essentially checks whether a value (end_capture) is close enough (within a margin of tol_obs) to any value in voltage_ends. Parameters ---------- end_capture : numeric The end time of the capture. voltage_ends : list of numeric List of times when the standard voltage ends. tol_obs : int, optional Tolerance for defining when the end of the capture = voltage end, by default 20 Returns ------- boolean True if the end of the capture coincides with the end of a voltage window. """ for voltage_end in voltage_ends: if np.abs(end_capture - voltage_end) < tol_obs: return True return False def filter_like_existing(config, example_fast5, example_filter_path, fast5_files, new_filter_path): # Filters a set of fast5 files exactly the same as an existing filter # TODO : #68 : implement raise NotImplementedError() def get_filter_pass_path(filter_set_id, read_id): return FILTER_PATH.filter_set_pass_path(filter_set_id) __DEFAULT_FILTER_PLUGINS = [ MeanFilter, StandardDeviationFilter, MedianFilter, MinimumFilter, MaximumFilter, LengthFilter, ] DEFAULT_FILTER_PLUGINS = { filter_plugin_class.name(): filter_plugin_class for filter_plugin_class in __DEFAULT_FILTER_PLUGINS } class Filtering(Protocol): """Classes that adhere to the Filtering protocol provide an 'apply' method to an input that returns True if and only if the input passes its filter. These are also callable, so calling a filter on an input is functionally equivalent to calling its apply method. """ def __call__(self, *args, **kwargs) -> bool: raise NotImplementedError("Filtering protocol hasn't implemented __call__ yet!") def apply(self, *args, **kwargs) -> bool: raise NotImplementedError("Filtering protocol hasn't implemented Apply yet!") @dataclass class Filter(Filtering): """A named filter that can be applied to some data. You can use this filter by just calling it on some data. my_signal = [1,2,3,4] filter = Filter(...) passed_filter: bool = filter(my_signal) Parameters ---------- config : FilterConfig A description of this filter's configuration (e.g. where it was loaded from). plugin : FilterPlugin The actual implementation of this filter. We have this class defined with """ config: FilterConfig plugin: FilterPlugin def __call__(self, *args, **kwargs) -> bool: return self.plugin(*args, **kwargs) def apply(self, *args, **kwargs) -> bool: return self.plugin.apply(*args, **kwargs) @property def name(self) -> FilterName: return FilterName(self.plugin.__class__.name()) def as_attr(self) -> Dict[str, Any]: name = self.name attrs = {**vars(self.config), **vars(self.plugin), name: name} return attrs def from_attr(self, attr) -> IsAttr: ... import json @dataclass class HDF5_FilterSerialable(Filter, HDF5_GroupSerialableDataclass): def as_group(self, parent_group: HDF5_Group, log: Optional[Logger] = None) -> HDF5_Group: log = log if log is not None else getLogger() # Note: This line simply registers a group with the name 'name' in the parent group. this_group = HDF5_Group(parent_group.require_group(self.name)) all_attrs = {**self.config, **vars(self.plugin)} this_group.create_attrs(all_attrs) # Implementers must now write their serialized instance to this group. return this_group @classmethod def from_group( cls, group: HDF5_Group, log: Optional[Logger] = None ) -> HDF5_GroupSerialableDataclass: # You see, the trouble is, in the above 'as_group' call, we lumped together # all the attributes of the FilterConfig and the FilterPlugin, not knowing # which attributes belonged to which class. # # Now, here in `from_group`, it's time to pay the piper and figure out which attribute # goes where to create a new Filter instance. # # This is likely achievable through the plugin architecture, since the plugin's # name is unique, we can try to find a plugin with a given name, then get its attributes from there. # Load log.warning("Filter.from_group not implemented...It's a whole thing (see comment)") # This is pure Hail Mary. return super().from_group(group, log) # class Filters(HDF5_GroupSerialableDataclass): # filters: Filters = Dict[FilterName, Filter] def get_filters(filter_configs: Optional[FilterConfigs] = None) -> Filters: """Creates Filters from a list of filter configurations. Parameters ---------- filter_configs : Optional[FilterConfigs] A mapping of filter names to their configurations, None by default (i.e. no filtering). Returns ------- Filters A set of callable/applyable filters. """ filter_configs = filter_configs if filter_configs is not None else FilterConfigs({}) my_filters = { name: filter_from_config(name, filter_config) for name, filter_config in filter_configs.items() } return my_filters def does_pass_filters(capture: CaptureOrTimeSeries, filters: Iterable[Filter]) -> bool: """ Check whether an array of values (e.g. a single nanopore capture) passes a set of filters. Filters can be based on summary statistics (e.g., mean) and/or a range of allowed values. Parameters ---------- capture : CaptureOrTimeSeries | NumpyArrayLike Capture containing time series of nanopore current values for a single capture, or the signal itself. filters : Iterable[Filter] The set of filters to apply. Write your own filter by subclassing FilterPlugin. Returns ------- boolean True if capture passes all filters; False otherwise. """ all_passed = True for some_filter in filters: if not some_filter(capture): return False return all_passed @dataclass(frozen=True) class FilterSetProtocol(Filtering, Protocol): filter_set_id: FilterSetId filters: Filters @classmethod def from_filter_configs(cls, name: FilterSetId, filter_configs: FilterConfigs = None): ... @dataclass(frozen=True, init=False) class FilterSet(FilterSetProtocol): """ A collection of filters with a name for easy identification. Essentially a mapping of filter names to their implementations. """ def validate(self): raise NotImplementedError("Implement validation for filters!") def __init__(self, filter_set_id: FilterSetId, filters: Filters) -> None: filterset = super().__init__(self) object.__setattr__(self, "filter_set_id", filter_set_id) object.__setattr__(self, "filters", filters) # self.name = name # self.filters = filters ############################ # # FilterSetProtocol # ############################ @classmethod def from_filter_configs(cls, name: FilterSetId, filter_configs: FilterConfigs = None): filters: Filters = get_filters(filter_configs) filter_set = cls.__new__(cls, name, filters) filter_set.__init__(name, filters) return filter_set def apply(self, capture: CaptureOrTimeSeries) -> bool: return does_pass_filters(capture, self.filters.values()) def __call__(self, capture: CaptureOrTimeSeries) -> bool: return self.apply(capture) class HDF5_FilterSet(FilterSet, HDF5_GroupSerialableDataclass): def __init__(self, filter_set: FilterSet) -> None: self._filterset = filter_set ############################ # # HDF5_GroupSerializable # ############################ def name(self): return self._filterset.filter_set_id def as_group(self, parent_group: HDF5_Group, log: Optional[Logger] = None) -> HDF5_Group: filter_set_group = parent_group.require_group(self.name()) for name, filter_t in self._filterset.filters.items(): hdf5_filter = HDF5_FilterSerialable(filter_t.config, filter_t.plugin) hdf5_filter.as_group(filter_set_group) return HDF5_Group(filter_set_group) # @classmethod # def from_group( # cls, group: HDF5_Group, log: Optional[Logger] = None # ) -> HDF5_GroupSerializable: # raise NotImplementedError( # f"from_group not implemented for {cls.__name__}. Make sure you write a method that returns a serialzied version of this object." # ) def filter_from_config(name: str, config: FilterConfig, log: Logger = getLogger()) -> Filter: """Creates a Filter from a config spefication. If no "filename" is present in the FilterConfig, it's assumed to be one of the default filtesr Parameters ---------- name : str The unique name of a filter. config : FilterConfig Filter configuration to build the plugin. log : Logger, optional Logger to use for information/warnings/debug, by default getLogger() Returns ------- Filter A filter that can be applied to some data. Raises ------ AttributeError A filter plugin could not be built from the configuration description. If this error is raised, be sure to check 1) A plugin class with the name in the configuration is defined at the filepath described in the configuration 2) The plugin class inherits from the `FilterPlugin` abstract base class. """ filepath = config.get("filepath", None) # TODO: For non-default FilterPlugins, load/unpickle the class from the filepath. https://github.com/uwmisl/poretitioner/issues/91 plugin = None if name in DEFAULT_FILTER_PLUGINS: plugin = DEFAULT_FILTER_PLUGINS[name]() else: # TODO: For non-default FilterPlugins, load the class from the filepath. https://github.com/uwmisl/poretitioner/issues/91 plugin = plugin_from_file(name, filepath) pass # Make sure any plugin attributes defined in the config are moved over to the plugin instance. try: # Here, we take care of setting whatever attributes the plugin config defines on the new plugin instance. for key, value in config.items(): object.__setattr__(plugin, key, value) except AttributeError as e: log.warning( """ Uh oh, couldn't find plugin '{name}'. Are you sure: 1) A plugin class with the name '{name}' is defined in the file {filepath}? 2) That plugin class inherits from `FilterPlugin`? """ ) raise e my_filter = Filter(config, plugin) return my_filter def plugin_from_file(name: str, filepath: PathLikeOrString): """[summary] Parameters ---------- name : str [description] filepath : PathLikeOrString [description] Returns ------- [type] [description] Raises ------ NotImplementedError [description] """ # TODO: For non-default FilterPlugins, load/unpickle the class from the filepath. https://github.com/uwmisl/poretitioner/issues/91 raise NotImplementedError( "Plugin from file has not been implemented! This method should take in a filepath and filter name, and return a runnable FilterPlugin!" )
[((51, 14, 51, 41), 'typing.NewType', 'NewType', ({(51, 22, 51, 35): '"""FilterSetId"""', (51, 37, 51, 40): 'str'}, {}), "('FilterSetId', str)", False, 'from typing import Any, Dict, Iterable, Mapping, NewType, Optional, Protocol, Type, TypedDict, Union\n'), ((54, 13, 54, 39), 'typing.NewType', 'NewType', ({(54, 21, 54, 33): '"""FilterName"""', (54, 35, 54, 38): 'str'}, {}), "('FilterName', str)", False, 'from typing import Any, Dict, Iterable, Mapping, NewType, Optional, Protocol, Type, TypedDict, Union\n'), ((73, 1, 73, 23), 'dataclasses.dataclass', 'dataclass', (), '', False, 'from dataclasses import dataclass\n'), ((110, 16, 110, 72), 'typing.NewType', 'NewType', ({(110, 24, 110, 39): '"""FilterConfigs"""', (110, 41, 110, 71): 'Dict[FilterName, FilterConfig]'}, {}), "('FilterConfigs', Dict[FilterName, FilterConfig])", False, 'from typing import Any, Dict, Iterable, Mapping, NewType, Optional, Protocol, Type, TypedDict, Union\n'), ((635, 1, 635, 23), 'dataclasses.dataclass', 'dataclass', (), '', False, 'from dataclasses import dataclass\n'), ((645, 1, 645, 35), 'dataclasses.dataclass', 'dataclass', (), '', False, 'from dataclasses import dataclass\n'), ((263, 15, 263, 29), 'numpy.std', 'np.std', ({(263, 22, 263, 28): 'signal'}, {}), '(signal)', True, 'import numpy as np\n'), ((275, 15, 275, 30), 'numpy.mean', 'np.mean', ({(275, 23, 275, 29): 'signal'}, {}), '(signal)', True, 'import numpy as np\n'), ((287, 15, 287, 32), 'numpy.median', 'np.median', ({(287, 25, 287, 31): 'signal'}, {}), '(signal)', True, 'import numpy as np\n'), ((299, 15, 299, 29), 'numpy.min', 'np.min', ({(299, 22, 299, 28): 'signal'}, {}), '(signal)', True, 'import numpy as np\n'), ((311, 15, 311, 29), 'numpy.max', 'np.max', ({(311, 22, 311, 28): 'signal'}, {}), '(signal)', True, 'import numpy as np\n'), ((361, 20, 361, 43), 'numpy.tanh', 'np.tanh', ({(361, 28, 361, 42): 'capture.signal'}, {}), '(capture.signal)', True, 'import numpy as np\n'), ((79, 26, 79, 68), 'pathlib.PosixPath', 'PosixPath', ({(79, 36, 79, 52): 'FILTER_PATH.ROOT', (79, 54, 79, 67): 'filter_set_id'}, {}), '(FILTER_PATH.ROOT, filter_set_id)', False, 'from pathlib import PosixPath\n'), ((456, 11, 456, 44), 'numpy.abs', 'np.abs', ({(456, 18, 456, 43): '(end_capture - voltage_end)'}, {}), '(end_capture - voltage_end)', True, 'import numpy as np\n'), ((247, 23, 247, 83), 'numpy.logical_and', 'np.logical_and', ({(247, 38, 247, 59): '(self.minimum <= value)', (247, 61, 247, 82): '(value <= self.maximum)'}, {}), '(self.minimum <= value, value <= self.maximum)', True, 'import numpy as np\n')]
nescience8/starting-out-with-python-global-4th-edition
Chapter 11/wrong_type.py
c16f93b7cbb4c7ae7b57653a7190bf192fe6b472
def main(): # Pass a string to show_mammal_info... show_mammal_info('I am a string') # The show_mammal_info function accepts an object # as an argument, and calls its show_species # and make_sound methods. def show_mammal_info(creature): creature.show_species() creature.make_sound() # Call the main function. main()
[]
Leodf/FIAP
fase2-exercicios/cap2/lista-de-exercicios/RM94336_EX04.py
e2acf897017c4f49357112f67702070b7dcbfe9d
""" 4 – Um grande cliente seu sofreu um ataque hacker: o servidor foi sequestrado por um software malicioso, que criptografou todos os discos e pede a digitação de uma senha para a liberação da máquina. E é claro que os criminosos exigem um pagamento para informar a senha. Ao analisar o código do programa deles, porém, você descobre que a senha é composta da palavra “LIBERDADE” seguida do fatorial dos minutos que a máquina estiver marcando no momento da digitação da senha (se a máquina estiver marcando 5 minutos, a senha será LIBERDADE120). Crie um programa que receba do usuário os minutos atuais e exiba na tela a senha necessária para desbloqueio. ATENÇÃO: seu programa não pode utilizar funções prontas para o cálculo do fatorial. Ele deve obrigatoriamente utilizar loop. """ print('\nPrograma para gerar de desbloqueio do servidor do ataque Hacker!!!\n') print('Descobrimos que a senha é a palavra LIBERDADE + o calculo de fatorial dos minutos no seu computador.\n') minuto = input('Digite os minutos que aparecem neste computador: ') minuto = int(minuto) fatorial = 1 for i in range (minuto, 0, -1): fatorial *= i print(f'\nA senha que você precisa digitar é LIBERDADE{fatorial} para desbloquear o servidor.\nAtenção!!!: você tem 60 segundos validos até que a senha mude novamente!!!\n')
[]
yasen-m/dosage
dosagelib/helpers.py
81fe088621ad335cac2a53fcbc7b9b37f49ddce2
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2005 Tristan Seligmann and Jonathan Jacobs # Copyright (C) 2012-2014 Bastian Kleineidam from .util import fetchUrl, getPageContent, getQueryParams def queryNamer(paramName, usePageUrl=False): """Get name from URL query part.""" @classmethod def _namer(cls, imageUrl, pageUrl): """Get URL query part.""" url = pageUrl if usePageUrl else imageUrl return getQueryParams(url)[paramName][0] return _namer def regexNamer(regex, usePageUrl=False): """Get name from regular expression.""" @classmethod def _namer(cls, imageUrl, pageUrl): """Get first regular expression group.""" url = pageUrl if usePageUrl else imageUrl mo = regex.search(url) if mo: return mo.group(1) return _namer def bounceStarter(url, nextSearch): """Get start URL by "bouncing" back and forth one time.""" @classmethod def _starter(cls): """Get bounced start URL.""" data, baseUrl = getPageContent(url, cls.session) url1 = fetchUrl(url, data, baseUrl, cls.prevSearch) data, baseUrl = getPageContent(url1, cls.session) return fetchUrl(url1, data, baseUrl, nextSearch) return _starter def indirectStarter(url, latestSearch): """Get start URL by indirection.""" @classmethod def _starter(cls): """Get indirect start URL.""" data, baseUrl = getPageContent(url, cls.session) return fetchUrl(url, data, baseUrl, latestSearch) return _starter
[]
akshit-protonn/models
research/object_detection/data_decoders/tf_example_decoder_test.py
38c8c6fe4144c93d6aadd19981c2b90570c29eba
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.data_decoders.tf_example_decoder.""" import os import numpy as np import six import tensorflow.compat.v1 as tf from object_detection.core import standard_fields as fields from object_detection.data_decoders import tf_example_decoder from object_detection.protos import input_reader_pb2 from object_detection.utils import dataset_util from object_detection.utils import test_case class TfExampleDecoderTest(test_case.TestCase): def _create_encoded_and_decoded_data(self, data, encoding_type): if encoding_type == 'jpeg': encode_fn = tf.image.encode_jpeg decode_fn = tf.image.decode_jpeg elif encoding_type == 'png': encode_fn = tf.image.encode_png decode_fn = tf.image.decode_png else: raise ValueError('Invalid encoding type.') def prepare_data_fn(): encoded_data = encode_fn(data) decoded_data = decode_fn(encoded_data) return encoded_data, decoded_data return self.execute_cpu(prepare_data_fn, []) def testDecodeAdditionalChannels(self): image = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data(image, 'jpeg') additional_channel = np.random.randint(256, size=(4, 5, 1)).astype(np.uint8) (encoded_additional_channel, decoded_additional_channel) = self._create_encoded_and_decoded_data( additional_channel, 'jpeg') def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/additional_channels/encoded': dataset_util.bytes_list_feature( [encoded_additional_channel] * 2), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/source_id': dataset_util.bytes_feature(six.b('image_id')), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( num_additional_channels=2) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( np.concatenate([decoded_additional_channel] * 2, axis=2), tensor_dict[fields.InputDataFields.image_additional_channels]) def testDecodeJpegImage(self): image = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, decoded_jpeg = self._create_encoded_and_decoded_data( image, 'jpeg') def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/source_id': dataset_util.bytes_feature(six.b('image_id')), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (output[fields.InputDataFields.image].get_shape().as_list()), [None, None, 3]) self.assertAllEqual( (output[fields.InputDataFields.original_image_spatial_shape] .get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(decoded_jpeg, tensor_dict[fields.InputDataFields.image]) self.assertAllEqual([4, 5], tensor_dict[fields.InputDataFields. original_image_spatial_shape]) self.assertEqual( six.b('image_id'), tensor_dict[fields.InputDataFields.source_id]) def testDecodeImageKeyAndFilename(self): image = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data(image, 'jpeg') def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/key/sha256': dataset_util.bytes_feature(six.b('abc')), 'image/filename': dataset_util.bytes_feature(six.b('filename')) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertEqual(six.b('abc'), tensor_dict[fields.InputDataFields.key]) self.assertEqual( six.b('filename'), tensor_dict[fields.InputDataFields.filename]) def testDecodePngImage(self): image = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_png, decoded_png = self._create_encoded_and_decoded_data( image, 'png') def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_png), 'image/format': dataset_util.bytes_feature(six.b('png')), 'image/source_id': dataset_util.bytes_feature(six.b('image_id')) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (output[fields.InputDataFields.image].get_shape().as_list()), [None, None, 3]) self.assertAllEqual( (output[fields.InputDataFields.original_image_spatial_shape] .get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(decoded_png, tensor_dict[fields.InputDataFields.image]) self.assertAllEqual([4, 5], tensor_dict[fields.InputDataFields. original_image_spatial_shape]) self.assertEqual( six.b('image_id'), tensor_dict[fields.InputDataFields.source_id]) def testDecodePngInstanceMasks(self): image = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_png, _ = self._create_encoded_and_decoded_data(image, 'png') mask_1 = np.random.randint(0, 2, size=(10, 10, 1)).astype(np.uint8) mask_2 = np.random.randint(0, 2, size=(10, 10, 1)).astype(np.uint8) encoded_png_1, _ = self._create_encoded_and_decoded_data(mask_1, 'png') decoded_png_1 = np.squeeze(mask_1.astype(np.float32)) encoded_png_2, _ = self._create_encoded_and_decoded_data(mask_2, 'png') decoded_png_2 = np.squeeze(mask_2.astype(np.float32)) encoded_masks = [encoded_png_1, encoded_png_2] decoded_masks = np.stack([decoded_png_1, decoded_png_2]) def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_png), 'image/format': dataset_util.bytes_feature(six.b('png')), 'image/object/mask': dataset_util.bytes_list_feature(encoded_masks) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True, instance_mask_type=input_reader_pb2.PNG_MASKS) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( decoded_masks, tensor_dict[fields.InputDataFields.groundtruth_instance_masks]) def testDecodeEmptyPngInstanceMasks(self): image_tensor = np.random.randint(256, size=(10, 10, 3)).astype(np.uint8) encoded_png, _ = self._create_encoded_and_decoded_data(image_tensor, 'png') encoded_masks = [] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_png), 'image/format': dataset_util.bytes_feature(six.b('png')), 'image/object/mask': dataset_util.bytes_list_feature(encoded_masks), 'image/height': dataset_util.int64_feature(10), 'image/width': dataset_util.int64_feature(10), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True, instance_mask_type=input_reader_pb2.PNG_MASKS) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_instance_masks].shape, [0, 10, 10]) def testDecodeBoundingBox(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_boxes].get_shape().as_list()), [None, 4]) return output tensor_dict = self.execute_cpu(graph_fn, []) expected_boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) def testDecodeKeypointDepth(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] keypoint_ys = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] keypoint_xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] keypoint_visibility = [1, 2, 0, 1, 0, 2] keypoint_depths = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] keypoint_depth_weights = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/keypoint/y': dataset_util.float_list_feature(keypoint_ys), 'image/object/keypoint/x': dataset_util.float_list_feature(keypoint_xs), 'image/object/keypoint/z': dataset_util.float_list_feature(keypoint_depths), 'image/object/keypoint/z/weights': dataset_util.float_list_feature(keypoint_depth_weights), 'image/object/keypoint/visibility': dataset_util.int64_list_feature(keypoint_visibility), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( num_keypoints=3, load_keypoint_depth_features=True) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (output[fields.InputDataFields.groundtruth_keypoint_depths].get_shape( ).as_list()), [2, 3]) self.assertAllEqual( (output[fields.InputDataFields.groundtruth_keypoint_depth_weights] .get_shape().as_list()), [2, 3]) return output tensor_dict = self.execute_cpu(graph_fn, []) expected_keypoint_depths = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] self.assertAllClose( expected_keypoint_depths, tensor_dict[fields.InputDataFields.groundtruth_keypoint_depths]) expected_keypoint_depth_weights = [[1.0, 0.9, 0.8], [0.7, 0.6, 0.5]] self.assertAllClose( expected_keypoint_depth_weights, tensor_dict[fields.InputDataFields.groundtruth_keypoint_depth_weights]) def testDecodeKeypointDepthNoDepth(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] keypoint_ys = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] keypoint_xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] keypoint_visibility = [1, 2, 0, 1, 0, 2] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/keypoint/y': dataset_util.float_list_feature(keypoint_ys), 'image/object/keypoint/x': dataset_util.float_list_feature(keypoint_xs), 'image/object/keypoint/visibility': dataset_util.int64_list_feature(keypoint_visibility), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( num_keypoints=3, load_keypoint_depth_features=True) output = example_decoder.decode(tf.convert_to_tensor(example)) return output tensor_dict = self.execute_cpu(graph_fn, []) expected_keypoints_depth_default = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] self.assertAllClose( expected_keypoints_depth_default, tensor_dict[fields.InputDataFields.groundtruth_keypoint_depths]) self.assertAllClose( expected_keypoints_depth_default, tensor_dict[fields.InputDataFields.groundtruth_keypoint_depth_weights]) def testDecodeKeypoint(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] keypoint_ys = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] keypoint_xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] keypoint_visibility = [1, 2, 0, 1, 0, 2] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/keypoint/y': dataset_util.float_list_feature(keypoint_ys), 'image/object/keypoint/x': dataset_util.float_list_feature(keypoint_xs), 'image/object/keypoint/visibility': dataset_util.int64_list_feature(keypoint_visibility), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder(num_keypoints=3) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_boxes].get_shape().as_list()), [None, 4]) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_keypoints].get_shape().as_list()), [2, 3, 2]) return output tensor_dict = self.execute_cpu(graph_fn, []) expected_boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) expected_keypoints = [ [[0.0, 1.0], [1.0, 2.0], [np.nan, np.nan]], [[3.0, 4.0], [np.nan, np.nan], [5.0, 6.0]]] self.assertAllClose( expected_keypoints, tensor_dict[fields.InputDataFields.groundtruth_keypoints]) expected_visibility = ( (np.array(keypoint_visibility) > 0).reshape((2, 3))) self.assertAllEqual( expected_visibility, tensor_dict[fields.InputDataFields.groundtruth_keypoint_visibilities]) def testDecodeKeypointNoVisibilities(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] keypoint_ys = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] keypoint_xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/keypoint/y': dataset_util.float_list_feature(keypoint_ys), 'image/object/keypoint/x': dataset_util.float_list_feature(keypoint_xs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder(num_keypoints=3) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_boxes].get_shape().as_list()), [None, 4]) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_keypoints].get_shape().as_list()), [2, 3, 2]) return output tensor_dict = self.execute_cpu(graph_fn, []) expected_boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) expected_keypoints = ( np.vstack([keypoint_ys, keypoint_xs]).transpose().reshape((2, 3, 2))) self.assertAllEqual( expected_keypoints, tensor_dict[fields.InputDataFields.groundtruth_keypoints]) expected_visibility = np.ones((2, 3)) self.assertAllEqual( expected_visibility, tensor_dict[fields.InputDataFields.groundtruth_keypoint_visibilities]) def testDecodeDefaultGroundtruthWeights(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_boxes].get_shape().as_list()), [None, 4]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllClose(tensor_dict[fields.InputDataFields.groundtruth_weights], np.ones(2, dtype=np.float32)) def testDecodeObjectLabel(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes = [0, 1] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/label': dataset_util.int64_list_feature(bbox_classes), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(bbox_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeMultiClassScores(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] flattened_multiclass_scores = [100., 50.] + [20., 30.] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/multiclass_scores': dataset_util.float_list_feature( flattened_multiclass_scores), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_multiclass_scores=True) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(flattened_multiclass_scores, tensor_dict[fields.InputDataFields.multiclass_scores]) def testDecodeEmptyMultiClassScores(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_multiclass_scores=True) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertEqual( (0,), tensor_dict[fields.InputDataFields.multiclass_scores].shape) def testDecodeObjectLabelNoText(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes = [1, 2] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/label': dataset_util.int64_list_feature(bbox_classes), })).SerializeToString() label_map_string = """ item { id:1 name:'cat' } item { id:2 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [None]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(bbox_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelWithText(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes_text = [six.b('cat'), six.b('dog')] # Annotation label gets overridden by labelmap id. annotated_bbox_classes = [3, 4] expected_bbox_classes = [1, 2] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), 'image/object/class/label': dataset_util.int64_list_feature(annotated_bbox_classes), })).SerializeToString() label_map_string = """ item { id:1 name:'cat' } item { id:2 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(expected_bbox_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelUnrecognizedName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes_text = [six.b('cat'), six.b('cheetah')] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:2 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [None]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual([2, -1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelWithMappingWithDisplayName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes_text = [six.b('cat'), six.b('dog')] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:3 display_name:'cat' } item { id:1 display_name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [None]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual([3, 1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelUnrecognizedNameWithMappingWithDisplayName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes_text = [six.b('cat'), six.b('cheetah')] bbox_classes_id = [5, 6] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), 'image/object/class/label': dataset_util.int64_list_feature(bbox_classes_id), })).SerializeToString() label_map_string = """ item { name:'/m/cat' id:3 display_name:'cat' } item { name:'/m/dog' id:1 display_name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual([3, -1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelWithMappingWithName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_classes_text = [six.b('cat'), six.b('dog')] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:3 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [None]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual([3, 1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectArea(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') object_area = [100., 174.] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/area': dataset_util.float_list_feature(object_area), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_area].get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(object_area, tensor_dict[fields.InputDataFields.groundtruth_area]) def testDecodeVerifiedNegClasses(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') neg_category_ids = [0, 5, 8] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/neg_category_ids': dataset_util.int64_list_feature(neg_category_ids), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( neg_category_ids, tensor_dict[fields.InputDataFields.groundtruth_verified_neg_classes]) def testDecodeNotExhaustiveClasses(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') not_exhaustive_category_ids = [0, 5, 8] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/not_exhaustive_category_ids': dataset_util.int64_list_feature( not_exhaustive_category_ids), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( not_exhaustive_category_ids, tensor_dict[fields.InputDataFields.groundtruth_not_exhaustive_classes]) def testDecodeObjectIsCrowd(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') object_is_crowd = [0, 1] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/is_crowd': dataset_util.int64_list_feature(object_is_crowd), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_is_crowd].get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( [bool(item) for item in object_is_crowd], tensor_dict[fields.InputDataFields.groundtruth_is_crowd]) def testDecodeObjectDifficult(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') object_difficult = [0, 1] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/difficult': dataset_util.int64_list_feature(object_difficult), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_difficult].get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( [bool(item) for item in object_difficult], tensor_dict[fields.InputDataFields.groundtruth_difficult]) def testDecodeObjectGroupOf(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') object_group_of = [0, 1] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/group_of': dataset_util.int64_list_feature(object_group_of), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_group_of].get_shape().as_list()), [2]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( [bool(item) for item in object_group_of], tensor_dict[fields.InputDataFields.groundtruth_group_of]) def testDecodeObjectWeight(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') object_weights = [0.75, 1.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/weight': dataset_util.float_list_feature(object_weights), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_weights].get_shape().as_list()), [None]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual(object_weights, tensor_dict[fields.InputDataFields.groundtruth_weights]) def testDecodeClassConfidence(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') class_confidence = [0.0, 1.0, 0.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/class/confidence': dataset_util.float_list_feature(class_confidence), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (output[fields.InputDataFields.groundtruth_image_confidences] .get_shape().as_list()), [3]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( class_confidence, tensor_dict[fields.InputDataFields.groundtruth_image_confidences]) def testDecodeInstanceSegmentation(self): num_instances = 4 image_height = 5 image_width = 3 # Randomly generate image. image_tensor = np.random.randint( 256, size=(image_height, image_width, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') # Randomly generate instance segmentation masks. instance_masks = ( np.random.randint(2, size=(num_instances, image_height, image_width)).astype(np.float32)) instance_masks_flattened = np.reshape(instance_masks, [-1]) # Randomly generate class labels for each instance. object_classes = np.random.randint( 100, size=(num_instances)).astype(np.int64) def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/height': dataset_util.int64_feature(image_height), 'image/width': dataset_util.int64_feature(image_width), 'image/object/mask': dataset_util.float_list_feature(instance_masks_flattened), 'image/object/class/label': dataset_util.int64_list_feature(object_classes) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True) output = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (output[fields.InputDataFields.groundtruth_instance_masks].get_shape( ).as_list()), [4, 5, 3]) self.assertAllEqual((output[ fields.InputDataFields.groundtruth_classes].get_shape().as_list()), [4]) return output tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllEqual( instance_masks.astype(np.float32), tensor_dict[fields.InputDataFields.groundtruth_instance_masks]) self.assertAllEqual(object_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testInstancesNotAvailableByDefault(self): num_instances = 4 image_height = 5 image_width = 3 # Randomly generate image. image_tensor = np.random.randint( 256, size=(image_height, image_width, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') # Randomly generate instance segmentation masks. instance_masks = ( np.random.randint(2, size=(num_instances, image_height, image_width)).astype(np.float32)) instance_masks_flattened = np.reshape(instance_masks, [-1]) # Randomly generate class labels for each instance. object_classes = np.random.randint( 100, size=(num_instances)).astype(np.int64) def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/height': dataset_util.int64_feature(image_height), 'image/width': dataset_util.int64_feature(image_width), 'image/object/mask': dataset_util.float_list_feature(instance_masks_flattened), 'image/object/class/label': dataset_util.int64_list_feature(object_classes) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertNotIn(fields.InputDataFields.groundtruth_instance_masks, tensor_dict) def testDecodeImageLabels(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') def graph_fn_1(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/class/label': dataset_util.int64_list_feature([1, 2]), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn_1, []) self.assertIn(fields.InputDataFields.groundtruth_image_classes, tensor_dict) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_image_classes], np.array([1, 2])) def graph_fn_2(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/class/text': dataset_util.bytes_list_feature( [six.b('dog'), six.b('cat')]), })).SerializeToString() label_map_string = """ item { id:3 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn_2, []) self.assertIn(fields.InputDataFields.groundtruth_image_classes, tensor_dict) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_image_classes], np.array([1, 3])) def testDecodeContextFeatures(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] num_features = 8 context_feature_length = 10 context_features = np.random.random(num_features*context_feature_length) def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/context_features': dataset_util.float_list_feature(context_features), 'image/context_feature_length': dataset_util.int64_feature(context_feature_length), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_context_features=True) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertAllClose( context_features.reshape(num_features, context_feature_length), tensor_dict[fields.InputDataFields.context_features]) self.assertAllEqual( context_feature_length, tensor_dict[fields.InputDataFields.context_feature_length]) def testContextFeaturesNotAvailableByDefault(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] num_features = 10 context_feature_length = 10 context_features = np.random.random(num_features*context_feature_length) def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/context_features': dataset_util.float_list_feature(context_features), 'image/context_feature_length': dataset_util.int64_feature(context_feature_length), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) self.assertNotIn(fields.InputDataFields.context_features, tensor_dict) def testExpandLabels(self): label_map_string = """ item { id:1 name:'cat' ancestor_ids: 2 } item { id:2 name:'animal' descendant_ids: 1 } item { id:3 name:'man' ancestor_ids: 5 } item { id:4 name:'woman' display_name:'woman' ancestor_ids: 5 } item { id:5 name:'person' descendant_ids: 3 descendant_ids: 4 } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] bbox_classes_text = [six.b('cat'), six.b('cat')] bbox_group_of = [0, 1] image_class_text = [six.b('cat'), six.b('person')] image_confidence = [1.0, 0.0] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), 'image/object/group_of': dataset_util.int64_list_feature(bbox_group_of), 'image/class/text': dataset_util.bytes_list_feature(image_class_text), 'image/class/confidence': dataset_util.float_list_feature(image_confidence), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path, expand_hierarchy_labels=True) return example_decoder.decode(tf.convert_to_tensor(example)) tensor_dict = self.execute_cpu(graph_fn, []) boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() expected_boxes = np.stack( [boxes[0, :], boxes[0, :], boxes[1, :], boxes[1, :]], axis=0) expected_boxes_class = np.array([1, 2, 1, 2]) expected_boxes_group_of = np.array([0, 0, 1, 1]) expected_image_class = np.array([1, 2, 3, 4, 5]) expected_image_confidence = np.array([1.0, 1.0, 0.0, 0.0, 0.0]) self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) self.assertAllEqual(expected_boxes_class, tensor_dict[fields.InputDataFields.groundtruth_classes]) self.assertAllEqual( expected_boxes_group_of, tensor_dict[fields.InputDataFields.groundtruth_group_of]) self.assertAllEqual( expected_image_class, tensor_dict[fields.InputDataFields.groundtruth_image_classes]) self.assertAllEqual( expected_image_confidence, tensor_dict[fields.InputDataFields.groundtruth_image_confidences]) def testDecodeDensePose(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0, 2.0] bbox_xmins = [1.0, 5.0, 8.0] bbox_ymaxs = [2.0, 6.0, 1.0] bbox_xmaxs = [3.0, 7.0, 3.3] densepose_num = [0, 4, 2] densepose_part_index = [2, 2, 3, 4, 2, 9] densepose_x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] densepose_y = [0.9, 0.8, 0.7, 0.6, 0.5, 0.4] densepose_u = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06] densepose_v = [0.99, 0.98, 0.97, 0.96, 0.95, 0.94] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/densepose/num': dataset_util.int64_list_feature(densepose_num), 'image/object/densepose/part_index': dataset_util.int64_list_feature(densepose_part_index), 'image/object/densepose/x': dataset_util.float_list_feature(densepose_x), 'image/object/densepose/y': dataset_util.float_list_feature(densepose_y), 'image/object/densepose/u': dataset_util.float_list_feature(densepose_u), 'image/object/densepose/v': dataset_util.float_list_feature(densepose_v), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_dense_pose=True) output = example_decoder.decode(tf.convert_to_tensor(example)) dp_num_points = output[fields.InputDataFields.groundtruth_dp_num_points] dp_part_ids = output[fields.InputDataFields.groundtruth_dp_part_ids] dp_surface_coords = output[ fields.InputDataFields.groundtruth_dp_surface_coords] return dp_num_points, dp_part_ids, dp_surface_coords dp_num_points, dp_part_ids, dp_surface_coords = self.execute_cpu( graph_fn, []) expected_dp_num_points = [0, 4, 2] expected_dp_part_ids = [ [0, 0, 0, 0], [2, 2, 3, 4], [2, 9, 0, 0] ] expected_dp_surface_coords = np.array( [ # Instance 0 (no points). [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]], # Instance 1 (4 points). [[0.9, 0.1, 0.99, 0.01], [0.8, 0.2, 0.98, 0.02], [0.7, 0.3, 0.97, 0.03], [0.6, 0.4, 0.96, 0.04]], # Instance 2 (2 points). [[0.5, 0.5, 0.95, 0.05], [0.4, 0.6, 0.94, 0.06], [0., 0., 0., 0.], [0., 0., 0., 0.]], ], dtype=np.float32) self.assertAllEqual(dp_num_points, expected_dp_num_points) self.assertAllEqual(dp_part_ids, expected_dp_part_ids) self.assertAllClose(dp_surface_coords, expected_dp_surface_coords) def testDecodeTrack(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg, _ = self._create_encoded_and_decoded_data( image_tensor, 'jpeg') bbox_ymins = [0.0, 4.0, 2.0] bbox_xmins = [1.0, 5.0, 8.0] bbox_ymaxs = [2.0, 6.0, 1.0] bbox_xmaxs = [3.0, 7.0, 3.3] track_labels = [0, 1, 2] def graph_fn(): example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature(six.b('jpeg')), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/track/label': dataset_util.int64_list_feature(track_labels), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_track_id=True) output = example_decoder.decode(tf.convert_to_tensor(example)) track_ids = output[fields.InputDataFields.groundtruth_track_ids] return track_ids track_ids = self.execute_cpu(graph_fn, []) expected_track_labels = [0, 1, 2] self.assertAllEqual(track_ids, expected_track_labels) if __name__ == '__main__': tf.test.main()
[((1650, 2, 1650, 16), 'tensorflow.compat.v1.test.main', 'tf.test.main', ({}, {}), '()', True, 'import tensorflow.compat.v1 as tf\n'), ((183, 20, 183, 60), 'numpy.stack', 'np.stack', ({(183, 29, 183, 59): '[decoded_png_1, decoded_png_2]'}, {}), '([decoded_png_1, decoded_png_2])', True, 'import numpy as np\n'), ((518, 26, 518, 41), 'numpy.ones', 'np.ones', ({(518, 34, 518, 40): '(2, 3)'}, {}), '((2, 3))', True, 'import numpy as np\n'), ((1187, 31, 1187, 63), 'numpy.reshape', 'np.reshape', ({(1187, 42, 1187, 56): 'instance_masks', (1187, 58, 1187, 62): '[-1]'}, {}), '(instance_masks, [-1])', True, 'import numpy as np\n'), ((1245, 31, 1245, 63), 'numpy.reshape', 'np.reshape', ({(1245, 42, 1245, 56): 'instance_masks', (1245, 58, 1245, 62): '[-1]'}, {}), '(instance_masks, [-1])', True, 'import numpy as np\n'), ((1342, 23, 1342, 76), 'numpy.random.random', 'np.random.random', ({(1342, 40, 1342, 75): 'num_features * context_feature_length'}, {}), '(num_features * context_feature_length)', True, 'import numpy as np\n'), ((1388, 23, 1388, 76), 'numpy.random.random', 'np.random.random', ({(1388, 40, 1388, 75): 'num_features * context_feature_length'}, {}), '(num_features * context_feature_length)', True, 'import numpy as np\n'), ((1499, 21, 1500, 69), 'numpy.stack', 'np.stack', (), '', True, 'import numpy as np\n'), ((1501, 27, 1501, 49), 'numpy.array', 'np.array', ({(1501, 36, 1501, 48): '[1, 2, 1, 2]'}, {}), '([1, 2, 1, 2])', True, 'import numpy as np\n'), ((1502, 30, 1502, 52), 'numpy.array', 'np.array', ({(1502, 39, 1502, 51): '[0, 0, 1, 1]'}, {}), '([0, 0, 1, 1])', True, 'import numpy as np\n'), ((1503, 27, 1503, 52), 'numpy.array', 'np.array', ({(1503, 36, 1503, 51): '[1, 2, 3, 4, 5]'}, {}), '([1, 2, 3, 4, 5])', True, 'import numpy as np\n'), ((1504, 32, 1504, 67), 'numpy.array', 'np.array', ({(1504, 41, 1504, 66): '[1.0, 1.0, 0.0, 0.0, 0.0]'}, {}), '([1.0, 1.0, 0.0, 0.0, 0.0])', True, 'import numpy as np\n'), ((1583, 33, 1600, 28), 'numpy.array', 'np.array', (), '', True, 'import numpy as np\n'), ((72, 24, 73, 36), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((78, 8, 78, 64), 'numpy.concatenate', 'np.concatenate', (), '', True, 'import numpy as np\n'), ((98, 24, 98, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((113, 8, 113, 25), 'six.b', 'six.b', ({(113, 14, 113, 24): '"""image_id"""'}, {}), "('image_id')", False, 'import six\n'), ((131, 24, 131, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((135, 21, 135, 33), 'six.b', 'six.b', ({(135, 27, 135, 32): '"""abc"""'}, {}), "('abc')", False, 'import six\n'), ((137, 8, 137, 25), 'six.b', 'six.b', ({(137, 14, 137, 24): '"""filename"""'}, {}), "('filename')", False, 'import six\n'), ((156, 24, 156, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((171, 8, 171, 25), 'six.b', 'six.b', ({(171, 14, 171, 24): '"""image_id"""'}, {}), "('image_id')", False, 'import six\n'), ((197, 24, 199, 56), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((228, 24, 230, 56), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((265, 24, 265, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((320, 24, 321, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((380, 24, 381, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((432, 24, 432, 76), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((495, 24, 495, 76), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((550, 24, 550, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((560, 24, 560, 52), 'numpy.ones', 'np.ones', (), '', True, 'import numpy as np\n'), ((580, 24, 580, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((624, 24, 625, 38), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((659, 24, 660, 38), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((698, 24, 699, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((716, 25, 716, 37), 'six.b', 'six.b', ({(716, 31, 716, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((716, 39, 716, 51), 'six.b', 'six.b', ({(716, 45, 716, 50): '"""dog"""'}, {}), "('dog')", False, 'import six\n'), ((748, 24, 749, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((761, 25, 761, 37), 'six.b', 'six.b', ({(761, 31, 761, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((761, 39, 761, 55), 'six.b', 'six.b', ({(761, 45, 761, 54): '"""cheetah"""'}, {}), "('cheetah')", False, 'import six\n'), ((788, 24, 789, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((804, 25, 804, 37), 'six.b', 'six.b', ({(804, 31, 804, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((804, 39, 804, 51), 'six.b', 'six.b', ({(804, 45, 804, 50): '"""dog"""'}, {}), "('dog')", False, 'import six\n'), ((831, 24, 832, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((848, 25, 848, 37), 'six.b', 'six.b', ({(848, 31, 848, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((848, 39, 848, 55), 'six.b', 'six.b', ({(848, 45, 848, 54): '"""cheetah"""'}, {}), "('cheetah')", False, 'import six\n'), ((880, 24, 881, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((892, 25, 892, 37), 'six.b', 'six.b', ({(892, 31, 892, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((892, 39, 892, 51), 'six.b', 'six.b', ({(892, 45, 892, 50): '"""dog"""'}, {}), "('dog')", False, 'import six\n'), ((919, 24, 920, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((950, 24, 950, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((980, 24, 980, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1008, 24, 1008, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1035, 24, 1035, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1066, 24, 1066, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1097, 24, 1097, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1128, 24, 1128, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1159, 24, 1159, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1210, 24, 1211, 35), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1268, 24, 1268, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1288, 24, 1288, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1295, 8, 1295, 24), 'numpy.array', 'np.array', ({(1295, 17, 1295, 23): '[1, 2]'}, {}), '([1, 2])', True, 'import numpy as np\n'), ((1322, 24, 1323, 46), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1330, 8, 1330, 24), 'numpy.array', 'np.array', ({(1330, 17, 1330, 23): '[1, 3]'}, {}), '([1, 3])', True, 'import numpy as np\n'), ((1366, 24, 1367, 37), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1412, 24, 1412, 61), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', ({}, {}), '()', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1451, 9, 1451, 44), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(1451, 23, 1451, 37): 'label_map_path', (1451, 39, 1451, 43): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((1460, 25, 1460, 37), 'six.b', 'six.b', ({(1460, 31, 1460, 36): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((1460, 39, 1460, 51), 'six.b', 'six.b', ({(1460, 45, 1460, 50): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((1462, 24, 1462, 36), 'six.b', 'six.b', ({(1462, 30, 1462, 35): '"""cat"""'}, {}), "('cat')", False, 'import six\n'), ((1462, 38, 1462, 53), 'six.b', 'six.b', ({(1462, 44, 1462, 52): '"""person"""'}, {}), "('person')", False, 'import six\n'), ((1491, 24, 1492, 76), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1565, 24, 1566, 31), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((1636, 24, 1637, 29), 'object_detection.data_decoders.tf_example_decoder.TfExampleDecoder', 'tf_example_decoder.TfExampleDecoder', (), '', False, 'from object_detection.data_decoders import tf_example_decoder\n'), ((49, 12, 49, 50), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((52, 25, 52, 63), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((74, 36, 74, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(74, 57, 74, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((82, 12, 82, 50), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((99, 38, 99, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(99, 59, 99, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((116, 12, 116, 50), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((132, 36, 132, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(132, 57, 132, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((140, 12, 140, 50), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((157, 38, 157, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(157, 59, 157, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((174, 12, 174, 50), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((176, 13, 176, 54), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((177, 13, 177, 54), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((200, 36, 200, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(200, 57, 200, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((208, 19, 208, 59), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((231, 36, 231, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(231, 57, 231, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((239, 19, 239, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((266, 38, 266, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(266, 59, 266, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((273, 21, 274, 44), 'numpy.vstack', 'np.vstack', ({(273, 31, 274, 43): '[bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]'}, {}), '([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs])', True, 'import numpy as np\n'), ((279, 19, 279, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((322, 38, 322, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(322, 59, 322, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((345, 19, 345, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((382, 38, 382, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(382, 59, 382, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((397, 19, 397, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((433, 38, 433, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(433, 59, 433, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((444, 21, 445, 44), 'numpy.vstack', 'np.vstack', ({(444, 31, 445, 43): '[bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]'}, {}), '([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs])', True, 'import numpy as np\n'), ((463, 19, 463, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((496, 38, 496, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(496, 59, 496, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((507, 21, 508, 44), 'numpy.vstack', 'np.vstack', ({(507, 31, 508, 43): '[bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]'}, {}), '([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs])', True, 'import numpy as np\n'), ((524, 19, 524, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((551, 38, 551, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(551, 59, 551, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((563, 19, 563, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((581, 38, 581, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(581, 59, 581, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((594, 19, 594, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((626, 36, 626, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(626, 57, 626, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((633, 19, 633, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((661, 36, 661, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(661, 57, 661, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((668, 19, 668, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((695, 11, 695, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(695, 25, 695, 39): 'label_map_path', (695, 41, 695, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((700, 38, 700, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(700, 59, 700, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((713, 19, 713, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((745, 11, 745, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(745, 25, 745, 39): 'label_map_path', (745, 41, 745, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((750, 36, 750, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(750, 57, 750, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((758, 19, 758, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((786, 11, 786, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(786, 25, 786, 39): 'label_map_path', (786, 41, 786, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((790, 38, 790, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(790, 59, 790, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((801, 19, 801, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((829, 11, 829, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(829, 25, 829, 39): 'label_map_path', (829, 41, 829, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((833, 38, 833, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(833, 59, 833, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((845, 19, 845, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((878, 11, 878, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(878, 25, 878, 39): 'label_map_path', (878, 41, 878, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((882, 36, 882, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(882, 57, 882, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((889, 19, 889, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((917, 11, 917, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(917, 25, 917, 39): 'label_map_path', (917, 41, 917, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((921, 38, 921, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(921, 59, 921, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((933, 19, 933, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((951, 38, 951, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(951, 59, 951, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((963, 19, 963, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((981, 38, 981, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(981, 59, 981, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((990, 19, 990, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1009, 38, 1009, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1009, 59, 1009, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1018, 19, 1018, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1036, 38, 1036, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1036, 59, 1036, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1049, 19, 1049, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1067, 38, 1067, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1067, 59, 1067, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1080, 19, 1080, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1098, 38, 1098, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1098, 59, 1098, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1111, 19, 1111, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1129, 38, 1129, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1129, 59, 1129, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1142, 19, 1142, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1160, 38, 1160, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1160, 59, 1160, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1178, 19, 1179, 49), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1185, 8, 1186, 48), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1190, 21, 1191, 34), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1212, 38, 1212, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1212, 59, 1212, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1236, 19, 1237, 49), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1243, 8, 1244, 48), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1248, 21, 1249, 34), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1269, 36, 1269, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1269, 57, 1269, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1276, 19, 1276, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1289, 36, 1289, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1289, 57, 1289, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1320, 11, 1320, 46), 'tensorflow.compat.v1.gfile.Open', 'tf.gfile.Open', ({(1320, 25, 1320, 39): 'label_map_path', (1320, 41, 1320, 45): '"""wb"""'}, {}), "(label_map_path, 'wb')", True, 'import tensorflow.compat.v1 as tf\n'), ((1324, 36, 1324, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1324, 57, 1324, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1333, 19, 1333, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1368, 36, 1368, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1368, 57, 1368, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1379, 19, 1379, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1413, 36, 1413, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1413, 57, 1413, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1453, 19, 1453, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1493, 36, 1493, 65), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1493, 57, 1493, 64): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1497, 12, 1498, 35), 'numpy.vstack', 'np.vstack', ({(1497, 22, 1498, 34): '[bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]'}, {}), '([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs])', True, 'import numpy as np\n'), ((1520, 19, 1520, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1567, 38, 1567, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1567, 59, 1567, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((1607, 19, 1607, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((1638, 38, 1638, 67), 'tensorflow.compat.v1.convert_to_tensor', 'tf.convert_to_tensor', ({(1638, 59, 1638, 66): 'example'}, {}), '(example)', True, 'import tensorflow.compat.v1 as tf\n'), ((457, 9, 457, 38), 'numpy.array', 'np.array', ({(457, 18, 457, 37): 'keypoint_visibility'}, {}), '(keypoint_visibility)', True, 'import numpy as np\n'), ((513, 8, 513, 45), 'numpy.vstack', 'np.vstack', ({(513, 18, 513, 44): '[keypoint_ys, keypoint_xs]'}, {}), '([keypoint_ys, keypoint_xs])', True, 'import numpy as np\n'), ((62, 22, 62, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(62, 49, 62, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((64, 22, 65, 59), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(65, 26, 65, 58): '[encoded_additional_channel] * 2'}, {}), '([encoded_additional_channel] * 2)', False, 'from object_detection.utils import dataset_util\n'), ((91, 22, 91, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(91, 49, 91, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((124, 22, 124, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(124, 49, 124, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((149, 22, 149, 61), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(149, 49, 149, 60): 'encoded_png'}, {}), '(encoded_png)', False, 'from object_detection.utils import dataset_util\n'), ((190, 22, 190, 61), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(190, 49, 190, 60): 'encoded_png'}, {}), '(encoded_png)', False, 'from object_detection.utils import dataset_util\n'), ((194, 22, 194, 68), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(194, 54, 194, 67): 'encoded_masks'}, {}), '(encoded_masks)', False, 'from object_detection.utils import dataset_util\n'), ((217, 22, 217, 61), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(217, 49, 217, 60): 'encoded_png'}, {}), '(encoded_png)', False, 'from object_detection.utils import dataset_util\n'), ((221, 22, 221, 68), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(221, 54, 221, 67): 'encoded_masks'}, {}), '(encoded_masks)', False, 'from object_detection.utils import dataset_util\n'), ((223, 22, 223, 52), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(223, 49, 223, 51): '10'}, {}), '(10)', False, 'from object_detection.utils import dataset_util\n'), ((225, 22, 225, 52), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(225, 49, 225, 51): '10'}, {}), '(10)', False, 'from object_detection.utils import dataset_util\n'), ((252, 22, 252, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(252, 49, 252, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((256, 22, 256, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(256, 54, 256, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((258, 22, 258, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(258, 54, 258, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((260, 22, 260, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(260, 54, 260, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((262, 22, 262, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(262, 54, 262, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((297, 22, 297, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(297, 49, 297, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((301, 22, 301, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(301, 54, 301, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((303, 22, 303, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(303, 54, 303, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((305, 22, 305, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(305, 54, 305, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((307, 22, 307, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(307, 54, 307, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((309, 22, 309, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(309, 54, 309, 65): 'keypoint_ys'}, {}), '(keypoint_ys)', False, 'from object_detection.utils import dataset_util\n'), ((311, 22, 311, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(311, 54, 311, 65): 'keypoint_xs'}, {}), '(keypoint_xs)', False, 'from object_detection.utils import dataset_util\n'), ((313, 22, 313, 70), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(313, 54, 313, 69): 'keypoint_depths'}, {}), '(keypoint_depths)', False, 'from object_detection.utils import dataset_util\n'), ((315, 22, 315, 77), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(315, 54, 315, 76): 'keypoint_depth_weights'}, {}), '(keypoint_depth_weights)', False, 'from object_detection.utils import dataset_util\n'), ((317, 22, 317, 74), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(317, 54, 317, 73): 'keypoint_visibility'}, {}), '(keypoint_visibility)', False, 'from object_detection.utils import dataset_util\n'), ((361, 22, 361, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(361, 49, 361, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((365, 22, 365, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(365, 54, 365, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((367, 22, 367, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(367, 54, 367, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((369, 22, 369, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(369, 54, 369, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((371, 22, 371, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(371, 54, 371, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((373, 22, 373, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(373, 54, 373, 65): 'keypoint_ys'}, {}), '(keypoint_ys)', False, 'from object_detection.utils import dataset_util\n'), ((375, 22, 375, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(375, 54, 375, 65): 'keypoint_xs'}, {}), '(keypoint_xs)', False, 'from object_detection.utils import dataset_util\n'), ((377, 22, 377, 74), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(377, 54, 377, 73): 'keypoint_visibility'}, {}), '(keypoint_visibility)', False, 'from object_detection.utils import dataset_util\n'), ((413, 22, 413, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(413, 49, 413, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((417, 22, 417, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(417, 54, 417, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((419, 22, 419, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(419, 54, 419, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((421, 22, 421, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(421, 54, 421, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((423, 22, 423, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(423, 54, 423, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((425, 22, 425, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(425, 54, 425, 65): 'keypoint_ys'}, {}), '(keypoint_ys)', False, 'from object_detection.utils import dataset_util\n'), ((427, 22, 427, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(427, 54, 427, 65): 'keypoint_xs'}, {}), '(keypoint_xs)', False, 'from object_detection.utils import dataset_util\n'), ((429, 22, 429, 74), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(429, 54, 429, 73): 'keypoint_visibility'}, {}), '(keypoint_visibility)', False, 'from object_detection.utils import dataset_util\n'), ((478, 22, 478, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(478, 49, 478, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((482, 22, 482, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(482, 54, 482, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((484, 22, 484, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(484, 54, 484, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((486, 22, 486, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(486, 54, 486, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((488, 22, 488, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(488, 54, 488, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((490, 22, 490, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(490, 54, 490, 65): 'keypoint_ys'}, {}), '(keypoint_ys)', False, 'from object_detection.utils import dataset_util\n'), ((492, 22, 492, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(492, 54, 492, 65): 'keypoint_xs'}, {}), '(keypoint_xs)', False, 'from object_detection.utils import dataset_util\n'), ((537, 22, 537, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(537, 49, 537, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((541, 22, 541, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(541, 54, 541, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((543, 22, 543, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(543, 54, 543, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((545, 22, 545, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(545, 54, 545, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((547, 22, 547, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(547, 54, 547, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((573, 22, 573, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(573, 49, 573, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((577, 22, 577, 67), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(577, 54, 577, 66): 'bbox_classes'}, {}), '(bbox_classes)', False, 'from object_detection.utils import dataset_util\n'), ((608, 22, 608, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(608, 49, 608, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((612, 22, 613, 54), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(613, 26, 613, 53): 'flattened_multiclass_scores'}, {}), '(flattened_multiclass_scores)', False, 'from object_detection.utils import dataset_util\n'), ((615, 22, 615, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(615, 54, 615, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((617, 22, 617, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(617, 54, 617, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((619, 22, 619, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(619, 54, 619, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((621, 22, 621, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(621, 54, 621, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((646, 22, 646, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(646, 49, 646, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((650, 22, 650, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(650, 54, 650, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((652, 22, 652, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(652, 54, 652, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((654, 22, 654, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(654, 54, 654, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((656, 22, 656, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(656, 54, 656, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((678, 22, 678, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(678, 49, 678, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((682, 22, 682, 67), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(682, 54, 682, 66): 'bbox_classes'}, {}), '(bbox_classes)', False, 'from object_detection.utils import dataset_util\n'), ((726, 22, 726, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(726, 49, 726, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((730, 22, 730, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(730, 54, 730, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((732, 22, 732, 77), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(732, 54, 732, 76): 'annotated_bbox_classes'}, {}), '(annotated_bbox_classes)', False, 'from object_detection.utils import dataset_util\n'), ((768, 22, 768, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(768, 49, 768, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((772, 22, 772, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(772, 54, 772, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((811, 22, 811, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(811, 49, 811, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((815, 22, 815, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(815, 54, 815, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((856, 22, 856, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(856, 49, 856, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((860, 22, 860, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(860, 54, 860, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((862, 22, 862, 70), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(862, 54, 862, 69): 'bbox_classes_id'}, {}), '(bbox_classes_id)', False, 'from object_detection.utils import dataset_util\n'), ((899, 22, 899, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(899, 49, 899, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((903, 22, 903, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(903, 54, 903, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((943, 22, 943, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(943, 49, 943, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((947, 22, 947, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(947, 54, 947, 65): 'object_area'}, {}), '(object_area)', False, 'from object_detection.utils import dataset_util\n'), ((973, 22, 973, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(973, 49, 973, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((977, 22, 977, 71), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(977, 54, 977, 70): 'neg_category_ids'}, {}), '(neg_category_ids)', False, 'from object_detection.utils import dataset_util\n'), ((1000, 22, 1000, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1000, 49, 1000, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1004, 22, 1005, 54), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1005, 26, 1005, 53): 'not_exhaustive_category_ids'}, {}), '(not_exhaustive_category_ids)', False, 'from object_detection.utils import dataset_util\n'), ((1028, 22, 1028, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1028, 49, 1028, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1032, 22, 1032, 70), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1032, 54, 1032, 69): 'object_is_crowd'}, {}), '(object_is_crowd)', False, 'from object_detection.utils import dataset_util\n'), ((1059, 22, 1059, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1059, 49, 1059, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1063, 22, 1063, 71), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1063, 54, 1063, 70): 'object_difficult'}, {}), '(object_difficult)', False, 'from object_detection.utils import dataset_util\n'), ((1090, 22, 1090, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1090, 49, 1090, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1094, 22, 1094, 70), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1094, 54, 1094, 69): 'object_group_of'}, {}), '(object_group_of)', False, 'from object_detection.utils import dataset_util\n'), ((1121, 22, 1121, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1121, 49, 1121, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1125, 22, 1125, 69), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1125, 54, 1125, 68): 'object_weights'}, {}), '(object_weights)', False, 'from object_detection.utils import dataset_util\n'), ((1152, 22, 1152, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1152, 49, 1152, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1156, 22, 1156, 71), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1156, 54, 1156, 70): 'class_confidence'}, {}), '(class_confidence)', False, 'from object_detection.utils import dataset_util\n'), ((1198, 22, 1198, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1198, 49, 1198, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1202, 22, 1202, 62), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1202, 49, 1202, 61): 'image_height'}, {}), '(image_height)', False, 'from object_detection.utils import dataset_util\n'), ((1204, 22, 1204, 61), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1204, 49, 1204, 60): 'image_width'}, {}), '(image_width)', False, 'from object_detection.utils import dataset_util\n'), ((1206, 22, 1206, 79), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1206, 54, 1206, 78): 'instance_masks_flattened'}, {}), '(instance_masks_flattened)', False, 'from object_detection.utils import dataset_util\n'), ((1208, 22, 1208, 69), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1208, 54, 1208, 68): 'object_classes'}, {}), '(object_classes)', False, 'from object_detection.utils import dataset_util\n'), ((1256, 22, 1256, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1256, 49, 1256, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1260, 22, 1260, 62), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1260, 49, 1260, 61): 'image_height'}, {}), '(image_height)', False, 'from object_detection.utils import dataset_util\n'), ((1262, 22, 1262, 61), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1262, 49, 1262, 60): 'image_width'}, {}), '(image_width)', False, 'from object_detection.utils import dataset_util\n'), ((1264, 22, 1264, 79), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1264, 54, 1264, 78): 'instance_masks_flattened'}, {}), '(instance_masks_flattened)', False, 'from object_detection.utils import dataset_util\n'), ((1266, 22, 1266, 69), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1266, 54, 1266, 68): 'object_classes'}, {}), '(object_classes)', False, 'from object_detection.utils import dataset_util\n'), ((1284, 35, 1284, 75), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1284, 62, 1284, 74): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1286, 39, 1286, 78), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1286, 71, 1286, 77): '[1, 2]'}, {}), '([1, 2])', False, 'from object_detection.utils import dataset_util\n'), ((1302, 22, 1302, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1302, 49, 1302, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1349, 22, 1349, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1349, 49, 1349, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1353, 22, 1353, 71), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1353, 54, 1353, 70): 'context_features'}, {}), '(context_features)', False, 'from object_detection.utils import dataset_util\n'), ((1355, 22, 1355, 72), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1355, 49, 1355, 71): 'context_feature_length'}, {}), '(context_feature_length)', False, 'from object_detection.utils import dataset_util\n'), ((1357, 22, 1357, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1357, 54, 1357, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((1359, 22, 1359, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1359, 54, 1359, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((1361, 22, 1361, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1361, 54, 1361, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1363, 22, 1363, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1363, 54, 1363, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1395, 22, 1395, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1395, 49, 1395, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1399, 22, 1399, 71), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1399, 54, 1399, 70): 'context_features'}, {}), '(context_features)', False, 'from object_detection.utils import dataset_util\n'), ((1401, 22, 1401, 72), 'object_detection.utils.dataset_util.int64_feature', 'dataset_util.int64_feature', ({(1401, 49, 1401, 71): 'context_feature_length'}, {}), '(context_feature_length)', False, 'from object_detection.utils import dataset_util\n'), ((1403, 22, 1403, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1403, 54, 1403, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((1405, 22, 1405, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1405, 54, 1405, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((1407, 22, 1407, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1407, 54, 1407, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1409, 22, 1409, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1409, 54, 1409, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1470, 22, 1470, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1470, 49, 1470, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1474, 22, 1474, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1474, 54, 1474, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((1476, 22, 1476, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1476, 54, 1476, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((1478, 22, 1478, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1478, 54, 1478, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1480, 22, 1480, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1480, 54, 1480, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1482, 22, 1482, 72), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(1482, 54, 1482, 71): 'bbox_classes_text'}, {}), '(bbox_classes_text)', False, 'from object_detection.utils import dataset_util\n'), ((1484, 22, 1484, 68), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1484, 54, 1484, 67): 'bbox_group_of'}, {}), '(bbox_group_of)', False, 'from object_detection.utils import dataset_util\n'), ((1486, 22, 1486, 71), 'object_detection.utils.dataset_util.bytes_list_feature', 'dataset_util.bytes_list_feature', ({(1486, 54, 1486, 70): 'image_class_text'}, {}), '(image_class_text)', False, 'from object_detection.utils import dataset_util\n'), ((1488, 22, 1488, 71), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1488, 54, 1488, 70): 'image_confidence'}, {}), '(image_confidence)', False, 'from object_detection.utils import dataset_util\n'), ((1539, 22, 1539, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1539, 49, 1539, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1543, 22, 1543, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1543, 54, 1543, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((1545, 22, 1545, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1545, 54, 1545, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((1547, 22, 1547, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1547, 54, 1547, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1549, 22, 1549, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1549, 54, 1549, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1551, 22, 1551, 68), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1551, 54, 1551, 67): 'densepose_num'}, {}), '(densepose_num)', False, 'from object_detection.utils import dataset_util\n'), ((1553, 22, 1553, 75), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1553, 54, 1553, 74): 'densepose_part_index'}, {}), '(densepose_part_index)', False, 'from object_detection.utils import dataset_util\n'), ((1555, 22, 1555, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1555, 54, 1555, 65): 'densepose_x'}, {}), '(densepose_x)', False, 'from object_detection.utils import dataset_util\n'), ((1557, 22, 1557, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1557, 54, 1557, 65): 'densepose_y'}, {}), '(densepose_y)', False, 'from object_detection.utils import dataset_util\n'), ((1559, 22, 1559, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1559, 54, 1559, 65): 'densepose_u'}, {}), '(densepose_u)', False, 'from object_detection.utils import dataset_util\n'), ((1561, 22, 1561, 66), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1561, 54, 1561, 65): 'densepose_v'}, {}), '(densepose_v)', False, 'from object_detection.utils import dataset_util\n'), ((1621, 22, 1621, 62), 'object_detection.utils.dataset_util.bytes_feature', 'dataset_util.bytes_feature', ({(1621, 49, 1621, 61): 'encoded_jpeg'}, {}), '(encoded_jpeg)', False, 'from object_detection.utils import dataset_util\n'), ((1625, 22, 1625, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1625, 54, 1625, 64): 'bbox_ymins'}, {}), '(bbox_ymins)', False, 'from object_detection.utils import dataset_util\n'), ((1627, 22, 1627, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1627, 54, 1627, 64): 'bbox_xmins'}, {}), '(bbox_xmins)', False, 'from object_detection.utils import dataset_util\n'), ((1629, 22, 1629, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1629, 54, 1629, 64): 'bbox_ymaxs'}, {}), '(bbox_ymaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1631, 22, 1631, 65), 'object_detection.utils.dataset_util.float_list_feature', 'dataset_util.float_list_feature', ({(1631, 54, 1631, 64): 'bbox_xmaxs'}, {}), '(bbox_xmaxs)', False, 'from object_detection.utils import dataset_util\n'), ((1633, 22, 1633, 67), 'object_detection.utils.dataset_util.int64_list_feature', 'dataset_util.int64_list_feature', ({(1633, 54, 1633, 66): 'track_labels'}, {}), '(track_labels)', False, 'from object_detection.utils import dataset_util\n'), ((67, 49, 67, 62), 'six.b', 'six.b', ({(67, 55, 67, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((69, 49, 69, 66), 'six.b', 'six.b', ({(69, 55, 69, 65): '"""image_id"""'}, {}), "('image_id')", False, 'import six\n'), ((93, 49, 93, 62), 'six.b', 'six.b', ({(93, 55, 93, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((95, 49, 95, 66), 'six.b', 'six.b', ({(95, 55, 95, 65): '"""image_id"""'}, {}), "('image_id')", False, 'import six\n'), ((126, 49, 126, 61), 'six.b', 'six.b', ({(126, 55, 126, 60): '"""abc"""'}, {}), "('abc')", False, 'import six\n'), ((128, 49, 128, 66), 'six.b', 'six.b', ({(128, 55, 128, 65): '"""filename"""'}, {}), "('filename')", False, 'import six\n'), ((151, 49, 151, 61), 'six.b', 'six.b', ({(151, 55, 151, 60): '"""png"""'}, {}), "('png')", False, 'import six\n'), ((153, 49, 153, 66), 'six.b', 'six.b', ({(153, 55, 153, 65): '"""image_id"""'}, {}), "('image_id')", False, 'import six\n'), ((192, 49, 192, 61), 'six.b', 'six.b', ({(192, 55, 192, 60): '"""png"""'}, {}), "('png')", False, 'import six\n'), ((219, 49, 219, 61), 'six.b', 'six.b', ({(219, 55, 219, 60): '"""png"""'}, {}), "('png')", False, 'import six\n'), ((254, 49, 254, 62), 'six.b', 'six.b', ({(254, 55, 254, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((299, 49, 299, 62), 'six.b', 'six.b', ({(299, 55, 299, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((363, 49, 363, 62), 'six.b', 'six.b', ({(363, 55, 363, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((415, 49, 415, 62), 'six.b', 'six.b', ({(415, 55, 415, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((480, 49, 480, 62), 'six.b', 'six.b', ({(480, 55, 480, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((539, 49, 539, 62), 'six.b', 'six.b', ({(539, 55, 539, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((575, 49, 575, 62), 'six.b', 'six.b', ({(575, 55, 575, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((610, 49, 610, 62), 'six.b', 'six.b', ({(610, 55, 610, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((648, 49, 648, 62), 'six.b', 'six.b', ({(648, 55, 648, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((680, 49, 680, 62), 'six.b', 'six.b', ({(680, 55, 680, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((728, 49, 728, 62), 'six.b', 'six.b', ({(728, 55, 728, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((770, 49, 770, 62), 'six.b', 'six.b', ({(770, 55, 770, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((813, 49, 813, 62), 'six.b', 'six.b', ({(813, 55, 813, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((858, 49, 858, 62), 'six.b', 'six.b', ({(858, 55, 858, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((901, 49, 901, 62), 'six.b', 'six.b', ({(901, 55, 901, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((945, 49, 945, 62), 'six.b', 'six.b', ({(945, 55, 945, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((975, 49, 975, 62), 'six.b', 'six.b', ({(975, 55, 975, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1002, 49, 1002, 62), 'six.b', 'six.b', ({(1002, 55, 1002, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1030, 49, 1030, 62), 'six.b', 'six.b', ({(1030, 55, 1030, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1061, 49, 1061, 62), 'six.b', 'six.b', ({(1061, 55, 1061, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1092, 49, 1092, 62), 'six.b', 'six.b', ({(1092, 55, 1092, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1123, 49, 1123, 62), 'six.b', 'six.b', ({(1123, 55, 1123, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1154, 49, 1154, 62), 'six.b', 'six.b', ({(1154, 55, 1154, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1200, 49, 1200, 62), 'six.b', 'six.b', ({(1200, 55, 1200, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1258, 49, 1258, 62), 'six.b', 'six.b', ({(1258, 55, 1258, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1285, 61, 1285, 74), 'six.b', 'six.b', ({(1285, 67, 1285, 73): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1304, 49, 1304, 62), 'six.b', 'six.b', ({(1304, 55, 1304, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1351, 49, 1351, 62), 'six.b', 'six.b', ({(1351, 55, 1351, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1397, 49, 1397, 62), 'six.b', 'six.b', ({(1397, 55, 1397, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1472, 49, 1472, 62), 'six.b', 'six.b', ({(1472, 55, 1472, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1541, 49, 1541, 62), 'six.b', 'six.b', ({(1541, 55, 1541, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1623, 49, 1623, 62), 'six.b', 'six.b', ({(1623, 55, 1623, 61): '"""jpeg"""'}, {}), "('jpeg')", False, 'import six\n'), ((1307, 27, 1307, 39), 'six.b', 'six.b', ({(1307, 33, 1307, 38): '"""dog"""'}, {}), "('dog')", False, 'import six\n'), ((1307, 41, 1307, 53), 'six.b', 'six.b', ({(1307, 47, 1307, 52): '"""cat"""'}, {}), "('cat')", False, 'import six\n')]
m10singh94/Python-programs
counting_capitals.py
a83083044b4a85afcf70c4b7024287a808b01fee
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 08:09:31 2020 @author: Shivadhar SIngh """ def count_capitals(string): count = 0 for ch in string: if ord(ch) >= 65 and ord(ch) <= 90: count += 1 return count def remove_substring_everywhere(string, substring): ''' Remove all occurrences of substring from string, and return the resulting string. Both arguments must be strings. ''' p = string.find(substring) if p == -1: return string i = p newstr = string[0:i] lsub = len(substring) # length of the substring while p < len(string) and string.find(substring) != -1: p = string.find(substring) if p==-1: return newstr+string[i+lsub:] newstr += string[p + lsub : p] return newstr
[]
astroumd/admit
admit/at/GenerateSpectrum_AT.py
bbf3d79bb6e1a6f7523553ed8ede0d358d106f2c
""" .. _GenerateSpectrum-at-api: **GenerateSpectrum_AT** --- Generates synthetic test spectra. ------------------------------------------------------------- This module defines the GenerateSpectrum_AT class. """ from admit.AT import AT import admit.util.bdp_types as bt from admit.bdp.CubeSpectrum_BDP import CubeSpectrum_BDP import admit.util.filter.Filter1D as Filter1D import admit.util.Table as Table import admit.util.utils as utils from admit.util import APlot import admit.util.Image as Image from admit.util import SpectralLineSearch from admit.Summary import SummaryEntry import os import numpy as np from copy import deepcopy class GenerateSpectrum_AT(AT): """ Define a synthetic CubeSpectrum for testing. This task is only intended to generate synthetic spectra with noise, and to efficiently test LineID with a CubeSpectrum_BDP input. You can add continuum as well, and add any number of gaussian's, or even optionally read in an ASCII spectrum, and add noise and gaussians to this. Multiple spectra can be in the CubeSpectrum_BDP. When noise is added, spectra have a fixed RMS = 1.0, i.e. spectra are assumed to be in dimensionless S/N units. **Keywords** **file**: string Name of an ASCII file that contains a spectrum, optional. The first column must be frequency and the second column must be the intensity. If you just want to read a spectrum and not add noise, set seed=-1. Default: blank. **nchan**: int Number of output channels per spectrum. Ignored when file= given. Default: 1000. **nspectra**: int Number of output spectra. More than one are meant for different random realizations of the input conditions (either from file= and/or from lines= via seed=), but they are all written to the same BDP. Default: 1. **seed**: int Seed for random number generator. 0 is a special value that uses a random realization per call, e.g. time of the day. Use any other positive value to seed with a repeatable random sequence. -1 is a special value to disable the random number generator noise (for example if an input spectrum should not be polluted with random noise). Default: 0. **contin**: float Continuum level level added to the noise spectra. You can only add a continuum level when noise is added as well, i.e. when seed >= 0. Default: 0.0. **freq**: float The central frequency of the band in GHz. Default: 115.2712018. **delta**: float The size of each channel in MHz. Default: 0.5. **lines**: list of tuples Parameters for each Gaussian line. Intensity (SNR), center frequency in GHz, FHWM in km/s. Examples: [(15.0, 110.201, 22.0)] Produce a single Gaussian centered at 110.201 GHz that is 15.0 sigma tall with a FWHM of 22.0 km/s. [(12.0, 109.98, 15.3), (6.0, 110.0, 15.0)] Produce two Gaussians, one centered at 109.98 GHz with a peak of 12.0 sigma and FWHM of 15.3 kms, and a second centered at 110.0 GHz with an intensity of 6.0 sigma and FWHM of 15.0 km/s. Default: []. **transitions**: list List of any transitions to be included in the spectrum. Each entry should be a list containing the molecule name, frequency range (in GHz), intensity(SNR), FWHM in km/s and offset in km/s. Any tranitions from the given molecule(s) and frequency range will be included. Example of entry: [("13COv=0", [110.15, 110.25], 6.0, 30.0, 5.0), ("CH3CNv=0", [110.2, 110.5], 4.5, 10.0, 0.0)] This will produce a single 13CO line with a peak intensity of 6 sigma, FWHM of 30.0 km/s and centered at a offset velocity of 5.0 km/s; and a set of 6 of CH3CN lines (with hyperfine components), with the highest line strength transition peaking at 4.5 sigma, and the rest proportionally weaker based on line strength, all with a FWHM of 10.0 km/s and no offset. Molecules can be given multiple times for the purpose of having multiple velocity components. Default: []. **hanning**: bool If True then do a final (1/4,1/2,1/4) hanning smooth over 3 channels. Default: False. **Input BDPs** None **Output BDPs** **CubeSpectrum_BDP**: count: 1 Spectrum through the cube. Stored as a single multi-plane table if nspectra > 1. Output BDP name takes from the input Image by replacing the extension with "csp". See also :ref:`CubeSpectrum-bdp-api`. Parameters ---------- keyval : dictionary, optional Keyword values. Attributes ---------- _version : string Version string. """ def __init__(self,**keyval): keys = {"file" : "", "nchan" : 1000, "nspectra" : 1, "seed" : 0, # -1 is special for no noise "contin" : 0.0, "freq" : 115.2712018, "delta" : 0.5, # channel width in MHz "lines" : [], # [(snr,freq0,fwhm),...] "transitions" : [], "hanning" : False, } AT.__init__(self,keys,keyval) self._version = "1.0.0" self.set_bdp_in([]) self.set_bdp_out([(CubeSpectrum_BDP,1)]) self.spec_description = [] # for summary() def summary(self): """Returns the summary dictionary from the AT, for merging into the ADMIT Summary object. GenerateSpectrum_AT adds the following to ADMIT summary: .. table:: :class: borderless +---------+----------+---------------------------+ | Key | type | Description | +=========+==========+===========================+ | spectra | list | the spectral plots | +---------+----------+---------------------------+ Parameters ---------- None Returns ------- dict Dictionary of SummaryEntry """ if hasattr(self,"_summary"): return self._summary else: return {} def run(self): """Runs the task. Parameters ---------- None Returns ------- None """ self._summary = {} dt = utils.Dtime("CubeSpectrum") seed = self.getkey("seed") if seed <= 0: np.random.seed() else: np.random.seed(seed) #print "RANDOM.GET_STATE:",np.random.get_state() contin = self.getkey("contin") rms = 1.0 # not a user parameter, we do all spectra in S/N space f0 = self.getkey("freq") # central frequency in band df = self.getkey("delta") / 1000.0 # channel width (in GHz) nspectra = self.getkey("nspectra") taskargs = " contin=%f freq=%f delta=%f nspectra=%f " % (contin,f0,df,nspectra) spec = range(nspectra) dt.tag("start") if self.getkey("file") != "": print "READING spectrum from",self.getkey("file") (freq, spec[0]) = getspec(self.getkey("file")) nchan = len(freq) print "Spectrum %d chans from %f to %f: min/max = %f %f" % (nchan, freq.min(), freq.max(), spec[0].min(), spec[0].max()) # @todo nspectra>1 not tested for i in range(1,nspectra): spec[i] = deepcopy(spec[0]) dt.tag("getspec") else: nchan = self.getkey("nchan") freq = np.arange(nchan, dtype=np.float64) center = int(nchan/2) for i in range(nchan): freq[i] = f0 + (float((i - center)) * df) for i in range(nspectra): spec[i] = np.zeros(nchan) chans = np.arange(nchan) taskargs += " nchan = %d" % nchan for i in range(nspectra): if seed >= 0: spec[i] += np.random.normal(contin, rms, nchan) # print "MEAN/STD",spec[i].mean(),spec[i].std() lines = self.getkey("lines") sls = SpectralLineSearch(False) for item in self.getkey("transitions"): kw = {"include_only_nrao" : True, "line_strengths": ["ls1", "ls2"], "energy_levels" : ["el2", "el4"], "fel" : True, "species" : item[0] } results = sls.search(item[1][0], item[1][1], "off", **kw) # look at line strengths if len(results) > 0: mx = 0.0 indx = -1 for i in range(len(results)): if results[i].getkey("linestrength") > mx: indx = i mx = results[i].getkey("linestrength") for res in results: if mx > 0.0: lines.append([item[2] * res.getkey("linestrength") / mx, res.getkey("frequency") + utils.veltofreq(item[4], res.getkey("frequency")), item[3]]) else: lines.append([item[2], res.getkey("frequency") + utils.veltofreq(item[4], res.getkey("frequency")), item[3]]) for item in lines: for i in range(nspectra): spec[i] += utils.gaussian1D(freq, item[0], item[1], utils.veltofreq(item[2], item[1])) if self.getkey("hanning"): for i in range(nspectra): filter = Filter1D.Filter1D(spec[i], "hanning", **{"width" : 3}) spec[i] = filter.run() dt.tag("hanning") center = int(nchan/2) dt.tag("open") bdp_name = self.mkext("Genspec","csp") b2 = CubeSpectrum_BDP(bdp_name) self.addoutput(b2) images = {} # png's accumulated for i in range(nspectra): sd = [] caption = "Generated Spectrum %d" % i # construct the Table for CubeSpectrum_BDP # @todo note data needs to be a tuple, later to be column_stack'd labels = ["channel" ,"frequency" ,"flux" ] units = ["number" ,"GHz" ,"" ] data = (chans ,freq ,spec[i] ) # plane 0 : we are allowing a multiplane table, so the first plane is special if i==0: table = Table(columns=labels,units=units,data=np.column_stack(data),planes=["0"]) else: table.addPlane(np.column_stack(data),"%d" % i) # example plot , one per position for now x = chans xlab = 'Channel' y = [spec[i]] sd.append(xlab) myplot = APlot(ptype=self._plot_type,pmode=self._plot_mode, abspath=self.dir()) ylab = 'Flux' p1 = "%s_%d" % (bdp_name,i) myplot.plotter(x,y,"",p1,xlab=xlab,ylab=ylab,thumbnail=True) # Why not use p1 as the key? ii = images["pos%d" % i] = myplot.getFigure(figno=myplot.figno,relative=True) thumbname = myplot.getThumbnail(figno=myplot.figno,relative=True) image = Image(images=images, description="CubeSpectrum") sd.extend([ii, thumbname, caption]) self.spec_description.append(sd) self._summary["spectra"] = SummaryEntry(self.spec_description,"GenerateSpectrum_AT",self.id(True), taskargs) dt.tag("table") b2.setkey("image",image) b2.setkey("table",table) b2.setkey("sigma",rms) b2.setkey("mean",contin) dt.tag("done") dt.end() # @todo this could go as a very generic routine in utils # def getspec(file, xcol=0, ycol=1): """ read a spectrum/table from column 1,2 returns: (freq,spec) """ lines = open(file).readlines() x = [] y = [] mincol = max(xcol,ycol) + 1 for line in lines: if line[0] == '#': continue w = line.split() if len(w) < mincol: continue x.append(float(w[xcol])) y.append(float(w[ycol])) return (np.array(x),np.array(y))
[]
nahidupa/grr
lib/flows/general/discovery_test.py
100a9d85ef2abb234e12e3ac2623caffb4116be7
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Tests for Interrogate.""" import socket from grr.client import vfs from grr.lib import action_mocks from grr.lib import aff4 from grr.lib import artifact_test from grr.lib import client_index from grr.lib import config_lib from grr.lib import flags from grr.lib import flow from grr.lib import rdfvalue from grr.lib import search from grr.lib import test_lib class DiscoveryTestEventListener(flow.EventListener): """A test listener to receive new client discoveries.""" well_known_session_id = rdfvalue.SessionID(flow_name="discovery_test") EVENTS = ["Discovery"] # For this test we just write the event as a class attribute. event = None @flow.EventHandler(auth_required=True) def ProcessMessage(self, message=None, event=None): _ = message DiscoveryTestEventListener.event = event class TestClientInterrogate(artifact_test.ArtifactTest): """Test the interrogate flow.""" def _CheckUsers(self, all_users): """Check all user stores.""" summary = self.fd.GetSummary() self.assertItemsEqual([x.username for x in summary.users], all_users) users = [x.username for x in self.fd.Get(self.fd.Schema.USER)] self.assertItemsEqual(users, all_users) self.assertItemsEqual(self.fd.Get(self.fd.Schema.USERNAMES), all_users) # Check kb users kbusers = [x.username for x in self.fd.Get(self.fd.Schema.KNOWLEDGE_BASE).users] self.assertItemsEqual(kbusers, all_users) def _CheckAFF4Object(self, hostname, system, install_date): self.assertEqual(self.fd.Get(self.fd.Schema.HOSTNAME), hostname) self.assertEqual(self.fd.Get(self.fd.Schema.SYSTEM), system) self.assertEqual(self.fd.Get(self.fd.Schema.INSTALL_DATE), install_date) def _CheckClientInfo(self): info = self.fd.Get(self.fd.Schema.CLIENT_INFO) self.assertEqual(info.client_name, config_lib.CONFIG["Client.name"]) self.assertEqual(info.client_version, int(config_lib.CONFIG["Client.version_numeric"])) self.assertEqual(info.build_time, config_lib.CONFIG["Client.build_time"]) def _CheckGRRConfig(self): """Check old and new client config.""" config_info = self.fd.Get(self.fd.Schema.GRR_CONFIGURATION) self.assertEqual(config_info["Client.control_urls"], ["http://localhost:8001/control"]) self.assertEqual(config_info["Client.poll_min"], 1.0) def _CheckClientIndex(self, host_pattern): """Check that the index has been updated.""" index_fd = aff4.FACTORY.Create(self.fd.Schema.client_index, "AFF4Index", mode="r", token=self.token) self.assertEqual( [self.fd.urn], [x for x in index_fd.Query([self.fd.Schema.HOSTNAME], host_pattern)]) def _CheckClientKwIndex(self, keywords, expected_count): # Tests that the client index has expected_count results when # searched for keywords. index = aff4.FACTORY.Create(client_index.MAIN_INDEX, aff4_type="ClientIndex", mode="rw", token=self.token) self.assertEqual(len(index.LookupClients(keywords)), expected_count) def _CheckNotificationsCreated(self): user_fd = aff4.FACTORY.Open("aff4:/users/test", token=self.token) notifications = user_fd.Get(user_fd.Schema.PENDING_NOTIFICATIONS) self.assertEqual(len(notifications), 1) notification = notifications[0] self.assertEqual(notification.subject, rdfvalue.RDFURN(self.client_id)) def _CheckClientSummary(self, osname, version, kernel="3.13.0-39-generic", release="5"): summary = self.fd.GetSummary() self.assertEqual(summary.client_info.client_name, config_lib.CONFIG["Client.name"]) self.assertEqual(summary.client_info.client_version, int(config_lib.CONFIG["Client.version_numeric"])) self.assertEqual(summary.client_info.build_time, config_lib.CONFIG["Client.build_time"]) self.assertEqual(summary.system_info.system, osname) self.assertEqual(summary.system_info.node, "test_node") self.assertEqual(summary.system_info.release, release) self.assertEqual(summary.system_info.version, version) self.assertEqual(summary.system_info.machine, "i386") self.assertEqual(summary.system_info.kernel, kernel) self.assertEqual(len(summary.interfaces), 1) self.assertEqual(summary.interfaces[0].mac_address, "123456") # Check that the client summary was published to the event listener. self.assertEqual(DiscoveryTestEventListener.event.client_id, self.client_id) self.assertEqual( DiscoveryTestEventListener.event.interfaces[0].mac_address, "123456") def _CheckNetworkInfo(self): net_fd = self.fd.OpenMember("network") interfaces = list(net_fd.Get(net_fd.Schema.INTERFACES)) self.assertEqual(interfaces[0].mac_address, "123456") self.assertEqual(interfaces[0].addresses[0].human_readable, "100.100.100.1") self.assertEqual(socket.inet_ntoa(interfaces[0].addresses[0].packed_bytes), "100.100.100.1") # Mac addresses should be available as hex for searching mac_addresses = self.fd.Get(self.fd.Schema.MAC_ADDRESS) self.assertTrue("123456".encode("hex") in str(mac_addresses)) # Same for IP addresses. ip_addresses = self.fd.Get(self.fd.Schema.HOST_IPS) self.assertTrue("100.100.100.1" in str(ip_addresses)) def _CheckVFS(self): # Check that virtual directories exist for the mount points fd = aff4.FACTORY.Open(self.client_id.Add("fs/os/mnt/data"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) fd = aff4.FACTORY.Open(self.client_id.Add("fs/tsk/dev/sda"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) fd = aff4.FACTORY.Open(self.client_id.Add("devices/dev/sda"), token=self.token) # But no directory listing exists yet - we will need to fetch a new one self.assertEqual(len(list(fd.OpenChildren())), 0) def _CheckLabelIndex(self): """Check that label indexes are updated.""" self.assertEqual( list(search.SearchClients("label:Label2", token=self.token)), [self.client_id]) def _CheckWindowsDiskInfo(self): client = aff4.FACTORY.Open(self.client_id, token=self.token) volumes = client.Get(client.Schema.VOLUMES) self.assertEqual(len(volumes), 2) for result in volumes: self.assertTrue(isinstance(result, rdfvalue.Volume)) self.assertTrue(result.windows.drive_letter in ["Z:", "C:"]) def _CheckRegistryPathspec(self): # This tests that we can click refresh on a key in the registry vfs subtree # even if we haven't downloaded any other key above it in the tree. fd = aff4.FACTORY.Open(self.client_id.Add("registry").Add( "HKEY_LOCAL_MACHINE").Add("random/path/bla"), token=self.token) pathspec = fd.real_pathspec self.assertEqual(pathspec.pathtype, rdfvalue.PathSpec.PathType.REGISTRY) self.assertEqual(pathspec.CollapsePath(), u"/HKEY_LOCAL_MACHINE/random/path/bla") def _CheckRelease(self, desired_release, desired_version): # Test for correct Linux release override behaviour. client = aff4.FACTORY.Open(self.client_id, token=self.token) release = str(client.Get(client.Schema.OS_RELEASE)) version = str(client.Get(client.Schema.OS_VERSION)) self.assertEqual(release, desired_release) self.assertEqual(version, desired_version) def testInterrogateLinuxWithWtmp(self): """Test the Interrogate flow.""" test_lib.ClientFixture(self.client_id, token=self.token) vfs.VFS_HANDLERS[ rdfvalue.PathSpec.PathType.OS] = test_lib.FakeTestDataVFSHandler config_lib.CONFIG.Set("Artifacts.knowledge_base", ["LinuxWtmp", "NetgroupConfiguration", "LinuxRelease"]) config_lib.CONFIG.Set("Artifacts.netgroup_filter_regexes", [r"^login$"]) self.SetLinuxClient() client_mock = action_mocks.InterrogatedClient("TransferBuffer", "StatFile", "Find", "HashBuffer", "ListDirectory", "FingerprintFile") client_mock.InitializeClient() for _ in test_lib.TestFlowHelper("Interrogate", client_mock, token=self.token, client_id=self.client_id): pass self.fd = aff4.FACTORY.Open(self.client_id, token=self.token) self._CheckAFF4Object("test_node", "Linux", 100 * 1000000) self._CheckClientInfo() self._CheckClientIndex(".*test.*") self._CheckGRRConfig() self._CheckNotificationsCreated() self._CheckClientSummary("Linux", "14.4", release="Ubuntu", kernel="3.13.0-39-generic") self._CheckRelease("Ubuntu", "14.4") # users 1,2,3 from wtmp # users yagharek, isaac from netgroup self._CheckUsers(["yagharek", "isaac", "user1", "user2", "user3"]) self._CheckNetworkInfo() self._CheckVFS() self._CheckLabelIndex() self._CheckClientKwIndex(["Linux"], 1) self._CheckClientKwIndex(["Label2"], 1) def testInterrogateWindows(self): """Test the Interrogate flow.""" test_lib.ClientFixture(self.client_id, token=self.token) vfs.VFS_HANDLERS[ rdfvalue.PathSpec.PathType.REGISTRY] = test_lib.FakeRegistryVFSHandler vfs.VFS_HANDLERS[ rdfvalue.PathSpec.PathType.OS] = test_lib.FakeFullVFSHandler client_mock = action_mocks.InterrogatedClient("TransferBuffer", "StatFile", "Find", "HashBuffer", "ListDirectory", "FingerprintFile") self.SetWindowsClient() client_mock.InitializeClient(system="Windows", version="6.1.7600", kernel="6.1.7601") # Run the flow in the simulated way for _ in test_lib.TestFlowHelper("Interrogate", client_mock, token=self.token, client_id=self.client_id): pass self.fd = aff4.FACTORY.Open(self.client_id, token=self.token) self._CheckAFF4Object("test_node", "Windows", 100 * 1000000) self._CheckClientInfo() self._CheckClientIndex(".*Host.*") self._CheckGRRConfig() self._CheckNotificationsCreated() self._CheckClientSummary("Windows", "6.1.7600", kernel="6.1.7601") # users Bert and Ernie added by the fixture should not be present (USERS # overriden by kb) # jim parsed from registry profile keys self._CheckUsers(["jim", "kovacs"]) self._CheckNetworkInfo() self._CheckVFS() self._CheckLabelIndex() self._CheckWindowsDiskInfo() self._CheckRegistryPathspec() self._CheckClientKwIndex(["Linux"], 0) self._CheckClientKwIndex(["Windows"], 1) self._CheckClientKwIndex(["Label2"], 1) def main(argv): # Run the full test suite test_lib.GrrTestProgram(argv=argv) if __name__ == "__main__": flags.StartMain(main)
[((23, 26, 23, 72), 'grr.lib.rdfvalue.SessionID', 'rdfvalue.SessionID', (), '', False, 'from grr.lib import rdfvalue\n'), ((29, 3, 29, 40), 'grr.lib.flow.EventHandler', 'flow.EventHandler', (), '', False, 'from grr.lib import flow\n'), ((284, 2, 284, 36), 'grr.lib.test_lib.GrrTestProgram', 'test_lib.GrrTestProgram', (), '', False, 'from grr.lib import test_lib\n'), ((287, 2, 287, 23), 'grr.lib.flags.StartMain', 'flags.StartMain', ({(287, 18, 287, 22): 'main'}, {}), '(main)', False, 'from grr.lib import flags\n'), ((73, 15, 74, 62), 'grr.lib.aff4.FACTORY.Create', 'aff4.FACTORY.Create', (), '', False, 'from grr.lib import aff4\n'), ((83, 12, 86, 49), 'grr.lib.aff4.FACTORY.Create', 'aff4.FACTORY.Create', (), '', False, 'from grr.lib import aff4\n'), ((91, 14, 91, 69), 'grr.lib.aff4.FACTORY.Open', 'aff4.FACTORY.Open', (), '', False, 'from grr.lib import aff4\n'), ((165, 13, 165, 64), 'grr.lib.aff4.FACTORY.Open', 'aff4.FACTORY.Open', (), '', False, 'from grr.lib import aff4\n'), ((186, 13, 186, 64), 'grr.lib.aff4.FACTORY.Open', 'aff4.FACTORY.Open', (), '', False, 'from grr.lib import aff4\n'), ((195, 4, 195, 60), 'grr.lib.test_lib.ClientFixture', 'test_lib.ClientFixture', (), '', False, 'from grr.lib import test_lib\n'), ((200, 4, 202, 71), 'grr.lib.config_lib.CONFIG.Set', 'config_lib.CONFIG.Set', ({(200, 26, 200, 52): '"""Artifacts.knowledge_base"""', (200, 54, 202, 70): "['LinuxWtmp', 'NetgroupConfiguration', 'LinuxRelease']"}, {}), "('Artifacts.knowledge_base', ['LinuxWtmp',\n 'NetgroupConfiguration', 'LinuxRelease'])", False, 'from grr.lib import config_lib\n'), ((203, 4, 203, 76), 'grr.lib.config_lib.CONFIG.Set', 'config_lib.CONFIG.Set', ({(203, 26, 203, 61): '"""Artifacts.netgroup_filter_regexes"""', (203, 63, 203, 75): "['^login$']"}, {}), "('Artifacts.netgroup_filter_regexes', ['^login$'])", False, 'from grr.lib import config_lib\n'), ((205, 18, 208, 68), 'grr.lib.action_mocks.InterrogatedClient', 'action_mocks.InterrogatedClient', ({(205, 50, 205, 66): '"""TransferBuffer"""', (205, 68, 205, 78): '"""StatFile"""', (206, 50, 206, 56): '"""Find"""', (206, 58, 206, 70): '"""HashBuffer"""', (207, 50, 207, 65): '"""ListDirectory"""', (208, 50, 208, 67): '"""FingerprintFile"""'}, {}), "('TransferBuffer', 'StatFile', 'Find',\n 'HashBuffer', 'ListDirectory', 'FingerprintFile')", False, 'from grr.lib import action_mocks\n'), ((211, 13, 213, 62), 'grr.lib.test_lib.TestFlowHelper', 'test_lib.TestFlowHelper', (), '', False, 'from grr.lib import test_lib\n'), ((216, 14, 216, 65), 'grr.lib.aff4.FACTORY.Open', 'aff4.FACTORY.Open', (), '', False, 'from grr.lib import aff4\n'), ((238, 4, 238, 60), 'grr.lib.test_lib.ClientFixture', 'test_lib.ClientFixture', (), '', False, 'from grr.lib import test_lib\n'), ((245, 18, 248, 68), 'grr.lib.action_mocks.InterrogatedClient', 'action_mocks.InterrogatedClient', ({(245, 50, 245, 66): '"""TransferBuffer"""', (245, 68, 245, 78): '"""StatFile"""', (246, 50, 246, 56): '"""Find"""', (246, 58, 246, 70): '"""HashBuffer"""', (247, 50, 247, 65): '"""ListDirectory"""', (248, 50, 248, 67): '"""FingerprintFile"""'}, {}), "('TransferBuffer', 'StatFile', 'Find',\n 'HashBuffer', 'ListDirectory', 'FingerprintFile')", False, 'from grr.lib import action_mocks\n'), ((255, 13, 257, 62), 'grr.lib.test_lib.TestFlowHelper', 'test_lib.TestFlowHelper', (), '', False, 'from grr.lib import test_lib\n'), ((260, 14, 260, 65), 'grr.lib.aff4.FACTORY.Open', 'aff4.FACTORY.Open', (), '', False, 'from grr.lib import aff4\n'), ((97, 43, 97, 74), 'grr.lib.rdfvalue.RDFURN', 'rdfvalue.RDFURN', ({(97, 59, 97, 73): 'self.client_id'}, {}), '(self.client_id)', False, 'from grr.lib import rdfvalue\n'), ((130, 21, 130, 78), 'socket.inet_ntoa', 'socket.inet_ntoa', ({(130, 38, 130, 77): 'interfaces[0].addresses[0].packed_bytes'}, {}), '(interfaces[0].addresses[0].packed_bytes)', False, 'import socket\n'), ((161, 13, 161, 67), 'grr.lib.search.SearchClients', 'search.SearchClients', (), '', False, 'from grr.lib import search\n')]
liff-engineer/articles
practices/20210112/GraphicsView.py
ad3386ef9cda5083793f485e309a9f85ab36f664
import sys from PySide2.QtWidgets import QGraphicsView, QGraphicsScene, QApplication from PySide2.QtCore import * from PySide2.QtGui import * class GraphicsView(QGraphicsView): def __init__(self, parent=None): super().__init__(parent) # 画布视图尺寸 self.w = 64000.0 self.h = 32000.0 # 缩放相关 self.zoomInFactor = 1.25 self.zoomClamp = True self.zoom = 10 self.zoomStep = 1 self.zoomRange = [0, 20] self.setRenderHints(QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setDragMode(QGraphicsView.RubberBandDrag) self.setScene(QGraphicsScene()) self.setSceneRect(-self.w/2, -self.h/2, self.w, self.h) def zoomImpl(self, bigOrSmall: bool): zoomOutFactor = 1 / self.zoomInFactor zoomFactor = zoomOutFactor if bigOrSmall: zoomFactor = self.zoomInFactor self.zoom += self.zoomStep else: zoomFactor = zoomOutFactor self.zoom -= self.zoomStep clamped = False if self.zoom < self.zoomRange[0]: self.zoom, clamped = self.zoomRange[0], True if self.zoom > self.zoomRange[1]: self.zoom, clamped = self.zoomRange[1], True if not clamped or self.zoomClamp is False: self.scale(zoomFactor, zoomFactor) def panBeginImpl(self, event): releaseEvent = QMouseEvent(QEvent.MouseButtonRelease, event.localPos(), event.screenPos(), Qt.LeftButton, Qt.NoButton, event.modifiers()) super().mouseReleaseEvent(releaseEvent) self.setDragMode(QGraphicsView.ScrollHandDrag) fakeEvent = QMouseEvent(event.type(), event.localPos(), event.screenPos(), Qt.LeftButton, event.buttons() | Qt.LeftButton, event.modifiers()) super().mousePressEvent(fakeEvent) def panEndImpl(self, event): fakeEvent = QMouseEvent(event.type(), event.localPos(), event.screenPos(), Qt.LeftButton, event.buttons() & ~Qt.LeftButton, event.modifiers()) super().mouseReleaseEvent(fakeEvent) self.setDragMode(QGraphicsView.RubberBandDrag) def keyPressEvent(self, event): if event.matches(QKeySequence.ZoomIn): self.zoomImpl(True) elif event.matches(QKeySequence.ZoomOut): self.zoomImpl(False) else: super().keyPressEvent(event) def wheelEvent(self, event): if self.dragMode() == QGraphicsView.ScrollHandDrag: return return self.zoomImpl(event.angleDelta().y() > 0) def mousePressEvent(self, event): if event.button() == Qt.MiddleButton: return self.panBeginImpl(event) super().mousePressEvent(event) def mouseReleaseEvent(self, event): if event.button() == Qt.MiddleButton: return self.panEndImpl(event) super().mouseReleaseEvent(event) if __name__ == "__main__": app = QApplication(sys.argv) appView = GraphicsView() appView.scene().addSimpleText('[email protected]') appView.scene().addRect(-200, -150, 400, 300) appView.show() sys.exit(app.exec_())
[((93, 10, 93, 32), 'PySide2.QtWidgets.QApplication', 'QApplication', ({(93, 23, 93, 31): 'sys.argv'}, {}), '(sys.argv)', False, 'from PySide2.QtWidgets import QGraphicsView, QGraphicsScene, QApplication\n'), ((31, 22, 31, 38), 'PySide2.QtWidgets.QGraphicsScene', 'QGraphicsScene', ({}, {}), '()', False, 'from PySide2.QtWidgets import QGraphicsView, QGraphicsScene, QApplication\n')]
joncotton/armstrong.hatband
armstrong/hatband/tests/_utils.py
c71aed4bd0b03a78d68a6b306e8a0ba9cd92324e
from armstrong.dev.tests.utils import ArmstrongTestCase import random def random_range(): # TODO: make sure this can only be generated once return range(random.randint(1000, 2000)) class HatbandTestCase(ArmstrongTestCase): pass class HatbandTestMixin(object): script_code = """ <script type="text/javascript" src="/static/ckeditor/ckeditor.js"></script> """.strip() textarea_code = 'class="ckeditor"></textarea>' def assertCkEditorPresent(self, response): self.assertContains(response, self.script_code) self.assertContains(response, self.textarea_code) def assertCkEditorNotPresent(self, response): self.assertNotContains(response, self.script_code) self.assertNotContains(response, self.textarea_code)
[((7, 17, 7, 43), 'random.randint', 'random.randint', ({(7, 32, 7, 36): '(1000)', (7, 38, 7, 42): '(2000)'}, {}), '(1000, 2000)', False, 'import random\n')]
ariroffe/logics
tests/propositional/test_natural_deduction.py
fb918ae8cf243a452e5b030f0df17add83f47f8b
import unittest from logics.classes.propositional import Inference, Formula from logics.classes.propositional.proof_theories import NaturalDeductionStep, NaturalDeductionRule from logics.utils.parsers import classical_parser from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system class TestClassicalNaturalDeductionSystem(unittest.TestCase): def test_natural_deduction_rule(self): """Test overriding of index and len methods in NaturalDeductionRule""" rule = NaturalDeductionRule([ '(...)', NaturalDeductionStep(Formula(['→', ['A'], ['B']])), '(...)', NaturalDeductionStep(Formula(['B']), 'E→', [0, 1]) ]) self.assertEqual(rule.index(NaturalDeductionStep(Formula(['B']), 'E→', [0, 1])), 1) self.assertEqual(len(rule), 2) def test_nd_system(self): """Test the method that tells if a step is a correct application of a rule""" # A correct derivation deriv = classical_parser.parse_derivation( """p; premise (p → q); premise q; E→; [1, 0]; [] p ∧ q; I∧; [0, 2]; []""", natural_deduction=True) # Check is application of the correct rule, and a different rule self.assertTrue(nd_system.is_correct_application(deriv, 2, nd_system.rules['E→'])) self.assertFalse(nd_system.is_correct_application(deriv, 2, nd_system.rules['E∧2'])) self.assertTrue(nd_system.is_correct_application(deriv, 3, nd_system.rules['I∧'])) self.assertFalse(nd_system.is_correct_application(deriv, 3, nd_system.rules['E→'])) # Check is correct derivation of the correct and an incorrect inference i = Inference([Formula(['p']), Formula(['→', ['p'], ['q']])], [Formula(['∧', ['p'], ['q']])]) self.assertTrue(nd_system.is_correct_derivation(deriv, i)) i2 = Inference([Formula(['p']), Formula(['→', ['p'], ['q']])], [Formula(['∧', ['q'], ['p']])]) self.assertFalse(nd_system.is_correct_derivation(deriv, i2)) # Repeating steps should not alter the outcome (should print a warning) # deriv2_0 = classical_parser.parse_derivation( # """p; supposition; []; [0] # p; repetition; [0, 0]; [0]""", # natural_deduction=True) # self.assertTrue(nd_system.is_correct_application(deriv2_0, 1, nd_system.rules['repetition'])) # Test step in the future deriv2_1 = classical_parser.parse_derivation( """p; supposition; []; [0] p; repetition; [1]; [0]""", natural_deduction=True) deriv2_2 = classical_parser.parse_derivation( """p; supposition; []; [0] p; repetition; [2]; [0]""", natural_deduction=True) self.assertFalse(nd_system.is_correct_application(deriv2_1, 1, nd_system.rules['repetition'])) self.assertFalse(nd_system.is_correct_application(deriv2_2, 1, nd_system.rules['repetition'])) # ------------------------------------------------- # Test incorrect use of suppositions # Using a step in a closed supposition deriv3_1 = classical_parser.parse_derivation( """p; supposition; []; [0] p; repetition; [0]; [0] (p → p); I→; [0, 1]; [] p; E→; [2, 0]; []""", natural_deduction=True) # Check correct application of rep and I→ self.assertTrue(nd_system.is_correct_application(deriv3_1, 1, nd_system.rules['repetition'])) self.assertTrue(nd_system.is_correct_application(deriv3_1, 2, nd_system.rules['I→'])) self.assertFalse(nd_system.is_correct_application(deriv3_1, 3, nd_system.rules['E→'])) # Closing a supposition with a rule that does not close deriv3_2 = classical_parser.parse_derivation(''' p; premise p; supposition; []; [1] p; repetition; [0]; [1] (p ∨ q); I∨1; [0]; []''', natural_deduction=True) self.assertFalse(nd_system.is_correct_application(deriv3_2, 3, nd_system.rules['I∨1'])) # Closing two suppositions at once deriv3_3 = classical_parser.parse_derivation( """p; supposition; []; [0] p; supposition; [0]; [0, 1] (p → p); I→; [0, 1]; []""", natural_deduction=True) self.assertFalse(nd_system.is_correct_application(deriv3_3, 2, nd_system.rules['I→'])) # Not closing a supposition with a rule that does close deriv3_4 = classical_parser.parse_derivation( """p; supposition; []; [0] p; repetition; [0]; [0] (p → p); I→; [0, 1]; [0]""", natural_deduction=True) self.assertFalse(nd_system.is_correct_application(deriv3_4, 2, nd_system.rules['I→'])) # Incorrect opening of suppositions deriv3_5 = classical_parser.parse_derivation( """p; supposition; []; []""", natural_deduction=True) self.assertFalse(nd_system.is_correct_derivation(deriv3_5, None)) deriv3_6 = classical_parser.parse_derivation( """p; premise; []; [] q; supposition; []; [0]""", natural_deduction=True) self.assertFalse(nd_system.is_correct_derivation(deriv3_6, None)) # ------------------------------------------------- # A correct derivation using all the rules deriv4 = classical_parser.parse_derivation( """q; premise; []; [] ~q; supposition; []; [1] ~q; repetition; [1]; [1] (q ∧ ~q); I∧; [0, 2]; [1] q; E∧1; [3]; [1] ⊥; E~; [1, 4]; [1] p; EFSQ; [5]; [1] ⊥; repetition; [5]; [1] ~~q; I~; [1, 7]; [] q; ~~; [8]; [] q; supposition; []; [10] q; repetition; [10]; [10] (q → q); I→; [10, 11]; [] q; E→; [12, 9]; [] (q ∨ p); I∨1; [13]; [] (p → q); premise; []; [] q; E∨; [14, 12, 15]; [] """, natural_deduction=True) i3 = Inference([Formula(['q']), Formula(['→', ['p'], ['q']])], [Formula(['q'])]) self.assertTrue(nd_system.is_correct_derivation(deriv4, i3)) def test_rule_order(self): # i1 is conjunction introduction i1 = Inference([Formula(['p']), Formula(['q'])], [Formula(['∧', ['p'], ['q']])]) # First derivation: standard one deriv1_1 = classical_parser.parse_derivation( """p; premise; []; [] q; premise; []; [] (p ∧ q); I∧; [0, 1]; []""", natural_deduction=True) self.assertTrue(nd_system.is_correct_derivation(deriv1_1, i1)) # Second derivation: reverse on_steps order deriv1_2 = classical_parser.parse_derivation( """p; premise; []; [] q; premise; []; [] (p ∧ q); I∧; [1, 0]; []""", natural_deduction=True) self.assertFalse(nd_system.is_correct_derivation(deriv1_2, i1)) i2 = Inference([Formula(['p']), Formula(['q'])], [Formula(['∧', ['q'], ['p']])]) # Third derivation: reverse the conjuncts deriv2_1 = classical_parser.parse_derivation( """p; premise; []; [] q; premise; []; [] (q ∧ p); I∧; [1, 0]; []""", natural_deduction=True) self.assertTrue(nd_system.is_correct_derivation(deriv2_1, i2)) # Fourth derivation: reverse the conjuncts and the on_steps deriv2_2 = classical_parser.parse_derivation( """p; premise; []; [] q; premise; []; [] (q ∧ p); I∧; [0, 1]; []""", natural_deduction=True) self.assertFalse(nd_system.is_correct_derivation(deriv2_2, i2)) if __name__ == '__main__': unittest.main()
[((184, 4, 184, 19), 'unittest.main', 'unittest.main', ({}, {}), '()', False, 'import unittest\n'), ((25, 16, 30, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((54, 19, 57, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((58, 19, 61, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((69, 19, 74, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((81, 19, 86, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((90, 19, 94, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((98, 19, 102, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((106, 19, 108, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((110, 19, 113, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((119, 17, 137, 40), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((148, 19, 152, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((156, 19, 160, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((167, 19, 171, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((175, 19, 179, 35), 'logics.utils.parsers.classical_parser.parse_derivation', 'classical_parser.parse_derivation', (), '', False, 'from logics.utils.parsers import classical_parser\n'), ((33, 24, 33, 91), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(33, 57, 33, 62): 'deriv', (33, 64, 33, 65): '(2)', (33, 67, 33, 90): "nd_system.rules['E→']"}, {}), "(deriv, 2, nd_system.rules['E→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((34, 25, 34, 93), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(34, 58, 34, 63): 'deriv', (34, 65, 34, 66): '(2)', (34, 68, 34, 92): "nd_system.rules['E∧2']"}, {}), "(deriv, 2, nd_system.rules['E∧2'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((35, 24, 35, 91), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(35, 57, 35, 62): 'deriv', (35, 64, 35, 65): '(3)', (35, 67, 35, 90): "nd_system.rules['I∧']"}, {}), "(deriv, 3, nd_system.rules['I∧'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((36, 25, 36, 92), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(36, 58, 36, 63): 'deriv', (36, 65, 36, 66): '(3)', (36, 68, 36, 91): "nd_system.rules['E→']"}, {}), "(deriv, 3, nd_system.rules['E→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((41, 24, 41, 65), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(41, 56, 41, 61): 'deriv', (41, 63, 41, 64): 'i'}, {}), '(deriv, i)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((44, 25, 44, 67), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(44, 57, 44, 62): 'deriv', (44, 64, 44, 66): 'i2'}, {}), '(deriv, i2)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((62, 25, 62, 101), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(62, 58, 62, 66): 'deriv2_1', (62, 68, 62, 69): '(1)', (62, 71, 62, 100): "nd_system.rules['repetition']"}, {}), "(deriv2_1, 1, nd_system.rules['repetition'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((63, 25, 63, 101), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(63, 58, 63, 66): 'deriv2_2', (63, 68, 63, 69): '(1)', (63, 71, 63, 100): "nd_system.rules['repetition']"}, {}), "(deriv2_2, 1, nd_system.rules['repetition'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((76, 24, 76, 100), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(76, 57, 76, 65): 'deriv3_1', (76, 67, 76, 68): '(1)', (76, 70, 76, 99): "nd_system.rules['repetition']"}, {}), "(deriv3_1, 1, nd_system.rules['repetition'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((77, 24, 77, 94), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(77, 57, 77, 65): 'deriv3_1', (77, 67, 77, 68): '(2)', (77, 70, 77, 93): "nd_system.rules['I→']"}, {}), "(deriv3_1, 2, nd_system.rules['I→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((78, 25, 78, 95), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(78, 58, 78, 66): 'deriv3_1', (78, 68, 78, 69): '(3)', (78, 71, 78, 94): "nd_system.rules['E→']"}, {}), "(deriv3_1, 3, nd_system.rules['E→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((87, 25, 87, 96), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(87, 58, 87, 66): 'deriv3_2', (87, 68, 87, 69): '(3)', (87, 71, 87, 95): "nd_system.rules['I∨1']"}, {}), "(deriv3_2, 3, nd_system.rules['I∨1'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((95, 25, 95, 95), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(95, 58, 95, 66): 'deriv3_3', (95, 68, 95, 69): '(2)', (95, 71, 95, 94): "nd_system.rules['I→']"}, {}), "(deriv3_3, 2, nd_system.rules['I→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((103, 25, 103, 95), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_application', 'nd_system.is_correct_application', ({(103, 58, 103, 66): 'deriv3_4', (103, 68, 103, 69): '(2)', (103, 71, 103, 94): "nd_system.rules['I→']"}, {}), "(deriv3_4, 2, nd_system.rules['I→'])", True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((109, 25, 109, 72), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(109, 57, 109, 65): 'deriv3_5', (109, 67, 109, 71): 'None'}, {}), '(deriv3_5, None)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((114, 25, 114, 72), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(114, 57, 114, 65): 'deriv3_6', (114, 67, 114, 71): 'None'}, {}), '(deriv3_6, None)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((140, 24, 140, 67), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(140, 56, 140, 62): 'deriv4', (140, 64, 140, 66): 'i3'}, {}), '(deriv4, i3)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((153, 24, 153, 69), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(153, 56, 153, 64): 'deriv1_1', (153, 66, 153, 68): 'i1'}, {}), '(deriv1_1, i1)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((161, 25, 161, 70), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(161, 57, 161, 65): 'deriv1_2', (161, 67, 161, 69): 'i1'}, {}), '(deriv1_2, i1)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((172, 24, 172, 69), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(172, 56, 172, 64): 'deriv2_1', (172, 66, 172, 68): 'i2'}, {}), '(deriv2_1, i2)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((180, 25, 180, 70), 'logics.instances.propositional.natural_deduction.classical_natural_deduction_system.is_correct_derivation', 'nd_system.is_correct_derivation', ({(180, 57, 180, 65): 'deriv2_2', (180, 67, 180, 69): 'i2'}, {}), '(deriv2_2, i2)', True, 'from logics.instances.propositional.natural_deduction import classical_natural_deduction_system as nd_system\n'), ((39, 23, 39, 37), 'logics.classes.propositional.Formula', 'Formula', ({(39, 31, 39, 36): "['p']"}, {}), "(['p'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((39, 39, 39, 69), 'logics.classes.propositional.Formula', 'Formula', ({(39, 47, 39, 68): "['→', ['p'], ['q']]"}, {}), "(['→', ['p'], ['q']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((40, 23, 40, 53), 'logics.classes.propositional.Formula', 'Formula', ({(40, 31, 40, 52): "['∧', ['p'], ['q']]"}, {}), "(['∧', ['p'], ['q']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((42, 24, 42, 38), 'logics.classes.propositional.Formula', 'Formula', ({(42, 32, 42, 37): "['p']"}, {}), "(['p'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((42, 40, 42, 70), 'logics.classes.propositional.Formula', 'Formula', ({(42, 48, 42, 69): "['→', ['p'], ['q']]"}, {}), "(['→', ['p'], ['q']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((43, 23, 43, 53), 'logics.classes.propositional.Formula', 'Formula', ({(43, 31, 43, 52): "['∧', ['q'], ['p']]"}, {}), "(['∧', ['q'], ['p']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((138, 24, 138, 38), 'logics.classes.propositional.Formula', 'Formula', ({(138, 32, 138, 37): "['q']"}, {}), "(['q'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((138, 40, 138, 70), 'logics.classes.propositional.Formula', 'Formula', ({(138, 48, 138, 69): "['→', ['p'], ['q']]"}, {}), "(['→', ['p'], ['q']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((139, 24, 139, 38), 'logics.classes.propositional.Formula', 'Formula', ({(139, 32, 139, 37): "['q']"}, {}), "(['q'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((144, 24, 144, 38), 'logics.classes.propositional.Formula', 'Formula', ({(144, 32, 144, 37): "['p']"}, {}), "(['p'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((144, 40, 144, 54), 'logics.classes.propositional.Formula', 'Formula', ({(144, 48, 144, 53): "['q']"}, {}), "(['q'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((145, 23, 145, 53), 'logics.classes.propositional.Formula', 'Formula', ({(145, 31, 145, 52): "['∧', ['p'], ['q']]"}, {}), "(['∧', ['p'], ['q']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((163, 24, 163, 38), 'logics.classes.propositional.Formula', 'Formula', ({(163, 32, 163, 37): "['p']"}, {}), "(['p'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((163, 40, 163, 54), 'logics.classes.propositional.Formula', 'Formula', ({(163, 48, 163, 53): "['q']"}, {}), "(['q'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((164, 24, 164, 54), 'logics.classes.propositional.Formula', 'Formula', ({(164, 32, 164, 53): "['∧', ['q'], ['p']]"}, {}), "(['∧', ['q'], ['p']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((14, 33, 14, 63), 'logics.classes.propositional.Formula', 'Formula', ({(14, 41, 14, 62): "['→', ['A'], ['B']]"}, {}), "(['→', ['A'], ['B']])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((16, 33, 16, 47), 'logics.classes.propositional.Formula', 'Formula', ({(16, 41, 16, 46): "['B']"}, {}), "(['B'])", False, 'from logics.classes.propositional import Inference, Formula\n'), ((18, 57, 18, 71), 'logics.classes.propositional.Formula', 'Formula', ({(18, 65, 18, 70): "['B']"}, {}), "(['B'])", False, 'from logics.classes.propositional import Inference, Formula\n')]
cohortfsllc/cohort-cocl2-sandbox
src/trusted/validator_arm/dgen_decoder_output.py
0ac6669d1a459d65a52007b80d5cffa4ef330287
#!/usr/bin/python # # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # """ Responsible for generating the decoder based on parsed table representations. """ import dgen_opt import dgen_output import dgen_actuals # This file generates the class decoder Decoder as defined by the # decoder tables. The code is specifically written to minimize the # number of decoder classes needed to parse valid ARM # instructions. Many rows in the table use the same decoder class. In # addition, we optimize tables by merging, so long as the same decoder # class is built. # # The following files are generated: # # decoder.h # decoder.cc # # decoder.h declares the generated decoder parser class while # decoder.cc contains the implementation of that decoder class. # # For testing purposes (see dgen_test_output.py) different rules are # applied. Note: It may be worth reading dgen_test_output.py preamble # to get a better understanding of decoder actions, and why we need # the "action_filter" methods. """The current command line arguments to use""" _cl_args = {} NEWLINE_STR=""" """ COMMENTED_NEWLINE_STR=""" //""" # Defines the header for decoder.h H_HEADER="""%(FILE_HEADER)s #ifndef %(IFDEF_NAME)s #define %(IFDEF_NAME)s #include "native_client/src/trusted/validator_arm/decode.h" #include "%(FILENAME_BASE)s_actuals.h" namespace nacl_arm_dec { """ DECODER_DECLARE_HEADER=""" // Defines a decoder class selector for instructions. class %(decoder_name)s : DecoderState { public: explicit %(decoder_name)s(); // Parses the given instruction, returning the decoder to use. virtual const ClassDecoder& decode(const Instruction) const; // Returns the class decoder to use to process the fictitious instruction // that is inserted before the first instruction in the code block by // the validator. const ClassDecoder &fictitious_decoder() const { return %(fictitious_decoder)s_instance_; } private: """ DECODER_DECLARE_METHOD_COMMENTS=""" // The following list of methods correspond to each decoder table, // and implements the pattern matching of the corresponding bit // patterns. After matching the corresponding bit patterns, they // either call other methods in this list (corresponding to another // decoder table), or they return the instance field that implements // the class decoder that should be used to decode the particular // instruction. """ DECODER_DECLARE_METHOD=""" inline const ClassDecoder& decode_%(table_name)s( const Instruction inst) const; """ DECODER_DECLARE_FIELD_COMMENTS=""" // The following fields define the set of class decoders // that can be returned by the API function "decode". They // are created once as instance fields, and then returned // by the table methods above. This speeds up the code since // the class decoders need to only be built once (and reused // for each call to "decode").""" DECODER_DECLARE_FIELD=""" const %(decoder)s %(decoder)s_instance_;""" DECODER_DECLARE_FOOTER=""" }; """ H_FOOTER=""" } // namespace nacl_arm_dec #endif // %(IFDEF_NAME)s """ def generate_h(decoder, decoder_name, filename, out, cl_args): """Entry point to the decoder for .h file. Args: decoder: The decoder defined by the list of Table objects to process. decoder_name: The name of the decoder state to build. filename: The (localized) name for the .h file. named_decoders: If true, generate a decoder state with named instances. out: a COutput object to write to. cl_args: A dictionary of additional command line arguments. """ global _cl_args assert filename.endswith('.h') _cl_args = cl_args # Before starting, remove all testing information from the parsed tables. decoder = decoder.action_filter(['actual']) values = { 'FILE_HEADER': dgen_output.HEADER_BOILERPLATE, 'IFDEF_NAME': dgen_output.ifdef_name(filename), 'FILENAME_BASE': filename[:-len('.h')], 'decoder_name': decoder_name, } out.write(H_HEADER % values) values['fictitious_decoder'] = ( decoder.get_value('FictitiousFirst').actual()) out.write(DECODER_DECLARE_HEADER % values) out.write(DECODER_DECLARE_METHOD_COMMENTS) for table in decoder.tables(): values['table_name'] = table.name out.write(DECODER_DECLARE_METHOD % values) out.write(DECODER_DECLARE_FIELD_COMMENTS) for action in decoder.action_filter(['actual']).decoders(): values['decoder'] = action.actual() out.write(DECODER_DECLARE_FIELD % values) out.write(DECODER_DECLARE_FOOTER % values) out.write(H_FOOTER % values) # Defines the header for DECODER.h CC_HEADER="""%(FILE_HEADER)s #include "%(header_filename)s" namespace nacl_arm_dec { """ CONSTRUCTOR_HEADER=""" %(decoder_name)s::%(decoder_name)s() : DecoderState()""" CONSTRUCTOR_FIELD_INIT=""" , %(decoder)s_instance_()""" CONSTRUCTOR_FOOTER=""" {} """ METHOD_HEADER=""" // Implementation of table: %(table_name)s. // Specified by: %(citation)s const ClassDecoder& %(decoder_name)s::decode_%(table_name)s( const Instruction inst) const {""" METHOD_HEADER_TRACE=""" fprintf(stderr, "decode %(table_name)s\\n"); """ METHOD_DISPATCH_BEGIN=""" if (%s""" METHOD_DISPATCH_CONTINUE=""" && %s""" METHOD_DISPATCH_END=") {""" METHOD_DISPATCH_TRACE=""" fprintf(stderr, "count = %s\\n");""" METHOD_DISPATCH_CLASS_DECODER=""" return %(decoder)s_instance_;""" METHOD_DISPATCH_SUBMETHOD=""" return decode_%(subtable_name)s(inst);""" METHOD_DISPATCH_CLOSE=""" } """ METHOD_FOOTER=""" // Catch any attempt to fall though ... return %(not_implemented)s_instance_; } """ DECODER_METHOD_HEADER=""" const ClassDecoder& %(decoder_name)s::decode(const Instruction inst) const {""" DECODER_METHOD_TRACE=""" fprintf(stderr, "Parsing %%08x\\n", inst.Bits());""" DECODER_METHOD_FOOTER=""" return decode_%(entry_table_name)s(inst); } """ CC_FOOTER=""" } // namespace nacl_arm_dec """ def generate_cc(decoder, decoder_name, filename, out, cl_args): """Implementation of the decoder in .cc file Args: decoder: The decoder defined by the list of Table objects to process. decoder_name: The name of the decoder state to build. filename: The (localized) name for the .h file. named_decoders: If true, generate a decoder state with named instances. out: a COutput object to write to. cl_args: A dictionary of additional command line arguments. """ global _cl_args assert filename.endswith('.cc') _cl_args = cl_args # Before starting, remove all testing information from the parsed # tables. decoder = decoder.action_filter(['actual']) values = { 'FILE_HEADER': dgen_output.HEADER_BOILERPLATE, 'header_filename': filename[:-2] + 'h', 'decoder_name': decoder_name, 'entry_table_name': decoder.primary.name, } out.write(CC_HEADER % values) _generate_constructors(decoder, values, out) _generate_methods(decoder, values, out) out.write(DECODER_METHOD_HEADER % values) if _cl_args.get('trace') == 'True': out.write(DECODER_METHOD_TRACE % values) out.write(DECODER_METHOD_FOOTER % values) out.write(CC_FOOTER % values) def _generate_constructors(decoder, values, out): out.write(CONSTRUCTOR_HEADER % values) for decoder in decoder.action_filter(['actual']).decoders(): values['decoder'] = decoder.actual() out.write(CONSTRUCTOR_FIELD_INIT % values) out.write(CONSTRUCTOR_FOOTER % values) def _generate_methods(decoder, values, out): global _cl_args for table in decoder.tables(): # Add the default row as the last in the optimized row, so that # it is applied if all other rows do not. opt_rows = sorted(dgen_opt.optimize_rows(table.rows(False))) if table.default_row: opt_rows.append(table.default_row) opt_rows = table.add_column_to_rows(opt_rows) print ("Table %s: %d rows minimized to %d" % (table.name, len(table.rows()), len(opt_rows))) values['table_name'] = table.name values['citation'] = table.citation out.write(METHOD_HEADER % values) if _cl_args.get('trace') == 'True': out.write(METHOD_HEADER_TRACE % values) # Add message to stop compilation warnings if this table # doesn't require subtables to select a class decoder. if not table.methods(): out.write("\n UNREFERENCED_PARAMETER(inst);") count = 0 for row in opt_rows: count = count + 1 # Each row consists of a set of bit patterns defining if the row # is applicable. Convert this into a sequence of anded C test # expressions. For example, convert the following pair of bit # patterns: # # xxxx1010xxxxxxxxxxxxxxxxxxxxxxxx # xxxxxxxxxxxxxxxxxxxxxxxxxxxx0101 # # Each instruction is masked to get the the bits, and then # tested against the corresponding expected bits. Hence, the # above example is converted to: # # ((inst & 0x0F000000) != 0x0C000000) && # ((inst & 0x0000000F) != 0x00000005) out.write(METHOD_DISPATCH_BEGIN % row.patterns[0].to_commented_bool()) for p in row.patterns[1:]: out.write(METHOD_DISPATCH_CONTINUE % p.to_commented_bool()) out.write(METHOD_DISPATCH_END) if _cl_args.get('trace') == 'True': out.write(METHOD_DISPATCH_TRACE % count) if row.action.__class__.__name__ == 'DecoderAction': values['decoder'] = row.action.actual() out.write(METHOD_DISPATCH_CLASS_DECODER % values) elif row.action.__class__.__name__ == 'DecoderMethod': values['subtable_name'] = row.action.name out.write(METHOD_DISPATCH_SUBMETHOD % values) else: raise Exception('Bad table action: %s' % repr(row.action)) out.write(METHOD_DISPATCH_CLOSE % values) values['not_implemented'] = decoder.get_value('NotImplemented').actual() out.write(METHOD_FOOTER % values)
[((135, 22, 135, 54), 'dgen_output.ifdef_name', 'dgen_output.ifdef_name', ({(135, 45, 135, 53): 'filename'}, {}), '(filename)', False, 'import dgen_output\n')]
ilinum/compose
compose/progress_stream.py
d1633d8e9df3c2dd4fa6f562c6b037cfe1af8ddb
from __future__ import absolute_import from __future__ import unicode_literals from compose import utils class StreamOutputError(Exception): pass def stream_output(output, stream): is_terminal = hasattr(stream, 'isatty') and stream.isatty() stream = utils.get_output_stream(stream) all_events = [] lines = {} diff = 0 for event in utils.json_stream(output): all_events.append(event) is_progress_event = 'progress' in event or 'progressDetail' in event if not is_progress_event: print_output_event(event, stream, is_terminal) stream.flush() continue if not is_terminal: continue # if it's a progress event and we have a terminal, then display the progress bars image_id = event.get('id') if not image_id: continue if image_id not in lines: lines[image_id] = len(lines) stream.write("\n") diff = len(lines) - lines[image_id] # move cursor up `diff` rows stream.write("%c[%dA" % (27, diff)) print_output_event(event, stream, is_terminal) if 'id' in event: # move cursor back down stream.write("%c[%dB" % (27, diff)) stream.flush() return all_events def print_output_event(event, stream, is_terminal): if 'errorDetail' in event: raise StreamOutputError(event['errorDetail']['message']) terminator = '' if is_terminal and 'stream' not in event: # erase current line stream.write("%c[2K\r" % 27) terminator = "\r" elif 'progressDetail' in event: return if 'time' in event: stream.write("[%s] " % event['time']) if 'id' in event: stream.write("%s: " % event['id']) if 'from' in event: stream.write("(from %s) " % event['from']) status = event.get('status', '') if 'progress' in event: stream.write("%s %s%s" % (status, event['progress'], terminator)) elif 'progressDetail' in event: detail = event['progressDetail'] total = detail.get('total') if 'current' in detail and total: percentage = float(detail['current']) / float(total) * 100 stream.write('%s (%.1f%%)%s' % (status, percentage, terminator)) else: stream.write('%s%s' % (status, terminator)) elif 'stream' in event: stream.write("%s%s" % (event['stream'], terminator)) else: stream.write("%s%s\n" % (status, terminator)) def get_digest_from_pull(events): for event in events: status = event.get('status') if not status or 'Digest' not in status: continue _, digest = status.split(':', 1) return digest.strip() return None def get_digest_from_push(events): for event in events: digest = event.get('aux', {}).get('Digest') if digest: return digest return None
[((13, 13, 13, 44), 'compose.utils.get_output_stream', 'utils.get_output_stream', ({(13, 37, 13, 43): 'stream'}, {}), '(stream)', False, 'from compose import utils\n'), ((18, 17, 18, 42), 'compose.utils.json_stream', 'utils.json_stream', ({(18, 35, 18, 41): 'output'}, {}), '(output)', False, 'from compose import utils\n')]
beloglazov/openstack-neat
tests/test_db.py
a5a853ae2affb0cdc582e3ab641737f5ebd3d0a7
# Copyright 2012 Anton Beloglazov # # 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 mocktest import * from pyqcy import * import datetime import neat.db_utils as db_utils import logging logging.disable(logging.CRITICAL) class Db(TestCase): @qc(1) def insert_select(): db = db_utils.init_db('sqlite:///:memory:') db.vms.insert().execute(uuid='test') assert db.vms.select().execute().first()['uuid'] == 'test' db.vm_resource_usage.insert().execute(vm_id=1, cpu_mhz=1000) assert db.vm_resource_usage.select(). \ execute().first()['cpu_mhz'] == 1000 @qc(10) def select_cpu_mhz_for_vm( uuid=str_(of='abc123-', min_length=36, max_length=36), cpu_mhz=list_(of=int_(min=0, max=3000), min_length=0, max_length=10), n=int_(min=1, max=10) ): db = db_utils.init_db('sqlite:///:memory:') result = db.vms.insert().execute(uuid=uuid) vm_id = result.inserted_primary_key[0] for mhz in cpu_mhz: db.vm_resource_usage.insert().execute( vm_id=vm_id, cpu_mhz=mhz) assert db.select_cpu_mhz_for_vm(uuid, n) == cpu_mhz[-n:] @qc(10) def select_last_cpu_mhz_for_vms( vms=dict_( keys=str_(of='abc123-', min_length=36, max_length=36), values=list_(of=int_(min=1, max=3000), min_length=0, max_length=10), min_length=0, max_length=3 ) ): db = db_utils.init_db('sqlite:///:memory:') res = {} for uuid, data in vms.items(): for value in data: db.insert_vm_cpu_mhz({uuid: value}) if data: res[uuid] = data[-1] assert db.select_last_cpu_mhz_for_vms() == res @qc(10) def select_vm_id( uuid1=str_(of='abc123-', min_length=36, max_length=36), uuid2=str_(of='abc123-', min_length=36, max_length=36) ): db = db_utils.init_db('sqlite:///:memory:') result = db.vms.insert().execute(uuid=uuid1) vm_id = result.inserted_primary_key[0] assert db.select_vm_id(uuid1) == vm_id assert db.select_vm_id(uuid2) == vm_id + 1 @qc(10) def insert_vm_cpu_mhz( vms=dict_( keys=str_(of='abc123-', min_length=36, max_length=36), values=tuple_(int_(min=1, max=3000), list_(of=int_(min=1, max=3000), min_length=0, max_length=10)), min_length=0, max_length=5 ) ): db = db_utils.init_db('sqlite:///:memory:') initial_data = [] data_to_submit = {} final_data = {} for uuid, data in vms.items(): vm_id = db.select_vm_id(uuid) data_to_submit[uuid] = data[0] final_data[uuid] = list(data[1]) final_data[uuid].append(data[0]) for cpu_mhz in data[1]: initial_data.append({'vm_id': vm_id, 'cpu_mhz': cpu_mhz}) if initial_data: db.vm_resource_usage.insert().execute(initial_data) db.insert_vm_cpu_mhz(data_to_submit) for uuid, data in final_data.items(): assert db.select_cpu_mhz_for_vm(uuid, 11) == data @qc(1) def update_host(): db = db_utils.init_db('sqlite:///:memory:') db.update_host('host1', 3000, 4, 4000) hosts = db.hosts.select().execute().fetchall() assert len(hosts) == 1 host = hosts[0] assert host['hostname'] == 'host1' assert host['cpu_mhz'] == 3000 assert host['cpu_cores'] == 4 assert host['ram'] == 4000 db.update_host('host1', 3500, 8, 8000L) hosts = db.hosts.select().execute().fetchall() assert len(hosts) == 1 host = hosts[0] assert host['hostname'] == 'host1' assert host['cpu_mhz'] == 3500 assert host['cpu_cores'] == 8 assert host['ram'] == 8000L @qc(10) def select_cpu_mhz_for_host( hostname=str_(of='abc123', min_length=5, max_length=10), cpu_mhz=list_(of=int_(min=0, max=3000), min_length=0, max_length=10), n=int_(min=1, max=10) ): db = db_utils.init_db('sqlite:///:memory:') host_id = db.update_host(hostname, 1, 1, 1) for mhz in cpu_mhz: db.host_resource_usage.insert().execute( host_id=host_id, cpu_mhz=mhz) assert db.select_cpu_mhz_for_host(hostname, n) == cpu_mhz[-n:] @qc(10) def select_last_cpu_mhz_for_hosts( hosts=dict_( keys=str_(of='abc123', min_length=5, max_length=10), values=list_(of=int_(min=1, max=3000), min_length=0, max_length=10), min_length=0, max_length=3 ) ): db = db_utils.init_db('sqlite:///:memory:') res = {} for hostname, data in hosts.items(): db.update_host(hostname, 1, 1, 1) for value in data: db.insert_host_cpu_mhz(hostname, value) if data: res[hostname] = data[-1] else: res[hostname] = 0 assert db.select_last_cpu_mhz_for_hosts() == res @qc(10) def insert_host_cpu_mhz( hostname=str_(of='abc123', min_length=5, max_length=10), cpu_mhz=list_(of=int_(min=0, max=3000), min_length=1, max_length=10) ): db = db_utils.init_db('sqlite:///:memory:') db.update_host(hostname, 1, 1, 1) for value in cpu_mhz: db.insert_host_cpu_mhz(hostname, value) assert db.select_cpu_mhz_for_host(hostname, len(cpu_mhz)) == cpu_mhz @qc(1) def select_host_characteristics(): db = db_utils.init_db('sqlite:///:memory:') assert db.select_host_characteristics() == ({}, {}, {}) db.update_host('host1', 3000, 4, 4000) db.update_host('host2', 3500, 8, 8000) assert db.select_host_characteristics() == \ ({'host1': 3000, 'host2': 3500}, {'host1': 4, 'host2': 8}, {'host1': 4000, 'host2': 8000}) @qc(1) def select_host_id(): db = db_utils.init_db('sqlite:///:memory:') host1_id = db.hosts.insert().execute( hostname='host1', cpu_mhz=1, cpu_cores=1, ram=1).inserted_primary_key[0] host2_id = db.hosts.insert().execute( hostname='host2', cpu_mhz=1, cpu_cores=1, ram=1).inserted_primary_key[0] assert db.select_host_id('host1') == host1_id assert db.select_host_id('host2') == host2_id @qc(1) def select_host_ids(): db = db_utils.init_db('sqlite:///:memory:') assert db.select_host_ids() == {} hosts = {} hosts['host1'] = db.update_host('host1', 1, 1, 1) hosts['host2'] = db.update_host('host2', 1, 1, 1) assert db.select_host_ids() == hosts @qc(1) def cleanup_vm_resource_usage( uuid=str_(of='abc123-', min_length=36, max_length=36) ): db = db_utils.init_db('sqlite:///:memory:') result = db.vms.insert().execute(uuid=uuid) vm_id = result.inserted_primary_key[0] time = datetime.datetime.today() for i in range(10): db.vm_resource_usage.insert().execute( vm_id=1, cpu_mhz=i, timestamp=time.replace(second=i)) assert db.select_cpu_mhz_for_vm(uuid, 100) == range(10) db.cleanup_vm_resource_usage(time.replace(second=5)) assert db.select_cpu_mhz_for_vm(uuid, 100) == range(5, 10) @qc(1) def cleanup_host_resource_usage( hostname=str_(of='abc123', min_length=5, max_length=10) ): db = db_utils.init_db('sqlite:///:memory:') host_id = db.update_host(hostname, 1, 1, 1) time = datetime.datetime.today() for i in range(10): db.host_resource_usage.insert().execute( host_id=1, cpu_mhz=i, timestamp=time.replace(second=i)) assert db.select_cpu_mhz_for_host(hostname, 100) == range(10) db.cleanup_host_resource_usage(time.replace(second=5)) assert db.select_cpu_mhz_for_host(hostname, 100) == range(5, 10) def test_insert_host_states(self): db = db_utils.init_db('sqlite:///:memory:') hosts = {} hosts['host1'] = db.update_host('host1', 1, 1, 1) hosts['host2'] = db.update_host('host2', 1, 1, 1) db.insert_host_states({'host1': 0, 'host2': 1}) db.insert_host_states({'host1': 0, 'host2': 0}) db.insert_host_states({'host1': 1, 'host2': 1}) result = db.host_states.select().execute().fetchall() host1 = [x[3] for x in sorted(filter( lambda x: x[1] == hosts['host1'], result), key=lambda x: x[0])] self.assertEqual(host1, [0, 0, 1]) host2 = [x[3] for x in sorted(filter( lambda x: x[1] == hosts['host2'], result), key=lambda x: x[0])] self.assertEqual(host2, [1, 0, 1]) @qc(10) def select_host_states( hosts=dict_( keys=str_(of='abc123', min_length=1, max_length=5), values=list_(of=int_(min=0, max=1), min_length=0, max_length=10), min_length=0, max_length=3 ) ): db = db_utils.init_db('sqlite:///:memory:') res = {} for host, data in hosts.items(): db.update_host(host, 1, 1, 1) for state in data: db.insert_host_states({host: state}) if data: res[host] = data[-1] else: res[host] = 1 assert db.select_host_states() == res @qc(10) def select_active_hosts( hosts=dict_( keys=str_(of='abc123', min_length=1, max_length=5), values=list_(of=int_(min=0, max=1), min_length=0, max_length=10), min_length=0, max_length=3 ) ): db = db_utils.init_db('sqlite:///:memory:') res = [] for host, data in hosts.items(): db.update_host(host, 1, 1, 1) for state in data: db.insert_host_states({host: state}) if data and data[-1] == 1 or not data: res.append(host) assert set(db.select_active_hosts()) == set(res) @qc(10) def select_inactive_hosts( hosts=dict_( keys=str_(of='abc123', min_length=1, max_length=5), values=list_(of=int_(min=0, max=1), min_length=0, max_length=10), min_length=0, max_length=3 ) ): hosts = {'1ab': [0], '3222': [0, 0, 1, 1, 1, 1, 0, 0], 'b222b': [0, 0, 1, 1, 1, 0, 1]} db = db_utils.init_db('sqlite:///:memory:') res = [] for host, data in hosts.items(): db.update_host(host, 1, 1, 1) for state in data: db.insert_host_states({host: state}) if data and data[-1] == 0: res.append(host) assert set(db.select_inactive_hosts()) == set(res) def test_insert_host_overload(self): db = db_utils.init_db('sqlite:///:memory:') hosts = {} hosts['host1'] = db.update_host('host1', 1, 1, 1) hosts['host2'] = db.update_host('host2', 1, 1, 1) db.insert_host_overload('host2', False) db.insert_host_overload('host1', True) db.insert_host_overload('host1', False) db.insert_host_overload('host2', True) result = db.host_overload.select().execute().fetchall() host1 = [x[3] for x in sorted(filter( lambda x: x[1] == hosts['host1'], result), key=lambda x: x[0])] self.assertEqual(host1, [1, 0]) host2 = [x[3] for x in sorted(filter( lambda x: x[1] == hosts['host2'], result), key=lambda x: x[0])] self.assertEqual(host2, [0, 1]) @qc(1) def insert_select(): db = db_utils.init_db('sqlite:///:memory:') db.vms.insert().execute(uuid='x' * 36).inserted_primary_key[0] vm_id = db.vms.insert().execute(uuid='vm' * 18).inserted_primary_key[0] host_id = db.update_host('host', 1, 1, 1) db.insert_vm_migration('vm' * 18, 'host') result = db.vm_migrations.select().execute().first() assert result[1] == vm_id assert result[2] == host_id
[]
GuillermoPerez32/EE2BIDS_backend
libs/BIDS.py
2cab240840e11e227ad60e4c8e17ac9ac87defd4
import os from bids_validator import BIDSValidator def validate(bids_directory): print('- Validate: init started.') file_paths = [] result = [] validator = BIDSValidator() for path, dirs, files in os.walk(bids_directory): for filename in files: if filename == '.bidsignore': continue if filename.endswith('_annotations.tsv'): continue if filename.endswith('_annotations.json'): continue temp = os.path.join(path, filename) file_paths.append(temp[len(bids_directory):len(temp)]) result.append(validator.is_bids(temp[len(bids_directory):len(temp)])) # print(validator.is_bids(temp[len(bids_directory):len(temp)])) return file_paths, result
[((9, 16, 9, 31), 'bids_validator.BIDSValidator', 'BIDSValidator', ({}, {}), '()', False, 'from bids_validator import BIDSValidator\n'), ((10, 29, 10, 52), 'os.walk', 'os.walk', ({(10, 37, 10, 51): 'bids_directory'}, {}), '(bids_directory)', False, 'import os\n'), ((21, 19, 21, 47), 'os.path.join', 'os.path.join', ({(21, 32, 21, 36): 'path', (21, 38, 21, 46): 'filename'}, {}), '(path, filename)', False, 'import os\n')]
peterbrazil/brazil
src/python/triangula/chassis.py
3823dca6f05b6946251800125d45069048d1bca1
from math import cos, sin, degrees, radians, pi from time import time from euclid import Vector2, Point2 from numpy import array as np_array from numpy.linalg import solve as np_solve __author__ = 'tom' def test(): chassis = HoloChassis(wheels=[ HoloChassis.OmniWheel(position=Point2(1, 0), angle=0, radius=60), HoloChassis.OmniWheel(position=Point2(-1, 0), angle=0, radius=60)] ) print chassis.get_wheel_speeds(Motion(translation=Vector2(0, 0), rotation=0.5)) print chassis.get_wheel_speeds(Motion(translation=Vector2(0, 0), rotation=0.5), origin=Point2(1, 0)) def rotate_point(point, angle, origin=None): """ Rotate a Point2 around another Point2 :param euclid.Point2 point: The point to rotate :param float angle: Angle in radians, clockwise rotation :param euclid.Point2 origin: Origin of the rotation, defaults to (0,0) if not specified :return: A new :class:`euclid.Point2` containing the rotated input point """ if origin is None: origin = Point2(0, 0) s = sin(-angle) c = cos(-angle) return Point2(c * (point.x - origin.x) - s * (point.y - origin.y) + origin.x, s * (point.x - origin.x) + c * (point.y - origin.y) + origin.y) def rotate_vector(vector, angle, origin=None): """ Rotate a :class:`euclid.Vector2` around a :class:`euclid.Point2` :param euclid.Vector2 vector: The vector to rotate :param float angle: Angle in radians, clockwise rotation :param euclid.Point2 origin: Origin of the rotation, defaults to (0,0) if not specified :return: A new :class:`euclid.Point2` containing the rotated input point """ if origin is None: origin = Point2(0, 0) s = sin(-angle) c = cos(-angle) return Vector2(c * (vector.x - origin.x) - s * (vector.y - origin.y) + origin.x, s * (vector.x - origin.x) + c * (vector.y - origin.y) + origin.y) def smallest_difference(a, b, max_value=2 * pi): """ Given two floats, a and b, and a maximum possible value for both a and b, calculate the smallest delta from a to b. For example, if a=1.0, b=2.5 and max_value=2.6, this should return -1.1, as subtracting 1.1 from a would result in -0.1, which will then be transformed to 2.5 after taking its modulus with 2.6. If max_value was 10, it would return +1.5, as this is the lower magnitude delta needed to go from 1.0 to 2.5. This function is used when calculating the shortest delta between two pose orientations, for this reason the max_value defaults to 2*pi for use when working in radians. If either a or b are less than zero or greater than the maximum value they will be treated as a % max_value or b % max_value respectively for the purposes of this calculation. :param float a: First value (see above) :param b: Second value (see above) :param max_value: Modulus, defaults to 2*pi if not specified :return: A value d such that (a + d) % max_value == b, and abs(d) is minimal (as there would be an infinite number of possible d that satisfy this relationship). """ mod_a = a % max_value mod_b = b % max_value if abs(mod_a - mod_b) <= max_value / 2: return mod_b - mod_a elif mod_a >= mod_b: return mod_b + (max_value - mod_a) else: return -(mod_a + (max_value - mod_b)) def get_regular_triangular_chassis(wheel_distance, wheel_radius, max_rotations_per_second): """ Build a HoloChassis object with three wheels, each identical in size and maximum speed. Each wheel is positioned at the corner of a regular triangle, and with direction perpendicular to the normal vector at that corner. :param wheel_distance: Distance in millimetres between the contact points of each pair of wheels (i.e. the length of each edge of the regular triangle) :param wheel_radius: Wheel radius in millimetres :param max_rotations_per_second: Maximum wheel speed in revolutions per second :return: An appropriately configured HoloChassis """ point = Point2(0, cos(radians(30)) * wheel_distance / 2.0) vector = Vector2(-2 * pi * wheel_radius, 0) # Pink wheel_a = HoloChassis.OmniWheel( position=point, vector=vector, max_speed=max_rotations_per_second) # Yellow wheel_b = HoloChassis.OmniWheel( position=rotate_point(point, pi * 2 / 3), vector=rotate_vector(vector, pi * 2 / 3), max_speed=max_rotations_per_second) # Green wheel_c = HoloChassis.OmniWheel( position=rotate_point(point, pi * 4 / 3), vector=rotate_vector(vector, pi * 4 / 3), max_speed=max_rotations_per_second) return HoloChassis(wheels=[wheel_a, wheel_b, wheel_c]) class WheelSpeeds: """ A simple container to hold desired wheel speeds, and to indicate whether any speeds were scaled back due to impossibly high values. """ def __init__(self, speeds, scaling): """ Create a new wheel speeds container :param speeds: A sequence of float values, one per wheel, in revolutions per second :param float scaling: If a requested translation or rotation was too fast for the chassis to perform, it will return an instance of this class with the scaling set to a value greater than 1.0. This indicates that it was unable to provide the requested trajectory but has instead provided the highest magnitude one possible. This parameter then contains the proportion of the requested trajectory that was possible to provide. For example, if the motion requested was a translation of 10mm/s in the X axis and a rotation of 10 radians per second, but on calculation this resulted in excessive wheel speeds which weren't possible, it might be scaled back to 6mm/s on X and 6 radians per second - the motion is proportionately the same just slower, and in this case the scaling value would be 0.6. """ self.speeds = speeds self.scaling = scaling def __str__(self): return 'WheelSpeeds[ speeds={}, scaling={} ]'.format(self.speeds, self.scaling) class Motion: """ A container to hold the translation and rotation vector representing the robot's motion. This is always expressed in the robot's coordinate frame, so a translation component of 0,1 always means the robot is heading forwards, irrespective of the current orientation of the robot (i.e. if the robot was turned 90 degrees in world space this 0,1 motion would be a movement along the X axis in world space, but the Y axis in robot space). The rotation component of the motion is expressed in radians per second, positive values corresponding to clockwise rotation when viewed from the direction relative to the plane such that X is positive to the right and Y positive upwards. """ def __init__(self, translation=None, rotation=0): """ Constructor :param euclid.Vector2 translation: Vector2 representing the translation component in robot coordinate space of the motion. Defaults to Vector2(0,0) :param float rotation: Rotation in radians per second. Defaults to 0. """ if translation is not None: self.translation = translation else: self.translation = Vector2(0, 0) self.rotation = rotation def __str__(self): return 'Motion[ x={}, y={}, theta={} (deg={}) ]'.format(self.translation.x, self.translation.y, self.rotation, degrees(self.rotation)) class DeadReckoning: """ Encapsulates the logic required to track the robot's position in world space using wheel encoders and chassis kinematics. To update the state of this object you need to call the update_from_counts function - this will compute the difference in counts for each wheel, and from this derive the rotational speed for each wheel since the last measurement. The :class:`triangula.chassis.HoloChassis` is then used to convert these speeds into an arc, with the assumption that wheel speeds were constant during the time interval. This arc is used to update the :class:`triangula.chassis.Pose` representing the current best estimate of the robot's position. Because this is in effect integrating over sensor readings, any errors, particularly in the chassis geometry or dimensions, or in the number of counts per revolution (for example if the gearing isn't quite what you think it is or there's enough slop in the gearbox that readings can drift) will accumulate over time. To mitigate this, if you have precise instantaneous information such as a compass reading every few seconds, these readings can be used to explicitly set the position, orientation, or both of the :class:`triangula.chassis.Pose` tracked by this class. As there's an implicit assumption that wheel speeds are constant between encoder readings, this class will yield more accurate results when updated frequently. The exact optimal update frequency will depend on the encoder resolutions, chassis geometry etc. Some manual tuning may be required. """ def __init__(self, chassis, counts_per_revolution=64 * 19, max_count_value=1 << 15): """ Constructor :param triangula.chassis.HoloChassis chassis: The :class:`triangula.chassis.HoloChassis` to be used to define kinematics for this DeadReckoning :param float counts_per_revolution: The number of counts registered by the wheel encoders per revolution of the wheel. Defaults to 64*19 to be the 64 count encoder fitted to a 19:1 reduction gearbox. :param int max_count_value: The largest value read from the encoders, this is used to determine when we've wrapped around the zero point, defaults to 1<<16 to reflect that count values are held in the microcontroller module as a uint16_t """ self.chassis = chassis self.counts_per_revolution = counts_per_revolution self.max_count_value = max_count_value self.last_encoder_values = None self.last_reading_time = None self.pose = None def reset(self): """ Clear the state of this :class:`triangula.chassis.DeadReckoning` """ self.last_encoder_values = None self.last_reading_time = None self.pose = None def set_position(self, position): """ Explicitly set the position of the robot in world coordinates. Overrides the current value tracked by this instance. Use this when you have better information and want to update the state accordingly. :param euclid.Point2 position: The new position to set, as a :class:`euclid.Point2`, coordinates are in mm """ self.pose.position = position return self.pose def set_orientation(self, orientation): """ Explicitly set the orientation of the robot in world coordinates. Use this to explicitly update the orientation, for example when you have a sufficiently accurate compass fix that it can be used to eliminate any accumulated errors built up by the dead reckoning algorithm. :param float orientation: The new orientation to set, in radians from the positive Y axis, clockwise rotations being positive. This value will be normalised to the range 0-2PI :return: The current (updated) value of the :class:`triangula.chassis.Pose` """ self.pose.orientation = orientation % (2 * pi) return self.pose def update_from_counts(self, counts): """ Update the pose from a new set of encoder values :param counts: A list of encoder counts, one per wheel :return: The updated :class:`triangula.chassis.Pose` object (this is also modified in the internal state of the DeadReckoning) """ reading_time = time() if self.last_encoder_values is None: self.last_encoder_values = counts self.last_reading_time = reading_time self.pose = Pose(Point2(0, 0), 0) else: time_delta = reading_time - self.last_reading_time wheel_speeds = [smallest_difference(current_reading, last_reading, self.max_count_value) / ( self.counts_per_revolution * time_delta) for last_reading, current_reading in zip(counts, self.last_encoder_values)] motion = self.chassis.calculate_motion(speeds=wheel_speeds) self.pose = self.pose.calculate_pose_change(motion, time_delta) self.last_encoder_values = counts self.last_reading_time = reading_time return self.pose class Pose: """ A container to hold the position as a Point2 along with orientation in radians, where 0 corresponds to the positive Y axis (0,1). Orientation is expressed in radians, with positive values indicating a rotation from the positive Y axis in the clockwise direction, i.e. a rotation of 0 is North, pi/2 East, pi South and 3pi/2 West. """ def __init__(self, position=None, orientation=0): """ Constructor :param euclid.Point2 position: A Point2 containing the position of the centre of the robot. Defaults to Point2(0,0) :param float orientation: Orientation in radians, 0 being the positive Y axis, positive values correspond to clockwise rotations, i.e. pi/4 is East. This value will be normalised to be between 0 and 2 * pi. Defaults to 0 """ if position is not None: self.position = position else: self.position = Point2(0, 0) self.orientation = orientation % (2 * pi) def distance_to_pose(self, to_pose): """ Return the distance to the other pose position :param triangula.chassis.Pose to_pose: The target pose """ return abs(self.position - to_pose.position) def is_close_to(self, to_pose, max_distance=0.001, max_orientation_difference=radians(1)): """ Check whether we're close to the specified pose, defining closeness as both distance on the plane and difference in orientation. :param to_pose: The target pose :param max_distance: Maximum distance within which we'll count as being close, defaults to 0.001 :param max_orientation_difference: Maximum number of radians we can be off the target pose's orientation to count as close, defaults to 1 degree (calculated with ``radians(1)``) :return: True if this pose is regarded as close to the other, False otherwise """ if self.distance_to_pose(to_pose) > max_distance: return False elif abs(smallest_difference(self.orientation, to_pose.orientation)) > max_orientation_difference: return False else: return True def translate(self, vector): """ Create a new pose, with the same orientation as this one and the specified translation applied to its position. :param euclid.Vector2 vector: Vector by which the position of this pose should be translated when creating the new Pose :return: Returns the new Pose """ return Pose(position=self.position + vector, orientation=self.orientation) def pose_to_pose_vector(self, to_pose): """ Calculates the Vector2, in robot coordinate space (remember that Pose objects use world coordinates!) that represents the translation required to move from this Pose to the specified target Pose. :param triangula.chassis.Pose to_pose: A target :class:`triangula.chassis.Pose`, the resultant vector in robot space will translate the robot to the position contained in this pose. Note that this does not take any account of the orientation component of the to_pose, only the starting one. :return: A :class:`euclid.Vector2` containing the translation part, in robot space, of the motion required to move from this Pose to the target. """ return rotate_vector( vector=Vector2(to_pose.position.x - self.position.x, to_pose.position.y - self.position.y), angle=-self.orientation) def pose_to_pose_motion(self, to_pose, time_seconds): """ Calculates a Motion which should be applied to the current Pose to move the robot towards the target, such that it should hit the target at no less than time_seconds into the future. This function must be called on any Pose update, i.e. from a dead reckoning module, as it doesn't do any course planning (it would, for example, be possible to calculate a single constant motion to move in an arc to the target Pose, but this would be rather inefficient, better to incrementally home in on the target by repeatedly calling this function). To move as fast as possible to the target, set the time to something implausibly small, then use the chassis functions to limit the resultant motion to the range possible for the chassis. This would require some kind of motion limit to avoid skidding and messing up the Pose calculation logic. :param to_pose: A target :class:`triangula.chassis.Pose` :param time_seconds: A the minimum number of seconds to transition to the target pose. :return: A :class:`triangula.chassis.Motion` containing the motion required to attain the target pose in the specified time. This is highly likely to be impossible, in which case using the chassis functions to determine the wheel power and extract the scaling factor will give the actual time (ignoring acceleration limits) to transition to the target. """ translation = self.pose_to_pose_vector(to_pose=to_pose) rotation = smallest_difference(self.orientation, to_pose.orientation) return Motion(translation=translation / time_seconds, rotation=rotation / time_seconds) def calculate_pose_change(self, motion, time_delta): """ Given this as the starting Pose, a Motion and a time in seconds, calculate the resultant Pose at the end of the time interval. This makes use of the fact that if you travel in a consistent direction while turning at a constant rate you will describe an arc. By calculating the centre point of this arc we can simply rotate the starting pose around this centre point. This is considerably simpler than integrating over the motion 3-vector. A special case is used to avoid division by zero errors when there is no rotation component to the motion. :param triangula.chassis.Motion motion: The motion of the robot, assumed to be constant for the duration of the time interval. The motion is expressed in the robot's coordinate frame, so a translation of (0,1) is always a forward motion, irrespective of the current orientation. :param float time_delta: The time in seconds during which the specified motion should be applied. :return: A :class:`triangula.chassis.Pose` which represents resultant pose after applying the supplied motion for the given time. """ # Total delta in orientation angle over the time interval orientation_delta = motion.rotation * time_delta # Scaled translation vector rotated into world coordinate space (motion uses robot space) translation_vector_world = rotate_vector(motion.translation, self.orientation) * time_delta ':type : euclid.Vector2' if orientation_delta == 0: # No orientation, trivially add the rotated, scaled, translation vector to the current pose return self.translate(translation_vector_world) else: centre_of_rotation = self.position + translation_vector_world.cross() / orientation_delta ':type : euclid.Point2' final_position = rotate_point(self.position, angle=orientation_delta, origin=centre_of_rotation) return Pose(position=final_position, orientation=self.orientation + orientation_delta) def __str__(self): return 'Pose[x={}, y={}, orientation={} (deg={})]'.format(self.position.x, self.position.y, self.orientation, degrees(self.orientation)) class HoloChassis: """ An assembly of wheels at various positions and angles, which can be driven independently to create a holonomic drive system. A holonomic system is one where number of degrees of freedom in the system is equal to the number of directly controllable degrees of freedom, so for a chassis intended to move in two dimensions the degrees of freedom are two axes of translation and one of rotation. For a full holonomic system we therefore need at least three wheels defined. """ def __init__(self, wheels): """ Create a new chassis, specifying a set of wheels. :param wheels: A sequence of :class:`triangula.chassis.HoloChassis.OmniWheel` objects defining the wheels for this chassis. """ self.wheels = wheels self._matrix_coefficients = np_array([[wheel.co_x, wheel.co_y, wheel.co_theta] for wheel in self.wheels]) def calculate_motion(self, speeds): """ Invert the motion to speed calculation to obtain the actual linear and angular velocity of the chassis given a vector of wheel speeds. See http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.solve.html :param speeds: An array of wheel speeds, expressed as floats with units of radians per second, positive being towards the wheel vector. :return: A :class:`triangula.chassis.Motion` object containing the calculated translation and rotation in the robot's coordinate space. """ motion_array = np_solve(self._matrix_coefficients, np_array(speeds)) return Motion(Vector2(x=float(motion_array[0]), y=float(motion_array[1])), rotation=float(motion_array[2])) def get_max_translation_speed(self): """ Calculate the maximum translation speed, assuming all directions are equivalent and that there is no rotation component to the motion. :return: Maximum speed in millimetres per second as a float """ unrealistic_speed = 10000.0 scaling = self.get_wheel_speeds(Motion(translation=Vector2(0, unrealistic_speed), rotation=0)).scaling return unrealistic_speed * scaling def get_max_rotation_speed(self): """ Calculate the maximum rotation speed around the origin in radians per second, assuming no translation motion at the same time. :return: Maximum radians per second as a float """ unrealistic_speed = 2 * pi * 100 scaling = self.get_wheel_speeds(Motion(translation=Vector2(0, 0), rotation=unrealistic_speed)).scaling return unrealistic_speed * scaling def get_wheel_speeds(self, motion, origin=Point2(x=0, y=0)): """ Calculate speeds to drive each wheel in the chassis at to attain the specified rotation / translation 3-vector. :param triangula.chassis.Motion motion: Desired motion of the robot chassis :param euclid.Point2 origin: Optional, can define the centre of rotation to be something other than 0,0. Units are in millimetres. Defaults to rotating around x=0, y=0. :return: A :class:`triangula.chassis.WheelSpeeds` containing both the target wheel speeds and the scaling, if any, which was required to bring those speeds into the allowed range for all wheels. This prevents unexpected motion in cases where only a single wheel is being asked to turn too fast, in such cases all wheel speeds will be scaled back such that the highest is within the bounds allowed for that particular wheel. This can accommodate wheels with different top speeds. """ def velocity_at(point): """ Compute the velocity as a Vector2 at the specified point given the enclosing translation and rotation values Method: Normalise the vector from the origin to the point, then take the cross of itself to produce a unit vector with direction that of a rotation around the origin. Scale this by the distance from the origin and by the rotation in radians per second, then simply add the translation vector. :param euclid.Point2 point: Point at which to calculate velocity :return: A :class:`euclid.Vector2` representing the velocity at the specified point in mm/s """ d = point - origin return d.cross() * motion.rotation + motion.translation wheel_speeds = list(wheel.speed(velocity_at(wheel.position)) for wheel in self.wheels) scale = 1.0 for speed, wheel in zip(wheel_speeds, self.wheels): if wheel.max_speed is not None and abs(speed) > wheel.max_speed: wheel_scale = wheel.max_speed / abs(speed) scale = min(scale, wheel_scale) return WheelSpeeds(speeds=list(speed * scale for speed in wheel_speeds), scaling=scale) class OmniWheel: """ Defines a single omni-wheel within a chassis assembly. Omni-wheels are wheels formed from rollers, where the motion of the roller is perpendicular to the motion of the primary wheel. This is distinct from a mechanum wheel where the rollers are at an angle (normally around 40-30 degrees) to the primary wheel. Omni-wheels must be positioned on the chassis with non-parallel unit vectors, mechanum wheels can in some cases be positioned with all unit vectors parallel. A wheel has a location relative to the chassis centre and a vector describing the direction of motion of the wheel when driven with a positive angular velocity. The location is specified in millimetres, and the magnitude of the wheel vector should be equal to the number of millimetres travelled in a single revolution. This allows for different sized wheels to be handled within the same chassis. """ def __init__(self, position, max_speed=0, angle=None, radius=None, vector=None): """ Create a new omni-wheel object, specifying the position and either a direction vector directly or the angle in degrees clockwise from the position Y axis along with the radius of the wheel. :param euclid.Point2 position: The wheel's contact point with the surface, specified relative to the centre of the chassis. Units are millimetres. :param float max_speed: The maximum number of revolutions per second allowed for this wheel. When calculating the wheel speeds required for a given trajectory this value is used to scale back all motion if any wheel would have to move at an impossible speed. If not specified this defaults to None, indicating that no speed limit should be placed on this wheel. :param angle: The angle, specified in radians from the positive Y axis where positive values are clockwise from this axis when viewed from above, of the direction of travel of the wheel when driven with a positive speed. If this value is specified then radius must also be specified and dx,dy left as None. :param radius: The radius in millimetres of the wheel, measuring from the centre to the contact point with the surface, this may be hard to determine for some wheels based on their geometry, particularly for wheels with cylindrical rollers, as the radius will vary. For these cases it may be worth directly measuring the circumference of the entire assembly and calculating radius rather than measuring directly. This is used to determine the magnitude of the direction vector. If this is not None then the angle must also be specified, and dx,dy left as None. :param euclid.Vector2 vector: 2 dimensional vector defining the translation of the wheel's contact point after a full revolution of the wheel. """ self.position = position self.max_speed = max_speed if angle is None and radius is None and vector is not None: # Specify wheel based on direct vector """ self.vector = vector elif angle is not None and radius is not None and vector is None: # Specify based on angle from positive Y axis and radius """ circumference = 2 * pi * radius self.vector = Vector2(sin(angle) * circumference, cos(angle) * circumference) else: raise ValueError('Must specify exactly one of angle and radius or translation vector') self.vector_magnitude_squared = self.vector.magnitude_squared() self.co_x = self.vector.x / self.vector_magnitude_squared self.co_y = self.vector.y / self.vector_magnitude_squared self.co_theta = (self.vector.x * self.position.y - self.vector.y * self.position.x) / self.vector_magnitude_squared def speed(self, velocity): """ Given a velocity at a wheel contact point, calculate the speed in revolutions per second at which the wheel should be driven. Method: we want to find the projection of the velocity onto the vector representing the drive of this wheel. We store the vector representing a single revolution of travel as self.vector, so the projection onto this would be velocity.dot(self.vector / abs(self.vector)). However, we want revolutions per second, so we must then divide again by abs(self.vector), leading to velocity.dot(self.vector / abs(self.vector))/abs(self.vector). Because the definition of the dot product is the sum of x1*x2, y1*y2, ... any scalar applied to each x, y ... of a single vector can be moved outside the dot product, so we can simplify as velocity.dot(self.vector) / abs(self.vector)^2. As the magnitude of the vector is taken by sqrt(x^2+y^2) we can simply express this as (x^2+y^2), held in the convenient function magnitude_squared(). So our final simplified form is velocity.dot(self.vector) / self.vector.magnitude_squared(). For efficiency, and because self.vector doesn't change, we can pre-compute this. :param euclid.Vector2 velocity: The velocity at the wheel's contact point with the surface, expressed in mm/s :return: Target wheel speed in rotations per second to hit the desired vector at the contact point. """ return velocity.dot(self.vector) / self.vector_magnitude_squared
[]
rocketbot-cl/genesysCloud
libs/PureCloudPlatformClientV2/models/management_unit.py
dd9d9b5ebb90a82bab98c0d88b9585c22c91f333
# coding: utf-8 """ Copyright 2016 SmartBear Software 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. Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat from six import iteritems import re import json from ..utils import sanitize_for_serialization class ManagementUnit(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ ManagementUnit - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'id': 'str', 'name': 'str', 'division': 'Division', 'business_unit': 'BusinessUnitReference', 'start_day_of_week': 'str', 'time_zone': 'str', 'settings': 'ManagementUnitSettingsResponse', 'metadata': 'WfmVersionedEntityMetadata', 'version': 'int', 'date_modified': 'datetime', 'modified_by': 'UserReference', 'self_uri': 'str' } self.attribute_map = { 'id': 'id', 'name': 'name', 'division': 'division', 'business_unit': 'businessUnit', 'start_day_of_week': 'startDayOfWeek', 'time_zone': 'timeZone', 'settings': 'settings', 'metadata': 'metadata', 'version': 'version', 'date_modified': 'dateModified', 'modified_by': 'modifiedBy', 'self_uri': 'selfUri' } self._id = None self._name = None self._division = None self._business_unit = None self._start_day_of_week = None self._time_zone = None self._settings = None self._metadata = None self._version = None self._date_modified = None self._modified_by = None self._self_uri = None @property def id(self): """ Gets the id of this ManagementUnit. The globally unique identifier for the object. :return: The id of this ManagementUnit. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this ManagementUnit. The globally unique identifier for the object. :param id: The id of this ManagementUnit. :type: str """ self._id = id @property def name(self): """ Gets the name of this ManagementUnit. :return: The name of this ManagementUnit. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this ManagementUnit. :param name: The name of this ManagementUnit. :type: str """ self._name = name @property def division(self): """ Gets the division of this ManagementUnit. The division to which this entity belongs. :return: The division of this ManagementUnit. :rtype: Division """ return self._division @division.setter def division(self, division): """ Sets the division of this ManagementUnit. The division to which this entity belongs. :param division: The division of this ManagementUnit. :type: Division """ self._division = division @property def business_unit(self): """ Gets the business_unit of this ManagementUnit. The business unit to which this management unit belongs :return: The business_unit of this ManagementUnit. :rtype: BusinessUnitReference """ return self._business_unit @business_unit.setter def business_unit(self, business_unit): """ Sets the business_unit of this ManagementUnit. The business unit to which this management unit belongs :param business_unit: The business_unit of this ManagementUnit. :type: BusinessUnitReference """ self._business_unit = business_unit @property def start_day_of_week(self): """ Gets the start_day_of_week of this ManagementUnit. Start day of week for scheduling and forecasting purposes. Moving to Business Unit :return: The start_day_of_week of this ManagementUnit. :rtype: str """ return self._start_day_of_week @start_day_of_week.setter def start_day_of_week(self, start_day_of_week): """ Sets the start_day_of_week of this ManagementUnit. Start day of week for scheduling and forecasting purposes. Moving to Business Unit :param start_day_of_week: The start_day_of_week of this ManagementUnit. :type: str """ allowed_values = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] if start_day_of_week.lower() not in map(str.lower, allowed_values): # print("Invalid value for start_day_of_week -> " + start_day_of_week) self._start_day_of_week = "outdated_sdk_version" else: self._start_day_of_week = start_day_of_week @property def time_zone(self): """ Gets the time_zone of this ManagementUnit. The time zone for the management unit in standard Olson format. Moving to Business Unit :return: The time_zone of this ManagementUnit. :rtype: str """ return self._time_zone @time_zone.setter def time_zone(self, time_zone): """ Sets the time_zone of this ManagementUnit. The time zone for the management unit in standard Olson format. Moving to Business Unit :param time_zone: The time_zone of this ManagementUnit. :type: str """ self._time_zone = time_zone @property def settings(self): """ Gets the settings of this ManagementUnit. The configuration settings for this management unit :return: The settings of this ManagementUnit. :rtype: ManagementUnitSettingsResponse """ return self._settings @settings.setter def settings(self, settings): """ Sets the settings of this ManagementUnit. The configuration settings for this management unit :param settings: The settings of this ManagementUnit. :type: ManagementUnitSettingsResponse """ self._settings = settings @property def metadata(self): """ Gets the metadata of this ManagementUnit. Version info metadata for this management unit. Deprecated, use settings.metadata :return: The metadata of this ManagementUnit. :rtype: WfmVersionedEntityMetadata """ return self._metadata @metadata.setter def metadata(self, metadata): """ Sets the metadata of this ManagementUnit. Version info metadata for this management unit. Deprecated, use settings.metadata :param metadata: The metadata of this ManagementUnit. :type: WfmVersionedEntityMetadata """ self._metadata = metadata @property def version(self): """ Gets the version of this ManagementUnit. The version of the underlying entity. Deprecated, use field from settings.metadata instead :return: The version of this ManagementUnit. :rtype: int """ return self._version @version.setter def version(self, version): """ Sets the version of this ManagementUnit. The version of the underlying entity. Deprecated, use field from settings.metadata instead :param version: The version of this ManagementUnit. :type: int """ self._version = version @property def date_modified(self): """ Gets the date_modified of this ManagementUnit. The date and time at which this entity was last modified. Deprecated, use field from settings.metadata instead. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :return: The date_modified of this ManagementUnit. :rtype: datetime """ return self._date_modified @date_modified.setter def date_modified(self, date_modified): """ Sets the date_modified of this ManagementUnit. The date and time at which this entity was last modified. Deprecated, use field from settings.metadata instead. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z :param date_modified: The date_modified of this ManagementUnit. :type: datetime """ self._date_modified = date_modified @property def modified_by(self): """ Gets the modified_by of this ManagementUnit. The user who last modified this entity. Deprecated, use field from settings.metadata instead :return: The modified_by of this ManagementUnit. :rtype: UserReference """ return self._modified_by @modified_by.setter def modified_by(self, modified_by): """ Sets the modified_by of this ManagementUnit. The user who last modified this entity. Deprecated, use field from settings.metadata instead :param modified_by: The modified_by of this ManagementUnit. :type: UserReference """ self._modified_by = modified_by @property def self_uri(self): """ Gets the self_uri of this ManagementUnit. The URI for this object :return: The self_uri of this ManagementUnit. :rtype: str """ return self._self_uri @self_uri.setter def self_uri(self, self_uri): """ Sets the self_uri of this ManagementUnit. The URI for this object :param self_uri: The self_uri of this ManagementUnit. :type: str """ self._self_uri = self_uri def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_json(self): """ Returns the model as raw JSON """ return json.dumps(sanitize_for_serialization(self.to_dict())) def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[((371, 23, 371, 52), 'six.iteritems', 'iteritems', ({(371, 33, 371, 51): 'self.swagger_types'}, {}), '(self.swagger_types)', False, 'from six import iteritems\n')]
a1fred/guitar_gammas
harmony_tools/core/colors.py
9933fe899af7a8e7f490f61d58004bb59f03271c
COLOR_BLUE = '\033[0;34m' COLOR_GREEN = '\033[0;32m' COLOR_CYAN = '\033[0;36m' COLOR_RED = '\033[0;31m' COLOR_PURPLE = '\033[0;35m' COLOR_BROWN = '\033[0;33m' COLOR_YELLOW = '\033[1;33m' COLOR_GRAY = '\033[1;30m' COLOR_RESET = '\033[0m' FG_COLORS = [ # COLOR_BLUE, COLOR_GREEN, # COLOR_CYAN, # COLOR_RED, # COLOR_PURPLE, # COLOR_BROWN, # COLOR_YELLOW, ] def next_color(color): assert color in FG_COLORS index = FG_COLORS.index(color) index += 1 try: return FG_COLORS[index] except IndexError: index = 0 return FG_COLORS[index] def c(string, color): global COLOR_RESET return f"{color}{string}{COLOR_RESET}"
[]
tegamax/ProjectCode
Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_8/8_5.py
0ed86e227fba50b453c5c4a2596afbadc39a167e
''' 8-5. Cities: Write a function called describe_city() that accepts the name of a city and its country. The function should print a simple sentence, such as Reykjavik is in Iceland. Give the parameter for the country a default value. Call your function for three different cities, at least one of which is not in the default country. ''' def describe_city(city,country='Iceland'): cities = ['Reykjavik','Kópavogur','Reykjanesbær','Garðabær','Mosfellsbær','Hafnarfjörður'] for i in cities: if i==city: print(f'{i} is in Iceland') break else: print(f'So you think {city} is a city Iceland?') describe_city('Garðabær','country') ''' Árborg Akureyri '''
[]
trnielsen/nexus-constructor
tests/test_geometry_loader.py
65efb6eedca30250b75f142dd29a46bc909958df
from nexus_constructor.geometry import OFFGeometryNoNexus from nexus_constructor.geometry.geometry_loader import load_geometry_from_file_object from nexus_constructor.off_renderer import repeat_shape_over_positions from PySide2.QtGui import QVector3D from io import StringIO def test_GIVEN_off_file_containing_geometry_WHEN_loading_geometry_to_file_THEN_vertices_and_faces_loaded_are_the_same_as_the_file(): model = OFFGeometryNoNexus() model.units = "m" off_file = ( "OFF\n" "# cube.off\n" "# A cube\n" "8 6 0\n" "-0.500000 -0.500000 0.500000\n" "0.500000 -0.500000 0.500000\n" "-0.500000 0.500000 0.500000\n" "0.500000 0.500000 0.500000\n" "-0.500000 0.500000 -0.500000\n" "0.500000 0.500000 -0.500000\n" "-0.500000 -0.500000 -0.500000\n" "0.500000 -0.500000 -0.500000\n" "4 0 1 3 2\n" "4 2 3 5 4\n" "4 4 5 7 6\n" "4 6 7 1 0\n" "4 1 7 5 3\n" "4 6 0 2 4\n" ) load_geometry_from_file_object(StringIO(off_file), ".off", model.units, model) assert model.vertices == [ QVector3D(-0.5, -0.5, 0.5), QVector3D(0.5, -0.5, 0.5), QVector3D(-0.5, 0.5, 0.5), QVector3D(0.5, 0.5, 0.5), QVector3D(-0.5, 0.5, -0.5), QVector3D(0.5, 0.5, -0.5), QVector3D(-0.5, -0.5, -0.5), QVector3D(0.5, -0.5, -0.5), ] assert model.faces == [ [0, 1, 3, 2], [2, 3, 5, 4], [4, 5, 7, 6], [6, 7, 1, 0], [1, 7, 5, 3], [6, 0, 2, 4], ] assert model.winding_order == [ 0, 1, 3, 2, 2, 3, 5, 4, 4, 5, 7, 6, 6, 7, 1, 0, 1, 7, 5, 3, 6, 0, 2, 4, ] assert model.winding_order_indices == [0, 4, 8, 12, 16, 20] def test_GIVEN_stl_file_with_cube_geometry_WHEN_loading_geometry_THEN_all_faces_are_present(): length = 30 left_lower_rear = QVector3D(0, 0, 0) right_lower_rear = QVector3D(length, 0, 0) left_upper_rear = QVector3D(0, length, 0) right_upper_rear = QVector3D(length, length, 0) left_lower_front = QVector3D(0, 0, length) right_lower_front = QVector3D(length, 0, length) left_upper_front = QVector3D(0, length, length) right_upper_front = QVector3D(length, length, length) # faces on a cube with a right hand winding order faces = [ [ left_lower_front, left_lower_rear, right_lower_rear, right_lower_front, ], # bottom [left_lower_front, left_upper_front, left_upper_rear, left_lower_rear], # left [ left_upper_front, left_lower_front, right_lower_front, right_upper_front, ], # front [ right_upper_front, right_lower_front, right_lower_rear, right_upper_rear, ], # right [right_upper_rear, right_lower_rear, left_lower_rear, left_upper_rear], # rear [left_upper_rear, left_upper_front, right_upper_front, right_upper_rear], # top ] cube = """solid vcg facet normal -1.000000e+00 0.000000e+00 0.000000e+00 outer loop vertex 0.000000e+00 3.000000e+01 0.000000e+00 vertex 0.000000e+00 0.000000e+00 3.000000e+01 vertex 0.000000e+00 3.000000e+01 3.000000e+01 endloop endfacet facet normal -1.000000e+00 0.000000e+00 0.000000e+00 outer loop vertex 0.000000e+00 0.000000e+00 0.000000e+00 vertex 0.000000e+00 0.000000e+00 3.000000e+01 vertex 0.000000e+00 3.000000e+01 0.000000e+00 endloop endfacet facet normal 1.000000e+00 -0.000000e+00 0.000000e+00 outer loop vertex 3.000000e+01 0.000000e+00 3.000000e+01 vertex 3.000000e+01 3.000000e+01 0.000000e+00 vertex 3.000000e+01 3.000000e+01 3.000000e+01 endloop endfacet facet normal 1.000000e+00 0.000000e+00 0.000000e+00 outer loop vertex 3.000000e+01 0.000000e+00 3.000000e+01 vertex 3.000000e+01 0.000000e+00 0.000000e+00 vertex 3.000000e+01 3.000000e+01 0.000000e+00 endloop endfacet facet normal 0.000000e+00 -1.000000e+00 0.000000e+00 outer loop vertex 3.000000e+01 0.000000e+00 0.000000e+00 vertex 3.000000e+01 0.000000e+00 3.000000e+01 vertex 0.000000e+00 0.000000e+00 0.000000e+00 endloop endfacet facet normal 0.000000e+00 -1.000000e+00 0.000000e+00 outer loop vertex 0.000000e+00 0.000000e+00 0.000000e+00 vertex 3.000000e+01 0.000000e+00 3.000000e+01 vertex 0.000000e+00 0.000000e+00 3.000000e+01 endloop endfacet facet normal 0.000000e+00 1.000000e+00 0.000000e+00 outer loop vertex 3.000000e+01 3.000000e+01 3.000000e+01 vertex 3.000000e+01 3.000000e+01 0.000000e+00 vertex 0.000000e+00 3.000000e+01 0.000000e+00 endloop endfacet facet normal 0.000000e+00 1.000000e+00 0.000000e+00 outer loop vertex 3.000000e+01 3.000000e+01 3.000000e+01 vertex 0.000000e+00 3.000000e+01 0.000000e+00 vertex 0.000000e+00 3.000000e+01 3.000000e+01 endloop endfacet facet normal 0.000000e+00 0.000000e+00 -1.000000e+00 outer loop vertex 0.000000e+00 3.000000e+01 0.000000e+00 vertex 3.000000e+01 3.000000e+01 0.000000e+00 vertex 0.000000e+00 0.000000e+00 0.000000e+00 endloop endfacet facet normal 0.000000e+00 0.000000e+00 -1.000000e+00 outer loop vertex 0.000000e+00 0.000000e+00 0.000000e+00 vertex 3.000000e+01 3.000000e+01 0.000000e+00 vertex 3.000000e+01 0.000000e+00 0.000000e+00 endloop endfacet facet normal 0.000000e+00 0.000000e+00 1.000000e+00 outer loop vertex 3.000000e+01 3.000000e+01 3.000000e+01 vertex 0.000000e+00 3.000000e+01 3.000000e+01 vertex 0.000000e+00 0.000000e+00 3.000000e+01 endloop endfacet facet normal 0.000000e+00 0.000000e+00 1.000000e+00 outer loop vertex 3.000000e+01 3.000000e+01 3.000000e+01 vertex 0.000000e+00 0.000000e+00 3.000000e+01 vertex 3.000000e+01 0.000000e+00 3.000000e+01 endloop endfacet endsolid vcg""" geometry = load_geometry_from_file_object(StringIO(cube), ".stl", "m") # 2 triangles per face, 6 faces in the cube assert len(geometry.faces) == 6 * 2 assert geometry.winding_order_indices == [i * 3 for i in range(12)] # each expected vertex is in the shape for vertex in [ left_lower_rear, right_lower_rear, left_upper_rear, right_upper_rear, left_lower_front, right_lower_front, left_upper_front, right_upper_front, ]: assert vertex in geometry.vertices # each face must be in the loaded geometry for face in faces: face_found = False # each face could be split into triangles in one of two ways for triangle_split in [ [[face[0], face[1], face[2]], [face[2], face[3], face[0]]], [[face[1], face[2], face[3]], [face[3], face[0], face[1]]], ]: triangle_matches = 0 # each triangle in the square's split must be in the loaded geometry for the square to be for triangle in triangle_split: # check the triangle against each rotation of each triangle in the geometry for candidate_triangle_indices in geometry.faces: a = geometry.vertices[candidate_triangle_indices[0]] b = geometry.vertices[candidate_triangle_indices[1]] c = geometry.vertices[candidate_triangle_indices[2]] if ( triangle == [a, b, c] or triangle == [b, c, a] or triangle == [c, a, b] ): triangle_matches += 1 if triangle_matches == 2: face_found = True assert face_found def test_GIVEN_unrecognised_file_extension_WHEN_loading_geometry_THEN_returns_empty_geometry(): geometry = load_geometry_from_file_object(StringIO(), ".txt", "m") assert len(geometry.vertices) == 0 assert len(geometry.faces) == 0 def get_dummy_OFF(): # A square with a triangle on the side original_vertices = [ QVector3D(0, 0, 0), QVector3D(0, 1, 0), QVector3D(1, 1, 0), QVector3D(1, 0, 0), QVector3D(1.5, 0.5, 0), ] original_faces = [[0, 1, 2, 3], [2, 3, 4]] return OFFGeometryNoNexus(vertices=original_vertices, faces=original_faces) def test_WHEN_generate_off_mesh_with_no_repeat_THEN_off_unchanged(): off_geometry = get_dummy_OFF() positions = [QVector3D(0, 0, 0)] faces, vertices = repeat_shape_over_positions(off_geometry, positions) assert faces == off_geometry.faces assert vertices == off_geometry.vertices def test_WHEN_generate_off_mesh_with_three_copies_THEN_original_shape_remains(): off_geometry = get_dummy_OFF() positions = [QVector3D(0, 0, 0), QVector3D(0, 0, 1), QVector3D(1, 0, 0)] faces, vertices = repeat_shape_over_positions(off_geometry, positions) assert faces[: len(off_geometry.faces)] == off_geometry.faces assert vertices[: len(off_geometry.vertices)] == off_geometry.vertices def _test_position_with_single_translation_helper(translation): off_geometry = get_dummy_OFF() positions = [QVector3D(0, 0, 0), translation] faces, vertices = repeat_shape_over_positions(off_geometry, positions) second_shape_faces = faces[len(off_geometry.faces) :] second_shape_vertices = vertices[len(off_geometry.vertices) :] # Faces will just be the same but every vertex added to be len(vertices) shifted_faces = [] for face in second_shape_faces: shifted_face = [] for vertex in face: shifted_face.append(vertex - len(off_geometry.vertices)) shifted_faces.append(shifted_face) assert shifted_faces == off_geometry.faces return off_geometry.vertices, second_shape_vertices def test_WHEN_generate_off_mesh_with_single_x_position_THEN_second_shape_just_translation_of_first(): ( original_vertices, second_shape_vertices, ) = _test_position_with_single_translation_helper(QVector3D(1, 0, 0)) # Vertices will be the same by shifted by 1 for vertex in second_shape_vertices: vertex.setX(vertex.x() - 1) assert second_shape_vertices == original_vertices def test_WHEN_generate_off_mesh_with_single_y_position_THEN_second_shape_just_translation_of_first(): ( original_vertices, second_shape_vertices, ) = _test_position_with_single_translation_helper(QVector3D(0, 1, 0)) # Vertices will be the same by shifted by 1 for vertex in second_shape_vertices: vertex.setY(vertex.y() - 1) assert second_shape_vertices == original_vertices def test_WHEN_generate_off_mesh_with_single_negative_z_position_THEN_second_shape_just_translation_of_first(): ( original_vertices, second_shape_vertices, ) = _test_position_with_single_translation_helper(QVector3D(0, 0, -1)) # Vertices will be the same by shifted by 1 for vertex in second_shape_vertices: vertex.setZ(vertex.z() + 1) assert second_shape_vertices == original_vertices def test_WHEN_generate_off_mesh_with_single_diagonal_position_THEN_second_shape_just_translation_of_first(): ( original_vertices, second_shape_vertices, ) = _test_position_with_single_translation_helper(QVector3D(0, 1, -1)) for vertex in second_shape_vertices: vertex.setZ(vertex.z() + 1) vertex.setY(vertex.y() - 1) assert second_shape_vertices == original_vertices
[((9, 12, 9, 32), 'nexus_constructor.geometry.OFFGeometryNoNexus', 'OFFGeometryNoNexus', ({}, {}), '()', False, 'from nexus_constructor.geometry import OFFGeometryNoNexus\n'), ((84, 22, 84, 40), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(84, 32, 84, 33): '0', (84, 35, 84, 36): '0', (84, 38, 84, 39): '0'}, {}), '(0, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((85, 23, 85, 46), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(85, 33, 85, 39): 'length', (85, 41, 85, 42): '0', (85, 44, 85, 45): '0'}, {}), '(length, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((86, 22, 86, 45), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(86, 32, 86, 33): '0', (86, 35, 86, 41): 'length', (86, 43, 86, 44): '0'}, {}), '(0, length, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((87, 23, 87, 51), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(87, 33, 87, 39): 'length', (87, 41, 87, 47): 'length', (87, 49, 87, 50): '0'}, {}), '(length, length, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((88, 23, 88, 46), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(88, 33, 88, 34): '0', (88, 36, 88, 37): '0', (88, 39, 88, 45): 'length'}, {}), '(0, 0, length)', False, 'from PySide2.QtGui import QVector3D\n'), ((89, 24, 89, 52), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(89, 34, 89, 40): 'length', (89, 42, 89, 43): '0', (89, 45, 89, 51): 'length'}, {}), '(length, 0, length)', False, 'from PySide2.QtGui import QVector3D\n'), ((90, 23, 90, 51), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(90, 33, 90, 34): '0', (90, 36, 90, 42): 'length', (90, 44, 90, 50): 'length'}, {}), '(0, length, length)', False, 'from PySide2.QtGui import QVector3D\n'), ((91, 24, 91, 57), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(91, 34, 91, 40): 'length', (91, 42, 91, 48): 'length', (91, 50, 91, 56): 'length'}, {}), '(length, length, length)', False, 'from PySide2.QtGui import QVector3D\n'), ((265, 11, 265, 79), 'nexus_constructor.geometry.OFFGeometryNoNexus', 'OFFGeometryNoNexus', (), '', False, 'from nexus_constructor.geometry import OFFGeometryNoNexus\n'), ((273, 22, 273, 74), 'nexus_constructor.off_renderer.repeat_shape_over_positions', 'repeat_shape_over_positions', ({(273, 50, 273, 62): 'off_geometry', (273, 64, 273, 73): 'positions'}, {}), '(off_geometry, positions)', False, 'from nexus_constructor.off_renderer import repeat_shape_over_positions\n'), ((284, 22, 284, 74), 'nexus_constructor.off_renderer.repeat_shape_over_positions', 'repeat_shape_over_positions', ({(284, 50, 284, 62): 'off_geometry', (284, 64, 284, 73): 'positions'}, {}), '(off_geometry, positions)', False, 'from nexus_constructor.off_renderer import repeat_shape_over_positions\n'), ((295, 22, 295, 74), 'nexus_constructor.off_renderer.repeat_shape_over_positions', 'repeat_shape_over_positions', ({(295, 50, 295, 62): 'off_geometry', (295, 64, 295, 73): 'positions'}, {}), '(off_geometry, positions)', False, 'from nexus_constructor.off_renderer import repeat_shape_over_positions\n'), ((33, 35, 33, 53), 'io.StringIO', 'StringIO', ({(33, 44, 33, 52): 'off_file'}, {}), '(off_file)', False, 'from io import StringIO\n'), ((204, 46, 204, 60), 'io.StringIO', 'StringIO', ({(204, 55, 204, 59): 'cube'}, {}), '(cube)', False, 'from io import StringIO\n'), ((249, 46, 249, 56), 'io.StringIO', 'StringIO', ({}, {}), '()', False, 'from io import StringIO\n'), ((257, 8, 257, 26), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(257, 18, 257, 19): '(0)', (257, 21, 257, 22): '(0)', (257, 24, 257, 25): '(0)'}, {}), '(0, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((258, 8, 258, 26), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(258, 18, 258, 19): '(0)', (258, 21, 258, 22): '(1)', (258, 24, 258, 25): '(0)'}, {}), '(0, 1, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((259, 8, 259, 26), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(259, 18, 259, 19): '(1)', (259, 21, 259, 22): '(1)', (259, 24, 259, 25): '(0)'}, {}), '(1, 1, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((260, 8, 260, 26), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(260, 18, 260, 19): '(1)', (260, 21, 260, 22): '(0)', (260, 24, 260, 25): '(0)'}, {}), '(1, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((261, 8, 261, 30), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(261, 18, 261, 21): '(1.5)', (261, 23, 261, 26): '(0.5)', (261, 28, 261, 29): '(0)'}, {}), '(1.5, 0.5, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((271, 17, 271, 35), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(271, 27, 271, 28): '(0)', (271, 30, 271, 31): '(0)', (271, 33, 271, 34): '(0)'}, {}), '(0, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((282, 17, 282, 35), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(282, 27, 282, 28): '(0)', (282, 30, 282, 31): '(0)', (282, 33, 282, 34): '(0)'}, {}), '(0, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((282, 37, 282, 55), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(282, 47, 282, 48): '(0)', (282, 50, 282, 51): '(0)', (282, 53, 282, 54): '(1)'}, {}), '(0, 0, 1)', False, 'from PySide2.QtGui import QVector3D\n'), ((282, 57, 282, 75), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(282, 67, 282, 68): '(1)', (282, 70, 282, 71): '(0)', (282, 73, 282, 74): '(0)'}, {}), '(1, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((293, 17, 293, 35), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(293, 27, 293, 28): '(0)', (293, 30, 293, 31): '(0)', (293, 33, 293, 34): '(0)'}, {}), '(0, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((317, 54, 317, 72), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(317, 64, 317, 65): '1', (317, 67, 317, 68): '0', (317, 70, 317, 71): '0'}, {}), '(1, 0, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((330, 54, 330, 72), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(330, 64, 330, 65): '0', (330, 67, 330, 68): '1', (330, 70, 330, 71): '0'}, {}), '(0, 1, 0)', False, 'from PySide2.QtGui import QVector3D\n'), ((343, 54, 343, 73), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(343, 64, 343, 65): '0', (343, 67, 343, 68): '0', (343, 70, 343, 72): '-1'}, {}), '(0, 0, -1)', False, 'from PySide2.QtGui import QVector3D\n'), ((356, 54, 356, 73), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(356, 64, 356, 65): '0', (356, 67, 356, 68): '1', (356, 70, 356, 72): '-1'}, {}), '(0, 1, -1)', False, 'from PySide2.QtGui import QVector3D\n'), ((36, 8, 36, 34), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(36, 18, 36, 22): '(-0.5)', (36, 24, 36, 28): '(-0.5)', (36, 30, 36, 33): '(0.5)'}, {}), '(-0.5, -0.5, 0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((37, 8, 37, 33), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(37, 18, 37, 21): '(0.5)', (37, 23, 37, 27): '(-0.5)', (37, 29, 37, 32): '(0.5)'}, {}), '(0.5, -0.5, 0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((38, 8, 38, 33), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(38, 18, 38, 22): '(-0.5)', (38, 24, 38, 27): '(0.5)', (38, 29, 38, 32): '(0.5)'}, {}), '(-0.5, 0.5, 0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((39, 8, 39, 32), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(39, 18, 39, 21): '(0.5)', (39, 23, 39, 26): '(0.5)', (39, 28, 39, 31): '(0.5)'}, {}), '(0.5, 0.5, 0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((40, 8, 40, 34), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(40, 18, 40, 22): '(-0.5)', (40, 24, 40, 27): '(0.5)', (40, 29, 40, 33): '(-0.5)'}, {}), '(-0.5, 0.5, -0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((41, 8, 41, 33), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(41, 18, 41, 21): '(0.5)', (41, 23, 41, 26): '(0.5)', (41, 28, 41, 32): '(-0.5)'}, {}), '(0.5, 0.5, -0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((42, 8, 42, 35), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(42, 18, 42, 22): '(-0.5)', (42, 24, 42, 28): '(-0.5)', (42, 30, 42, 34): '(-0.5)'}, {}), '(-0.5, -0.5, -0.5)', False, 'from PySide2.QtGui import QVector3D\n'), ((43, 8, 43, 34), 'PySide2.QtGui.QVector3D', 'QVector3D', ({(43, 18, 43, 21): '(0.5)', (43, 23, 43, 27): '(-0.5)', (43, 29, 43, 33): '(-0.5)'}, {}), '(0.5, -0.5, -0.5)', False, 'from PySide2.QtGui import QVector3D\n')]
Chum4k3r/Verteste
verteste/ui/ui_about.py
216c04468ff14c392ee3c6aebe12a0fa0e98767c
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'aboutdialog.ui' ## ## Created by: Qt User Interface Compiler version 6.1.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import * # type: ignore from PySide6.QtGui import * # type: ignore from PySide6.QtWidgets import * # type: ignore class Ui_AboutDialog(QDialog): # Caixa de diálogo utilizada para criação ou edição de linhas def __init__(self, parent=None): QDialog.__init__(self, parent=parent) self.setupUi(self) return def setupUi(self, Dialog): if not Dialog.objectName(): Dialog.setObjectName(u"Dialog") Dialog.resize(400, 300) self.verticalLayout = QVBoxLayout(Dialog) self.verticalLayout.setObjectName(u"verticalLayout") self.label = QLabel(Dialog) self.label.setObjectName(u"label") font = QFont() font.setFamilies([u"Sandoval"]) font.setPointSize(18) self.label.setFont(font) self.label.setAlignment(Qt.AlignCenter) self.verticalLayout.addWidget(self.label) self.label_4 = QLabel(Dialog) self.label_4.setObjectName(u"label_4") self.label_4.setTextFormat(Qt.AutoText) self.label_4.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.verticalLayout.addWidget(self.label_4) self.label_2 = QLabel(Dialog) self.label_2.setObjectName(u"label_2") self.verticalLayout.addWidget(self.label_2) self.label_3 = QLabel(Dialog) self.label_3.setObjectName(u"label_3") self.label_3.setAlignment(Qt.AlignCenter) self.verticalLayout.addWidget(self.label_3) self.label_5 = QLabel(Dialog) self.label_5.setObjectName(u"label_5") self.verticalLayout.addWidget(self.label_5) self.label_6 = QLabel(Dialog) self.label_6.setObjectName(u"label_6") self.label_6.setTextFormat(Qt.MarkdownText) self.label_6.setAlignment(Qt.AlignCenter) self.verticalLayout.addWidget(self.label_6) self.retranslateUi(Dialog) QMetaObject.connectSlotsByName(Dialog) # setupUi def retranslateUi(self, Dialog): Dialog.setWindowTitle(QCoreApplication.translate("Dialog", u"Sobre", None)) self.label.setText(QCoreApplication.translate("Dialog", u"Verteste", None)) self.label_4.setText(QCoreApplication.translate("Dialog", u"Vers\u00e3o 1.0.0", None)) self.label_2.setText(QCoreApplication.translate("Dialog", u"Desenvolvido por:", None)) self.label_3.setText(QCoreApplication.translate("Dialog", u"Jo\u00e3o Vitor Gutkoski Paes", None)) self.label_5.setText(QCoreApplication.translate("Dialog", u"C\u00f3digo fonte dispon\u00edvel em:", None)) self.label_6.setText(QCoreApplication.translate("Dialog", u"https://github.com/Chum4k3r/Verteste.git", None)) # retranslateUi
[]
Qix-/aiohttp
tests/test_base_protocol.py
aee067dccad3dc0e79778a1b213105f20bf39baf
import asyncio from contextlib import suppress from unittest import mock import pytest from aiohttp.base_protocol import BaseProtocol async def test_loop() -> None: loop = asyncio.get_event_loop() asyncio.set_event_loop(None) pr = BaseProtocol(loop) assert pr._loop is loop async def test_pause_writing() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop) assert not pr._paused pr.pause_writing() assert pr._paused async def test_resume_writing_no_waiters() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) pr.pause_writing() assert pr._paused pr.resume_writing() assert not pr._paused async def test_connection_made() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() assert pr.transport is None pr.connection_made(tr) assert pr.transport is not None async def test_connection_lost_not_paused() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) assert not pr._connection_lost pr.connection_lost(None) assert pr.transport is None assert pr._connection_lost async def test_connection_lost_paused_without_waiter() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) assert not pr._connection_lost pr.pause_writing() pr.connection_lost(None) assert pr.transport is None assert pr._connection_lost async def test_drain_lost() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.connection_lost(None) with pytest.raises(ConnectionResetError): await pr._drain_helper() async def test_drain_not_paused() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) assert pr._drain_waiter is None await pr._drain_helper() assert pr._drain_waiter is None async def test_resume_drain_waited() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.pause_writing() t = loop.create_task(pr._drain_helper()) await asyncio.sleep(0) assert pr._drain_waiter is not None pr.resume_writing() assert (await t) is None assert pr._drain_waiter is None async def test_lost_drain_waited_ok() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.pause_writing() t = loop.create_task(pr._drain_helper()) await asyncio.sleep(0) assert pr._drain_waiter is not None pr.connection_lost(None) assert (await t) is None assert pr._drain_waiter is None async def test_lost_drain_waited_exception() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.pause_writing() t = loop.create_task(pr._drain_helper()) await asyncio.sleep(0) assert pr._drain_waiter is not None exc = RuntimeError() pr.connection_lost(exc) with pytest.raises(RuntimeError) as cm: await t assert cm.value is exc assert pr._drain_waiter is None async def test_lost_drain_cancelled() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.pause_writing() fut = loop.create_future() async def wait(): fut.set_result(None) await pr._drain_helper() t = loop.create_task(wait()) await fut t.cancel() assert pr._drain_waiter is not None pr.connection_lost(None) with suppress(asyncio.CancelledError): await t assert pr._drain_waiter is None async def test_resume_drain_cancelled() -> None: loop = asyncio.get_event_loop() pr = BaseProtocol(loop=loop) tr = mock.Mock() pr.connection_made(tr) pr.pause_writing() fut = loop.create_future() async def wait(): fut.set_result(None) await pr._drain_helper() t = loop.create_task(wait()) await fut t.cancel() assert pr._drain_waiter is not None pr.resume_writing() with suppress(asyncio.CancelledError): await t assert pr._drain_waiter is None
[((11, 11, 11, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((12, 4, 12, 32), 'asyncio.set_event_loop', 'asyncio.set_event_loop', ({(12, 27, 12, 31): 'None'}, {}), '(None)', False, 'import asyncio\n'), ((13, 9, 13, 27), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', ({(13, 22, 13, 26): 'loop'}, {}), '(loop)', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((18, 11, 18, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((19, 9, 19, 27), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', ({(19, 22, 19, 26): 'loop'}, {}), '(loop)', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((26, 11, 26, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((27, 9, 27, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((35, 11, 35, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((36, 9, 36, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((37, 9, 37, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((44, 11, 44, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((45, 9, 45, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((46, 9, 46, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((55, 11, 55, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((56, 9, 56, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((57, 9, 57, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((67, 11, 67, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((68, 9, 68, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((69, 9, 69, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((77, 11, 77, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((78, 9, 78, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((79, 9, 79, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((87, 11, 87, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((88, 9, 88, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((89, 9, 89, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((103, 11, 103, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((104, 9, 104, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((105, 9, 105, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((119, 11, 119, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((120, 9, 120, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((121, 9, 121, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((138, 11, 138, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((139, 9, 139, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((140, 9, 140, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((162, 11, 162, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((163, 9, 163, 32), 'aiohttp.base_protocol.BaseProtocol', 'BaseProtocol', (), '', False, 'from aiohttp.base_protocol import BaseProtocol\n'), ((164, 9, 164, 20), 'unittest.mock.Mock', 'mock.Mock', ({}, {}), '()', False, 'from unittest import mock\n'), ((72, 9, 72, 44), 'pytest.raises', 'pytest.raises', ({(72, 23, 72, 43): 'ConnectionResetError'}, {}), '(ConnectionResetError)', False, 'import pytest\n'), ((94, 10, 94, 26), 'asyncio.sleep', 'asyncio.sleep', ({(94, 24, 94, 25): '(0)'}, {}), '(0)', False, 'import asyncio\n'), ((110, 10, 110, 26), 'asyncio.sleep', 'asyncio.sleep', ({(110, 24, 110, 25): '(0)'}, {}), '(0)', False, 'import asyncio\n'), ((126, 10, 126, 26), 'asyncio.sleep', 'asyncio.sleep', ({(126, 24, 126, 25): '(0)'}, {}), '(0)', False, 'import asyncio\n'), ((131, 9, 131, 36), 'pytest.raises', 'pytest.raises', ({(131, 23, 131, 35): 'RuntimeError'}, {}), '(RuntimeError)', False, 'import pytest\n'), ((156, 9, 156, 41), 'contextlib.suppress', 'suppress', ({(156, 18, 156, 40): 'asyncio.CancelledError'}, {}), '(asyncio.CancelledError)', False, 'from contextlib import suppress\n'), ((180, 9, 180, 41), 'contextlib.suppress', 'suppress', ({(180, 18, 180, 40): 'asyncio.CancelledError'}, {}), '(asyncio.CancelledError)', False, 'from contextlib import suppress\n')]
marcusviniciusteixeira/RPAPython
main.py
8055e7283e6a8dd8910139cbbaa914761e2924f2
import PySimpleGUI as sg import os import time import pyautogui class TelaPython: def __init__(self): layout = [ [sg.Text('Usuário',size=(10,0)), sg.Input(size=(20,0),key='usuario')], [sg.Text('Senha',size=(10,0)), sg.Input(size=(20,0),key='senha')], [sg.Text('Número',size=(10,0)), sg.Input(size=(20,0),key='num')], [sg.Text('Time1',size=(10,0)), sg.Slider(range=(0,30), default_value=0, orientation='h',size=(10,15),key='time1')], [sg.Text('Time2',size=(10,0)), sg.Slider(range=(0,30), default_value=0, orientation='h',size=(10,15),key='time2')], [sg.Button('Executar')] ] janela = sg.Window("Macro Portal CLARO").layout(layout) self.button, self.values = janela.read() def Iniciar(self): usuario = self.values['usuario'] senha = self.values['senha'] num = self.values['num'] time1 = self.values['time1'] time2 = self.values['time2'] os.startfile('PortalClaro.exe') time.sleep(time1) pyautogui.moveTo(571, 409)#USUÁRIO pyautogui.click() pyautogui.write(usuario) pyautogui.press('tab')#SENHA pyautogui.write(senha)#Pjfa#412 pyautogui.moveTo(672, 530) pyautogui.click() time.sleep(time2) pyautogui.moveTo(556, 472)#NUM pyautogui.click() pyautogui.write(num) pyautogui.moveTo(683, 505) pyautogui.click() time.sleep(1) pyautogui.moveTo(576, 437) pyautogui.click() tela = TelaPython() tela.Iniciar()
[((27, 8, 27, 39), 'os.startfile', 'os.startfile', ({(27, 21, 27, 38): '"""PortalClaro.exe"""'}, {}), "('PortalClaro.exe')", False, 'import os\n'), ((28, 8, 28, 25), 'time.sleep', 'time.sleep', ({(28, 19, 28, 24): 'time1'}, {}), '(time1)', False, 'import time\n'), ((29, 8, 29, 34), 'pyautogui.moveTo', 'pyautogui.moveTo', ({(29, 25, 29, 28): '(571)', (29, 30, 29, 33): '(409)'}, {}), '(571, 409)', False, 'import pyautogui\n'), ((30, 8, 30, 25), 'pyautogui.click', 'pyautogui.click', ({}, {}), '()', False, 'import pyautogui\n'), ((31, 8, 31, 32), 'pyautogui.write', 'pyautogui.write', ({(31, 24, 31, 31): 'usuario'}, {}), '(usuario)', False, 'import pyautogui\n'), ((32, 8, 32, 30), 'pyautogui.press', 'pyautogui.press', ({(32, 24, 32, 29): '"""tab"""'}, {}), "('tab')", False, 'import pyautogui\n'), ((33, 8, 33, 30), 'pyautogui.write', 'pyautogui.write', ({(33, 24, 33, 29): 'senha'}, {}), '(senha)', False, 'import pyautogui\n'), ((34, 8, 34, 34), 'pyautogui.moveTo', 'pyautogui.moveTo', ({(34, 25, 34, 28): '(672)', (34, 30, 34, 33): '(530)'}, {}), '(672, 530)', False, 'import pyautogui\n'), ((35, 8, 35, 25), 'pyautogui.click', 'pyautogui.click', ({}, {}), '()', False, 'import pyautogui\n'), ((36, 8, 36, 25), 'time.sleep', 'time.sleep', ({(36, 19, 36, 24): 'time2'}, {}), '(time2)', False, 'import time\n'), ((37, 8, 37, 34), 'pyautogui.moveTo', 'pyautogui.moveTo', ({(37, 25, 37, 28): '(556)', (37, 30, 37, 33): '(472)'}, {}), '(556, 472)', False, 'import pyautogui\n'), ((38, 8, 38, 25), 'pyautogui.click', 'pyautogui.click', ({}, {}), '()', False, 'import pyautogui\n'), ((39, 8, 39, 28), 'pyautogui.write', 'pyautogui.write', ({(39, 24, 39, 27): 'num'}, {}), '(num)', False, 'import pyautogui\n'), ((40, 8, 40, 34), 'pyautogui.moveTo', 'pyautogui.moveTo', ({(40, 25, 40, 28): '(683)', (40, 30, 40, 33): '(505)'}, {}), '(683, 505)', False, 'import pyautogui\n'), ((41, 8, 41, 25), 'pyautogui.click', 'pyautogui.click', ({}, {}), '()', False, 'import pyautogui\n'), ((42, 8, 42, 21), 'time.sleep', 'time.sleep', ({(42, 19, 42, 20): '(1)'}, {}), '(1)', False, 'import time\n'), ((43, 8, 43, 34), 'pyautogui.moveTo', 'pyautogui.moveTo', ({(43, 25, 43, 28): '(576)', (43, 30, 43, 33): '(437)'}, {}), '(576, 437)', False, 'import pyautogui\n'), ((44, 8, 44, 25), 'pyautogui.click', 'pyautogui.click', ({}, {}), '()', False, 'import pyautogui\n'), ((9, 13, 9, 44), 'PySimpleGUI.Text', 'sg.Text', (), '', True, 'import PySimpleGUI as sg\n'), ((9, 46, 9, 81), 'PySimpleGUI.Input', 'sg.Input', (), '', True, 'import PySimpleGUI as sg\n'), ((10, 13, 10, 41), 'PySimpleGUI.Text', 'sg.Text', (), '', True, 'import PySimpleGUI as sg\n'), ((10, 43, 10, 76), 'PySimpleGUI.Input', 'sg.Input', (), '', True, 'import PySimpleGUI as sg\n'), ((11, 13, 11, 43), 'PySimpleGUI.Text', 'sg.Text', (), '', True, 'import PySimpleGUI as sg\n'), ((11, 45, 11, 76), 'PySimpleGUI.Input', 'sg.Input', (), '', True, 'import PySimpleGUI as sg\n'), ((12, 13, 12, 41), 'PySimpleGUI.Text', 'sg.Text', (), '', True, 'import PySimpleGUI as sg\n'), ((12, 43, 12, 125), 'PySimpleGUI.Slider', 'sg.Slider', (), '', True, 'import PySimpleGUI as sg\n'), ((13, 13, 13, 41), 'PySimpleGUI.Text', 'sg.Text', (), '', True, 'import PySimpleGUI as sg\n'), ((13, 43, 13, 125), 'PySimpleGUI.Slider', 'sg.Slider', (), '', True, 'import PySimpleGUI as sg\n'), ((14, 13, 14, 34), 'PySimpleGUI.Button', 'sg.Button', ({(14, 23, 14, 33): '"""Executar"""'}, {}), "('Executar')", True, 'import PySimpleGUI as sg\n'), ((17, 17, 17, 48), 'PySimpleGUI.Window', 'sg.Window', ({(17, 27, 17, 47): '"""Macro Portal CLARO"""'}, {}), "('Macro Portal CLARO')", True, 'import PySimpleGUI as sg\n')]
eliben/deep-learning-samples
logistic-regression/plot_binary_losses.py
d5ca86c5db664fabfb302cbbc231c50ec3d6a103
# Helper code to plot binary losses. # # Eli Bendersky (http://eli.thegreenplace.net) # This code is in the public domain from __future__ import print_function import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': fig, ax = plt.subplots() fig.set_tight_layout(True) xs = np.linspace(-2, 2, 500) # plot L0/1 loss ax.plot(xs, np.where(xs < 0, np.ones_like(xs), np.zeros_like(xs)), color='r', linewidth=2.0, label='$L_{01}$') # plot square loss ax.plot(xs, (xs - 1) ** 2, linestyle='-.', label='$L_2$') # plot hinge loss ax.plot(xs, np.maximum(np.zeros_like(xs), 1 - xs), color='g', linewidth=2.0, label='$L_h$') ax.grid(True) plt.ylim((-1, 4)) ax.legend() fig.savefig('loss.png', dpi=80) plt.show()
[((11, 14, 11, 28), 'matplotlib.pyplot.subplots', 'plt.subplots', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((14, 9, 14, 32), 'numpy.linspace', 'np.linspace', ({(14, 21, 14, 23): '-2', (14, 25, 14, 26): '2', (14, 28, 14, 31): '500'}, {}), '(-2, 2, 500)', True, 'import numpy as np\n'), ((29, 4, 29, 21), 'matplotlib.pyplot.ylim', 'plt.ylim', ({(29, 13, 29, 20): '(-1, 4)'}, {}), '((-1, 4))', True, 'import matplotlib.pyplot as plt\n'), ((33, 4, 33, 14), 'matplotlib.pyplot.show', 'plt.show', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((17, 33, 17, 49), 'numpy.ones_like', 'np.ones_like', ({(17, 46, 17, 48): 'xs'}, {}), '(xs)', True, 'import numpy as np\n'), ((17, 51, 17, 68), 'numpy.zeros_like', 'np.zeros_like', ({(17, 65, 17, 67): 'xs'}, {}), '(xs)', True, 'import numpy as np\n'), ((24, 27, 24, 44), 'numpy.zeros_like', 'np.zeros_like', ({(24, 41, 24, 43): 'xs'}, {}), '(xs)', True, 'import numpy as np\n')]
K-Fitzpatrick/crop_planner
utils/watch-less.py
2605c0886fd3b4681c2ea3ac5e88e1d8555178f5
#!/usr/bin/env python3 ################################ # Development tool # Auto-compiles style.less to style.css # # Requires lessc and less clean css to be installed: # npm install -g less # npm install -g less-plugin-clean-css ################################ import os, time from os import path from math import floor from _helper import * # Main application class Main: style_less = "style.less" style_css = "style.css" def __init__(self): clear() os.chdir("../") header("Watching style.less for changes\nctrl+c to exit") print() while True: if not os.path.exists(self.style_less): print(self.style_less + " does not exist. Exiting.") return if not os.path.exists(self.style_css): self.compile() elif path.getmtime(self.style_less) > path.getmtime(self.style_css): self.compile() time.sleep(.2) def compile(self): start = time.time() os.system("lessc " + self.style_less + " " + self.style_css + " --clean-css") touch(self.style_css, path.getmtime(self.style_less)) print("Recompiled [" + str(floor((time.time() - start) * 100)) + " ms]") print() # Run application if __name__ == "__main__": try: app = Main() except KeyboardInterrupt: print("Exiting")
[((24, 2, 24, 17), 'os.chdir', 'os.chdir', ({(24, 11, 24, 16): '"""../"""'}, {}), "('../')", False, 'import os, time\n'), ((41, 10, 41, 21), 'time.time', 'time.time', ({}, {}), '()', False, 'import os, time\n'), ((42, 2, 42, 79), 'os.system', 'os.system', ({(42, 12, 42, 78): "('lessc ' + self.style_less + ' ' + self.style_css + ' --clean-css')"}, {}), "('lessc ' + self.style_less + ' ' + self.style_css + ' --clean-css')", False, 'import os, time\n'), ((38, 3, 38, 17), 'time.sleep', 'time.sleep', ({(38, 14, 38, 16): '(0.2)'}, {}), '(0.2)', False, 'import os, time\n'), ((43, 24, 43, 54), 'os.path.getmtime', 'path.getmtime', ({(43, 38, 43, 53): 'self.style_less'}, {}), '(self.style_less)', False, 'from os import path\n'), ((29, 10, 29, 41), 'os.path.exists', 'os.path.exists', ({(29, 25, 29, 40): 'self.style_less'}, {}), '(self.style_less)', False, 'import os, time\n'), ((33, 10, 33, 40), 'os.path.exists', 'os.path.exists', ({(33, 25, 33, 39): 'self.style_css'}, {}), '(self.style_css)', False, 'import os, time\n'), ((35, 8, 35, 38), 'os.path.getmtime', 'path.getmtime', ({(35, 22, 35, 37): 'self.style_less'}, {}), '(self.style_less)', False, 'from os import path\n'), ((35, 41, 35, 70), 'os.path.getmtime', 'path.getmtime', ({(35, 55, 35, 69): 'self.style_css'}, {}), '(self.style_css)', False, 'from os import path\n'), ((44, 36, 44, 47), 'time.time', 'time.time', ({}, {}), '()', False, 'import os, time\n')]
instituciones-abiertas/django-admin-export-action
testapp/app/app/tests/test_export_action.py
bb089180e418915e1bba31927554537249fbec78
# -- encoding: UTF-8 -- import json import uuid from admin_export_action import report from admin_export_action.admin import export_selected_objects from admin_export_action.config import default_config, get_config from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase, RequestFactory from django.urls import reverse from django.utils.http import urlencode from news.models import Attachment, Category, News, NewsTag, Video from news.admin import NewsAdmin class FakeDict(object): def __getitem__(self, key): return object() class WS(object): def __init__(self): self.rows = [] self.cells = [] self.column_dimensions = FakeDict() def cell(self, row, column): pass def append(self, row): self.rows.append(row) class FakeQueryset(object): def __init__(self, num): self.num = num self.model = News def values_list(self, field, flat=True): return [i for i in range(1, self.num)] class AdminExportActionTest(TestCase): fixtures = ["tests.json"] def test_config(self): self.assertEqual(default_config.get('ENABLE_SITEWIDE'), True) self.assertEqual(get_config('ENABLE_SITEWIDE'), False) with self.settings(ADMIN_EXPORT_ACTION=None): self.assertEqual(get_config('ENABLE_SITEWIDE'), True) def test_export_selected_objects_session(self): factory = RequestFactory() request = factory.get('/news/admin/') request.session = {} modeladmin = NewsAdmin(model=News, admin_site=AdminSite()) qs = FakeQueryset(2000) self.assertEqual(len(request.session), 0) export_selected_objects(modeladmin, request, qs) self.assertEqual(len(request.session), 1) els = list(request.session.items()) self.assertEqual(els[0][1], qs.values_list('id')) def test_get_field_verbose_name(self): res = report.get_field_verbose_name(News.objects, 'tags__name') assert res == 'all tags verbose name' res = report.get_field_verbose_name(News.objects, 'share') assert res == 'share' def test_list_to_method_response_should_return_200_and_correct_values( self): admin = User.objects.get(pk=1) data, messages = report.report_to_list(News.objects.all(), ['id', 'title', 'status'], admin) method = getattr(report, 'list_to_{}_response'.format('html')) res = method(data) assert res.status_code == 200 method = getattr(report, 'list_to_{}_response'.format('csv')) res = method(data) assert res.status_code == 200 assert res.content == b'1,Lucio Dalla,published\r\n2,La mano de Dios,draft\r\n' method = getattr(report, 'list_to_{}_response'.format('xlsx')) res = method(data) assert res.status_code == 200 method = getattr(report, 'list_to_{}_response'.format('json')) res = method(data, header=['id', 'title', 'status']) d = json.loads(res.content) assert d[0]['id'] == 1 assert d[0]['title'] == "Lucio Dalla" assert d[0]['status'] == 'published' assert d[1]['id'] == 2 assert d[1]['title'] == "La mano de Dios" assert d[1]['status'] == 'draft' assert res.status_code == 200 data, messages = report.report_to_list(News.objects.all(), ['id', 'title', 'status'], admin, raw_choices=True) method = getattr(report, 'list_to_{}_response'.format('json')) res = method(data, header=['id', 'title', 'status']) d = json.loads(res.content) assert d[0]['id'] == 1 assert d[0]['title'] == "Lucio Dalla" assert d[0]['status'] == 2 assert d[1]['id'] == 2 assert d[1]['title'] == "La mano de Dios" assert d[1]['status'] == 1 assert res.status_code == 200 def test_list_to_csv_response_should_have_expected_content(self): admin = User.objects.get(pk=1) data, messages = report.report_to_list(News.objects.all(), ['id', 'title'], admin) method = getattr(report, 'list_to_{}_response'.format('csv')) res = method(data) assert res.status_code == 200 assert res.content == b'1,Lucio Dalla\r\n2,La mano de Dios\r\n' def test_list_to_json_response_should_have_expected_content(self): admin = User.objects.get(pk=1) data, messages = report.report_to_list(News.objects.all(), ['id', 'title'], admin) method = getattr(report, 'list_to_{}_response'.format('json')) res = method(data, header=['id', 'title']) d = json.loads(res.content) assert d[0]['id'] == 1 assert d[0]['title'] == "Lucio Dalla" assert d[1]['id'] == 2 assert d[1]['title'] == "La mano de Dios" assert res.status_code == 200 def test_admin_export_post_should_return_200(self): for output_format in ['html', 'csv', 'xslx', 'json']: params = { 'ct': ContentType.objects.get_for_model(News).pk, 'ids': ','.join( repr(pk) for pk in News.objects.values_list('pk', flat=True)) } data = { "title": "on", "__format": output_format, } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') response = self.client.post(url, data=data) assert response.status_code == 200 def test_admin_export_get_should_return_200(self): params = { 'ct': ContentType.objects.get_for_model(News).pk, 'ids': ','.join( repr(pk) for pk in News.objects.values_list('pk', flat=True)) } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') response = self.client.get(url) assert response.status_code == 200 def test_admin_export_with_related_get_should_return_200(self): params = { 'related': True, 'model_ct': ContentType.objects.get_for_model(News).pk, 'field': 'category', 'path': 'category.name', } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') response = self.client.get(url) assert response.status_code == 200 def test_admin_export_with_related_of_indirect_field_get_should_return_200( self): params = { 'related': True, 'model_ct': ContentType.objects.get_for_model(News).pk, 'field': 'newstag', 'path': 'newstag.id', } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') response = self.client.get(url) assert response.status_code == 200 def test_admin_export_with_unregistered_model_should_raise_ValueError( self): params = { 'ct': ContentType.objects.get_for_model(NewsTag).pk, 'ids': ','.join( repr(pk) for pk in NewsTag.objects.values_list('pk', flat=True)) } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') try: self.client.get(url) self.fail() except ValueError: pass def test_admin_action_should_redirect_to_export_view(self): objects = News.objects.all() ids = [repr(obj.pk) for obj in objects] data = { "action": "export_selected_objects", "_selected_action": ids, } url = reverse('admin:news_news_changelist') self.client.login(username='admin', password='admin') response = self.client.post(url, data=data) expected_url = "{}?ct={ct}&ids={ids}".format( reverse('admin_export_action:export'), ct=ContentType.objects.get_for_model(News).pk, ids=','.join(reversed(ids))) assert response.status_code == 302 assert response.url.endswith(expected_url) def test_export_with_related_should_return_200(self): for output_format in ['html', 'csv', 'xslx', 'json']: news = News.objects.all() params = { 'ct': ContentType.objects.get_for_model(News).pk, 'ids': ','.join( repr(pk) for pk in News.objects.values_list('pk', flat=True)) } data = { 'id': 'on', 'title': 'on', 'status': 'on', 'category__name': 'on', 'tags__name': 'on', 'newstag__created_on': 'on', "__format": output_format, } url = "{}?{}".format(reverse('admin_export_action:export'), urlencode(params)) self.client.login(username='admin', password='admin') response = self.client.post(url, data=data) assert response.status_code == 200 assert response.content def test_build_sheet_convert_function(self): data = [ ['1', 5, 'convert', 9, {"foo": "bar"}, [1, 2], uuid.UUID("12345678123456781234567812345678")], ] ws = WS() report.build_sheet(data, ws, sheet_name='report', header=None, widths=None) self.assertEqual(ws.rows, [['1', 5, 'converted', 9, "{'foo': 'bar'}", '[1, 2]', '12345678-1234-5678-1234-567812345678']])
[((58, 18, 58, 34), 'django.test.RequestFactory', 'RequestFactory', ({}, {}), '()', False, 'from django.test import TestCase, RequestFactory\n'), ((65, 8, 65, 56), 'admin_export_action.admin.export_selected_objects', 'export_selected_objects', ({(65, 32, 65, 42): 'modeladmin', (65, 44, 65, 51): 'request', (65, 53, 65, 55): 'qs'}, {}), '(modeladmin, request, qs)', False, 'from admin_export_action.admin import export_selected_objects\n'), ((71, 14, 71, 71), 'admin_export_action.report.get_field_verbose_name', 'report.get_field_verbose_name', ({(71, 44, 71, 56): 'News.objects', (71, 58, 71, 70): '"""tags__name"""'}, {}), "(News.objects, 'tags__name')", False, 'from admin_export_action import report\n'), ((73, 14, 73, 66), 'admin_export_action.report.get_field_verbose_name', 'report.get_field_verbose_name', ({(73, 44, 73, 56): 'News.objects', (73, 58, 73, 65): '"""share"""'}, {}), "(News.objects, 'share')", False, 'from admin_export_action import report\n'), ((78, 16, 78, 38), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((98, 12, 98, 35), 'json.loads', 'json.loads', ({(98, 23, 98, 34): 'res.content'}, {}), '(res.content)', False, 'import json\n'), ((114, 12, 114, 35), 'json.loads', 'json.loads', ({(114, 23, 114, 34): 'res.content'}, {}), '(res.content)', False, 'import json\n'), ((124, 16, 124, 38), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((135, 16, 135, 38), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((141, 12, 141, 35), 'json.loads', 'json.loads', ({(141, 23, 141, 34): 'res.content'}, {}), '(res.content)', False, 'import json\n'), ((231, 18, 231, 36), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((238, 14, 238, 51), 'django.urls.reverse', 'reverse', ({(238, 22, 238, 50): '"""admin:news_news_changelist"""'}, {}), "('admin:news_news_changelist')", False, 'from django.urls import reverse\n'), ((284, 8, 284, 83), 'admin_export_action.report.build_sheet', 'report.build_sheet', (), '', False, 'from admin_export_action import report\n'), ((51, 25, 51, 62), 'admin_export_action.config.default_config.get', 'default_config.get', ({(51, 44, 51, 61): '"""ENABLE_SITEWIDE"""'}, {}), "('ENABLE_SITEWIDE')", False, 'from admin_export_action.config import default_config, get_config\n'), ((52, 25, 52, 54), 'admin_export_action.config.get_config', 'get_config', ({(52, 36, 52, 53): '"""ENABLE_SITEWIDE"""'}, {}), "('ENABLE_SITEWIDE')", False, 'from admin_export_action.config import default_config, get_config\n'), ((79, 47, 79, 65), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((107, 47, 107, 65), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((125, 47, 125, 65), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((136, 47, 136, 65), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((176, 29, 176, 66), 'django.urls.reverse', 'reverse', ({(176, 37, 176, 65): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((177, 29, 177, 46), 'django.utils.http.urlencode', 'urlencode', ({(177, 39, 177, 45): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((189, 29, 189, 66), 'django.urls.reverse', 'reverse', ({(189, 37, 189, 65): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((190, 29, 190, 46), 'django.utils.http.urlencode', 'urlencode', ({(190, 39, 190, 45): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((203, 29, 203, 66), 'django.urls.reverse', 'reverse', ({(203, 37, 203, 65): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((204, 29, 204, 46), 'django.utils.http.urlencode', 'urlencode', ({(204, 39, 204, 45): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((220, 29, 220, 66), 'django.urls.reverse', 'reverse', ({(220, 37, 220, 65): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((221, 29, 221, 46), 'django.utils.http.urlencode', 'urlencode', ({(221, 39, 221, 45): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((243, 12, 243, 49), 'django.urls.reverse', 'reverse', ({(243, 20, 243, 48): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((251, 19, 251, 37), 'news.models.News.objects.all', 'News.objects.all', ({}, {}), '()', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((55, 29, 55, 58), 'admin_export_action.config.get_config', 'get_config', ({(55, 40, 55, 57): '"""ENABLE_SITEWIDE"""'}, {}), "('ENABLE_SITEWIDE')", False, 'from admin_export_action.config import default_config, get_config\n'), ((61, 54, 61, 65), 'django.contrib.admin.sites.AdminSite', 'AdminSite', ({}, {}), '()', False, 'from django.contrib.admin.sites import AdminSite\n'), ((162, 33, 162, 70), 'django.urls.reverse', 'reverse', ({(162, 41, 162, 69): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((163, 33, 163, 50), 'django.utils.http.urlencode', 'urlencode', ({(163, 43, 163, 49): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((171, 12, 171, 51), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(171, 46, 171, 50): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((185, 24, 185, 63), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(185, 58, 185, 62): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((199, 24, 199, 63), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(199, 58, 199, 62): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((214, 12, 214, 54), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(214, 46, 214, 53): 'NewsTag'}, {}), '(NewsTag)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((270, 33, 270, 70), 'django.urls.reverse', 'reverse', ({(270, 41, 270, 69): '"""admin_export_action:export"""'}, {}), "('admin_export_action:export')", False, 'from django.urls import reverse\n'), ((271, 33, 271, 50), 'django.utils.http.urlencode', 'urlencode', ({(271, 43, 271, 49): 'params'}, {}), '(params)', False, 'from django.utils.http import urlencode\n'), ((279, 59, 279, 104), 'uuid.UUID', 'uuid.UUID', ({(279, 69, 279, 103): '"""12345678123456781234567812345678"""'}, {}), "('12345678123456781234567812345678')", False, 'import uuid\n'), ((152, 16, 152, 55), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(152, 50, 152, 54): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((244, 15, 244, 54), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(244, 49, 244, 53): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((255, 16, 255, 55), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', ({(255, 50, 255, 54): 'News'}, {}), '(News)', False, 'from django.contrib.contenttypes.models import ContentType\n'), ((174, 35, 174, 76), 'news.models.News.objects.values_list', 'News.objects.values_list', (), '', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((218, 26, 218, 70), 'news.models.NewsTag.objects.values_list', 'NewsTag.objects.values_list', (), '', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((156, 30, 156, 71), 'news.models.News.objects.values_list', 'News.objects.values_list', (), '', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n'), ((259, 30, 259, 71), 'news.models.News.objects.values_list', 'News.objects.values_list', (), '', False, 'from news.models import Attachment, Category, News, NewsTag, Video\n')]
martinogden/django-shapeshifter
shapeshifter/tests/conftest.py
dbcba74c0a6914af181c1e8f0ba23369d4c3c94b
from pytest_djangoapp import configure_djangoapp_plugin pytest_plugins = configure_djangoapp_plugin( extend_INSTALLED_APPS=[ 'django.contrib.sessions', 'django.contrib.messages', ], extend_MIDDLEWARE=[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] )
[((3, 17, 12, 1), 'pytest_djangoapp.configure_djangoapp_plugin', 'configure_djangoapp_plugin', (), '', False, 'from pytest_djangoapp import configure_djangoapp_plugin\n')]
seymayucer/FacialPhenotypes
face_attribute_verification.py
043f3ecf956cad53095d93f19383c4c94e033692
import argparse import numpy as np from sklearn.model_selection import StratifiedKFold import sklearn import cv2 import datetime import mxnet as mx from mxnet import ndarray as nd import pandas as pd from numpy import linalg as line import logging logging.basicConfig( format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p", level=logging.INFO ) class FaceVerification: def __init__(self, model=None, batch_size=32, data_dir=None): super().__init__() logging.info("Face Verification for RFW.") self.data_dir = data_dir self.image_size = 112 self.batch_size = batch_size self.model = model def load_model(self, model_dir=None): logging.info("Model Loading") ctx = mx.gpu(0) sym, arg_params, aux_params = mx.model.load_checkpoint(model_dir, 1) all_layers = sym.get_internals() sym = all_layers["fc1_output"] self.model = mx.mod.Module(symbol=sym, context=ctx, label_names=None) self.model.bind( data_shapes=[ ("data", (self.batch_size, 3, self.image_size, self.image_size)) ] ) self.model.set_params(arg_params, aux_params) return self.model def load_images(self, inp_csv_file): logging.info("Image Data Loading") issame_list, data_list = [], [] pairs = pd.read_csv(inp_csv_file) # data_list = list( # np.empty((2, pairs.shape[0] * 2, 3, self.image_size, self.image_size)) # ) for flip in [0, 1]: data = nd.empty((pairs.shape[0] * 2, 3, self.image_size, self.image_size)) data_list.append(data) j = 0 for i, row in pairs.iterrows(): if i % 1000 == 0: logging.info("processing {}".format(i)) issame_list.append(row.issame) path1 = "{}/{}/{}_{:04d}.jpg".format( self.data_dir, row.Class_ID_s1, row.Class_ID_s1.split("/")[1], int(row.img_id_s1), ) path2 = "{}/{}/{}_{:04d}.jpg".format( self.data_dir, row.Class_ID_s2, row.Class_ID_s2.split("/")[1], int(row.img_id_s2), ) im1 = cv2.imread(path1) im1 = cv2.cvtColor(im1, cv2.COLOR_BGR2RGB) im1 = np.transpose(im1, (2, 0, 1)) # 3*112*112, RGB im1 = mx.nd.array(im1) im2 = cv2.imread(path2) im2 = cv2.cvtColor(im2, cv2.COLOR_BGR2RGB) im2 = np.transpose(im2, (2, 0, 1)) # 3*112*112, RGB im2 = mx.nd.array(im2) for flip in [0, 1]: if flip == 1: im1 = mx.ndarray.flip(im1, 2) data_list[flip][j][:] = im1 for flip in [0, 1]: if flip == 1: im2 = mx.ndarray.flip(im2, 2) data_list[flip][j + 1][:] = im2 # data_list[flip][i][:] = img j = j + 2 # bins shape should be 2,12000,3,112,112 # data = np.asarray(data_list) self.issame = np.asarray(issame_list) self.data = data_list logging.info("Pairs are loaded, shape: 2x{}.".format(self.data[0].shape)) return self.data, self.issame, pairs.shape def clean_data(self): self.data = None self.issame = None def verify(self, model=None): data_list = self.data embeddings_list = [] time_consumed = 0 _label = nd.ones((self.batch_size,)) for i in range(len(data_list)): data = data_list[i] embeddings = None ba = 0 while ba < data.shape[0]: bb = min(ba + self.batch_size, data.shape[0]) count = bb - ba _data = nd.slice_axis(data, axis=0, begin=bb - self.batch_size, end=bb) time0 = datetime.datetime.now() db = mx.io.DataBatch(data=(_data,), label=(_label,)) self.model.forward(db, is_train=False) net_out = self.model.get_outputs() _embeddings = net_out[0].asnumpy() time_now = datetime.datetime.now() diff = time_now - time0 time_consumed += diff.total_seconds() if embeddings is None: embeddings = np.zeros((data.shape[0], _embeddings.shape[1])) embeddings[ba:bb, :] = _embeddings[(self.batch_size - count) :, :] ba = bb embeddings_list.append(embeddings) _xnorm = 0.0 _xnorm_cnt = 0 for embed in embeddings_list: for i in range(embed.shape[0]): _em = embed[i] _norm = np.linalg.norm(_em) _xnorm += _norm _xnorm_cnt += 1 _xnorm /= _xnorm_cnt acc1 = 0.0 std1 = 0.0 embeddings = embeddings_list[0] + embeddings_list[1] embeddings = sklearn.preprocessing.normalize(embeddings) print(embeddings.shape) print("infer time", time_consumed) tpr, fpr, accuracy, best_thresholds = self.evaluate( embeddings, self.issame, nrof_folds=10 ) acc2, std2 = np.mean(accuracy), np.std(accuracy) logging.info("Accuracy {}".format(acc2)) return tpr, fpr, acc2, std2 def evaluate(self, embeddings, actual_issame, nrof_folds=10): # Calculate evaluation metrics thresholds = np.arange(-1, 1, 0.001) embeddings1 = embeddings[0::2] embeddings2 = embeddings[1::2] tpr, fpr, accuracy, best_thresholds = self.calculate_roc( thresholds, embeddings1, embeddings2, np.asarray(actual_issame), nrof_folds=nrof_folds, ) return tpr, fpr, accuracy, best_thresholds def calculate_roc( self, thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10 ): assert embeddings1.shape[1] == embeddings2.shape[1] nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) nrof_thresholds = len(thresholds) # k_fold = LFold(n_splits=nrof_folds, shuffle=False) k_fold = StratifiedKFold(n_splits=nrof_folds, shuffle=False) tprs = np.zeros((nrof_folds, nrof_thresholds)) fprs = np.zeros((nrof_folds, nrof_thresholds)) tnrs = np.zeros((nrof_folds, nrof_thresholds)) fnrs = np.zeros((nrof_folds, nrof_thresholds)) f1s = np.zeros((nrof_folds)) accuracy = np.zeros((nrof_folds)) indices = np.arange(nrof_pairs) veclist = np.concatenate((embeddings1, embeddings2), axis=0) meana = np.mean(veclist, axis=0) embeddings1 -= meana embeddings2 -= meana dist = np.sum(embeddings1 * embeddings2, axis=1) dist = dist / line.norm(embeddings1, axis=1) / line.norm(embeddings2, axis=1) for fold_idx, (train_set, test_set) in enumerate( k_fold.split(indices, actual_issame) ): # print(train_set.shape, actual_issame[train_set].sum()) # print(test_set.shape, actual_issame[test_set].sum()) # Find the best threshold for the fold acc_train = np.zeros((nrof_thresholds)) for threshold_idx, threshold in enumerate(thresholds): _, _, _, _, acc_train[threshold_idx], f1 = self.calculate_accuracy( threshold, dist[train_set], actual_issame[train_set] ) best_threshold_index = np.argmax(acc_train) # print('threshold', thresholds[best_threshold_index]) for threshold_idx, threshold in enumerate(thresholds): ( tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], tnrs[fold_idx, threshold_idx], fnrs[fold_idx, threshold_idx], _, _, ) = self.calculate_accuracy( threshold, dist[test_set], actual_issame[test_set] ) _, _, _, _, accuracy[fold_idx], f1s[fold_idx] = self.calculate_accuracy( thresholds[best_threshold_index], dist[test_set], actual_issame[test_set], ) tpr = np.mean(tprs, 0)[best_threshold_index] fpr = np.mean(fprs, 0)[best_threshold_index] # tnr = np.mean(tnrs, 0)[best_threshold_index] # fnr = np.mean(fnrs, 0)[best_threshold_index] return tpr, fpr, accuracy, thresholds[best_threshold_index] def calculate_accuracy(self, threshold, dist, actual_issame): predict_issame = np.less(dist, threshold) actual_issame = np.less(actual_issame, 0.5) tn, fp, fn, tp = sklearn.metrics.confusion_matrix( actual_issame, predict_issame ).ravel() tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn) fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn) tnr = 0 if (fp + tn == 0) else float(tn) / float(fp + tn) fnr = 0 if (fn + tp == 0) else float(fn) / float(fn + tp) acc = float(tp + tn) / dist.size f1 = sklearn.metrics.f1_score(predict_issame, actual_issame) return tpr, fpr, tnr, fnr, acc, f1 if __name__ == "__main__": parser = argparse.ArgumentParser(description="Face Verification for RFW") parser.add_argument( "--data_dir", type=str, default="RFW/test/aligned_data", help="dataset root" ) parser.add_argument( "--pair_file", type=str, default="./AttributePairs/eye_narrow_pairs_6000_selected.csv", help="pair file to test", ) parser.add_argument( "--model_dir", type=str, default="/model/", help="pre-trained model directory" ) parser.add_argument("--batch_size", type=int, default="32", help="batch_size") args = parser.parse_args() validation = FaceVerification( batch_size=args.batch_size, model=None, data_dir=args.data_dir ) validation.load_model(model_dir=args.model_dir) _, _, _shape = validation.load_images(args.pair_file) tpr, fpr, acc, std = validation.verify() logging.info( "Testing Accuracy {} for {} in shape {}".format(acc, args.pair_file, _shape[0]) )
[((13, 0, 15, 1), 'logging.basicConfig', 'logging.basicConfig', (), '', False, 'import logging\n'), ((266, 13, 266, 77), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (), '', False, 'import argparse\n'), ((21, 8, 21, 50), 'logging.info', 'logging.info', ({(21, 21, 21, 49): '"""Face Verification for RFW."""'}, {}), "('Face Verification for RFW.')", False, 'import logging\n'), ((28, 8, 28, 37), 'logging.info', 'logging.info', ({(28, 21, 28, 36): '"""Model Loading"""'}, {}), "('Model Loading')", False, 'import logging\n'), ((29, 14, 29, 23), 'mxnet.gpu', 'mx.gpu', ({(29, 21, 29, 22): '0'}, {}), '(0)', True, 'import mxnet as mx\n'), ((30, 38, 30, 76), 'mxnet.model.load_checkpoint', 'mx.model.load_checkpoint', ({(30, 63, 30, 72): 'model_dir', (30, 74, 30, 75): '1'}, {}), '(model_dir, 1)', True, 'import mxnet as mx\n'), ((33, 21, 33, 77), 'mxnet.mod.Module', 'mx.mod.Module', (), '', True, 'import mxnet as mx\n'), ((43, 8, 43, 42), 'logging.info', 'logging.info', ({(43, 21, 43, 41): '"""Image Data Loading"""'}, {}), "('Image Data Loading')", False, 'import logging\n'), ((45, 16, 45, 41), 'pandas.read_csv', 'pd.read_csv', ({(45, 28, 45, 40): 'inp_csv_file'}, {}), '(inp_csv_file)', True, 'import pandas as pd\n'), ((98, 22, 98, 45), 'numpy.asarray', 'np.asarray', ({(98, 33, 98, 44): 'issame_list'}, {}), '(issame_list)', True, 'import numpy as np\n'), ((113, 17, 113, 44), 'mxnet.ndarray.ones', 'nd.ones', ({(113, 25, 113, 43): '(self.batch_size,)'}, {}), '((self.batch_size,))', True, 'from mxnet import ndarray as nd\n'), ((151, 21, 151, 64), 'sklearn.preprocessing.normalize', 'sklearn.preprocessing.normalize', ({(151, 53, 151, 63): 'embeddings'}, {}), '(embeddings)', False, 'import sklearn\n'), ((165, 21, 165, 44), 'numpy.arange', 'np.arange', ({(165, 31, 165, 33): '-1', (165, 35, 165, 36): '1', (165, 38, 165, 43): '0.001'}, {}), '(-1, 1, 0.001)', True, 'import numpy as np\n'), ((186, 17, 186, 68), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', (), '', False, 'from sklearn.model_selection import StratifiedKFold\n'), ((188, 15, 188, 54), 'numpy.zeros', 'np.zeros', ({(188, 24, 188, 53): '(nrof_folds, nrof_thresholds)'}, {}), '((nrof_folds, nrof_thresholds))', True, 'import numpy as np\n'), ((189, 15, 189, 54), 'numpy.zeros', 'np.zeros', ({(189, 24, 189, 53): '(nrof_folds, nrof_thresholds)'}, {}), '((nrof_folds, nrof_thresholds))', True, 'import numpy as np\n'), ((191, 15, 191, 54), 'numpy.zeros', 'np.zeros', ({(191, 24, 191, 53): '(nrof_folds, nrof_thresholds)'}, {}), '((nrof_folds, nrof_thresholds))', True, 'import numpy as np\n'), ((192, 15, 192, 54), 'numpy.zeros', 'np.zeros', ({(192, 24, 192, 53): '(nrof_folds, nrof_thresholds)'}, {}), '((nrof_folds, nrof_thresholds))', True, 'import numpy as np\n'), ((194, 14, 194, 36), 'numpy.zeros', 'np.zeros', ({(194, 24, 194, 34): 'nrof_folds'}, {}), '(nrof_folds)', True, 'import numpy as np\n'), ((196, 19, 196, 41), 'numpy.zeros', 'np.zeros', ({(196, 29, 196, 39): 'nrof_folds'}, {}), '(nrof_folds)', True, 'import numpy as np\n'), ((197, 18, 197, 39), 'numpy.arange', 'np.arange', ({(197, 28, 197, 38): 'nrof_pairs'}, {}), '(nrof_pairs)', True, 'import numpy as np\n'), ((199, 18, 199, 68), 'numpy.concatenate', 'np.concatenate', (), '', True, 'import numpy as np\n'), ((200, 16, 200, 40), 'numpy.mean', 'np.mean', (), '', True, 'import numpy as np\n'), ((203, 15, 203, 56), 'numpy.sum', 'np.sum', (), '', True, 'import numpy as np\n'), ((246, 25, 246, 49), 'numpy.less', 'np.less', ({(246, 33, 246, 37): 'dist', (246, 39, 246, 48): 'threshold'}, {}), '(dist, threshold)', True, 'import numpy as np\n'), ((247, 24, 247, 51), 'numpy.less', 'np.less', ({(247, 32, 247, 45): 'actual_issame', (247, 47, 247, 50): '0.5'}, {}), '(actual_issame, 0.5)', True, 'import numpy as np\n'), ((260, 13, 260, 68), 'sklearn.metrics.f1_score', 'sklearn.metrics.f1_score', ({(260, 38, 260, 52): 'predict_issame', (260, 54, 260, 67): 'actual_issame'}, {}), '(predict_issame, actual_issame)', False, 'import sklearn\n'), ((50, 19, 50, 86), 'mxnet.ndarray.empty', 'nd.empty', ({(50, 28, 50, 85): '(pairs.shape[0] * 2, 3, self.image_size, self.image_size)'}, {}), '((pairs.shape[0] * 2, 3, self.image_size, self.image_size))', True, 'from mxnet import ndarray as nd\n'), ((72, 18, 72, 35), 'cv2.imread', 'cv2.imread', ({(72, 29, 72, 34): 'path1'}, {}), '(path1)', False, 'import cv2\n'), ((73, 18, 73, 54), 'cv2.cvtColor', 'cv2.cvtColor', ({(73, 31, 73, 34): 'im1', (73, 36, 73, 53): 'cv2.COLOR_BGR2RGB'}, {}), '(im1, cv2.COLOR_BGR2RGB)', False, 'import cv2\n'), ((74, 18, 74, 46), 'numpy.transpose', 'np.transpose', ({(74, 31, 74, 34): 'im1', (74, 36, 74, 45): '(2, 0, 1)'}, {}), '(im1, (2, 0, 1))', True, 'import numpy as np\n'), ((75, 18, 75, 34), 'mxnet.nd.array', 'mx.nd.array', ({(75, 30, 75, 33): 'im1'}, {}), '(im1)', True, 'import mxnet as mx\n'), ((77, 18, 77, 35), 'cv2.imread', 'cv2.imread', ({(77, 29, 77, 34): 'path2'}, {}), '(path2)', False, 'import cv2\n'), ((78, 18, 78, 54), 'cv2.cvtColor', 'cv2.cvtColor', ({(78, 31, 78, 34): 'im2', (78, 36, 78, 53): 'cv2.COLOR_BGR2RGB'}, {}), '(im2, cv2.COLOR_BGR2RGB)', False, 'import cv2\n'), ((79, 18, 79, 46), 'numpy.transpose', 'np.transpose', ({(79, 31, 79, 34): 'im2', (79, 36, 79, 45): '(2, 0, 1)'}, {}), '(im2, (2, 0, 1))', True, 'import numpy as np\n'), ((80, 18, 80, 34), 'mxnet.nd.array', 'mx.nd.array', ({(80, 30, 80, 33): 'im2'}, {}), '(im2)', True, 'import mxnet as mx\n'), ((159, 21, 159, 38), 'numpy.mean', 'np.mean', ({(159, 29, 159, 37): 'accuracy'}, {}), '(accuracy)', True, 'import numpy as np\n'), ((159, 40, 159, 56), 'numpy.std', 'np.std', ({(159, 47, 159, 55): 'accuracy'}, {}), '(accuracy)', True, 'import numpy as np\n'), ((172, 12, 172, 37), 'numpy.asarray', 'np.asarray', ({(172, 23, 172, 36): 'actual_issame'}, {}), '(actual_issame)', True, 'import numpy as np\n'), ((204, 55, 204, 85), 'numpy.linalg.norm', 'line.norm', (), '', True, 'from numpy import linalg as line\n'), ((213, 24, 213, 51), 'numpy.zeros', 'np.zeros', ({(213, 34, 213, 49): 'nrof_thresholds'}, {}), '(nrof_thresholds)', True, 'import numpy as np\n'), ((218, 35, 218, 55), 'numpy.argmax', 'np.argmax', ({(218, 45, 218, 54): 'acc_train'}, {}), '(acc_train)', True, 'import numpy as np\n'), ((237, 14, 237, 30), 'numpy.mean', 'np.mean', ({(237, 22, 237, 26): 'tprs', (237, 28, 237, 29): '(0)'}, {}), '(tprs, 0)', True, 'import numpy as np\n'), ((238, 14, 238, 30), 'numpy.mean', 'np.mean', ({(238, 22, 238, 26): 'fprs', (238, 28, 238, 29): '(0)'}, {}), '(fprs, 0)', True, 'import numpy as np\n'), ((121, 24, 121, 87), 'mxnet.ndarray.slice_axis', 'nd.slice_axis', (), '', True, 'from mxnet import ndarray as nd\n'), ((122, 24, 122, 47), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((124, 21, 124, 68), 'mxnet.io.DataBatch', 'mx.io.DataBatch', (), '', True, 'import mxnet as mx\n'), ((129, 27, 129, 50), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((143, 24, 143, 43), 'numpy.linalg.norm', 'np.linalg.norm', ({(143, 39, 143, 42): '_em'}, {}), '(_em)', True, 'import numpy as np\n'), ((204, 22, 204, 52), 'numpy.linalg.norm', 'line.norm', (), '', True, 'from numpy import linalg as line\n'), ((249, 25, 251, 9), 'sklearn.metrics.confusion_matrix', 'sklearn.metrics.confusion_matrix', ({(250, 12, 250, 25): 'actual_issame', (250, 27, 250, 41): 'predict_issame'}, {}), '(actual_issame, predict_issame)', False, 'import sklearn\n'), ((85, 26, 85, 49), 'mxnet.ndarray.flip', 'mx.ndarray.flip', ({(85, 42, 85, 45): 'im1', (85, 47, 85, 48): '2'}, {}), '(im1, 2)', True, 'import mxnet as mx\n'), ((90, 26, 90, 49), 'mxnet.ndarray.flip', 'mx.ndarray.flip', ({(90, 42, 90, 45): 'im2', (90, 47, 90, 48): '2'}, {}), '(im2, 2)', True, 'import mxnet as mx\n'), ((133, 33, 133, 80), 'numpy.zeros', 'np.zeros', ({(133, 42, 133, 79): '(data.shape[0], _embeddings.shape[1])'}, {}), '((data.shape[0], _embeddings.shape[1]))', True, 'import numpy as np\n')]
mornfall/nixpkgs
pkgs/applications/virtualization/virt-manager/custom_runner.py
0eb6f056b9ce3e32dbc3297f298472aef19f8c73
#!/usr/bin/python -t # this script was written to use /etc/nixos/nixpkgs/pkgs/development/python-modules/generic/wrap.sh # which already automates python executable wrapping by extending the PATH/pythonPath # from http://docs.python.org/library/subprocess.html # Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details. from subprocess import Popen, PIPE, STDOUT cmd = 'PYTHON_EXECUTABLE_PATH -t THE_CUSTOM_PATH/share/virt-manager/THE_CUSTOM_PROGRAM.py' p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output = p.stdout.read() print output
[]
Pix-00/jsonform
jsonform/fields.py
d62543474d96b258606ec38dd427693232daeda3
import base64 import datetime from abc import ABC, abstractmethod from .conditions import AnyValue from .errors import FieldError, FormError __all__ = [ 'Field', 'StringField', 'IntegerField', 'FloatField', 'BooleanField', 'DateTimeField', 'DateField', 'TimeField', 'ListField','SetField', 'EnumField', 'BytesField' ] class Field(ABC): _default = None def __new__(cls, *args, **kwargs): if 'init' in kwargs: kwargs.pop('init') return super().__new__(cls) return UnboundField(cls, *args, **kwargs) def __init__(self, condition=AnyValue(), optional: bool = False, default=None, init=False): self.condition = condition self.optional = optional self.default = default or self._default self._data = None self.is_empty = False @property def data(self): return self._data def mark_empty(self): if not self.optional: raise FieldError('cannot be blank') self.is_empty = True if callable(self.default): self._data = self.default() else: self._data = self.default @abstractmethod def process_data(self, value): self.condition.check(self) class UnboundField: def __init__(self, field_cls, *args, **kwargs): self.field_cls = field_cls self.args = args self.kwargs = kwargs self.kwargs['init'] = True def bind(self): return self.field_cls(*self.args, **self.kwargs) class StringField(Field): _default = '' def process_data(self, value): if not isinstance(value, str): raise FieldError('invalid string') self._data = value super().process_data(value) class IntegerField(Field): _default = 0 def process_data(self, value): if not isinstance(value, int): raise FieldError('invalid integer') self._data = value super().process_data(value) class FloatField(Field): _default = 0.0 def process_data(self, value): if not isinstance(value, float): raise FieldError('invalid float') self._data = value super().process_data(value) class BooleanField(Field): def process_data(self, value): if not isinstance(value, bool): raise FieldError('invalid boolean') self._data = value super().process_data(value) class DateTimeField(Field): def __init__(self, pattern='%Y-%m-%dT%H:%M:%S', **kwargs): super().__init__(**kwargs) self.pattern = pattern def process_data(self, value): try: self._data = datetime.datetime.strptime(value, self.pattern) except ValueError: raise FieldError('invalid datetime') super().process_data(value) class DateField(DateTimeField): def __init__(self, pattern='%Y-%m-%d', **kwargs): super().__init__(pattern, **kwargs) def process_data(self, value): try: self._data = datetime.datetime.strptime(value, self.pattern).date() except ValueError: raise FieldError('invalid date') super().process_data(value) class TimeField(DateTimeField): def __init__(self, pattern='%H:%M:%S', **kwargs): super().__init__(pattern, **kwargs) def process_jsondata(self, value): try: self._data = datetime.datetime.strptime(value, self.pattern).time() except ValueError: raise FieldError('invalid time') super().process_data(value) class EnumField(Field): def __init__(self, enum_class, **kwargs): super().__init__(**kwargs) self.enum_class = enum_class def process_data(self, value): try: enum_obj = self.enum_class[value] except KeyError: raise FieldError('invalid enum') self._data = enum_obj super().process_data(value) class BytesField(Field): def __init__(self, length, **kwargs): super().__init__(**kwargs) self.length = length def process_data(self, value): try: self.data = base64.decodebytes(value) except (ValueError, TypeError): raise FieldError('invalid base64 string') if len(self.data) != self.length: raise FieldError('invalid length') super().process_data(value) class ListField(Field): def __init__(self, field, default=list, **kwargs): self.field = field self.data_ = None super().__init__(default=default, **kwargs) @property def data(self): if not self.data_: self.data_ = [field.data for field in self._data] return self.data_ def process_data(self, value): if not isinstance(value, list): raise FieldError('invalid list') self._data = list() e = FieldError() for i, val in enumerate(value): field = self.field.bind() try: field.process_data(val) except FieldError as e_: e[i] = e_.error self._data.append(field) if e: raise e super().process_data(value) class SetField(Field): def __init__(self, field, default=set, **kwargs): self.field = field self.data_ = None super().__init__(default=default, **kwargs) @property def data(self): if not self.data_: self.data_ = {field.data for field in self._data} return self.data_ def process_data(self, value): if not isinstance(value, list): raise FieldError('invalid list') self._data = set() e = FieldError() for i, val in enumerate(set(value)): field = self.field.bind() try: field.process_data(val) except FieldError as e_: e[i] = e_.error self._data.add(field) if e: raise e super().process_data(value) class SubForm(Field): def __init__(self, form, **kwargs): self.form = form kwargs.pop('condition', None) super().__init__(**kwargs) def process_data(self, value): try: self.form.process(jsondata=value) except FormError as e_: e = FieldError() if e_.error: e['error'] = e_.error if e_.f_errors: e['f_errors'] = e_.f_errors raise e self._data = {name: self.form[name] for name in self.form.fields}
[((109, 25, 109, 72), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(109, 52, 109, 57): 'value', (109, 59, 109, 71): 'self.pattern'}, {}), '(value, self.pattern)', False, 'import datetime\n'), ((160, 24, 160, 49), 'base64.decodebytes', 'base64.decodebytes', ({(160, 43, 160, 48): 'value'}, {}), '(value)', False, 'import base64\n'), ((121, 25, 121, 72), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(121, 52, 121, 57): 'value', (121, 59, 121, 71): 'self.pattern'}, {}), '(value, self.pattern)', False, 'import datetime\n'), ((133, 25, 133, 72), 'datetime.datetime.strptime', 'datetime.datetime.strptime', ({(133, 52, 133, 57): 'value', (133, 59, 133, 71): 'self.pattern'}, {}), '(value, self.pattern)', False, 'import datetime\n')]
napari/napari-gui
napari/layers/_source.py
9beb1a0b797890718e1c4f372cbd6256747f9101
from __future__ import annotations from contextlib import contextmanager from contextvars import ContextVar from typing import Optional, Tuple from magicgui.widgets import FunctionGui from pydantic import BaseModel class Source(BaseModel): """An object to store the provenance of a layer. Parameters ---------- path: str, optional filpath/url associated with layer reader_plugin: str, optional name of reader plugin that loaded the file (if applicable) sample: Tuple[str, str], optional Tuple of (sample_plugin, sample_name), if layer was loaded via `viewer.open_sample`. widget: FunctionGui, optional magicgui widget, if the layer was added via a magicgui widget. """ path: Optional[str] = None reader_plugin: Optional[str] = None sample: Optional[Tuple[str, str]] = None widget: Optional[FunctionGui] = None class Config: arbitrary_types_allowed = True frozen = True def __deepcopy__(self, memo): """Custom deepcopy implementation. this prevents deep copy. `Source` doesn't really need to be copied (i.e. if we deepcopy a layer, it essentially has the same `Source`). Moreover, deepcopying a widget is challenging, and maybe odd anyway. """ return self # layer source context management _LAYER_SOURCE: ContextVar[dict] = ContextVar('_LAYER_SOURCE', default={}) @contextmanager def layer_source(**source_kwargs): """Creates context in which all layers will be given `source_kwargs`. The module-level variable `_LAYER_SOURCE` holds a set of key-value pairs that can be used to create a new `Source` object. Any routine in napari that may result in the creation of a new layer (such as opening a file, using a particular plugin, or calling a magicgui widget) can use this context manager to declare that any layers created within the context result from a specific source. (This applies even if the layer isn't "directly" created in the context, but perhaps in some sub-function within the context). `Layer.__init__` will call :func:`current_source`, to query the current state of the `_LAYER_SOURCE` variable. Contexts may be stacked, meaning a given layer.source can reflect the actions of multiple events (for instance, an `open_sample` call that in turn resulted in a `reader_plugin` opening a file). However, the "deepest" context will "win" in the case where multiple calls to `layer_source` provide conflicting values. Parameters ---------- **source_kwargs keys/values should be valid parameters for :class:`Source`. Examples -------- >>> with layer_source(path='file.ext', reader_plugin='plugin'): # doctest: +SKIP ... points = some_function_that_creates_points() ... >>> assert points.source == Source(path='file.ext', reader_plugin='plugin') # doctest: +SKIP """ token = _LAYER_SOURCE.set({**_LAYER_SOURCE.get(), **source_kwargs}) try: yield finally: _LAYER_SOURCE.reset(token) def current_source(): """Get the current layer :class:`Source` (inferred from context). The main place this function is used is in :meth:`Layer.__init__`. """ return Source(**_LAYER_SOURCE.get())
[((48, 34, 48, 73), 'contextvars.ContextVar', 'ContextVar', (), '', False, 'from contextvars import ContextVar\n')]
vpalex999/project-mars
tests/unit/test_BaseDirection.py
6e21c5acfe6105a7b7c87a79770e7420bda46f26
import pytest import src.constants as cnst from src.directions import BaseDirection @pytest.fixture def base_direction(): return BaseDirection() def test_init_BaseDirection(base_direction): assert isinstance(base_direction, BaseDirection) def test_current_direction_is(base_direction): assert base_direction.current == cnst.NORTH @pytest.mark.parametrize(["turn_func", "expected_direction"], [ # turn_left (lambda f: f.turn_left(), cnst.WEST), (lambda f: f.turn_left().turn_left(), cnst.SOUTH), (lambda f: f.turn_left().turn_left().turn_left(), cnst.EAST), (lambda f: f.turn_left().turn_left().turn_left().turn_left(), cnst.NORTH), (lambda f: f.turn_left().turn_left().turn_left().turn_left().turn_left(), cnst.WEST), # turn_right() (lambda f: f.turn_right(), cnst.EAST), (lambda f: f.turn_right().turn_right(), cnst.SOUTH), (lambda f: f.turn_right().turn_right().turn_right(), cnst.WEST), (lambda f: f.turn_right().turn_right().turn_right().turn_right(), cnst.NORTH), (lambda f: f.turn_right().turn_right().turn_right().turn_right().turn_right(), cnst.EAST), # any combinations (lambda f: f.turn_left().turn_right(), cnst.NORTH), (lambda f: f.turn_left().turn_left().turn_right(), cnst.WEST), (lambda f: f.turn_left().turn_right().turn_left(), cnst.WEST), (lambda f: f.turn_left().turn_right().turn_left().turn_right().turn_right(), cnst.EAST), ] ) def test_turn_direction(base_direction, turn_func, expected_direction): turn_func(base_direction) assert base_direction.current == expected_direction
[((9, 11, 9, 26), 'src.directions.BaseDirection', 'BaseDirection', ({}, {}), '()', False, 'from src.directions import BaseDirection\n')]
Payal197bhadra/ComputerVision
OpenCV-Computer-Vision-Examples-with-Python-A-Complete-Guide-for-Dummies-master/Source Code/opencv_operations/draw-circles.py
d66b5037ece99b6189dd4306b2c9be67cffd14af
import numpy as np import cv2 #define a canvas of size 300x300 px, with 3 channels (R,G,B) and data type as 8 bit unsigned integer canvas = np.zeros((300,300,3), dtype ="uint8") #define color #draw a circle #arguments are canvas/image, midpoint, radius, color, thickness(optional) #display in cv2 window green = (0,255,0) cv2.circle(canvas,(100,100), 10, green) cv2.imshow("Single circle", canvas) cv2.waitKey(0) # draw concentric white circles # calculate the center point of canvas # generate circles using for loop # clearning the canvas canvas = np.zeros((300,300,3), dtype ="uint8") white = (255,255,255) (centerX, centerY) = (canvas.shape[1]//2, canvas.shape[0]//2) for r in range(0,175,25): cv2.circle(canvas, (centerX,centerY), r, white) cv2.imshow("concentric circles", canvas) cv2.waitKey(0) # generate random radius, center point, color # draw circles in for loop canvas = np.zeros((300,300,3), dtype ="uint8") for i in range(0, 25): radius = np.random.randint(5, high = 200) color = np.random.randint(0, high = 256, size = (3,)).tolist() pt = np.random.randint(0, high = 300, size = (2,)) cv2.circle(canvas, tuple(pt), radius, color, -1) cv2.imshow("Canvas", canvas) cv2.waitKey(0)
[((5, 9, 5, 46), 'numpy.zeros', 'np.zeros', (), '', True, 'import numpy as np\n'), ((12, 0, 12, 39), 'cv2.circle', 'cv2.circle', ({(12, 11, 12, 17): 'canvas', (12, 18, 12, 27): '(100, 100)', (12, 29, 12, 31): '(10)', (12, 33, 12, 38): 'green'}, {}), '(canvas, (100, 100), 10, green)', False, 'import cv2\n'), ((13, 0, 13, 35), 'cv2.imshow', 'cv2.imshow', ({(13, 11, 13, 26): '"""Single circle"""', (13, 28, 13, 34): 'canvas'}, {}), "('Single circle', canvas)", False, 'import cv2\n'), ((14, 0, 14, 14), 'cv2.waitKey', 'cv2.waitKey', ({(14, 12, 14, 13): '(0)'}, {}), '(0)', False, 'import cv2\n'), ((20, 9, 20, 46), 'numpy.zeros', 'np.zeros', (), '', True, 'import numpy as np\n'), ((27, 0, 27, 40), 'cv2.imshow', 'cv2.imshow', ({(27, 11, 27, 31): '"""concentric circles"""', (27, 33, 27, 39): 'canvas'}, {}), "('concentric circles', canvas)", False, 'import cv2\n'), ((28, 0, 28, 14), 'cv2.waitKey', 'cv2.waitKey', ({(28, 12, 28, 13): '(0)'}, {}), '(0)', False, 'import cv2\n'), ((33, 9, 33, 46), 'numpy.zeros', 'np.zeros', (), '', True, 'import numpy as np\n'), ((39, 0, 39, 28), 'cv2.imshow', 'cv2.imshow', ({(39, 11, 39, 19): '"""Canvas"""', (39, 21, 39, 27): 'canvas'}, {}), "('Canvas', canvas)", False, 'import cv2\n'), ((40, 0, 40, 14), 'cv2.waitKey', 'cv2.waitKey', ({(40, 12, 40, 13): '(0)'}, {}), '(0)', False, 'import cv2\n'), ((25, 4, 25, 51), 'cv2.circle', 'cv2.circle', ({(25, 15, 25, 21): 'canvas', (25, 23, 25, 40): '(centerX, centerY)', (25, 42, 25, 43): 'r', (25, 45, 25, 50): 'white'}, {}), '(canvas, (centerX, centerY), r, white)', False, 'import cv2\n'), ((35, 13, 35, 45), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((37, 9, 37, 54), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n'), ((36, 12, 36, 57), 'numpy.random.randint', 'np.random.randint', (), '', True, 'import numpy as np\n')]
cscutcher/tmux_cssh
tmux_cssh/main.py
bfbb7eb26d5f5864c0888fa8e614122401ed4f5f
# -*- coding: utf-8 -*- """ Main Script """ import logging import argh import sarge import tmuxp DEV_LOGGER = logging.getLogger(__name__) def get_current_session(server=None): ''' Seems to be no easy way to grab current attached session in tmuxp so this provides a simple alternative. ''' server = tmuxp.Server() if server is None else server session_name = sarge.get_stdout('tmux display-message -p "#S"').strip() session = server.findWhere({"session_name": session_name}) return session @argh.arg('commands', nargs='+') def clustered_window(commands): ''' Creates new clustered window on session with commands. A clustered session is one where you operate on all panes/commands at once using the synchronized-panes option. :param commands: Sequence of commands. Each one will run in its own pane. ''' session = get_current_session() window = session.new_window() # Create additional panes while len(window.panes) < len(commands): window.panes[-1].split_window() for pane, command in zip(window.panes, commands): pane.send_keys(command) window.select_layout('tiled') window.set_window_option('synchronize-panes', 'on') return window @argh.arg('hosts', nargs='+') def clustered_ssh(hosts): ''' Creates new cluster window with an ssh connection to each host. A clustered session is one where you operate on all panes/commands at once using the synchronized-panes option. :param hosts: Sequence of hosts to connect to. ''' return clustered_window( ['ssh \'{}\''.format(host) for host in hosts])
[((11, 13, 11, 40), 'logging.getLogger', 'logging.getLogger', ({(11, 31, 11, 39): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((25, 1, 25, 32), 'argh.arg', 'argh.arg', (), '', False, 'import argh\n'), ((50, 1, 50, 29), 'argh.arg', 'argh.arg', (), '', False, 'import argh\n'), ((19, 13, 19, 27), 'tmuxp.Server', 'tmuxp.Server', ({}, {}), '()', False, 'import tmuxp\n'), ((20, 19, 20, 67), 'sarge.get_stdout', 'sarge.get_stdout', ({(20, 36, 20, 66): '"""tmux display-message -p "#S\\""""'}, {}), '(\'tmux display-message -p "#S"\')', False, 'import sarge\n')]
david-kn/nautobot-plugin-capacity-metrics
nautobot_capacity_metrics/management/commands/__init__.py
df2a635257a464b8340b788d8723b5f00e3e238f
"""Additional Django management commands added by nautobot_capacity_metrics plugin."""
[]
kmedian/nptweak
nptweak/__init__.py
222f46b8abb9b00f1ae8065d38d0514193aa8a4b
from .to_2darray import to_2darray
[]
sphildreth/roadie-python
resources/models/Image.py
1465ac0f4282356ab5a074020b4f0a9f28058a86
import io from PIL import Image as PILImage from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String from resources.models.ModelBase import Base class Image(Base): # If this is used then the image is stored in the database image = Column(LargeBinary(length=16777215), default=None) # If this is used then the image is remote and this is the url url = Column(String(500)) caption = Column(String(100)) # This is a PhotoHash of the image for assistance in deduping signature = Column(String(50)) artistId = Column(Integer, ForeignKey("artist.id"), index=True) releaseId = Column(Integer, ForeignKey("release.id"), index=True) def averageHash(self): try: hash_size = 8 # Open the image, resize it and convert it to black & white. image = PILImage.open(io.BytesIO(self.image)).resize((hash_size, hash_size), PILImage.ANTIALIAS).convert( 'L') pixels = list(image.getdata()) # Compute the hash based on each pixels value compared to the average. avg = sum(pixels) / len(pixels) bits = "".join(map(lambda pixel: '1' if pixel > avg else '0', pixels)) hashformat = "0{hashlength}x".format(hashlength=hash_size ** 2 // 4) return int(bits, 2).__format__(hashformat) except: return None def __unicode__(self): return self.caption def __str__(self): return self.caption or self.signature
[((10, 19, 10, 47), 'sqlalchemy.LargeBinary', 'LargeBinary', (), '', False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((12, 17, 12, 28), 'sqlalchemy.String', 'String', ({(12, 24, 12, 27): '500'}, {}), '(500)', False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((13, 21, 13, 32), 'sqlalchemy.String', 'String', ({(13, 28, 13, 31): '100'}, {}), '(100)', False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((15, 23, 15, 33), 'sqlalchemy.String', 'String', ({(15, 30, 15, 32): '50'}, {}), '(50)', False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((17, 31, 17, 54), 'sqlalchemy.ForeignKey', 'ForeignKey', ({(17, 42, 17, 53): '"""artist.id"""'}, {}), "('artist.id')", False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((18, 32, 18, 56), 'sqlalchemy.ForeignKey', 'ForeignKey', ({(18, 43, 18, 55): '"""release.id"""'}, {}), "('release.id')", False, 'from sqlalchemy import Column, ForeignKey, LargeBinary, Index, Integer, String\n'), ((24, 34, 24, 56), 'io.BytesIO', 'io.BytesIO', ({(24, 45, 24, 55): 'self.image'}, {}), '(self.image)', False, 'import io\n')]
gabrielasuchopar/arch2vec
arch2vec/search_methods/reinforce_darts.py
1fc47d2cc7d63832e0d6337b8482669366b4aef2
import os import sys import argparse import json import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from arch2vec.models.pretraining_nasbench101 import configs from arch2vec.utils import load_json, preprocessing, one_hot_darts from arch2vec.preprocessing.gen_isomorphism_graphs import process from arch2vec.models.model import Model from torch.distributions import MultivariateNormal from arch2vec.darts.cnn.train_search import Train class Env(object): def __init__(self, name, seed, cfg, data_path=None, save=False): self.name = name self.seed = seed self.model = Model(input_dim=args.input_dim, hidden_dim=args.hidden_dim, latent_dim=args.dim, num_hops=args.hops, num_mlp_layers=args.mlps, dropout=args.dropout, **cfg['GAE']).cuda() self.dir_name = 'pretrained/dim-{}'.format(args.dim) if not os.path.exists(os.path.join(self.dir_name, 'model-darts.pt')): exit() self.model.load_state_dict(torch.load(os.path.join(self.dir_name, 'model-darts.pt').format(args.dim))['model_state']) self.visited = {} self.features = [] self.genotype = [] self.embedding = {} self._reset(data_path, save) def _reset(self, data_path, save): if not save: print("extract arch2vec on DARTS search space ...") dataset = load_json(data_path) print("length of the dataset: {}".format(len(dataset))) self.f_path = os.path.join(self.dir_name, 'arch2vec-darts.pt') if os.path.exists(self.f_path): print('{} is already saved'.format(self.f_path)) exit() print('save to {}'.format(self.f_path)) counter = 0 self.model.eval() for k, v in dataset.items(): adj = torch.Tensor(v[0]).unsqueeze(0).cuda() ops = torch.Tensor(one_hot_darts(v[1])).unsqueeze(0).cuda() adj, ops, prep_reverse = preprocessing(adj, ops, **cfg['prep']) with torch.no_grad(): x, _ = self.model._encoder(ops, adj) self.embedding[counter] = {'feature': x.squeeze(0).mean(dim=0).cpu(), 'genotype': process(v[2])} print("{}/{}".format(counter, len(dataset))) counter += 1 torch.save(self.embedding, self.f_path) print("finished arch2vec extraction") exit() else: self.f_path = os.path.join(self.dir_name, 'arch2vec-darts.pt') print("load arch2vec from: {}".format(self.f_path)) self.embedding = torch.load(self.f_path) for ind in range(len(self.embedding)): self.features.append(self.embedding[ind]['feature']) self.genotype.append(self.embedding[ind]['genotype']) self.features = torch.stack(self.features, dim=0) print('loading finished. pretrained embeddings shape: {}'.format(self.features.shape)) def get_init_state(self): """ :return: 1 x dim """ rand_indices = random.randint(0, self.features.shape[0]) self.visited[rand_indices] = True return self.features[rand_indices], self.genotype[rand_indices] def step(self, action): """ action: 1 x dim self.features. N x dim """ dist = torch.norm(self.features - action.cpu(), dim=1) knn = (-1 * dist).topk(dist.shape[0]) min_dist, min_idx = knn.values, knn.indices count = 0 while True: if len(self.visited) == dist.shape[0]: print("CANNOT FIND IN THE DATASET!") exit() if min_idx[count].item() not in self.visited: self.visited[min_idx[count].item()] = True break count += 1 return self.features[min_idx[count].item()], self.genotype[min_idx[count].item()] class Policy(nn.Module): def __init__(self, hidden_dim1, hidden_dim2): super(Policy, self).__init__() self.fc1 = nn.Linear(hidden_dim1, hidden_dim2) self.fc2 = nn.Linear(hidden_dim2, hidden_dim1) self.saved_log_probs = [] self.rewards = [] def forward(self, input): x = F.relu(self.fc1(input)) out = self.fc2(x) return out class Policy_LSTM(nn.Module): def __init__(self, hidden_dim1, hidden_dim2): super(Policy_LSTM, self).__init__() self.lstm = torch.nn.LSTMCell(input_size=hidden_dim1, hidden_size=hidden_dim2) self.fc = nn.Linear(hidden_dim2, hidden_dim1) self.saved_log_probs = [] self.rewards = [] self.hx = None self.cx = None def forward(self, input): if self.hx is None and self.cx is None: self.hx, self.cx = self.lstm(input) else: self.hx, self.cx = self.lstm(input, (self.hx, self.cx)) mean = self.fc(self.hx) return mean def select_action(state, policy): """ MVN based action selection. :param state: 1 x dim :param policy: policy network :return: selected action: 1 x dim """ mean = policy(state.view(1, state.shape[0])) mvn = MultivariateNormal(mean, torch.eye(state.shape[0]).cuda()) action = mvn.sample() policy.saved_log_probs.append(torch.mean(mvn.log_prob(action))) return action def finish_episode(policy, optimizer): R = 0 policy_loss = [] returns = [] for r in policy.rewards: R = r + args.gamma * R returns.append(R) returns = torch.Tensor(policy.rewards) val, indices = torch.sort(returns) print("sorted validation reward:", val) returns = returns - args.objective for log_prob, R in zip(policy.saved_log_probs, returns): policy_loss.append(-log_prob * R) optimizer.zero_grad() policy_loss = torch.mean(torch.stack(policy_loss, dim=0)) print("average reward: {}, policy loss: {}".format(sum(policy.rewards)/len(policy.rewards), policy_loss.item())) policy_loss.backward() optimizer.step() del policy.rewards[:] del policy.saved_log_probs[:] policy.hx = None policy.cx = None def query(counter, seed, genotype, epochs): trainer = Train() rewards, rewards_test = trainer.main(counter, seed, genotype, epochs=epochs, train_portion=args.train_portion, save=args.logging_path) val_sum = 0 for epoch, val_acc in rewards: val_sum += val_acc val_avg = val_sum / len(rewards) return val_avg / 100. , rewards_test[-1][-1] / 100. def reinforce_search(env): """ implementation of arch2vec-RL on DARTS Search Space """ policy = Policy_LSTM(args.dim, 128).cuda() optimizer = optim.Adam(policy.parameters(), lr=1e-2) counter = 0 MAX_BUDGET = args.max_budgets state, genotype = env.get_init_state() CURR_BEST_VALID = 0 CURR_BEST_TEST = 0 CURR_BEST_GENOTYPE = None test_trace = [] valid_trace = [] genotype_trace = [] counter_trace = [] while counter < MAX_BUDGET: for c in range(args.bs): state = state.cuda() action = select_action(state, policy) state, genotype = env.step(action) reward, reward_test = query(counter=counter, seed=args.seed, genotype=genotype, epochs=args.inner_epochs) policy.rewards.append(reward) counter += 1 print('counter: {}, validation reward: {}, test reward: {}, genotype: {}'.format(counter, reward, reward_test, genotype)) if reward > CURR_BEST_VALID: CURR_BEST_VALID = reward CURR_BEST_TEST = reward_test CURR_BEST_GENOTYPE = genotype valid_trace.append(float(CURR_BEST_VALID)) test_trace.append(float(CURR_BEST_TEST)) genotype_trace.append(CURR_BEST_GENOTYPE) counter_trace.append(counter) if counter >= MAX_BUDGET: break finish_episode(policy, optimizer) res = dict() res['validation_acc'] = valid_trace res['test_acc'] = test_trace res['genotype'] = genotype_trace res['counter'] = counter_trace save_path = os.path.join(args.output_path, 'dim{}'.format(args.dim)) if not os.path.exists(save_path): os.mkdir(save_path) print('save to {}'.format(save_path)) fh = open(os.path.join(save_path, 'run_{}_arch2vec_model_darts.json'.format(args.seed)), 'w') json.dump(res, fh) fh.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description="arch2vec-REINFORCE") parser.add_argument("--gamma", type=float, default=0.8, help="discount factor (default 0.99)") parser.add_argument("--seed", type=int, default=3, help="random seed") parser.add_argument('--cfg', type=int, default=4, help='configuration (default: 4)') parser.add_argument('--bs', type=int, default=16, help='batch size') parser.add_argument('--objective', type=float, default=0.95, help='rl baseline') parser.add_argument('--max_budgets', type=int, default=100, help='number of queries') parser.add_argument('--inner_epochs', type=int, default=50, help='inner loop epochs') parser.add_argument('--train_portion', type=float, default=0.9, help='train/validation split portion') parser.add_argument('--output_path', type=str, default='rl', help='rl/bo (default: rl)') parser.add_argument('--logging_path', type=str, default='', help='search logging path') parser.add_argument('--saved_arch2vec', action="store_true", default=False) parser.add_argument('--input_dim', type=int, default=11) parser.add_argument('--hidden_dim', type=int, default=128) parser.add_argument('--dim', type=int, default=16, help='feature dimension (default: 16)') parser.add_argument('--hops', type=int, default=5) parser.add_argument('--mlps', type=int, default=2) parser.add_argument('--dropout', type=float, default=0.3) args = parser.parse_args() cfg = configs[args.cfg] env = Env('REINFORCE', args.seed, cfg, data_path='data/data_darts_counter600000.json', save=args.saved_arch2vec) torch.manual_seed(args.seed) reinforce_search(env)
[((154, 14, 154, 42), 'torch.Tensor', 'torch.Tensor', ({(154, 27, 154, 41): 'policy.rewards'}, {}), '(policy.rewards)', False, 'import torch\n'), ((155, 19, 155, 38), 'torch.sort', 'torch.sort', ({(155, 30, 155, 37): 'returns'}, {}), '(returns)', False, 'import torch\n'), ((172, 14, 172, 21), 'arch2vec.darts.cnn.train_search.Train', 'Train', ({}, {}), '()', False, 'from arch2vec.darts.cnn.train_search import Train\n'), ((230, 4, 230, 22), 'json.dump', 'json.dump', ({(230, 14, 230, 17): 'res', (230, 19, 230, 21): 'fh'}, {}), '(res, fh)', False, 'import json\n'), ((235, 13, 235, 70), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (), '', False, 'import argparse\n'), ((257, 4, 257, 32), 'torch.manual_seed', 'torch.manual_seed', ({(257, 22, 257, 31): 'args.seed'}, {}), '(args.seed)', False, 'import torch\n'), ((74, 23, 74, 64), 'random.randint', 'random.randint', ({(74, 38, 74, 39): '0', (74, 41, 74, 63): 'self.features.shape[0]'}, {}), '(0, self.features.shape[0])', False, 'import random\n'), ((102, 19, 102, 54), 'torch.nn.Linear', 'nn.Linear', ({(102, 29, 102, 40): 'hidden_dim1', (102, 42, 102, 53): 'hidden_dim2'}, {}), '(hidden_dim1, hidden_dim2)', True, 'import torch.nn as nn\n'), ((103, 19, 103, 54), 'torch.nn.Linear', 'nn.Linear', ({(103, 29, 103, 40): 'hidden_dim2', (103, 42, 103, 53): 'hidden_dim1'}, {}), '(hidden_dim2, hidden_dim1)', True, 'import torch.nn as nn\n'), ((116, 20, 116, 86), 'torch.nn.LSTMCell', 'torch.nn.LSTMCell', (), '', False, 'import torch\n'), ((117, 18, 117, 53), 'torch.nn.Linear', 'nn.Linear', ({(117, 28, 117, 39): 'hidden_dim2', (117, 41, 117, 52): 'hidden_dim1'}, {}), '(hidden_dim2, hidden_dim1)', True, 'import torch.nn as nn\n'), ((162, 29, 162, 60), 'torch.stack', 'torch.stack', (), '', False, 'import torch\n'), ((226, 11, 226, 36), 'os.path.exists', 'os.path.exists', ({(226, 26, 226, 35): 'save_path'}, {}), '(save_path)', False, 'import os\n'), ((227, 8, 227, 27), 'os.mkdir', 'os.mkdir', ({(227, 17, 227, 26): 'save_path'}, {}), '(save_path)', False, 'import os\n'), ((38, 22, 38, 42), 'arch2vec.utils.load_json', 'load_json', ({(38, 32, 38, 41): 'data_path'}, {}), '(data_path)', False, 'from arch2vec.utils import load_json, preprocessing, one_hot_darts\n'), ((40, 26, 40, 74), 'os.path.join', 'os.path.join', ({(40, 39, 40, 52): 'self.dir_name', (40, 54, 40, 73): '"""arch2vec-darts.pt"""'}, {}), "(self.dir_name, 'arch2vec-darts.pt')", False, 'import os\n'), ((41, 15, 41, 42), 'os.path.exists', 'os.path.exists', ({(41, 30, 41, 41): 'self.f_path'}, {}), '(self.f_path)', False, 'import os\n'), ((56, 12, 56, 51), 'torch.save', 'torch.save', ({(56, 23, 56, 37): 'self.embedding', (56, 39, 56, 50): 'self.f_path'}, {}), '(self.embedding, self.f_path)', False, 'import torch\n'), ((60, 26, 60, 74), 'os.path.join', 'os.path.join', ({(60, 39, 60, 52): 'self.dir_name', (60, 54, 60, 73): '"""arch2vec-darts.pt"""'}, {}), "(self.dir_name, 'arch2vec-darts.pt')", False, 'import os\n'), ((62, 29, 62, 52), 'torch.load', 'torch.load', ({(62, 40, 62, 51): 'self.f_path'}, {}), '(self.f_path)', False, 'import torch\n'), ((66, 28, 66, 61), 'torch.stack', 'torch.stack', (), '', False, 'import torch\n'), ((23, 21, 24, 104), 'arch2vec.models.model.Model', 'Model', (), '', False, 'from arch2vec.models.model import Model\n'), ((26, 30, 26, 75), 'os.path.join', 'os.path.join', ({(26, 43, 26, 56): 'self.dir_name', (26, 58, 26, 74): '"""model-darts.pt"""'}, {}), "(self.dir_name, 'model-darts.pt')", False, 'import os\n'), ((50, 41, 50, 79), 'arch2vec.utils.preprocessing', 'preprocessing', ({(50, 55, 50, 58): 'adj', (50, 60, 50, 63): 'ops'}, {}), "(adj, ops, **cfg['prep'])", False, 'from arch2vec.utils import load_json, preprocessing, one_hot_darts\n'), ((141, 35, 141, 60), 'torch.eye', 'torch.eye', ({(141, 45, 141, 59): 'state.shape[0]'}, {}), '(state.shape[0])', False, 'import torch\n'), ((51, 21, 51, 36), 'torch.no_grad', 'torch.no_grad', ({}, {}), '()', False, 'import torch\n'), ((53, 102, 53, 115), 'arch2vec.preprocessing.gen_isomorphism_graphs.process', 'process', ({(53, 110, 53, 114): 'v[2]'}, {}), '(v[2])', False, 'from arch2vec.preprocessing.gen_isomorphism_graphs import process\n'), ((28, 46, 28, 91), 'os.path.join', 'os.path.join', ({(28, 59, 28, 72): 'self.dir_name', (28, 74, 28, 90): '"""model-darts.pt"""'}, {}), "(self.dir_name, 'model-darts.pt')", False, 'import os\n'), ((48, 22, 48, 40), 'torch.Tensor', 'torch.Tensor', ({(48, 35, 48, 39): 'v[0]'}, {}), '(v[0])', False, 'import torch\n'), ((49, 35, 49, 54), 'arch2vec.utils.one_hot_darts', 'one_hot_darts', ({(49, 49, 49, 53): 'v[1]'}, {}), '(v[1])', False, 'from arch2vec.utils import load_json, preprocessing, one_hot_darts\n')]
mentaal/r_map
setup.py
42986e90b31018b1e7fc992a53b0f5f6e559253f
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Arguments marked as "Required" below must be included for upload to PyPI. # Fields marked as "Optional" may be commented out. setup( name='r_map', # Required version='0.9.0', # Required description='A data structure for working with register map information', # Required long_description=long_description, # Optional long_description_content_type='text/markdown', # Optional (see note above) url='https://github.com/mentaal/r_map', # Optional # This should be your name or the name of the organization which owns the # project. author='Gregory Kuhn', # Optional # This should be a valid email address corresponding to the author listed # above. author_email='[email protected]', # Optional # Classifiers help users find your project by categorizing it. # # For a list of valid classifiers, see https://pypi.org/classifiers/ classifiers=[ # Optional # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3.6', ], keywords='register bitfield registermap', # Optional packages=['r_map'], python_requires='>=3.6', project_urls={ # Optional 'Bug Reports': 'https://github.com/mentaal/r_map/issues', 'Source': 'https://github.com/mentaal/r_map', }, )
[((22, 0, 67, 1), 'setuptools.setup', 'setup', (), '', False, 'from setuptools import setup, find_packages\n'), ((13, 20, 13, 42), 'os.path.dirname', 'path.dirname', ({(13, 33, 13, 41): '__file__'}, {}), '(__file__)', False, 'from os import path\n'), ((16, 10, 16, 38), 'os.path.join', 'path.join', ({(16, 20, 16, 24): 'here', (16, 26, 16, 37): '"""README.md"""'}, {}), "(here, 'README.md')", False, 'from os import path\n')]
karianjahi/fahrer_minijob
dont_worry.py
020a9de27b77f8e0bcdec198a37cfb7f1d4736ed
class Hey: def __init__(jose, name="mours"): jose.name = name def get_name(jose): return jose.name class Person(object): def __init__(self, name, phone): self.name = name self.phone = phone class Teenager(Person): def __init__(self, *args, **kwargs): self.website = kwargs.pop("website") super(Teenager, self).__init__(*args, **kwargs) if __name__ == "__main__": #print(Hey().get_name()) teen = Teenager("Joseph Njeri", 924, "www.fowr.gd") print(teen.website)
[]
dynalz/odmantic
tests/zoo/tree.py
f20f08f8ab1768534c1e743f7539bfe4f8c73bdd
import enum from typing import Dict, List from odmantic.field import Field from odmantic.model import Model class TreeKind(str, enum.Enum): BIG = "big" SMALL = "small" class TreeModel(Model): name: str = Field(primary_key=True, default="Acacia des montagnes") average_size: float = Field(mongo_name="size") discovery_year: int kind: TreeKind genesis_continents: List[str] per_continent_density: Dict[str, float]
[((14, 16, 14, 71), 'odmantic.field.Field', 'Field', (), '', False, 'from odmantic.field import Field\n'), ((15, 26, 15, 50), 'odmantic.field.Field', 'Field', (), '', False, 'from odmantic.field import Field\n')]
eustomaqua/adanet
adanet/core/estimator_test.py
9c1de82428a4e661768af8e764041afebfec2e6f
"""Test AdaNet estimator single graph implementation. Copyright 2018 The AdaNet Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import time from absl import logging from absl.testing import parameterized from adanet import replay from adanet import tf_compat from adanet.core import testing_utils as tu from adanet.core.estimator import Estimator from adanet.core.evaluator import Evaluator from adanet.core.report_materializer import ReportMaterializer from adanet.distributed.placement import RoundRobinStrategy from adanet.ensemble import AllStrategy from adanet.ensemble import ComplexityRegularizedEnsembler from adanet.ensemble import GrowStrategy from adanet.ensemble import MixtureWeightType from adanet.ensemble import SoloStrategy from adanet.subnetwork import Builder from adanet.subnetwork import Generator from adanet.subnetwork import MaterializedReport from adanet.subnetwork import Report from adanet.subnetwork import SimpleGenerator from adanet.subnetwork import Subnetwork from adanet.subnetwork import TrainOpSpec import numpy as np import tensorflow as tf # pylint: disable=g-direct-tensorflow-import from tensorflow.python.eager import context from tensorflow.python.framework import test_util from tensorflow.python.tools import saved_model_utils # pylint: enable=g-direct-tensorflow-import from tensorflow_estimator.python.estimator.canned.head import _binary_logistic_head_with_sigmoid_cross_entropy_loss as binary_class_head_v1 from tensorflow_estimator.python.estimator.export import export from tensorflow_estimator.python.estimator.head import binary_class_head from tensorflow_estimator.python.estimator.head import multi_head as multi_head_lib from tensorflow_estimator.python.estimator.head import regression_head logging.set_verbosity(logging.INFO) XOR_FEATURES = [[1., 0.], [0., 0], [0., 1.], [1., 1.]] XOR_LABELS = [[1.], [0.], [1.], [0.]] class _DNNBuilder(Builder): """A simple DNN subnetwork builder.""" def __init__(self, name, learning_rate=.001, mixture_weight_learning_rate=.001, return_penultimate_layer=True, layer_size=1, subnetwork_chief_hooks=None, subnetwork_hooks=None, mixture_weight_chief_hooks=None, mixture_weight_hooks=None, seed=13): self._name = name self._learning_rate = learning_rate self._mixture_weight_learning_rate = mixture_weight_learning_rate self._return_penultimate_layer = return_penultimate_layer self._layer_size = layer_size self._subnetwork_chief_hooks = subnetwork_chief_hooks self._subnetwork_hooks = subnetwork_hooks self._mixture_weight_chief_hooks = mixture_weight_chief_hooks self._mixture_weight_hooks = mixture_weight_hooks self._seed = seed @property def name(self): return self._name def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): seed = self._seed if previous_ensemble: # Increment seed so different iterations don't learn the exact same thing. seed += 1 with tf_compat.v1.variable_scope("dnn"): persisted_tensors = {} with tf_compat.v1.variable_scope("hidden_layer"): w = tf_compat.v1.get_variable( shape=[2, self._layer_size], initializer=tf_compat.v1.glorot_uniform_initializer(seed=seed), name="weight") disjoint_op = tf.constant([1], name="disjoint_op") with tf_compat.v1.colocate_with(disjoint_op): # tests b/118865235 hidden_layer = tf.matmul(features["x"], w) if previous_ensemble: other_hidden_layer = previous_ensemble.weighted_subnetworks[ -1].subnetwork.persisted_tensors["hidden_layer"] hidden_layer = tf.concat([hidden_layer, other_hidden_layer], axis=1) # Use a leaky-relu activation so that gradients can flow even when # outputs are negative. Leaky relu has a non-zero slope when x < 0. # Otherwise success at learning is completely dependent on random seed. hidden_layer = tf.nn.leaky_relu(hidden_layer, alpha=.2) persisted_tensors["hidden_layer"] = hidden_layer if training: # This change will only be in the next iteration if # `freeze_training_graph` is `True`. persisted_tensors["hidden_layer"] = 2 * hidden_layer last_layer = hidden_layer with tf_compat.v1.variable_scope("logits"): logits = tf_compat.v1.layers.dense( hidden_layer, logits_dimension, kernel_initializer=tf_compat.v1.glorot_uniform_initializer(seed=seed)) summary.scalar("scalar", 3) batch_size = features["x"].get_shape().as_list()[0] summary.image("image", tf.ones([batch_size, 3, 3, 1])) with tf_compat.v1.variable_scope("nested"): summary.scalar("scalar", 5) return Subnetwork( last_layer=last_layer if self._return_penultimate_layer else logits, logits=logits, complexity=3, persisted_tensors=persisted_tensors, shared=persisted_tensors) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble): optimizer = tf_compat.v1.train.GradientDescentOptimizer( learning_rate=self._learning_rate) train_op = optimizer.minimize(loss, var_list=var_list) if not self._subnetwork_hooks: return train_op return TrainOpSpec(train_op, self._subnetwork_chief_hooks, self._subnetwork_hooks) def build_mixture_weights_train_op(self, loss, var_list, logits, labels, iteration_step, summary): optimizer = tf_compat.v1.train.GradientDescentOptimizer( learning_rate=self._mixture_weight_learning_rate) train_op = optimizer.minimize(loss, var_list=var_list) if not self._mixture_weight_hooks: return train_op return TrainOpSpec(train_op, self._mixture_weight_chief_hooks, self._mixture_weight_hooks) def build_subnetwork_report(self): return Report( hparams={"layer_size": self._layer_size}, attributes={"complexity": tf.constant(3, dtype=tf.int32)}, metrics={ "moo": (tf.constant(3, dtype=tf.int32), tf.constant(3, dtype=tf.int32)) }) class _SimpleBuilder(Builder): """A simple subnetwork builder that takes feature_columns.""" def __init__(self, name, feature_columns, seed=42): self._name = name self._feature_columns = feature_columns self._seed = seed @property def name(self): return self._name def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): seed = self._seed if previous_ensemble: # Increment seed so different iterations don't learn the exact same thing. seed += 1 with tf_compat.v1.variable_scope("simple"): input_layer = tf_compat.v1.feature_column.input_layer( features=features, feature_columns=self._feature_columns) last_layer = input_layer with tf_compat.v1.variable_scope("logits"): logits = tf_compat.v1.layers.dense( last_layer, logits_dimension, kernel_initializer=tf_compat.v1.glorot_uniform_initializer(seed=seed)) return Subnetwork( last_layer=last_layer, logits=logits, complexity=1, persisted_tensors={}, ) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble): optimizer = tf_compat.v1.train.GradientDescentOptimizer(learning_rate=.001) return optimizer.minimize(loss, var_list=var_list) def build_mixture_weights_train_op(self, loss, var_list, logits, labels, iteration_step, summary): optimizer = tf_compat.v1.train.GradientDescentOptimizer(learning_rate=.001) return optimizer.minimize(loss, var_list=var_list) class _NanLossBuilder(Builder): """A subnetwork builder always produces a NaN loss.""" @property def name(self): return "nan" def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): logits = tf_compat.v1.layers.dense( features["x"], logits_dimension, kernel_initializer=tf_compat.v1.glorot_uniform_initializer( seed=42)) * np.nan return Subnetwork(last_layer=logits, logits=logits, complexity=0) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble): return tf.no_op() class _LinearBuilder(Builder): """A simple linear subnetwork builder.""" def __init__(self, name, mixture_weight_learning_rate=.001, seed=42): self._name = name self._mixture_weight_learning_rate = mixture_weight_learning_rate self._seed = seed @property def name(self): return self._name def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): logits = tf_compat.v1.layers.dense( features["x"], logits_dimension, kernel_initializer=tf_compat.v1.glorot_uniform_initializer( seed=self._seed)) return Subnetwork( last_layer=features["x"], logits=logits, complexity=1, persisted_tensors={}, ) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble): optimizer = tf_compat.v1.train.GradientDescentOptimizer(learning_rate=.001) return optimizer.minimize(loss, var_list=var_list) def build_mixture_weights_train_op(self, loss, var_list, logits, labels, iteration_step, summary): optimizer = tf_compat.v1.train.GradientDescentOptimizer( learning_rate=self._mixture_weight_learning_rate) return optimizer.minimize(loss, var_list=var_list) class _FakeGenerator(Generator): """Generator that exposed generate_candidates' arguments.""" def __init__(self, spy_fn, subnetwork_builders): """Checks the arguments passed to generate_candidates. Args: spy_fn: (iteration_number, previous_ensemble_reports, all_reports) -> (). Spies on the arguments passed to generate_candidates whenever it is called. subnetwork_builders: List of `Builder`s to return in every call to generate_candidates. """ self._spy_fn = spy_fn self._subnetwork_builders = subnetwork_builders def generate_candidates(self, previous_ensemble, iteration_number, previous_ensemble_reports, all_reports): """Spys on arguments passed in, then returns a fixed list of candidates.""" del previous_ensemble # unused self._spy_fn(iteration_number, previous_ensemble_reports, all_reports) return self._subnetwork_builders class _WidthLimitingDNNBuilder(_DNNBuilder): """Limits the width of the previous_ensemble.""" def __init__(self, name, learning_rate=.001, mixture_weight_learning_rate=.001, return_penultimate_layer=True, layer_size=1, width_limit=None, seed=13): if width_limit is not None and width_limit == 0: raise ValueError("width_limit must be at least 1 or None.") super(_WidthLimitingDNNBuilder, self).__init__(name, learning_rate, mixture_weight_learning_rate, return_penultimate_layer, layer_size, seed) self._width_limit = width_limit def prune_previous_ensemble(self, previous_ensemble): indices = range(len(previous_ensemble.weighted_subnetworks)) if self._width_limit is None: return indices if self._width_limit == 1: return [] return indices[-self._width_limit + 1:] # pylint: disable=invalid-unary-operand-type class _FakeEvaluator(object): """Fakes an `adanet.Evaluator`.""" def __init__(self, input_fn): self._input_fn = input_fn @property def input_fn(self): """Return the input_fn.""" return self._input_fn @property def steps(self): """Return the number of evaluation steps.""" return 1 @property def metric_name(self): """Returns the name of the metric being optimized.""" return "adanet_loss" @property def objective_fn(self): """Always returns the minimize objective.""" return np.nanargmin def evaluate(self, sess, ensemble_metrics): """Abstract method to be overridden in subclasses.""" del sess, ensemble_metrics # Unused. raise NotImplementedError class _AlwaysLastEvaluator(_FakeEvaluator): def evaluate(self, sess, ensemble_metrics): """Always makes the last loss the smallest.""" del sess # Unused. losses = [np.inf] * len(ensemble_metrics) losses[-1] = 0. return losses class _AlwaysSecondToLastEvaluator(_FakeEvaluator): def evaluate(self, sess, ensemble_metrics): """Always makes the second to last loss the smallest.""" del sess # Unused. losses = [np.inf] * len(ensemble_metrics) losses[-2] = 0. return losses class _EarlyStoppingHook(tf_compat.SessionRunHook): """Hook that immediately requests training to stop.""" def after_run(self, run_context, run_values): run_context.request_stop() class EstimatorTest(tu.AdanetTestCase): @parameterized.named_parameters( { "testcase_name": "one_step", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 1, "steps": 1, "max_steps": None, "want_loss": 0.49899703, "want_iteration": 0, "want_global_step": 1, }, { "testcase_name": "none_max_iteration_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": None, "steps": 300, "max_steps": None, "want_loss": 0.32487726, "want_iteration": 0, "want_global_step": 300, }, { "testcase_name": "single_builder_max_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 200, "max_steps": 300, "want_loss": 0.32420248, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 200, "steps": 300, "max_steps": None, "want_loss": 0.32420248, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_two_max_iteration_fewer_max_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 200, "max_iterations": 2, "max_steps": 300, "want_loss": 0.32420248, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_no_bias", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 200, "use_bias": False, "want_loss": 0.496736, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_subnetwork_hooks", "subnetwork_generator": SimpleGenerator([ _DNNBuilder( "dnn", subnetwork_chief_hooks=[ tu.ModifierSessionRunHook("chief_hook_var") ], subnetwork_hooks=[tu.ModifierSessionRunHook("hook_var")]) ]), "max_iteration_steps": 200, "use_bias": False, "want_loss": 0.496736, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_mixture_weight_hooks", "subnetwork_generator": SimpleGenerator([ _DNNBuilder( "dnn", mixture_weight_chief_hooks=[ tu.ModifierSessionRunHook("chief_hook_var") ], mixture_weight_hooks=[ tu.ModifierSessionRunHook("hook_var") ]) ]), "max_iteration_steps": 200, "use_bias": False, "want_loss": 0.496736, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_scalar_mixture_weight", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn", return_penultimate_layer=False)]), "max_iteration_steps": 200, "mixture_weight_type": MixtureWeightType.SCALAR, "want_loss": 0.32317898, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_vector_mixture_weight", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn", return_penultimate_layer=False)]), "max_iteration_steps": 200, "mixture_weight_type": MixtureWeightType.VECTOR, "want_loss": 0.32317898, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_replicate_ensemble_in_training", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "replicate_ensemble_in_training": True, "max_iteration_steps": 200, "max_steps": 300, "want_loss": 0.32420215, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "single_builder_with_hook", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 200, "hooks": [tu.ModifierSessionRunHook()], "want_loss": 0.32420248, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "high_max_iteration_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 500, "want_loss": 0.32487726, "want_iteration": 0, "want_global_step": 300, }, { "testcase_name": "two_builders", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", seed=99)]), "max_iteration_steps": 200, "want_loss": 0.27713922, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "two_builders_different_layer_sizes", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 200, "want_loss": 0.29696745, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "two_builders_one_max_iteration_none_steps_and_none_max_steps", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 200, "max_iterations": 1, "steps": None, "max_steps": None, "want_loss": 0.35249719, "want_iteration": 0, "want_global_step": 200, }, { "testcase_name": "two_builders_one_max_iteration_two_hundred_steps", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 200, "max_iterations": 1, "steps": 300, "max_steps": None, "want_loss": 0.35249719, "want_iteration": 0, "want_global_step": 200, }, { "testcase_name": "two_builders_two_max_iteration_none_steps_and_none_max_steps", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 200, "max_iterations": 2, "steps": None, "max_steps": None, "want_loss": 0.26503286, "want_iteration": 1, "want_global_step": 400, }, { "testcase_name": "two_builders_different_layer_sizes_three_iterations", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 100, "want_loss": 0.26433355, "want_iteration": 2, "want_global_step": 300, }, { "testcase_name": "two_dnn_export_subnetworks", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "max_iteration_steps": 100, "want_loss": 0.26433355, "want_iteration": 2, "want_global_step": 300, "export_subnetworks": True, }, { "testcase_name": "width_limiting_builder_no_pruning", "subnetwork_generator": SimpleGenerator([_WidthLimitingDNNBuilder("no_pruning")]), "max_iteration_steps": 75, "want_loss": 0.32001898, "want_iteration": 3, "want_global_step": 300, }, { "testcase_name": "width_limiting_builder_some_pruning", "subnetwork_generator": SimpleGenerator( [_WidthLimitingDNNBuilder("some_pruning", width_limit=2)]), "max_iteration_steps": 75, "want_loss": 0.38592532, "want_iteration": 3, "want_global_step": 300, }, { "testcase_name": "width_limiting_builder_prune_all", "subnetwork_generator": SimpleGenerator( [_WidthLimitingDNNBuilder("prune_all", width_limit=1)]), "max_iteration_steps": 75, "want_loss": 0.43492866, "want_iteration": 3, "want_global_step": 300, }, { "testcase_name": "width_limiting_builder_mixed", "subnetwork_generator": SimpleGenerator([ _WidthLimitingDNNBuilder("no_pruning"), _WidthLimitingDNNBuilder("some_pruning", width_limit=2), _WidthLimitingDNNBuilder("prune_all", width_limit=1) ]), "max_iteration_steps": 75, "want_loss": 0.32001898, "want_iteration": 3, "want_global_step": 300, }, { "testcase_name": "evaluator_good_input", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "evaluator": Evaluator( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=3), "max_iteration_steps": 200, "want_loss": 0.36189985, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "evaluator_bad_input", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "evaluator": Evaluator( input_fn=tu.dummy_input_fn([[1., 1.]], [[1.]]), steps=3), "max_iteration_steps": 200, "want_loss": 0.29696745, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "evaluator_always_last", "subnetwork_generator": SimpleGenerator([ _DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3), ]), "evaluator": _AlwaysLastEvaluator( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]])), "max_iteration_steps": None, "want_loss": 0.31389591, "want_iteration": 0, "want_global_step": 300, }, { "testcase_name": "evaluator_always_second_to_last", "subnetwork_generator": SimpleGenerator([ _DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3), ]), "evaluator": _AlwaysSecondToLastEvaluator( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]])), "max_iteration_steps": None, "want_loss": 0.32487726, "want_iteration": 0, "want_global_step": 300, }, { "testcase_name": "report_materializer", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "report_materializer": ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1), "max_iteration_steps": 200, "want_loss": 0.29696745, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "all_strategy", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "ensemble_strategies": [AllStrategy()], "max_iteration_steps": 200, "want_loss": 0.29196805, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "all_strategy_multiple_ensemblers", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "ensemble_strategies": [AllStrategy()], "ensemblers": [ ComplexityRegularizedEnsembler(), ComplexityRegularizedEnsembler(use_bias=True, name="with_bias") ], "max_iteration_steps": 200, "want_loss": 0.23053232, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "solo_strategy", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "ensemble_strategies": [SoloStrategy()], "max_iteration_steps": 200, "want_loss": 0.35249719, "want_iteration": 1, "want_global_step": 300, }, { "testcase_name": "solo_strategy_three_iterations", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "ensemble_strategies": [SoloStrategy()], "max_iteration_steps": 100, "want_loss": 0.36163166, "want_iteration": 2, "want_global_step": 300, }, { "testcase_name": "multi_ensemble_strategy", "subnetwork_generator": SimpleGenerator( [_DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3)]), "ensemble_strategies": [AllStrategy(), GrowStrategy(), SoloStrategy()], "max_iteration_steps": 100, "want_loss": 0.24838975, "want_iteration": 2, "want_global_step": 300, }, { "testcase_name": "dataset_train_input_fn", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), # pylint: disable=g-long-lambda "train_input_fn": lambda: tf.data.Dataset.from_tensors(({ "x": XOR_FEATURES }, XOR_LABELS)).repeat(), # pylint: enable=g-long-lambda "max_iteration_steps": 100, "want_loss": 0.32219219, "want_iteration": 2, "want_global_step": 300, }, { "testcase_name": "early_stopping_subnetwork", "subnetwork_generator": SimpleGenerator([ _DNNBuilder("dnn"), _DNNBuilder("dnn2", subnetwork_hooks=[_EarlyStoppingHook()]) ]), "max_iteration_steps": 100, "max_steps": 200, "want_loss": 0.2958503, # Since one subnetwork stops after 1 step and global step is the # mean of iteration steps, global step will be incremented at half # the rate. "want_iteration": 3, "want_global_step": 200, }) def test_lifecycle(self, subnetwork_generator, want_loss, want_iteration, want_global_step, max_iteration_steps, mixture_weight_type=MixtureWeightType.MATRIX, evaluator=None, use_bias=True, replicate_ensemble_in_training=False, hooks=None, ensemblers=None, ensemble_strategies=None, max_steps=300, steps=None, report_materializer=None, train_input_fn=None, max_iterations=None, export_subnetworks=False): """Train entire estimator lifecycle using XOR dataset.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) def _metric_fn(predictions): mean = tf.keras.metrics.Mean() mean.update_state(predictions["predictions"]) return {"keras_mean": mean} default_ensembler_kwargs = { "mixture_weight_type": mixture_weight_type, "mixture_weight_initializer": tf_compat.v1.zeros_initializer(), "warm_start_mixture_weights": True, "use_bias": use_bias, } if ensemblers: default_ensembler_kwargs = {} estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=max_iteration_steps, evaluator=evaluator, ensemblers=ensemblers, ensemble_strategies=ensemble_strategies, report_materializer=report_materializer, replicate_ensemble_in_training=replicate_ensemble_in_training, metric_fn=_metric_fn, model_dir=self.test_subdirectory, config=run_config, max_iterations=max_iterations, export_subnetwork_logits=export_subnetworks, export_subnetwork_last_layer=export_subnetworks, **default_ensembler_kwargs) if not train_input_fn: train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) # Train. estimator.train( input_fn=train_input_fn, steps=steps, max_steps=max_steps, hooks=hooks) # Evaluate. eval_results = estimator.evaluate( input_fn=train_input_fn, steps=10, hooks=hooks) logging.info("%s", eval_results) self.assertAlmostEqual(want_loss, eval_results["loss"], places=3) self.assertEqual(want_global_step, eval_results["global_step"]) self.assertEqual(want_iteration, eval_results["iteration"]) # Predict. predictions = estimator.predict( input_fn=tu.dataset_input_fn(features=[0., 0.], labels=None)) for prediction in predictions: self.assertIsNotNone(prediction["predictions"]) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") return tf.estimator.export.ServingInputReceiver( features={"x": tf.constant([[0., 0.]], name="serving_x")}, receiver_tensors=serialized_example) export_saved_model_fn = getattr(estimator, "export_saved_model", None) if not callable(export_saved_model_fn): export_saved_model_fn = estimator.export_savedmodel export_dir_base = os.path.join(self.test_subdirectory, "export") export_saved_model_fn( export_dir_base=export_dir_base, serving_input_receiver_fn=serving_input_fn) if export_subnetworks: saved_model = saved_model_utils.read_saved_model( os.path.join(export_dir_base, tf.io.gfile.listdir(export_dir_base)[0])) export_signature_def = saved_model.meta_graphs[0].signature_def self.assertIn("subnetwork_logits", export_signature_def.keys()) self.assertIn("subnetwork_last_layer", export_signature_def.keys()) @parameterized.named_parameters( { "testcase_name": "hash_bucket_with_one_hot", "feature_column": (tf.feature_column.indicator_column( categorical_column=( tf.feature_column.categorical_column_with_hash_bucket( key="human_names", hash_bucket_size=4, dtype=tf.string))) ), }, { "testcase_name": "vocab_list_with_one_hot", "feature_column": (tf.feature_column.indicator_column( categorical_column=( tf.feature_column.categorical_column_with_vocabulary_list( key="human_names", vocabulary_list=["alice", "bob"], dtype=tf.string)))), }, { "testcase_name": "hash_bucket_with_embedding", "feature_column": (tf.feature_column.embedding_column( categorical_column=( tf.feature_column.categorical_column_with_hash_bucket( key="human_names", hash_bucket_size=4, dtype=tf.string)), dimension=2)), }, { "testcase_name": "vocab_list_with_embedding", "feature_column": (tf.feature_column.embedding_column( categorical_column=( tf.feature_column.categorical_column_with_vocabulary_list( key="human_names", vocabulary_list=["alice", "bob"], dtype=tf.string)), dimension=2)), }) def test_categorical_columns(self, feature_column): def train_input_fn(): input_features = { "human_names": tf.constant([["alice"], ["bob"]], name="human_names") } input_labels = tf.constant([[1.], [0.]], name="starts_with_a") return input_features, input_labels report_materializer = ReportMaterializer(input_fn=train_input_fn, steps=1) estimator = Estimator( head=regression_head.RegressionHead(), subnetwork_generator=SimpleGenerator( [_SimpleBuilder(name="simple", feature_columns=[feature_column])]), report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=1, use_bias=True, model_dir=self.test_subdirectory) estimator.train(input_fn=train_input_fn, max_steps=3) @parameterized.named_parameters( { "testcase_name": "no_subnetwork_generator", "subnetwork_generator": None, "max_iteration_steps": 100, "want_error": ValueError, }, { "testcase_name": "negative_max_iteration_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": -1, "want_error": ValueError, }, { "testcase_name": "zero_max_iteration_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 0, "want_error": ValueError, }, { "testcase_name": "negative_max_iterations", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 1, "max_iterations": -1, "want_error": ValueError, }, { "testcase_name": "zero_max_iterations", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 1, "max_iterations": 0, "want_error": ValueError, }, { "testcase_name": "steps_and_max_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 1, "steps": 1, "max_steps": 1, "want_error": ValueError, }, { "testcase_name": "zero_steps", "subnetwork_generator": SimpleGenerator([_DNNBuilder("dnn")]), "max_iteration_steps": 1, "steps": 0, "max_steps": None, "want_error": ValueError, }, { "testcase_name": "nan_loss_builder", "subnetwork_generator": SimpleGenerator([_NanLossBuilder()]), "max_iteration_steps": 1, "max_steps": None, "want_error": tf_compat.v1.estimator.NanLossDuringTrainingError, }, { "testcase_name": "nan_loss_builder_first", "subnetwork_generator": SimpleGenerator([ _NanLossBuilder(), _DNNBuilder("dnn"), ]), "max_iteration_steps": 1, "max_steps": None, "want_error": tf_compat.v1.estimator.NanLossDuringTrainingError, }, { "testcase_name": "nan_loss_builder_last", "subnetwork_generator": SimpleGenerator([ _DNNBuilder("dnn"), _NanLossBuilder(), ]), "max_iteration_steps": 1, "max_steps": None, "want_error": tf_compat.v1.estimator.NanLossDuringTrainingError, }, ) def test_train_error(self, subnetwork_generator, max_iteration_steps, want_error, steps=None, max_steps=10, max_iterations=None): report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) with self.assertRaises(want_error): estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=max_iteration_steps, use_bias=True, max_iterations=max_iterations, model_dir=self.test_subdirectory) train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.train(input_fn=train_input_fn, steps=steps, max_steps=max_steps) def test_binary_head_asserts_are_disabled(self): """Tests b/140267630.""" subnetwork_generator = SimpleGenerator([ _DNNBuilder("dnn"), _NanLossBuilder(), ]) estimator = Estimator( head=binary_class_head_v1(), subnetwork_generator=subnetwork_generator, max_iteration_steps=10, model_dir=self.test_subdirectory) eval_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.evaluate(input_fn=eval_input_fn, steps=1) class KerasCNNBuilder(Builder): """Builds a CNN subnetwork for AdaNet.""" def __init__(self, learning_rate, seed=42): """Initializes a `SimpleCNNBuilder`. Args: learning_rate: The float learning rate to use. seed: The random seed. Returns: An instance of `SimpleCNNBuilder`. """ self._learning_rate = learning_rate self._seed = seed def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): """See `adanet.subnetwork.Builder`.""" seed = self._seed if previous_ensemble: seed += len(previous_ensemble.weighted_subnetworks) images = list(features.values())[0] images = tf.reshape(images, [-1, 2, 2, 1]) kernel_initializer = tf_compat.v1.keras.initializers.he_normal(seed=seed) x = tf.keras.layers.Conv2D( filters=3, kernel_size=1, padding="same", activation="relu", kernel_initializer=kernel_initializer)( images) x = tf.keras.layers.MaxPool2D(pool_size=2, strides=1)(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense( units=3, activation="relu", kernel_initializer=kernel_initializer)( x) logits = tf_compat.v1.layers.Dense( units=1, activation=None, kernel_initializer=kernel_initializer)( x) complexity = tf.constant(1) return Subnetwork( last_layer=x, logits=logits, complexity=complexity, persisted_tensors={}) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble=None): optimizer = tf_compat.v1.train.GradientDescentOptimizer(self._learning_rate) return optimizer.minimize(loss=loss, var_list=var_list) def build_mixture_weights_train_op(self, loss, var_list, logits, labels, iteration_step, summary): return tf.no_op() @property def name(self): return "simple_cnn" class EstimatorKerasLayersTest(tu.AdanetTestCase): def test_lifecycle(self): """Train entire estimator lifecycle using XOR dataset.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) estimator = Estimator( head=tu.head(), subnetwork_generator=SimpleGenerator( [KerasCNNBuilder(learning_rate=.001)]), max_iteration_steps=3, evaluator=Evaluator( input_fn=tu.dummy_input_fn([[1., 1., .1, .1]], [[0.]]), steps=3), model_dir=self.test_subdirectory, config=run_config) xor_features = [[1., 0., 1., 0.], [0., 0., 0., 0.], [0., 1., 0., 1.], [1., 1., 1., 1.]] xor_labels = [[1.], [0.], [1.], [0.]] train_input_fn = tu.dummy_input_fn(xor_features, xor_labels) # Train. estimator.train(input_fn=train_input_fn, max_steps=9) # Evaluate. eval_results = estimator.evaluate(input_fn=train_input_fn, steps=3) logging.info("%s", eval_results) want_loss = 0.16915826 if tf_compat.version_greater_or_equal("1.10.0"): # After TF v1.10.0 the loss computed from a neural network using Keras # layers changed, however it is not clear why. want_loss = 0.26195815 self.assertAlmostEqual(want_loss, eval_results["loss"], places=3) # Predict. predictions = estimator.predict( input_fn=tu.dataset_input_fn(features=[0., 0., 0., 0.], labels=None)) for prediction in predictions: self.assertIsNotNone(prediction["predictions"]) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") return tf.estimator.export.ServingInputReceiver( features={"x": tf.constant([[0., 0., 0., 0.]], name="serving_x")}, receiver_tensors=serialized_example) export_saved_model_fn = getattr(estimator, "export_saved_model", None) if not callable(export_saved_model_fn): export_saved_model_fn = estimator.export_savedmodel export_saved_model_fn( export_dir_base=self.test_subdirectory, serving_input_receiver_fn=serving_input_fn) class MultiHeadBuilder(Builder): """Builds a subnetwork for AdaNet that uses dict labels.""" def __init__(self, learning_rate=.001, split_logits=False, seed=42): """Initializes a `LabelsDictBuilder`. Args: learning_rate: The float learning rate to use. split_logits: Whether to return a dict of logits or a single concatenated logits `Tensor`. seed: The random seed. Returns: An instance of `MultiHeadBuilder`. """ self._learning_rate = learning_rate self._split_logits = split_logits self._seed = seed def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): """See `adanet.subnetwork.Builder`.""" seed = self._seed if previous_ensemble: seed += len(previous_ensemble.weighted_subnetworks) kernel_initializer = tf_compat.v1.keras.initializers.he_normal(seed=seed) x = features["x"] logits = tf_compat.v1.layers.dense( x, units=logits_dimension, activation=None, kernel_initializer=kernel_initializer) if self._split_logits: # Return different logits, one for each head. logits1, logits2 = tf.split(logits, [1, 1], 1) logits = { "head1": logits1, "head2": logits2, } complexity = tf.constant(1) return Subnetwork( last_layer=logits, logits=logits, complexity=complexity, persisted_tensors={}) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble=None): optimizer = tf_compat.v1.train.GradientDescentOptimizer(self._learning_rate) return optimizer.minimize(loss=loss, var_list=var_list) def build_mixture_weights_train_op(self, loss, var_list, logits, labels, iteration_step, summary): optimizer = tf_compat.v1.train.GradientDescentOptimizer(self._learning_rate) return optimizer.minimize(loss=loss, var_list=var_list) @property def name(self): return "multi_head" class EstimatorMultiHeadTest(tu.AdanetTestCase): @parameterized.named_parameters( { "testcase_name": "concatenated_logits", "builders": [MultiHeadBuilder()], "want_loss": 3.218, }, { "testcase_name": "split_logits_with_export_subnetworks", "builders": [MultiHeadBuilder(split_logits=True)], "want_loss": 3.224, "export_subnetworks": True, }, { "testcase_name": "split_logits", "builders": [MultiHeadBuilder(split_logits=True)], "want_loss": 3.224, }) def test_lifecycle(self, builders, want_loss, export_subnetworks=False): """Train entire estimator lifecycle using XOR dataset.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) xor_features = [[1., 0., 1., 0.], [0., 0., 0., 0.], [0., 1., 0., 1.], [1., 1., 1., 1.]] xor_labels = [[1.], [0.], [1.], [0.]] def train_input_fn(): return { "x": tf.constant(xor_features) }, { "head1": tf.constant(xor_labels), "head2": tf.constant(xor_labels) } estimator = Estimator( head=multi_head_lib.MultiHead(heads=[ regression_head.RegressionHead( name="head1", loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), regression_head.RegressionHead( name="head2", loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), ]), subnetwork_generator=SimpleGenerator(builders), max_iteration_steps=3, evaluator=Evaluator(input_fn=train_input_fn, steps=1), model_dir=self.test_subdirectory, config=run_config, export_subnetwork_logits=export_subnetworks, export_subnetwork_last_layer=export_subnetworks) # Train. estimator.train(input_fn=train_input_fn, max_steps=9) # Evaluate. eval_results = estimator.evaluate(input_fn=train_input_fn, steps=3) self.assertAlmostEqual(want_loss, eval_results["loss"], places=3) # Predict. predictions = estimator.predict( input_fn=tu.dataset_input_fn(features=[0., 0., 0., 0.], labels=None)) for prediction in predictions: self.assertIsNotNone(prediction[("head1", "predictions")]) self.assertIsNotNone(prediction[("head2", "predictions")]) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") return tf.estimator.export.ServingInputReceiver( features={"x": tf.constant([[0., 0., 0., 0.]], name="serving_x")}, receiver_tensors=serialized_example) export_saved_model_fn = getattr(estimator, "export_saved_model", None) if not callable(export_saved_model_fn): export_saved_model_fn = estimator.export_savedmodel export_dir_base = os.path.join(self.test_subdirectory, "export") export_saved_model_fn( export_dir_base=export_dir_base, serving_input_receiver_fn=serving_input_fn) if export_subnetworks: saved_model = saved_model_utils.read_saved_model( os.path.join(export_dir_base, tf.io.gfile.listdir(export_dir_base)[0])) export_signature_def = saved_model.meta_graphs[0].signature_def self.assertIn("subnetwork_logits_head1", export_signature_def.keys()) self.assertIn("subnetwork_logits_head2", export_signature_def.keys()) self.assertIn("subnetwork_last_layer_head1", export_signature_def.keys()) self.assertIn("subnetwork_last_layer_head2", export_signature_def.keys()) class EstimatorCallingModelFnDirectlyTest(tu.AdanetTestCase): """Tests b/112108745. Warn users not to call model_fn directly.""" def test_calling_model_fn_directly(self): subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, max_iteration_steps=3, use_bias=True, model_dir=self.test_subdirectory) model_fn = estimator.model_fn train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) tf_compat.v1.train.create_global_step() features, labels = train_input_fn() with self.assertRaises(UserWarning): model_fn( features=features, mode=tf.estimator.ModeKeys.TRAIN, labels=labels, config={}) def test_calling_model_fn_directly_for_predict(self): with context.graph_mode(): subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, max_iteration_steps=3, use_bias=True, model_dir=self.test_subdirectory) model_fn = estimator.model_fn train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) tf_compat.v1.train.create_global_step() features, labels = train_input_fn() model_fn( features=features, mode=tf.estimator.ModeKeys.PREDICT, labels=labels, config=tf.estimator.RunConfig( save_checkpoints_steps=1, keep_checkpoint_max=3, model_dir=self.test_subdirectory, )) class EstimatorCheckpointTest(tu.AdanetTestCase): """Tests estimator checkpoints.""" @parameterized.named_parameters( { "testcase_name": "single_iteration", "max_iteration_steps": 3, "keep_checkpoint_max": 3, "want_num_checkpoints": 3, }, { "testcase_name": "single_iteration_keep_one", "max_iteration_steps": 3, "keep_checkpoint_max": 1, "want_num_checkpoints": 1, }, { "testcase_name": "three_iterations", "max_iteration_steps": 1, "keep_checkpoint_max": 3, "want_num_checkpoints": 3, }, { "testcase_name": "three_iterations_keep_one", "max_iteration_steps": 1, "keep_checkpoint_max": 1, "want_num_checkpoints": 1, }) def test_checkpoints(self, max_iteration_steps, keep_checkpoint_max, want_num_checkpoints, max_steps=3): config = tf.estimator.RunConfig( save_checkpoints_steps=1, keep_checkpoint_max=keep_checkpoint_max, ) subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=max_iteration_steps, use_bias=True, config=config, model_dir=self.test_subdirectory) train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.train(input_fn=train_input_fn, max_steps=max_steps) checkpoints = tf.io.gfile.glob( os.path.join(self.test_subdirectory, "*.meta")) self.assertEqual(want_num_checkpoints, len(checkpoints)) def _check_eventfile_for_keyword(keyword, dir_): """Checks event files for the keyword.""" tf_compat.v1.summary.FileWriterCache.clear() if not tf.io.gfile.exists(dir_): raise ValueError("Directory '{}' not found.".format(dir_)) # Get last `Event` written. filenames = os.path.join(dir_, "events*") event_paths = tf.io.gfile.glob(filenames) if not event_paths: raise ValueError("Path '{}' not found.".format(filenames)) for last_event in tf_compat.v1.train.summary_iterator(event_paths[-1]): if last_event.summary is not None: for value in last_event.summary.value: if keyword == value.tag: if value.HasField("simple_value"): return value.simple_value if value.HasField("image"): return (value.image.height, value.image.width, value.image.colorspace) if value.HasField("tensor"): return value.tensor.string_val raise ValueError("Keyword '{}' not found in path '{}'.".format( keyword, filenames)) class _FakeMetric(object): """A fake metric.""" def __init__(self, value, dtype): self._value = value self._dtype = dtype def to_metric(self): tensor = tf.convert_to_tensor(value=self._value, dtype=self._dtype) return (tensor, tensor) class _EvalMetricsHead(object): """A fake head with the given evaluation metrics.""" def __init__(self, fake_metrics): self._fake_metrics = fake_metrics @property def logits_dimension(self): return 1 def create_estimator_spec(self, features, mode, logits, labels=None, train_op_fn=None): del features # Unused metric_ops = None if self._fake_metrics: metric_ops = {} for k, fake_metric in self._fake_metrics.items(): metric_ops[k] = fake_metric.to_metric() return tf.estimator.EstimatorSpec( mode=mode, predictions=logits, loss=tf.reduce_mean(input_tensor=labels - logits), eval_metric_ops=metric_ops, train_op=train_op_fn(1)) def _mean_keras_metric(value): """Returns the mean of given value as a Keras metric.""" mean = tf.keras.metrics.Mean() mean.update_state(value) return mean class EstimatorSummaryWriterTest(tu.AdanetTestCase): """Test that Tensorboard summaries get written correctly.""" @tf_compat.skip_for_tf2 def test_summaries(self): """Tests that summaries are written to candidate directory.""" run_config = tf.estimator.RunConfig( tf_random_seed=42, log_step_count_steps=2, save_summary_steps=2) subnetwork_generator = SimpleGenerator( [_DNNBuilder("dnn", mixture_weight_learning_rate=.001)]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=10, use_bias=True, config=run_config, model_dir=self.test_subdirectory) train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.train(input_fn=train_input_fn, max_steps=3) ensemble_loss = 1. self.assertAlmostEqual( ensemble_loss, _check_eventfile_for_keyword("loss", self.test_subdirectory), places=3) self.assertIsNotNone( _check_eventfile_for_keyword("global_step/sec", self.test_subdirectory)) self.assertEqual( 0., _check_eventfile_for_keyword("iteration/adanet/iteration", self.test_subdirectory)) subnetwork_subdir = os.path.join(self.test_subdirectory, "subnetwork/t0_dnn") self.assertAlmostEqual( 3., _check_eventfile_for_keyword("scalar", subnetwork_subdir), places=3) self.assertEqual((3, 3, 1), _check_eventfile_for_keyword("image/image/0", subnetwork_subdir)) self.assertAlmostEqual( 5., _check_eventfile_for_keyword("nested/scalar", subnetwork_subdir), places=3) ensemble_subdir = os.path.join( self.test_subdirectory, "ensemble/t0_dnn_grow_complexity_regularized") self.assertAlmostEqual( ensemble_loss, _check_eventfile_for_keyword( "adanet_loss/adanet/adanet_weighted_ensemble", ensemble_subdir), places=3) self.assertAlmostEqual( 0., _check_eventfile_for_keyword( "complexity_regularization/adanet/adanet_weighted_ensemble", ensemble_subdir), places=3) self.assertAlmostEqual( 0., _check_eventfile_for_keyword( "mixture_weight_norms/adanet/" "adanet_weighted_ensemble/subnetwork_0", ensemble_subdir), places=3) @tf_compat.skip_for_tf2 def test_disable_summaries(self): """Tests that summaries can be disabled for ensembles and subnetworks.""" run_config = tf.estimator.RunConfig( tf_random_seed=42, log_step_count_steps=2, save_summary_steps=2) subnetwork_generator = SimpleGenerator( [_DNNBuilder("dnn", mixture_weight_learning_rate=.001)]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=10, use_bias=True, config=run_config, model_dir=self.test_subdirectory, enable_ensemble_summaries=False, enable_subnetwork_summaries=False, ) train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.train(input_fn=train_input_fn, max_steps=3) ensemble_loss = 1. self.assertAlmostEqual( ensemble_loss, _check_eventfile_for_keyword("loss", self.test_subdirectory), places=3) self.assertIsNotNone( _check_eventfile_for_keyword("global_step/sec", self.test_subdirectory)) self.assertEqual( 0., _check_eventfile_for_keyword("iteration/adanet/iteration", self.test_subdirectory)) subnetwork_subdir = os.path.join(self.test_subdirectory, "subnetwork/t0_dnn") with self.assertRaises(ValueError): _check_eventfile_for_keyword("scalar", subnetwork_subdir) with self.assertRaises(ValueError): _check_eventfile_for_keyword("image/image/0", subnetwork_subdir) with self.assertRaises(ValueError): _check_eventfile_for_keyword("nested/scalar", subnetwork_subdir) ensemble_subdir = os.path.join( self.test_subdirectory, "ensemble/t0_dnn_grow_complexity_regularized") with self.assertRaises(ValueError): _check_eventfile_for_keyword( "adanet_loss/adanet/adanet_weighted_ensemble", ensemble_subdir) with self.assertRaises(ValueError): _check_eventfile_for_keyword( "complexity_regularization/adanet/adanet_weighted_ensemble", ensemble_subdir) with self.assertRaises(ValueError): _check_eventfile_for_keyword( "mixture_weight_norms/adanet/" "adanet_weighted_ensemble/subnetwork_0", ensemble_subdir) # pylint: disable=g-long-lambda @parameterized.named_parameters( { "testcase_name": "none_metrics", "head": _EvalMetricsHead(None), "want_summaries": [], "want_loss": -1.791, }, { "testcase_name": "metrics_fn", "head": _EvalMetricsHead(None), "metric_fn": lambda predictions: { "avg": tf_compat.v1.metrics.mean(predictions) }, "want_summaries": ["avg"], "want_loss": -1.791, }, { "testcase_name": "keras_metrics_fn", "head": _EvalMetricsHead(None), "metric_fn": lambda predictions: { "avg": _mean_keras_metric(predictions) }, "want_summaries": ["avg"], "want_loss": -1.791, }, { "testcase_name": "empty_metrics", "head": _EvalMetricsHead({}), "want_summaries": [], "want_loss": -1.791, }, { "testcase_name": "evaluation_name", "head": _EvalMetricsHead({}), "evaluation_name": "continuous", "want_summaries": [], "want_loss": -1.791, "global_subdir": "eval_continuous", "subnetwork_subdir": "subnetwork/t0_dnn/eval_continuous", "ensemble_subdir": "ensemble/t0_dnn_grow_complexity_regularized/eval_continuous", }, { "testcase_name": "regression_head", "head": regression_head.RegressionHead( loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), "want_summaries": ["average_loss"], "want_loss": .256, }, { "testcase_name": "binary_classification_head", "head": binary_class_head.BinaryClassHead( loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), "learning_rate": .6, "want_summaries": ["average_loss", "accuracy", "recall"], "want_loss": 0.122, }, { "testcase_name": "all_metrics", "head": _EvalMetricsHead({ "float32": _FakeMetric(1., tf.float32), "float64": _FakeMetric(1., tf.float64), "serialized_summary": _FakeMetric( tf_compat.v1.Summary(value=[ tf_compat.v1.Summary.Value( tag="summary_tag", simple_value=1.) ]).SerializeToString(), tf.string), }), "want_summaries": [ "float32", "float64", "serialized_summary/0", ], "want_loss": -1.791, }) # pylint: enable=g-long-lambda def test_eval_metrics( self, head, want_loss, want_summaries, evaluation_name=None, metric_fn=None, learning_rate=.01, global_subdir="eval", subnetwork_subdir="subnetwork/t0_dnn/eval", ensemble_subdir="ensemble/t0_dnn_grow_complexity_regularized/eval"): """Test that AdaNet evaluation metrics get persisted correctly.""" seed = 42 run_config = tf.estimator.RunConfig(tf_random_seed=seed) subnetwork_generator = SimpleGenerator([ _DNNBuilder( "dnn", learning_rate=learning_rate, mixture_weight_learning_rate=0., layer_size=8, seed=seed) ]) estimator = Estimator( head=head, subnetwork_generator=subnetwork_generator, max_iteration_steps=100, metric_fn=metric_fn, config=run_config, model_dir=self.test_subdirectory) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) estimator.train(input_fn=train_input_fn, max_steps=100) metrics = estimator.evaluate( input_fn=train_input_fn, steps=1, name=evaluation_name) self.assertAlmostEqual(want_loss, metrics["loss"], places=3) global_subdir = os.path.join(self.test_subdirectory, global_subdir) subnetwork_subdir = os.path.join(self.test_subdirectory, subnetwork_subdir) ensemble_subdir = os.path.join(self.test_subdirectory, ensemble_subdir) self.assertAlmostEqual( want_loss, _check_eventfile_for_keyword("loss", subnetwork_subdir), places=3) for metric in want_summaries: self.assertIsNotNone( _check_eventfile_for_keyword(metric, subnetwork_subdir), msg="{} should be under 'eval'.".format(metric)) for dir_ in [global_subdir, ensemble_subdir]: self.assertAlmostEqual(metrics["loss"], _check_eventfile_for_keyword("loss", dir_)) self.assertEqual([b"| dnn |"], _check_eventfile_for_keyword( "architecture/adanet/ensembles/0", dir_)) for metric in want_summaries: self.assertTrue( _check_eventfile_for_keyword(metric, dir_) > 0., msg="{} should be under 'eval'.".format(metric)) class EstimatorMembersOverrideTest(tu.AdanetTestCase): """Tests b/77494544 fix.""" def test_assert_members_are_not_overridden(self): """Assert that AdaNet estimator does not break other estimators.""" config = tf.estimator.RunConfig() subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) adanet = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=10, use_bias=True, config=config) self.assertIsNotNone(adanet) if hasattr(tf.estimator, "LinearEstimator"): estimator_fn = tf.estimator.LinearEstimator else: estimator_fn = tf.contrib.estimator.LinearEstimator linear = estimator_fn( head=tu.head(), feature_columns=[tf.feature_column.numeric_column("x")]) self.assertIsNotNone(linear) def _dummy_feature_dict_input_fn(features, labels): """Returns an input_fn that returns feature and labels `Tensors`.""" def _input_fn(): input_features = {} for key, feature in features.items(): input_features[key] = tf.constant(feature, name=key) input_labels = tf.constant(labels, name="labels") return input_features, input_labels return _input_fn class EstimatorDifferentFeaturesPerModeTest(tu.AdanetTestCase): """Tests b/109751254.""" @parameterized.named_parameters( { "testcase_name": "extra_train_features", "train_features": { "x": [[1., 0.]], "extra": [[1., 0.]], }, "eval_features": { "x": [[1., 0.]], }, "predict_features": { "x": [[1., 0.]], }, }, { "testcase_name": "extra_eval_features", "train_features": { "x": [[1., 0.]], }, "eval_features": { "x": [[1., 0.]], "extra": [[1., 0.]], }, "predict_features": { "x": [[1., 0.]], }, }, { "testcase_name": "extra_predict_features", "train_features": { "x": [[1., 0.]], }, "eval_features": { "x": [[1., 0.]], }, "predict_features": { "x": [[1., 0.]], "extra": [[1., 0.]], }, }) def test_different_features_per_mode(self, train_features, eval_features, predict_features): """Tests tests different numbers of features per mode.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=1, use_bias=True, model_dir=self.test_subdirectory, config=run_config) labels = [[1.]] train_input_fn = _dummy_feature_dict_input_fn(train_features, labels) # Train. estimator.train(input_fn=train_input_fn, max_steps=2) # Evaluate. eval_input_fn = _dummy_feature_dict_input_fn(eval_features, labels) estimator.evaluate(input_fn=eval_input_fn, steps=1) # Predict. predict_input_fn = _dummy_feature_dict_input_fn(predict_features, None) estimator.predict(input_fn=predict_input_fn) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") features = {} for key, value in predict_features.items(): features[key] = tf.constant(value) return tf.estimator.export.ServingInputReceiver( features=features, receiver_tensors=serialized_example) export_saved_model_fn = getattr(estimator, "export_saved_model", None) if not callable(export_saved_model_fn): export_saved_model_fn = estimator.export_savedmodel export_saved_model_fn( export_dir_base=self.test_subdirectory, serving_input_receiver_fn=serving_input_fn) class EstimatorExportSavedModelTest(tu.AdanetTestCase): def test_export_saved_model_for_predict(self): """Tests SavedModel exporting functionality for predict (b/110435640).""" run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=1, use_bias=True, model_dir=self.test_subdirectory, config=run_config) features = {"x": [[1., 0.]]} labels = [[1.]] train_input_fn = _dummy_feature_dict_input_fn(features, labels) # Train. estimator.train(input_fn=train_input_fn, max_steps=2) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") for key, value in features.items(): features[key] = tf.constant(value) return tf.estimator.export.ServingInputReceiver( features=features, receiver_tensors=serialized_example) estimator.export_saved_model( export_dir_base=self.test_subdirectory, serving_input_receiver_fn=serving_input_fn, experimental_mode=tf.estimator.ModeKeys.PREDICT) @test_util.run_in_graph_and_eager_modes def test_export_saved_model_for_eval(self): """Tests SavedModel exporting functionality for eval (b/110991908).""" run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator( [_DNNBuilder("dnn", layer_size=8, learning_rate=1.)]) estimator = Estimator( head=binary_class_head.BinaryClassHead(), subnetwork_generator=subnetwork_generator, max_iteration_steps=100, model_dir=self.test_subdirectory, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) # Train. estimator.train(input_fn=train_input_fn, max_steps=300) metrics = estimator.evaluate(input_fn=train_input_fn, steps=1) self.assertAlmostEqual(.067, metrics["average_loss"], places=3) self.assertAlmostEqual(1., metrics["recall"], places=3) self.assertAlmostEqual(1., metrics["accuracy"], places=3) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") return export.SupervisedInputReceiver( features={"x": tf.constant(XOR_FEATURES)}, labels=tf.constant(XOR_LABELS), receiver_tensors=serialized_example) export_dir_base = os.path.join(self.test_subdirectory, "export") try: estimator.export_saved_model( export_dir_base=export_dir_base, serving_input_receiver_fn=serving_input_fn, experimental_mode=tf.estimator.ModeKeys.EVAL) except AttributeError: pass try: tf.contrib.estimator.export_saved_model_for_mode( estimator, export_dir_base=export_dir_base, input_receiver_fn=serving_input_fn, mode=tf.estimator.ModeKeys.EVAL) except AttributeError: pass subdir = tf.io.gfile.listdir(export_dir_base)[0] with context.graph_mode(), self.test_session() as sess: meta_graph_def = tf_compat.v1.saved_model.loader.load( sess, ["eval"], os.path.join(export_dir_base, subdir)) signature_def = meta_graph_def.signature_def.get("eval") # Read zero metric. self.assertAlmostEqual( 0., sess.run( tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/average_loss/value"])), places=3) # Run metric update op. sess.run((tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/average_loss/update_op"]), tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/accuracy/update_op"]), tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/recall/update_op"]))) # Read metric again; it should no longer be zero. self.assertAlmostEqual( 0.067, sess.run( tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/average_loss/value"])), places=3) self.assertAlmostEqual( 1., sess.run( tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/recall/value"])), places=3) self.assertAlmostEqual( 1., sess.run( tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info( signature_def.outputs["metrics/accuracy/value"])), places=3) def test_export_saved_model_always_uses_replication_placement(self): """Tests b/137675014.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator( [_DNNBuilder("dnn1"), _DNNBuilder("dnn2")]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=1, model_dir=self.test_subdirectory, config=run_config, experimental_placement_strategy=RoundRobinStrategy()) features = {"x": [[1., 0.]]} labels = [[1.]] train_input_fn = _dummy_feature_dict_input_fn(features, labels) # Train. estimator.train(input_fn=train_input_fn, max_steps=2) # Export SavedModel. def serving_input_fn(): """Input fn for serving export, starting from serialized example.""" serialized_example = tf_compat.v1.placeholder( dtype=tf.string, shape=(None), name="serialized_example") tensor_features = {} for key, value in features.items(): tensor_features[key] = tf.constant(value) return tf.estimator.export.ServingInputReceiver( features=tensor_features, receiver_tensors=serialized_example) # Fake the number of PS replicas so RoundRobinStrategy will be used. estimator._config._num_ps_replicas = 2 # If we're still using RoundRobinStrategy, this call will fail by trying # to place ops on non-existent devices. # Check all three export methods. estimator.export_saved_model( export_dir_base=self.test_subdirectory, serving_input_receiver_fn=serving_input_fn, experimental_mode=tf.estimator.ModeKeys.PREDICT) try: estimator.export_savedmodel( export_dir_base=self.test_subdirectory, serving_input_receiver_fn=serving_input_fn) except AttributeError as error: # Log deprecation errors. logging.warning("Testing estimator#export_savedmodel: %s", error) estimator.experimental_export_all_saved_models( export_dir_base=self.test_subdirectory, input_receiver_fn_map={ tf.estimator.ModeKeys.PREDICT: serving_input_fn, }) class EstimatorReportTest(tu.AdanetTestCase): """Tests report generation and usage.""" def compare_report_lists(self, report_list1, report_list2): # Essentially assertEqual(report_list1, report_list2), but ignoring # the "metrics" attribute. def make_qualified_name(iteration_number, name): return "iteration_{}/{}".format(iteration_number, name) report_dict_1 = { make_qualified_name(report.iteration_number, report.name): report for report in report_list1 } report_dict_2 = { make_qualified_name(report.iteration_number, report.name): report for report in report_list2 } self.assertEqual(len(report_list1), len(report_list2)) for qualified_name in report_dict_1.keys(): report_1 = report_dict_1[qualified_name] report_2 = report_dict_2[qualified_name] self.assertEqual( report_1.hparams, report_2.hparams, msg="{} vs. {}".format(report_1, report_2)) self.assertEqual( report_1.attributes, report_2.attributes, msg="{} vs. {}".format(report_1, report_2)) self.assertEqual( report_1.included_in_final_ensemble, report_2.included_in_final_ensemble, msg="{} vs. {}".format(report_1, report_2)) for metric_key, metric_value in report_1.metrics.items(): self.assertEqual( metric_value, report_2.metrics[metric_key], msg="{} vs. {}".format(report_1, report_2)) @parameterized.named_parameters( { "testcase_name": "one_iteration_one_subnetwork", "subnetwork_builders": [_DNNBuilder("dnn", layer_size=1),], "num_iterations": 1, "want_materialized_iteration_reports": [[ MaterializedReport( iteration_number=0, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ]], "want_previous_ensemble_reports": [], "want_all_reports": [], }, { "testcase_name": "one_iteration_three_subnetworks", "subnetwork_builders": [ # learning_rate is set to 0 for all but one Builder # to make sure that only one of them can learn. _DNNBuilder( "dnn_1", layer_size=1, learning_rate=0., mixture_weight_learning_rate=0.), _DNNBuilder( "dnn_2", layer_size=2, learning_rate=0., mixture_weight_learning_rate=0.), # fixing the match for dnn_3 to win. _DNNBuilder("dnn_3", layer_size=3), ], "num_iterations": 1, "want_materialized_iteration_reports": [[ MaterializedReport( iteration_number=0, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ]], "want_previous_ensemble_reports": [], "want_all_reports": [], }, { "testcase_name": "three_iterations_one_subnetwork", "subnetwork_builders": [_DNNBuilder("dnn", layer_size=1),], "num_iterations": 3, "want_materialized_iteration_reports": [ [ MaterializedReport( iteration_number=0, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ) ], [ MaterializedReport( iteration_number=1, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], [ MaterializedReport( iteration_number=2, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=2, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], ], "want_previous_ensemble_reports": [ MaterializedReport( iteration_number=0, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), MaterializedReport( iteration_number=1, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], "want_all_reports": [ MaterializedReport( iteration_number=0, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), MaterializedReport( iteration_number=1, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], }, { "testcase_name": "three_iterations_three_subnetworks", "subnetwork_builders": [ # learning_rate is set to 0 for all but one Builder # to make sure that only one of them can learn. _DNNBuilder( "dnn_1", layer_size=1, learning_rate=0., mixture_weight_learning_rate=0.), _DNNBuilder( "dnn_2", layer_size=2, learning_rate=0., mixture_weight_learning_rate=0.), # fixing the match for dnn_3 to win in every iteration. _DNNBuilder("dnn_3", layer_size=3), ], "num_iterations": 3, "want_materialized_iteration_reports": [ [ MaterializedReport( iteration_number=0, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], [ MaterializedReport( iteration_number=1, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], [ MaterializedReport( iteration_number=2, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=2, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=2, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=2, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], ], "want_previous_ensemble_reports": [ MaterializedReport( iteration_number=0, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), MaterializedReport( iteration_number=1, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], "want_all_reports": [ MaterializedReport( iteration_number=0, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=0, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), MaterializedReport( iteration_number=1, name="previous_ensemble", hparams={}, attributes={}, metrics={}, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_1", hparams={"layer_size": 1}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_2", hparams={"layer_size": 2}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=False, ), MaterializedReport( iteration_number=1, name="dnn_3", hparams={"layer_size": 3}, attributes={ "complexity": 3, }, metrics={ "moo": 3, }, included_in_final_ensemble=True, ), ], }, ) def test_report_generation_and_usage(self, subnetwork_builders, num_iterations, want_materialized_iteration_reports, want_previous_ensemble_reports, want_all_reports): # Stores the iteration_number, previous_ensemble_reports and all_reports # arguments in the self._iteration_reports dictionary, overwriting what # was seen in previous iterations. spied_iteration_reports = {} def _spy_fn(iteration_number, previous_ensemble_reports, all_reports): spied_iteration_reports[iteration_number] = { "previous_ensemble_reports": previous_ensemble_reports, "all_reports": all_reports, } subnetwork_generator = _FakeGenerator( spy_fn=_spy_fn, subnetwork_builders=subnetwork_builders) max_iteration_steps = 5 max_steps = max_iteration_steps * num_iterations + 1 train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, mixture_weight_type=MixtureWeightType.MATRIX, mixture_weight_initializer=tf_compat.v1.zeros_initializer(), warm_start_mixture_weights=True, max_iteration_steps=max_iteration_steps, use_bias=True, report_materializer=ReportMaterializer( input_fn=train_input_fn, steps=1), model_dir=self.test_subdirectory) report_accessor = estimator._report_accessor estimator.train(input_fn=train_input_fn, max_steps=max_steps) materialized_iteration_reports = list( report_accessor.read_iteration_reports()) self.assertEqual(num_iterations, len(materialized_iteration_reports)) for i in range(num_iterations): want_materialized_reports = (want_materialized_iteration_reports[i]) materialized_reports = materialized_iteration_reports[i] self.compare_report_lists(want_materialized_reports, materialized_reports) # Compute argmin adanet loss. argmin_adanet_loss = 0 smallest_known_adanet_loss = float("inf") for j, materialized_subnetwork_report in enumerate(materialized_reports): if (smallest_known_adanet_loss > materialized_subnetwork_report.metrics["adanet_loss"]): smallest_known_adanet_loss = ( materialized_subnetwork_report.metrics["adanet_loss"]) argmin_adanet_loss = j # Check that the subnetwork with the lowest adanet loss is the one # that is included in the final ensemble. for j, materialized_reports in enumerate(materialized_reports): self.assertEqual(j == argmin_adanet_loss, materialized_reports.included_in_final_ensemble) # Check the arguments passed into the generate_candidates method of the # Generator. iteration_report = spied_iteration_reports[num_iterations - 1] self.compare_report_lists(want_previous_ensemble_reports, iteration_report["previous_ensemble_reports"]) self.compare_report_lists(want_all_reports, iteration_report["all_reports"]) class EstimatorForceGrowTest(tu.AdanetTestCase): """Tests the force_grow override. Uses linear subnetworks with the same seed. They will produce identical outputs, so unless the `force_grow` override is set, none of the new subnetworks will improve the AdaNet objective, and AdaNet will not add them to the ensemble. """ @parameterized.named_parameters( { "testcase_name": "one_builder_no_force_grow", "builders": [_LinearBuilder("linear", mixture_weight_learning_rate=0.)], "force_grow": False, "want_subnetworks": 1, }, { "testcase_name": "one_builder", "builders": [_LinearBuilder("linear", mixture_weight_learning_rate=0.)], "force_grow": True, "want_subnetworks": 2, }, { "testcase_name": "two_builders", "builders": [ _LinearBuilder("linear", mixture_weight_learning_rate=0.), _LinearBuilder("linear2", mixture_weight_learning_rate=0.) ], "force_grow": True, "want_subnetworks": 2, }, { "testcase_name": "two_builders_with_evaluator", "builders": [ _LinearBuilder("linear", mixture_weight_learning_rate=0.), _LinearBuilder("linear2", mixture_weight_learning_rate=0.) ], "force_grow": True, "evaluator": Evaluator( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1), "want_subnetworks": 3, }) def test_force_grow(self, builders, force_grow, want_subnetworks, evaluator=None): """Train entire estimator lifecycle using XOR dataset.""" run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator(builders) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=1, evaluator=evaluator, force_grow=force_grow, model_dir=self.test_subdirectory, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) # Train for four iterations. estimator.train(input_fn=train_input_fn, max_steps=3) # Evaluate. eval_results = estimator.evaluate(input_fn=train_input_fn, steps=1) self.assertEqual( want_subnetworks, str(eval_results["architecture/adanet/ensembles"]).count(" linear ")) class EstimatorDebugTest(tu.AdanetTestCase): """Tests b/125483534. Detect NaNs in input_fns.""" # pylint: disable=g-long-lambda @parameterized.named_parameters( { "testcase_name": "nan_features", "head": regression_head.RegressionHead( name="y", loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), "input_fn": lambda: ({ "x": tf.math.log([[1., 0.]]) }, tf.zeros([1, 1])) }, { "testcase_name": "nan_label", "head": regression_head.RegressionHead( name="y", loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), "input_fn": lambda: ({ "x": tf.ones([1, 2]) }, tf.math.log([[0.]])) }, { "testcase_name": "nan_labels_dict", "head": multi_head_lib.MultiHead(heads=[ regression_head.RegressionHead( name="y", loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), ]), "input_fn": lambda: ({ "x": tf.ones([1, 2]) }, { "y": tf.math.log([[0.]]) }) }) # pylint: enable=g-long-lambda def test_nans_from_input_fn(self, head, input_fn): subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) estimator = Estimator( head=head, subnetwork_generator=subnetwork_generator, max_iteration_steps=3, model_dir=self.test_subdirectory, debug=True) with self.assertRaises(tf.errors.InvalidArgumentError): estimator.train(input_fn=input_fn, max_steps=3) class EstimatorEvaluateDuringTrainHookTest(tu.AdanetTestCase): """Tests b/129000842 with a hook that calls estimator.evaluate().""" def test_train(self): run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=1, model_dir=self.test_subdirectory, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) class EvalTrainHook(tf.estimator.SessionRunHook): def end(self, session): estimator.evaluate(input_fn=train_input_fn, steps=1) # This should not infinite loop. estimator.train( input_fn=train_input_fn, max_steps=3, hooks=[EvalTrainHook()]) class CheckpointSaverHookDuringTrainingTest(tu.AdanetTestCase): """Tests b/139057887.""" def test_checkpoint_saver_hooks_not_decorated_during_training(self): run_config = tf.estimator.RunConfig(tf_random_seed=42) subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=1, model_dir=self.test_subdirectory, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) saver_hook = tf_compat.v1.train.CheckpointSaverHook( checkpoint_dir=self.test_subdirectory, save_steps=10) listener = tf_compat.v1.train.CheckpointSaverListener() estimator.train( input_fn=train_input_fn, max_steps=3, hooks=[saver_hook], saving_listeners=[listener]) # If CheckpointSaverHook was not recognized during training then all # saving_listeners would be attached to a default CheckpointSaverHook that # Estimator creates. self.assertLen(saver_hook._listeners, 1) self.assertIs(saver_hook._listeners[0], listener) class EstimatorTFLearnRunConfigTest(tu.AdanetTestCase): """Tests b/129483642 for tf.contrib.learn.RunConfig. Checks that TF_CONFIG is overwritten correctly when no cluster is specified in the RunConfig and the only task is of type chief. """ def test_train(self): try: run_config = tf.contrib.learn.RunConfig(tf_random_seed=42) # Removed in TF 1.15 (nightly). See # https://travis-ci.org/tensorflow/adanet/jobs/583471908 _ = run_config._session_creation_timeout_secs except AttributeError: self.skipTest("There is no tf.contrib in TF 2.0.") try: tf_config = { "task": { "type": "chief", "index": 0 }, } os.environ["TF_CONFIG"] = json.dumps(tf_config) run_config = tf.contrib.learn.RunConfig(tf_random_seed=42) run_config._is_chief = True # pylint: disable=protected-access subnetwork_generator = SimpleGenerator([_DNNBuilder("dnn")]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=1, model_dir=self.test_subdirectory, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) # Will fail if TF_CONFIG is not overwritten correctly in # Estimator#prepare_next_iteration. estimator.train(input_fn=train_input_fn, max_steps=3) finally: # Revert TF_CONFIG environment variable in order to not break other tests. del os.environ["TF_CONFIG"] class EstimatorReplayTest(tu.AdanetTestCase): @parameterized.named_parameters( { "testcase_name": "no_evaluator", "evaluator": None, "replay_evaluator": None, "want_architecture": " dnn3 | dnn3 | dnn ", }, { "testcase_name": "evaluator", "evaluator": Evaluator( input_fn=tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS), steps=1), "replay_evaluator": Evaluator( input_fn=tu.dummy_input_fn([[0., 0.], [0., 0], [0., 0.], [0., 0.]], [[0], [0], [0], [0]]), steps=1), "want_architecture": " dnn3 | dnn3 | dnn ", }) def test_replay(self, evaluator, replay_evaluator, want_architecture): """Train entire estimator lifecycle using Replay.""" original_model_dir = os.path.join(self.test_subdirectory, "original") run_config = tf.estimator.RunConfig( tf_random_seed=42, model_dir=original_model_dir) subnetwork_generator = SimpleGenerator([ _DNNBuilder("dnn"), _DNNBuilder("dnn2", layer_size=3), _DNNBuilder("dnn3", layer_size=5), ]) estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=10, evaluator=evaluator, config=run_config) train_input_fn = tu.dummy_input_fn(XOR_FEATURES, XOR_LABELS) # Train for three iterations. estimator.train(input_fn=train_input_fn, max_steps=30) # Evaluate. eval_results = estimator.evaluate(input_fn=train_input_fn, steps=1) self.assertIn(want_architecture, str(eval_results["architecture/adanet/ensembles"])) replay_run_config = tf.estimator.RunConfig( tf_random_seed=42, model_dir=os.path.join(self.test_subdirectory, "replayed")) # Use different features and labels to represent a shift in the data # distribution. different_features = [[0., 0.], [0., 0], [0., 0.], [0., 0.]] different_labels = [[0], [0], [0], [0]] replay_estimator = Estimator( head=tu.head(), subnetwork_generator=subnetwork_generator, max_iteration_steps=10, evaluator=replay_evaluator, config=replay_run_config, replay_config=replay.Config(best_ensemble_indices=[2, 3, 1])) train_input_fn = tu.dummy_input_fn(different_features, different_labels) # Train for three iterations. replay_estimator.train(input_fn=train_input_fn, max_steps=30) # Evaluate. eval_results = replay_estimator.evaluate(input_fn=train_input_fn, steps=1) self.assertIn(want_architecture, str(eval_results["architecture/adanet/ensembles"])) if __name__ == "__main__": tf.test.main()
[((60, 0, 60, 35), 'absl.logging.set_verbosity', 'logging.set_verbosity', ({(60, 22, 60, 34): 'logging.INFO'}, {}), '(logging.INFO)', False, 'from absl import logging\n'), ((1654, 3, 1675, 8), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', ({(1655, 6, 1660, 7): "{'testcase_name': 'single_iteration', 'max_iteration_steps': 3,\n 'keep_checkpoint_max': 3, 'want_num_checkpoints': 3}", (1660, 9, 1665, 7): "{'testcase_name': 'single_iteration_keep_one', 'max_iteration_steps': 3,\n 'keep_checkpoint_max': 1, 'want_num_checkpoints': 1}", (1665, 9, 1670, 7): "{'testcase_name': 'three_iterations', 'max_iteration_steps': 1,\n 'keep_checkpoint_max': 3, 'want_num_checkpoints': 3}", (1670, 9, 1675, 7): "{'testcase_name': 'three_iterations_keep_one', 'max_iteration_steps': 1,\n 'keep_checkpoint_max': 1, 'want_num_checkpoints': 1}"}, {}), "({'testcase_name': 'single_iteration',\n 'max_iteration_steps': 3, 'keep_checkpoint_max': 3,\n 'want_num_checkpoints': 3}, {'testcase_name':\n 'single_iteration_keep_one', 'max_iteration_steps': 3,\n 'keep_checkpoint_max': 1, 'want_num_checkpoints': 1}, {'testcase_name':\n 'three_iterations', 'max_iteration_steps': 1, 'keep_checkpoint_max': 3,\n 'want_num_checkpoints': 3}, {'testcase_name':\n 'three_iterations_keep_one', 'max_iteration_steps': 1,\n 'keep_checkpoint_max': 1, 'want_num_checkpoints': 1})", False, 'from absl.testing import parameterized\n'), ((1710, 2, 1710, 46), 'adanet.tf_compat.v1.summary.FileWriterCache.clear', 'tf_compat.v1.summary.FileWriterCache.clear', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1716, 14, 1716, 43), 'os.path.join', 'os.path.join', ({(1716, 27, 1716, 31): 'dir_', (1716, 33, 1716, 42): '"""events*"""'}, {}), "(dir_, 'events*')", False, 'import os\n'), ((1717, 16, 1717, 43), 'tensorflow.io.gfile.glob', 'tf.io.gfile.glob', ({(1717, 33, 1717, 42): 'filenames'}, {}), '(filenames)', True, 'import tensorflow as tf\n'), ((1721, 20, 1721, 72), 'adanet.tf_compat.v1.train.summary_iterator', 'tf_compat.v1.train.summary_iterator', ({(1721, 56, 1721, 71): 'event_paths[-1]'}, {}), '(event_paths[-1])', False, 'from adanet import tf_compat\n'), ((1783, 9, 1783, 32), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((2124, 3, 2161, 8), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', ({(2125, 6, 2137, 7): "{'testcase_name': 'extra_train_features', 'train_features': {'x': [[1.0, \n 0.0]], 'extra': [[1.0, 0.0]]}, 'eval_features': {'x': [[1.0, 0.0]]},\n 'predict_features': {'x': [[1.0, 0.0]]}}", (2137, 9, 2149, 7): "{'testcase_name': 'extra_eval_features', 'train_features': {'x': [[1.0, 0.0\n ]]}, 'eval_features': {'x': [[1.0, 0.0]], 'extra': [[1.0, 0.0]]},\n 'predict_features': {'x': [[1.0, 0.0]]}}", (2149, 9, 2161, 7): "{'testcase_name': 'extra_predict_features', 'train_features': {'x': [[1.0, \n 0.0]]}, 'eval_features': {'x': [[1.0, 0.0]]}, 'predict_features': {'x':\n [[1.0, 0.0]], 'extra': [[1.0, 0.0]]}}"}, {}), "({'testcase_name': 'extra_train_features',\n 'train_features': {'x': [[1.0, 0.0]], 'extra': [[1.0, 0.0]]},\n 'eval_features': {'x': [[1.0, 0.0]]}, 'predict_features': {'x': [[1.0, \n 0.0]]}}, {'testcase_name': 'extra_eval_features', 'train_features': {\n 'x': [[1.0, 0.0]]}, 'eval_features': {'x': [[1.0, 0.0]], 'extra': [[1.0,\n 0.0]]}, 'predict_features': {'x': [[1.0, 0.0]]}}, {'testcase_name':\n 'extra_predict_features', 'train_features': {'x': [[1.0, 0.0]]},\n 'eval_features': {'x': [[1.0, 0.0]]}, 'predict_features': {'x': [[1.0, \n 0.0]], 'extra': [[1.0, 0.0]]}})", False, 'from absl.testing import parameterized\n'), ((3303, 2, 3303, 16), 'tensorflow.test.main', 'tf.test.main', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((146, 11, 151, 33), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((155, 16, 156, 42), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((160, 11, 161, 46), 'adanet.subnetwork.TrainOpSpec', 'TrainOpSpec', ({(160, 23, 160, 31): 'train_op', (160, 33, 160, 61): 'self._subnetwork_chief_hooks', (161, 23, 161, 45): 'self._subnetwork_hooks'}, {}), '(train_op, self._subnetwork_chief_hooks, self._subnetwork_hooks)', False, 'from adanet.subnetwork import TrainOpSpec\n'), ((165, 16, 166, 57), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((170, 11, 171, 50), 'adanet.subnetwork.TrainOpSpec', 'TrainOpSpec', ({(170, 23, 170, 31): 'train_op', (170, 33, 170, 65): 'self._mixture_weight_chief_hooks', (171, 23, 171, 49): 'self._mixture_weight_hooks'}, {}), '(train_op, self._mixture_weight_chief_hooks, self.\n _mixture_weight_hooks)', False, 'from adanet.subnetwork import TrainOpSpec\n'), ((218, 11, 223, 5), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((227, 16, 227, 79), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((232, 16, 232, 79), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((255, 11, 255, 69), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((259, 11, 259, 21), 'tensorflow.no_op', 'tf.no_op', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((288, 11, 293, 5), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((297, 16, 297, 79), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((302, 16, 303, 57), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', (), '', False, 'from adanet import tf_compat\n'), ((1040, 17, 1040, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1082, 4, 1082, 36), 'absl.logging.info', 'logging.info', ({(1082, 17, 1082, 21): '"""%s"""', (1082, 23, 1082, 35): 'eval_results'}, {}), "('%s', eval_results)", False, 'from absl import logging\n'), ((1105, 22, 1105, 68), 'os.path.join', 'os.path.join', ({(1105, 35, 1105, 57): 'self.test_subdirectory', (1105, 59, 1105, 67): '"""export"""'}, {}), "(self.test_subdirectory, 'export')", False, 'import os\n'), ((1163, 26, 1163, 78), 'adanet.core.report_materializer.ReportMaterializer', 'ReportMaterializer', (), '', False, 'from adanet.core.report_materializer import ReportMaterializer\n'), ((1301, 20, 1301, 57), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1301, 38, 1301, 48): '[[1.0, 0.0]]', (1301, 50, 1301, 56): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1334, 13, 1334, 46), 'tensorflow.reshape', 'tf.reshape', ({(1334, 24, 1334, 30): 'images', (1334, 32, 1334, 45): '[-1, 2, 2, 1]'}, {}), '(images, [-1, 2, 2, 1])', True, 'import tensorflow as tf\n'), ((1335, 25, 1335, 77), 'adanet.tf_compat.v1.keras.initializers.he_normal', 'tf_compat.v1.keras.initializers.he_normal', (), '', False, 'from adanet import tf_compat\n'), ((1351, 17, 1351, 31), 'tensorflow.constant', 'tf.constant', ({(1351, 29, 1351, 30): '1'}, {}), '(1)', True, 'import tensorflow as tf\n'), ((1352, 11, 1356, 29), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((1366, 16, 1366, 80), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', ({(1366, 60, 1366, 79): 'self._learning_rate'}, {}), '(self._learning_rate)', False, 'from adanet import tf_compat\n'), ((1371, 11, 1371, 21), 'tensorflow.no_op', 'tf.no_op', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((1383, 17, 1383, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1397, 21, 1397, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1397, 39, 1397, 51): 'xor_features', (1397, 53, 1397, 63): 'xor_labels'}, {}), '(xor_features, xor_labels)', True, 'from adanet.core import testing_utils as tu\n'), ((1404, 4, 1404, 36), 'absl.logging.info', 'logging.info', ({(1404, 17, 1404, 21): '"""%s"""', (1404, 23, 1404, 35): 'eval_results'}, {}), "('%s', eval_results)", False, 'from absl import logging\n'), ((1406, 7, 1406, 51), 'adanet.tf_compat.version_greater_or_equal', 'tf_compat.version_greater_or_equal', ({(1406, 42, 1406, 50): '"""1.10.0"""'}, {}), "('1.10.0')", False, 'from adanet import tf_compat\n'), ((1466, 25, 1466, 77), 'adanet.tf_compat.v1.keras.initializers.he_normal', 'tf_compat.v1.keras.initializers.he_normal', (), '', False, 'from adanet import tf_compat\n'), ((1468, 13, 1472, 46), 'adanet.tf_compat.v1.layers.dense', 'tf_compat.v1.layers.dense', (), '', False, 'from adanet import tf_compat\n'), ((1481, 17, 1481, 31), 'tensorflow.constant', 'tf.constant', ({(1481, 29, 1481, 30): '1'}, {}), '(1)', True, 'import tensorflow as tf\n'), ((1482, 11, 1486, 29), 'adanet.subnetwork.Subnetwork', 'Subnetwork', (), '', False, 'from adanet.subnetwork import Subnetwork\n'), ((1496, 16, 1496, 80), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', ({(1496, 60, 1496, 79): 'self._learning_rate'}, {}), '(self._learning_rate)', False, 'from adanet import tf_compat\n'), ((1501, 16, 1501, 80), 'adanet.tf_compat.v1.train.GradientDescentOptimizer', 'tf_compat.v1.train.GradientDescentOptimizer', ({(1501, 60, 1501, 79): 'self._learning_rate'}, {}), '(self._learning_rate)', False, 'from adanet import tf_compat\n'), ((1529, 17, 1529, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1584, 22, 1584, 68), 'os.path.join', 'os.path.join', ({(1584, 35, 1584, 57): 'self.test_subdirectory', (1584, 59, 1584, 67): '"""export"""'}, {}), "(self.test_subdirectory, 'export')", False, 'import os\n'), ((1614, 21, 1614, 58), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1614, 39, 1614, 49): '[[1.0, 0.0]]', (1614, 51, 1614, 57): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1615, 4, 1615, 43), 'adanet.tf_compat.v1.train.create_global_step', 'tf_compat.v1.train.create_global_step', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1681, 13, 1684, 5), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1699, 21, 1699, 58), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1699, 39, 1699, 49): '[[1.0, 0.0]]', (1699, 51, 1699, 57): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1712, 9, 1712, 33), 'tensorflow.io.gfile.exists', 'tf.io.gfile.exists', ({(1712, 28, 1712, 32): 'dir_'}, {}), '(dir_)', True, 'import tensorflow as tf\n'), ((1745, 13, 1745, 71), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (), '', True, 'import tensorflow as tf\n'), ((1795, 17, 1796, 72), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1812, 21, 1812, 58), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1812, 39, 1812, 49): '[[1.0, 0.0]]', (1812, 51, 1812, 57): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1827, 24, 1828, 57), 'os.path.join', 'os.path.join', ({(1827, 37, 1827, 59): 'self.test_subdirectory', (1828, 37, 1828, 56): '"""subnetwork/t0_dnn"""'}, {}), "(self.test_subdirectory, 'subnetwork/t0_dnn')", False, 'import os\n'), ((1839, 22, 1840, 78), 'os.path.join', 'os.path.join', ({(1840, 8, 1840, 30): 'self.test_subdirectory', (1840, 32, 1840, 77): '"""ensemble/t0_dnn_grow_complexity_regularized"""'}, {}), "(self.test_subdirectory,\n 'ensemble/t0_dnn_grow_complexity_regularized')", False, 'import os\n'), ((1863, 17, 1864, 72), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1883, 21, 1883, 58), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1883, 39, 1883, 49): '[[1.0, 0.0]]', (1883, 51, 1883, 57): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1898, 24, 1899, 57), 'os.path.join', 'os.path.join', ({(1898, 37, 1898, 59): 'self.test_subdirectory', (1899, 37, 1899, 56): '"""subnetwork/t0_dnn"""'}, {}), "(self.test_subdirectory, 'subnetwork/t0_dnn')", False, 'import os\n'), ((1907, 22, 1908, 78), 'os.path.join', 'os.path.join', ({(1908, 8, 1908, 30): 'self.test_subdirectory', (1908, 32, 1908, 77): '"""ensemble/t0_dnn_grow_complexity_regularized"""'}, {}), "(self.test_subdirectory,\n 'ensemble/t0_dnn_grow_complexity_regularized')", False, 'import os\n'), ((2032, 17, 2032, 60), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((2041, 16, 2047, 41), 'adanet.core.estimator.Estimator', 'Estimator', (), '', False, 'from adanet.core.estimator import Estimator\n'), ((2048, 21, 2048, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2048, 39, 2048, 51): 'XOR_FEATURES', (2048, 53, 2048, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((2055, 20, 2055, 71), 'os.path.join', 'os.path.join', ({(2055, 33, 2055, 55): 'self.test_subdirectory', (2055, 57, 2055, 70): 'global_subdir'}, {}), '(self.test_subdirectory, global_subdir)', False, 'import os\n'), ((2056, 24, 2056, 79), 'os.path.join', 'os.path.join', ({(2056, 37, 2056, 59): 'self.test_subdirectory', (2056, 61, 2056, 78): 'subnetwork_subdir'}, {}), '(self.test_subdirectory, subnetwork_subdir)', False, 'import os\n'), ((2057, 22, 2057, 75), 'os.path.join', 'os.path.join', ({(2057, 35, 2057, 57): 'self.test_subdirectory', (2057, 59, 2057, 74): 'ensemble_subdir'}, {}), '(self.test_subdirectory, ensemble_subdir)', False, 'import os\n'), ((2084, 13, 2084, 37), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((2115, 19, 2115, 53), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((2166, 17, 2166, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((2220, 17, 2220, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((2262, 17, 2262, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((2272, 21, 2272, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2272, 39, 2272, 51): 'XOR_FEATURES', (2272, 53, 2272, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((2292, 22, 2292, 68), 'os.path.join', 'os.path.join', ({(2292, 35, 2292, 57): 'self.test_subdirectory', (2292, 59, 2292, 67): '"""export"""'}, {}), "(self.test_subdirectory, 'export')", False, 'import os\n'), ((2357, 17, 2357, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((2945, 21, 2945, 58), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2945, 39, 2945, 49): '[[1.0, 0.0]]', (2945, 51, 2945, 57): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((3046, 17, 3046, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3047, 27, 3047, 52), 'adanet.subnetwork.SimpleGenerator', 'SimpleGenerator', ({(3047, 43, 3047, 51): 'builders'}, {}), '(builders)', False, 'from adanet.subnetwork import SimpleGenerator\n'), ((3057, 21, 3057, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3057, 39, 3057, 51): 'XOR_FEATURES', (3057, 53, 3057, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((3112, 16, 3117, 19), 'adanet.core.estimator.Estimator', 'Estimator', (), '', False, 'from adanet.core.estimator import Estimator\n'), ((3126, 17, 3126, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3135, 21, 3135, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3135, 39, 3135, 51): 'XOR_FEATURES', (3135, 53, 3135, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((3151, 17, 3151, 58), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3159, 21, 3159, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3159, 39, 3159, 51): 'XOR_FEATURES', (3159, 53, 3159, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((3161, 17, 3162, 61), 'adanet.tf_compat.v1.train.CheckpointSaverHook', 'tf_compat.v1.train.CheckpointSaverHook', (), '', False, 'from adanet import tf_compat\n'), ((3163, 15, 3163, 59), 'adanet.tf_compat.v1.train.CheckpointSaverListener', 'tf_compat.v1.train.CheckpointSaverListener', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((3249, 25, 3249, 73), 'os.path.join', 'os.path.join', ({(3249, 38, 3249, 60): 'self.test_subdirectory', (3249, 62, 3249, 72): '"""original"""'}, {}), "(self.test_subdirectory, 'original')", False, 'import os\n'), ((3250, 17, 3251, 56), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3264, 21, 3264, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3264, 39, 3264, 51): 'XOR_FEATURES', (3264, 53, 3264, 63): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((3291, 21, 3291, 76), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3291, 39, 3291, 57): 'different_features', (3291, 59, 3291, 75): 'different_labels'}, {}), '(different_features, different_labels)', True, 'from adanet.core import testing_utils as tu\n'), ((106, 9, 106, 43), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(106, 37, 106, 42): '"""dnn"""'}, {}), "('dnn')", False, 'from adanet import tf_compat\n'), ((125, 21, 125, 61), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (), '', True, 'import tensorflow as tf\n'), ((134, 9, 134, 46), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(134, 37, 134, 45): '"""logits"""'}, {}), "('logits')", False, 'from adanet import tf_compat\n'), ((142, 27, 142, 57), 'tensorflow.ones', 'tf.ones', ({(142, 35, 142, 56): '[batch_size, 3, 3, 1]'}, {}), '([batch_size, 3, 3, 1])', True, 'import tensorflow as tf\n'), ((143, 9, 143, 46), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(143, 37, 143, 45): '"""nested"""'}, {}), "('nested')", False, 'from adanet import tf_compat\n'), ((207, 9, 207, 46), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(207, 37, 207, 45): '"""simple"""'}, {}), "('simple')", False, 'from adanet import tf_compat\n'), ((208, 20, 209, 67), 'adanet.tf_compat.v1.feature_column.input_layer', 'tf_compat.v1.feature_column.input_layer', (), '', False, 'from adanet import tf_compat\n'), ((212, 9, 212, 46), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(212, 37, 212, 45): '"""logits"""'}, {}), "('logits')", False, 'from adanet import tf_compat\n'), ((1043, 13, 1043, 36), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((1049, 38, 1049, 70), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1073, 23, 1073, 66), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1073, 41, 1073, 53): 'XOR_FEATURES', (1073, 55, 1073, 65): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((1096, 27, 1097, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((1160, 21, 1160, 68), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1286, 23, 1286, 60), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1286, 41, 1286, 51): '[[1.0, 0.0]]', (1286, 53, 1286, 59): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1336, 8, 1341, 46), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (), '', True, 'import tensorflow as tf\n'), ((1343, 8, 1343, 57), 'tensorflow.keras.layers.MaxPool2D', 'tf.keras.layers.MaxPool2D', (), '', True, 'import tensorflow as tf\n'), ((1344, 8, 1344, 33), 'tensorflow.keras.layers.Flatten', 'tf.keras.layers.Flatten', ({}, {}), '()', True, 'import tensorflow as tf\n'), ((1345, 8, 1346, 74), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (), '', True, 'import tensorflow as tf\n'), ((1348, 13, 1349, 72), 'adanet.tf_compat.v1.layers.Dense', 'tf_compat.v1.layers.Dense', (), '', False, 'from adanet import tf_compat\n'), ((1421, 27, 1422, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((1475, 25, 1475, 52), 'tensorflow.split', 'tf.split', ({(1475, 34, 1475, 40): 'logits', (1475, 42, 1475, 48): '[1, 1]', (1475, 50, 1475, 51): '1'}, {}), '(logits, [1, 1], 1)', True, 'import tensorflow as tf\n'), ((1575, 27, 1576, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((1625, 9, 1625, 29), 'tensorflow.python.eager.context.graph_mode', 'context.graph_mode', ({}, {}), '()', False, 'from tensorflow.python.eager import context\n'), ((1637, 23, 1637, 60), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1637, 41, 1637, 51): '[[1.0, 0.0]]', (1637, 53, 1637, 59): '[[1.0]]'}, {}), '([[1.0, 0.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1638, 6, 1638, 45), 'adanet.tf_compat.v1.train.create_global_step', 'tf_compat.v1.train.create_global_step', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1703, 8, 1703, 54), 'os.path.join', 'os.path.join', ({(1703, 21, 1703, 43): 'self.test_subdirectory', (1703, 45, 1703, 53): '"""*.meta"""'}, {}), "(self.test_subdirectory, '*.meta')", False, 'import os\n'), ((1977, 14, 1978, 63), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((1986, 14, 1987, 63), 'tensorflow_estimator.python.estimator.head.binary_class_head.BinaryClassHead', 'binary_class_head.BinaryClassHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import binary_class_head\n'), ((2114, 28, 2114, 58), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((2199, 27, 2200, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((2204, 13, 2205, 65), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (), '', True, 'import tensorflow as tf\n'), ((2246, 27, 2247, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((2250, 13, 2251, 65), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (), '', True, 'import tensorflow as tf\n'), ((2285, 27, 2286, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((2302, 6, 2306, 42), 'tensorflow.contrib.estimator.export_saved_model_for_mode', 'tf.contrib.estimator.export_saved_model_for_mode', (), '', True, 'import tensorflow as tf\n'), ((2310, 13, 2310, 49), 'tensorflow.io.gfile.listdir', 'tf.io.gfile.listdir', ({(2310, 33, 2310, 48): 'export_dir_base'}, {}), '(export_dir_base)', True, 'import tensorflow as tf\n'), ((2312, 9, 2312, 29), 'tensorflow.python.eager.context.graph_mode', 'context.graph_mode', ({}, {}), '()', False, 'from tensorflow.python.eager import context\n'), ((2378, 27, 2379, 67), 'adanet.tf_compat.v1.placeholder', 'tf_compat.v1.placeholder', (), '', False, 'from adanet import tf_compat\n'), ((2383, 13, 2384, 72), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (), '', True, 'import tensorflow as tf\n'), ((3078, 14, 3079, 73), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((3088, 14, 3089, 73), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((3186, 19, 3186, 64), 'tensorflow.contrib.learn.RunConfig', 'tf.contrib.learn.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3200, 32, 3200, 53), 'json.dumps', 'json.dumps', ({(3200, 43, 3200, 52): 'tf_config'}, {}), '(tf_config)', False, 'import json\n'), ((3201, 19, 3201, 64), 'tensorflow.contrib.learn.RunConfig', 'tf.contrib.learn.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((3211, 23, 3211, 66), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3211, 41, 3211, 53): 'XOR_FEATURES', (3211, 55, 3211, 65): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((108, 11, 108, 54), 'adanet.tf_compat.v1.variable_scope', 'tf_compat.v1.variable_scope', ({(108, 39, 108, 53): '"""hidden_layer"""'}, {}), "('hidden_layer')", False, 'from adanet import tf_compat\n'), ((113, 22, 113, 58), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((120, 23, 120, 76), 'tensorflow.concat', 'tf.concat', (), '', True, 'import tensorflow as tf\n'), ((285, 27, 286, 28), 'adanet.tf_compat.v1.glorot_uniform_initializer', 'tf_compat.v1.glorot_uniform_initializer', (), '', False, 'from adanet import tf_compat\n'), ((1056, 13, 1056, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1089, 17, 1089, 68), 'adanet.core.testing_utils.dataset_input_fn', 'tu.dataset_input_fn', (), '', True, 'from adanet.core import testing_utils as tu\n'), ((582, 20, 582, 47), 'adanet.core.testing_utils.ModifierSessionRunHook', 'tu.ModifierSessionRunHook', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((893, 34, 893, 47), 'adanet.ensemble.AllStrategy', 'AllStrategy', ({}, {}), '()', False, 'from adanet.ensemble import AllStrategy\n'), ((910, 34, 910, 47), 'adanet.ensemble.AllStrategy', 'AllStrategy', ({}, {}), '()', False, 'from adanet.ensemble import AllStrategy\n'), ((912, 14, 912, 46), 'adanet.ensemble.ComplexityRegularizedEnsembler', 'ComplexityRegularizedEnsembler', ({}, {}), '()', False, 'from adanet.ensemble import ComplexityRegularizedEnsembler\n'), ((913, 14, 913, 77), 'adanet.ensemble.ComplexityRegularizedEnsembler', 'ComplexityRegularizedEnsembler', (), '', False, 'from adanet.ensemble import ComplexityRegularizedEnsembler\n'), ((931, 34, 931, 48), 'adanet.ensemble.SoloStrategy', 'SoloStrategy', ({}, {}), '()', False, 'from adanet.ensemble import SoloStrategy\n'), ((948, 34, 948, 48), 'adanet.ensemble.SoloStrategy', 'SoloStrategy', ({}, {}), '()', False, 'from adanet.ensemble import SoloStrategy\n'), ((966, 15, 966, 28), 'adanet.ensemble.AllStrategy', 'AllStrategy', ({}, {}), '()', False, 'from adanet.ensemble import AllStrategy\n'), ((966, 30, 966, 44), 'adanet.ensemble.GrowStrategy', 'GrowStrategy', ({}, {}), '()', False, 'from adanet.ensemble import GrowStrategy\n'), ((967, 15, 967, 29), 'adanet.ensemble.SoloStrategy', 'SoloStrategy', ({}, {}), '()', False, 'from adanet.ensemble import SoloStrategy\n'), ((1158, 25, 1158, 78), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1165, 13, 1165, 45), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', ({}, {}), '()', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((1170, 35, 1170, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1273, 17, 1273, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1273, 35, 1273, 45): '[[1.0, 1.0]]', (1273, 47, 1273, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1297, 13, 1297, 35), 'tensorflow_estimator.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss', 'binary_class_head_v1', ({}, {}), '()', True, 'from tensorflow_estimator.python.estimator.canned.head import _binary_logistic_head_with_sigmoid_cross_entropy_loss as binary_class_head_v1\n'), ((1385, 13, 1385, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1414, 17, 1414, 76), 'adanet.core.testing_utils.dataset_input_fn', 'tu.dataset_input_fn', (), '', True, 'from adanet.core import testing_utils as tu\n'), ((1550, 29, 1550, 54), 'adanet.subnetwork.SimpleGenerator', 'SimpleGenerator', ({(1550, 45, 1550, 53): 'builders'}, {}), '(builders)', False, 'from adanet.subnetwork import SimpleGenerator\n'), ((1552, 18, 1552, 61), 'adanet.core.evaluator.Evaluator', 'Evaluator', (), '', False, 'from adanet.core.evaluator import Evaluator\n'), ((1567, 17, 1567, 76), 'adanet.core.testing_utils.dataset_input_fn', 'tu.dataset_input_fn', (), '', True, 'from adanet.core import testing_utils as tu\n'), ((1605, 17, 1605, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1605, 35, 1605, 45): '[[1.0, 1.0]]', (1605, 47, 1605, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1607, 13, 1607, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1687, 17, 1687, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1687, 35, 1687, 45): '[[1.0, 1.0]]', (1687, 47, 1687, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1689, 13, 1689, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1693, 35, 1693, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1775, 13, 1775, 57), 'tensorflow.reduce_mean', 'tf.reduce_mean', (), '', True, 'import tensorflow as tf\n'), ((1800, 17, 1800, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1800, 35, 1800, 45): '[[1.0, 1.0]]', (1800, 47, 1800, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1802, 13, 1802, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1806, 35, 1806, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1868, 17, 1868, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1868, 35, 1868, 45): '[[1.0, 1.0]]', (1868, 47, 1868, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1870, 13, 1870, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1874, 35, 1874, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((2087, 17, 2087, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2087, 35, 2087, 45): '[[1.0, 1.0]]', (2087, 47, 2087, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((2089, 13, 2089, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2093, 35, 2093, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((2104, 13, 2104, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2169, 17, 2169, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2169, 35, 2169, 45): '[[1.0, 1.0]]', (2169, 47, 2169, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((2171, 13, 2171, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2175, 35, 2175, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((2203, 24, 2203, 42), 'tensorflow.constant', 'tf.constant', ({(2203, 36, 2203, 41): 'value'}, {}), '(value)', True, 'import tensorflow as tf\n'), ((2223, 17, 2223, 54), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(2223, 35, 2223, 45): '[[1.0, 1.0]]', (2223, 47, 2223, 53): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((2225, 13, 2225, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2229, 35, 2229, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((2249, 24, 2249, 42), 'tensorflow.constant', 'tf.constant', ({(2249, 36, 2249, 41): 'value'}, {}), '(value)', True, 'import tensorflow as tf\n'), ((2266, 13, 2266, 48), 'tensorflow_estimator.python.estimator.head.binary_class_head.BinaryClassHead', 'binary_class_head.BinaryClassHead', ({}, {}), '()', False, 'from tensorflow_estimator.python.estimator.head import binary_class_head\n'), ((2314, 26, 2314, 63), 'os.path.join', 'os.path.join', ({(2314, 39, 2314, 54): 'export_dir_base', (2314, 56, 2314, 62): 'subdir'}, {}), '(export_dir_base, subdir)', False, 'import os\n'), ((2361, 13, 2361, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2366, 40, 2366, 60), 'adanet.distributed.placement.RoundRobinStrategy', 'RoundRobinStrategy', ({}, {}), '()', False, 'from adanet.distributed.placement import RoundRobinStrategy\n'), ((2382, 31, 2382, 49), 'tensorflow.constant', 'tf.constant', ({(2382, 43, 2382, 48): 'value'}, {}), '(value)', True, 'import tensorflow as tf\n'), ((2401, 6, 2401, 71), 'absl.logging.warning', 'logging.warning', ({(2401, 22, 2401, 63): '"""Testing estimator#export_savedmodel: %s"""', (2401, 65, 2401, 70): 'error'}, {}), "('Testing estimator#export_savedmodel: %s', error)", False, 'from absl import logging\n'), ((2947, 13, 2947, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((2950, 35, 2950, 67), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((2954, 28, 2955, 45), 'adanet.core.report_materializer.ReportMaterializer', 'ReportMaterializer', (), '', False, 'from adanet.core.report_materializer import ReportMaterializer\n'), ((2600, 14, 2611, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2612, 14, 2623, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2626, 14, 2637, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2638, 14, 2645, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2646, 14, 2657, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2814, 14, 2825, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2826, 14, 2837, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2840, 14, 2851, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2852, 14, 2863, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2864, 14, 2875, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2876, 14, 2883, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2884, 14, 2895, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2896, 14, 2907, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2908, 14, 2919, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((3049, 13, 3049, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3129, 13, 3129, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3154, 13, 3154, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3258, 13, 3258, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3276, 18, 3276, 66), 'os.path.join', 'os.path.join', ({(3276, 31, 3276, 53): 'self.test_subdirectory', (3276, 55, 3276, 65): '"""replayed"""'}, {}), "(self.test_subdirectory, 'replayed')", False, 'import os\n'), ((3284, 13, 3284, 22), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3289, 22, 3289, 68), 'adanet.replay.Config', 'replay.Config', (), '', False, 'from adanet import replay\n'), ((114, 13, 114, 52), 'adanet.tf_compat.v1.colocate_with', 'tf_compat.v1.colocate_with', ({(114, 40, 114, 51): 'disjoint_op'}, {}), '(disjoint_op)', False, 'from adanet import tf_compat\n'), ((115, 25, 115, 52), 'tensorflow.matmul', 'tf.matmul', ({(115, 35, 115, 48): "features['x']", (115, 50, 115, 51): 'w'}, {}), "(features['x'], w)", True, 'import tensorflow as tf\n'), ((138, 29, 138, 79), 'adanet.tf_compat.v1.glorot_uniform_initializer', 'tf_compat.v1.glorot_uniform_initializer', (), '', False, 'from adanet import tf_compat\n'), ((176, 34, 176, 64), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((216, 29, 216, 79), 'adanet.tf_compat.v1.glorot_uniform_initializer', 'tf_compat.v1.glorot_uniform_initializer', (), '', False, 'from adanet import tf_compat\n'), ((253, 27, 254, 20), 'adanet.tf_compat.v1.glorot_uniform_initializer', 'tf_compat.v1.glorot_uniform_initializer', (), '', False, 'from adanet import tf_compat\n'), ((798, 27, 798, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(798, 45, 798, 55): '[[1.0, 1.0]]', (798, 57, 798, 63): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((817, 27, 817, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(817, 45, 817, 55): '[[1.0, 1.0]]', (817, 57, 817, 63): '[[1.0]]'}, {}), '([[1.0, 1.0]], [[1.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((837, 27, 837, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(837, 45, 837, 55): '[[1.0, 1.0]]', (837, 57, 837, 63): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((857, 27, 857, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(857, 45, 857, 55): '[[1.0, 1.0]]', (857, 57, 857, 63): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((876, 27, 876, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(876, 45, 876, 55): '[[1.0, 1.0]]', (876, 57, 876, 63): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1123, 18, 1124, 77), 'tensorflow.feature_column.categorical_column_with_hash_bucket', 'tf.feature_column.categorical_column_with_hash_bucket', (), '', True, 'import tensorflow as tf\n'), ((1131, 18, 1134, 38), 'tensorflow.feature_column.categorical_column_with_vocabulary_list', 'tf.feature_column.categorical_column_with_vocabulary_list', (), '', True, 'import tensorflow as tf\n'), ((1140, 18, 1141, 77), 'tensorflow.feature_column.categorical_column_with_hash_bucket', 'tf.feature_column.categorical_column_with_hash_bucket', (), '', True, 'import tensorflow as tf\n'), ((1148, 18, 1151, 38), 'tensorflow.feature_column.categorical_column_with_vocabulary_list', 'tf.feature_column.categorical_column_with_vocabulary_list', (), '', True, 'import tensorflow as tf\n'), ((1276, 15, 1276, 24), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1280, 37, 1280, 69), 'adanet.tf_compat.v1.zeros_initializer', 'tf_compat.v1.zeros_initializer', ({}, {}), '()', False, 'from adanet import tf_compat\n'), ((1537, 15, 1537, 40), 'tensorflow.constant', 'tf.constant', ({(1537, 27, 1537, 39): 'xor_features'}, {}), '(xor_features)', True, 'import tensorflow as tf\n'), ((1539, 19, 1539, 42), 'tensorflow.constant', 'tf.constant', ({(1539, 31, 1539, 41): 'xor_labels'}, {}), '(xor_labels)', True, 'import tensorflow as tf\n'), ((1540, 19, 1540, 42), 'tensorflow.constant', 'tf.constant', ({(1540, 31, 1540, 41): 'xor_labels'}, {}), '(xor_labels)', True, 'import tensorflow as tf\n'), ((1628, 19, 1628, 56), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1628, 37, 1628, 47): '[[1.0, 1.0]]', (1628, 49, 1628, 55): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1630, 15, 1630, 24), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((1644, 17, 1648, 11), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', (), '', True, 'import tensorflow as tf\n'), ((1935, 25, 1935, 63), 'adanet.tf_compat.v1.metrics.mean', 'tf_compat.v1.metrics.mean', ({(1935, 51, 1935, 62): 'predictions'}, {}), '(predictions)', False, 'from adanet import tf_compat\n'), ((2104, 41, 2104, 78), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', ({(2104, 74, 2104, 77): '"""x"""'}, {}), "('x')", True, 'import tensorflow as tf\n'), ((2289, 17, 2289, 40), 'tensorflow.constant', 'tf.constant', ({(2289, 29, 2289, 39): 'XOR_LABELS'}, {}), '(XOR_LABELS)', True, 'import tensorflow as tf\n'), ((2321, 14, 2322, 70), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2322, 18, 2322, 69): "signature_def.outputs['metrics/average_loss/value']"}, {}), "(signature_def.\n outputs['metrics/average_loss/value'])", False, 'from adanet import tf_compat\n'), ((2326, 16, 2327, 66), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2327, 10, 2327, 65): "signature_def.outputs['metrics/average_loss/update_op']"}, {}), "(signature_def.\n outputs['metrics/average_loss/update_op'])", False, 'from adanet import tf_compat\n'), ((2328, 16, 2329, 72), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2329, 20, 2329, 71): "signature_def.outputs['metrics/accuracy/update_op']"}, {}), "(signature_def.\n outputs['metrics/accuracy/update_op'])", False, 'from adanet import tf_compat\n'), ((2330, 16, 2331, 70), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2331, 20, 2331, 69): "signature_def.outputs['metrics/recall/update_op']"}, {}), "(signature_def.\n outputs['metrics/recall/update_op'])", False, 'from adanet import tf_compat\n'), ((2337, 14, 2338, 70), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2338, 18, 2338, 69): "signature_def.outputs['metrics/average_loss/value']"}, {}), "(signature_def.\n outputs['metrics/average_loss/value'])", False, 'from adanet import tf_compat\n'), ((2343, 14, 2344, 64), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2344, 18, 2344, 63): "signature_def.outputs['metrics/recall/value']"}, {}), "(signature_def.\n outputs['metrics/recall/value'])", False, 'from adanet import tf_compat\n'), ((2350, 14, 2351, 66), 'adanet.tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', 'tf_compat.v1.saved_model.utils.get_tensor_from_tensor_info', ({(2351, 18, 2351, 65): "signature_def.outputs['metrics/accuracy/value']"}, {}), "(signature_def.\n outputs['metrics/accuracy/value'])", False, 'from adanet import tf_compat\n'), ((2457, 14, 2468, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2493, 14, 2504, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2505, 14, 2516, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2517, 14, 2528, 15), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2541, 18, 2552, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2555, 18, 2562, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2563, 18, 2574, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2577, 18, 2584, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2585, 18, 2596, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2683, 18, 2694, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2695, 18, 2706, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2707, 18, 2718, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2721, 18, 2728, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2729, 18, 2740, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2741, 18, 2752, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2753, 18, 2764, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2767, 18, 2774, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2775, 18, 2786, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2787, 18, 2798, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((2799, 18, 2810, 19), 'adanet.subnetwork.MaterializedReport', 'MaterializedReport', (), '', False, 'from adanet.subnetwork import MaterializedReport\n'), ((3035, 27, 3035, 64), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3035, 45, 3035, 55): '[[1.0, 1.0]]', (3035, 57, 3035, 63): '[[0.0]]'}, {}), '([[1.0, 1.0]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((3083, 17, 3083, 33), 'tensorflow.zeros', 'tf.zeros', ({(3083, 26, 3083, 32): '[1, 1]'}, {}), '([1, 1])', True, 'import tensorflow as tf\n'), ((3093, 17, 3093, 36), 'tensorflow.math.log', 'tf.math.log', ({(3093, 29, 3093, 35): '[[0.0]]'}, {}), '([[0.0]])', True, 'import tensorflow as tf\n'), ((3206, 15, 3206, 24), 'adanet.core.testing_utils.head', 'tu.head', ({}, {}), '()', True, 'from adanet.core import testing_utils as tu\n'), ((3236, 27, 3236, 70), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3236, 45, 3236, 57): 'XOR_FEATURES', (3236, 59, 3236, 69): 'XOR_LABELS'}, {}), '(XOR_FEATURES, XOR_LABELS)', True, 'from adanet.core import testing_utils as tu\n'), ((3240, 27, 3241, 78), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(3240, 45, 3241, 55): '[[0.0, 0.0], [0.0, 0], [0.0, 0.0], [0.0, 0.0]]', (3241, 57, 3241, 77): '[[0], [0], [0], [0]]'}, {}), '([[0.0, 0.0], [0.0, 0], [0.0, 0.0], [0.0, 0.0]], [[0], [0],\n [0], [0]])', True, 'from adanet.core import testing_utils as tu\n'), ((111, 24, 111, 74), 'adanet.tf_compat.v1.glorot_uniform_initializer', 'tf_compat.v1.glorot_uniform_initializer', (), '', False, 'from adanet import tf_compat\n'), ((178, 20, 179, 47), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((179, 49, 179, 79), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1099, 25, 1099, 66), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1112, 23, 1112, 59), 'tensorflow.io.gfile.listdir', 'tf.io.gfile.listdir', ({(1112, 43, 1112, 58): 'export_dir_base'}, {}), '(export_dir_base)', True, 'import tensorflow as tf\n'), ((984, 22, 986, 29), 'tensorflow.data.Dataset.from_tensors', 'tf.data.Dataset.from_tensors', ({(984, 51, 986, 28): "({'x': XOR_FEATURES}, XOR_LABELS)"}, {}), "(({'x': XOR_FEATURES}, XOR_LABELS))", True, 'import tensorflow as tf\n'), ((1390, 21, 1390, 66), 'adanet.core.testing_utils.dummy_input_fn', 'tu.dummy_input_fn', ({(1390, 39, 1390, 57): '[[1.0, 1.0, 0.1, 0.1]]', (1390, 59, 1390, 65): '[[0.0]]'}, {}), '([[1.0, 1.0, 0.1, 0.1]], [[0.0]])', True, 'from adanet.core import testing_utils as tu\n'), ((1424, 25, 1424, 74), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1578, 25, 1578, 74), 'tensorflow.constant', 'tf.constant', (), '', True, 'import tensorflow as tf\n'), ((1591, 23, 1591, 59), 'tensorflow.io.gfile.listdir', 'tf.io.gfile.listdir', ({(1591, 43, 1591, 58): 'export_dir_base'}, {}), '(export_dir_base)', True, 'import tensorflow as tf\n'), ((2288, 25, 2288, 50), 'tensorflow.constant', 'tf.constant', ({(2288, 37, 2288, 49): 'XOR_FEATURES'}, {}), '(XOR_FEATURES)', True, 'import tensorflow as tf\n'), ((3082, 23, 3082, 46), 'tensorflow.math.log', 'tf.math.log', ({(3082, 35, 3082, 45): '[[1.0, 0.0]]'}, {}), '([[1.0, 0.0]])', True, 'import tensorflow as tf\n'), ((3092, 23, 3092, 38), 'tensorflow.ones', 'tf.ones', ({(3092, 31, 3092, 37): '[1, 2]'}, {}), '([1, 2])', True, 'import tensorflow as tf\n'), ((3099, 18, 3100, 77), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((3104, 23, 3104, 38), 'tensorflow.ones', 'tf.ones', ({(3104, 31, 3104, 37): '[1, 2]'}, {}), '([1, 2])', True, 'import tensorflow as tf\n'), ((3106, 23, 3106, 42), 'tensorflow.math.log', 'tf.math.log', ({(3106, 35, 3106, 41): '[[0.0]]'}, {}), '([[0.0]])', True, 'import tensorflow as tf\n'), ((1545, 12, 1546, 75), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((1547, 12, 1548, 75), 'tensorflow_estimator.python.estimator.head.regression_head.RegressionHead', 'regression_head.RegressionHead', (), '', False, 'from tensorflow_estimator.python.estimator.head import regression_head\n'), ((494, 26, 494, 69), 'adanet.core.testing_utils.ModifierSessionRunHook', 'tu.ModifierSessionRunHook', ({(494, 52, 494, 68): '"""chief_hook_var"""'}, {}), "('chief_hook_var')", True, 'from adanet.core import testing_utils as tu\n'), ((496, 40, 496, 77), 'adanet.core.testing_utils.ModifierSessionRunHook', 'tu.ModifierSessionRunHook', ({(496, 66, 496, 76): '"""hook_var"""'}, {}), "('hook_var')", True, 'from adanet.core import testing_utils as tu\n'), ((517, 26, 517, 69), 'adanet.core.testing_utils.ModifierSessionRunHook', 'tu.ModifierSessionRunHook', ({(517, 52, 517, 68): '"""chief_hook_var"""'}, {}), "('chief_hook_var')", True, 'from adanet.core import testing_utils as tu\n'), ((520, 26, 520, 63), 'adanet.core.testing_utils.ModifierSessionRunHook', 'tu.ModifierSessionRunHook', ({(520, 52, 520, 62): '"""hook_var"""'}, {}), "('hook_var')", True, 'from adanet.core import testing_utils as tu\n'), ((2005, 30, 2006, 69), 'adanet.tf_compat.v1.Summary.Value', 'tf_compat.v1.Summary.Value', (), '', False, 'from adanet import tf_compat\n')]
nyg1/classroom-finder
ua_roomseeker/uploader.py
13b6332187c2afb9833a1acd82bdf31ab81af5c8
from seeker.models import Building, Classroom, Time import json import os os.chdir('../data') fileList = os.listdir() #loops through each json file for jsonfile in fileList: #opens the jsonfile and loads the data f = open(jsonfile, 'r') data = f.read() jsondata = json.loads(data) #create the building building = Building(BuildingName=os.path.splitext(jsonfile)[0]) building.save() for day in jsondata: for room in jsondata[day].keys(): #creates each classroom, adding one only if one doesn't exist classroom = Classroom.objects.get_or_create(building = Building.objects.get(BuildingName = os.path.splitext(jsonfile)[0]), ClassroomName = os.path.splitext(jsonfile)[0] + ' - ' + room) for time in jsondata[day][room]: #creates each time time = Time(building=Building.objects.get(BuildingName = os.path.splitext(jsonfile)[0]), classroom=Classroom.objects.get(ClassroomName = os.path.splitext(jsonfile)[0] + ' - ' + room), DayofWeek=day, TimeValue=time) time.save() #IMPORTANT!!!!!!! # This program must be run inside a python manage.py shell for it to work, in the future a fix may be found, # but for the time being, follow these steps: # 1. open powershell and navigate to the folder that contains this file # 2. type in "python manage.py shell" # 3. copy and paste the code into the shell and press enter # 4. wait time is around 5 minutes
[((5, 0, 5, 19), 'os.chdir', 'os.chdir', ({(5, 9, 5, 18): '"""../data"""'}, {}), "('../data')", False, 'import os\n'), ((6, 11, 6, 23), 'os.listdir', 'os.listdir', ({}, {}), '()', False, 'import os\n'), ((13, 15, 13, 31), 'json.loads', 'json.loads', ({(13, 26, 13, 30): 'data'}, {}), '(data)', False, 'import json\n'), ((15, 37, 15, 63), 'os.path.splitext', 'os.path.splitext', ({(15, 54, 15, 62): 'jsonfile'}, {}), '(jsonfile)', False, 'import os\n'), ((20, 103, 20, 129), 'os.path.splitext', 'os.path.splitext', ({(20, 120, 20, 128): 'jsonfile'}, {}), '(jsonfile)', False, 'import os\n'), ((20, 151, 20, 177), 'os.path.splitext', 'os.path.splitext', ({(20, 168, 20, 176): 'jsonfile'}, {}), '(jsonfile)', False, 'import os\n'), ((23, 73, 23, 99), 'os.path.splitext', 'os.path.splitext', ({(23, 90, 23, 98): 'jsonfile'}, {}), '(jsonfile)', False, 'import os\n'), ((23, 153, 23, 179), 'os.path.splitext', 'os.path.splitext', ({(23, 170, 23, 178): 'jsonfile'}, {}), '(jsonfile)', False, 'import os\n')]
luiztauffer/dash-daq
dash_daq/Slider.py
4975093449bdc4d7ff4cd366ac82a847cdf24c34
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Slider(Component): """A Slider component. A slider component with support for a target value. Keyword arguments: - id (string; optional): The ID used to identify this component in Dash callbacks. - className (string; optional): Additional CSS class for the root DOM node. - color (dict; default colors.DARKER_PRIMARY): Color configuration for the slider's track. `color` is a string | dict with keys: - default (string; optional): Fallback color to use when color.ranges has gaps. - gradient (boolean; optional): Display ranges as a gradient between given colors. Requires color.ranges to be contiguous along the entirety of the gauge's range of values. - ranges (dict; optional): Define multiple color ranges on the slider's track. The key determines the color of the range and the value is the start,end of the range itself. `ranges` is a dict with keys: - color (list of numbers; optional) - disabled (boolean; optional): If True, the handles can't be moved. - dots (boolean; optional): When the step value is greater than 1, you can set the dots to True if you want to render the slider with dots. Note: dots are disabled automatically when using color.ranges. - handleLabel (dict; optional): Configuration of the slider handle's label. Passing falsy value will disable the label. `handleLabel` is a string | dict with keys: - color (string; optional) - label (string; optional) - showCurrentValue (boolean; optional) - style (dict; optional) - included (boolean; optional): If the value is True, it means a continuous value is included. Otherwise, it is an independent value. - labelPosition (a value equal to: 'top', 'bottom'; default 'bottom'): Where the component label is positioned. - marks (dict; optional): Marks on the slider. The key determines the position, and the value determines what will show. If you want to set the style of a specific mark point, the value should be an object which contains style and label properties. `marks` is a dict with keys: - number (dict; optional) `number` is a string Or dict with keys: - label (string; optional) - style (dict; optional) - max (number; optional): Maximum allowed value of the slider. - min (number; default 0): Minimum allowed value of the slider. - persisted_props (list of a value equal to: 'value's; default ['value']): Properties whose user interactions will persist after refreshing the component or the page. Since only `value` is allowed this prop can normally be ignored. - persistence (boolean | string | number; optional): Used to allow user interactions in this component to be persisted when the component - or the page - is refreshed. If `persisted` is truthy and hasn't changed from its previous value, a `value` that the user has changed while using the app will keep that change, as long as the new `value` also matches what was given originally. Used in conjunction with `persistence_type`. - persistence_type (a value equal to: 'local', 'session', 'memory'; default 'local'): Where persisted user changes will be stored: memory: only kept in memory, reset on page refresh. local: window.localStorage, data is kept after the browser quit. session: window.sessionStorage, data is cleared once the browser quit. - size (number; default 265): Size of the slider in pixels. - step (number; optional): Value by which increments or decrements are made. - targets (dict; optional): Targets on the slider. The key determines the position, and the value determines what will show. If you want to set the style of a specific target point, the value should be an object which contains style and label properties. `targets` is a dict with keys: - number (dict; optional) `number` is a string Or dict with keys: - color (string; optional) - label (string; optional) - showCurrentValue (boolean; optional) - style (dict; optional) - theme (dict; default light): Theme configuration to be set by a ThemeProvider. - updatemode (a value equal to: 'mouseup', 'drag'; default 'mouseup'): Determines when the component should update its value. If `mouseup`, then the slider will only trigger its value when the user has finished dragging the slider. If `drag`, then the slider will update its value continuously as it is being dragged. Only use `drag` if your updates are fast. - value (number; optional): The value of the input. - vertical (boolean; optional): If True, the slider will be vertical.""" @_explicitize_args def __init__(self, id=Component.UNDEFINED, marks=Component.UNDEFINED, color=Component.UNDEFINED, value=Component.UNDEFINED, className=Component.UNDEFINED, labelPosition=Component.UNDEFINED, disabled=Component.UNDEFINED, dots=Component.UNDEFINED, included=Component.UNDEFINED, min=Component.UNDEFINED, max=Component.UNDEFINED, step=Component.UNDEFINED, vertical=Component.UNDEFINED, size=Component.UNDEFINED, targets=Component.UNDEFINED, theme=Component.UNDEFINED, handleLabel=Component.UNDEFINED, updatemode=Component.UNDEFINED, persistence=Component.UNDEFINED, persisted_props=Component.UNDEFINED, persistence_type=Component.UNDEFINED, **kwargs): self._prop_names = ['id', 'className', 'color', 'disabled', 'dots', 'handleLabel', 'included', 'labelPosition', 'marks', 'max', 'min', 'persisted_props', 'persistence', 'persistence_type', 'size', 'step', 'targets', 'theme', 'updatemode', 'value', 'vertical'] self._type = 'Slider' self._namespace = 'dash_daq' self._valid_wildcard_attributes = [] self.available_properties = ['id', 'className', 'color', 'disabled', 'dots', 'handleLabel', 'included', 'labelPosition', 'marks', 'max', 'min', 'persisted_props', 'persistence', 'persistence_type', 'size', 'step', 'targets', 'theme', 'updatemode', 'value', 'vertical'] self.available_wildcard_properties = [] _explicit_args = kwargs.pop('_explicit_args') _locals = locals() _locals.update(kwargs) # For wildcard attrs args = {k: _locals[k] for k in _explicit_args if k != 'children'} for k in []: if k not in args: raise TypeError( 'Required argument `' + k + '` was not specified.') super(Slider, self).__init__(**args)
[]
ooshyun/filterdesign
src/util/__init__.py
59dbea191b8cd44aa9f2d02d3787b5805d486ae2
"""Utility function for process to raw data """ from .util import ( cvt_pcm2wav, cvt_float2fixed, cvt_char2num, plot_frequency_response, plot_pole_zero_analysis, ) from .fi import fi __all__ = [ "fi", "cvt_pcm2wav", "cvt_float2fixed", "cvt_char2num", "plot_frequency_response", "plot_pole_zero_analysis", ]
[]
datosgobar/infra.datos.gob.ar
infra/apps/catalog/tests/views/distribution_upload_tests.py
9f6ae7f0fc741aad79d074e7b2eb2a7dddf8b2cf
import pytest from django.core.files import File from django.urls import reverse from freezegun import freeze_time from infra.apps.catalog.tests.helpers.open_catalog import open_catalog pytestmark = pytest.mark.django_db @pytest.fixture(autouse=True) def give_user_edit_rights(user, node): node.admins.add(user) def _call(client, distribution): return client.get(reverse('catalog:distribution_uploads', kwargs={'node_id': distribution.catalog.id, 'identifier': distribution.identifier})) def test_older_versions_listed(logged_client, distribution_upload): distribution = distribution_upload.distribution with freeze_time('2019-01-01'): with open_catalog('test_data.csv') as fd: other = distribution.distributionupload_set \ .create(file=File(fd)) response = _call(logged_client, distribution) assert str(other.uploaded_at) in response.content.decode('utf-8') def test_catalog_identifier_in_page(logged_client, distribution): response = _call(logged_client, distribution) assert distribution.catalog.identifier in response.content.decode('utf-8')
[((11, 1, 11, 29), 'pytest.fixture', 'pytest.fixture', (), '', False, 'import pytest\n'), ((17, 22, 19, 77), 'django.urls.reverse', 'reverse', (), '', False, 'from django.urls import reverse\n'), ((24, 9, 24, 34), 'freezegun.freeze_time', 'freeze_time', ({(24, 21, 24, 33): '"""2019-01-01"""'}, {}), "('2019-01-01')", False, 'from freezegun import freeze_time\n'), ((25, 13, 25, 42), 'infra.apps.catalog.tests.helpers.open_catalog.open_catalog', 'open_catalog', ({(25, 26, 25, 41): '"""test_data.csv"""'}, {}), "('test_data.csv')", False, 'from infra.apps.catalog.tests.helpers.open_catalog import open_catalog\n'), ((27, 29, 27, 37), 'django.core.files.File', 'File', ({(27, 34, 27, 36): 'fd'}, {}), '(fd)', False, 'from django.core.files import File\n')]
Embracing/unrealcv
examples/model_zoo/build_binaries.py
19305da8554c3a0e683a5e27a1e487cc2cf42776
import subprocess, os ue4_win = r"C:\Program Files\Epic Games\UE_4.16" ue4_linux = "/home/qiuwch/workspace/UE416" ue4_mac = '/Users/Shared/Epic Games/UE_4.16' win_uprojects = [ r'C:\qiuwch\workspace\uprojects\UE4RealisticRendering\RealisticRendering.uproject', r'C:\qiuwch\workspace\uprojects\UE4ArchinteriorsVol2Scene1\ArchinteriorsVol2Scene1.uproject', r'C:\qiuwch\workspace\uprojects\UE4ArchinteriorsVol2Scene2\ArchinteriorsVol2Scene2.uproject', r'C:\qiuwch\workspace\uprojects\UE4ArchinteriorsVol2Scene3\ArchinteriorsVol2Scene3.uproject', r'C:\qiuwch\workspace\uprojects\UE4UrbanCity\UrbanCity.uproject', r'D:\workspace\uprojects\Matinee\Matinee.uproject', r'D:\workspace\uprojects\PhotorealisticCharacter\PhotorealisticCharacter2.uproject', ] linux_uprojects = [ os.path.expanduser('~/workspace/uprojects/UE4RealisticRendering/RealisticRendering.uproject'), os.path.expanduser('~/workspace/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject'), os.path.expanduser('~/workspace/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject'), os.path.expanduser('~/workspace/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject'), os.path.expanduser("~/workspace/uprojects/UE4UrbanCity/UrbanCity.uproject"), ] mac_uprojects = [ os.path.expanduser('~/workspace/UnrealEngine/Templates/FP_FirstPerson/FP_FirstPerson.uproject'), os.path.expanduser('~/uprojects/RealisticRendering/RealisticRendering.uproject'), os.path.expanduser('~/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject'), os.path.expanduser('~/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject'), os.path.expanduser('~/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject'), os.path.expanduser('~/uprojects/UE4UrbanCity/UrbanCity.uproject'), ] uprojects = [] for uproject_path in win_uprojects: uproject_name = os.path.basename(uproject_path).split('.')[0] uprojects.append( dict( uproject_path = uproject_path, ue4_path = ue4_win, log_file = 'log/win_%s.log' % uproject_name ), ) for uproject_path in linux_uprojects: uproject_name = os.path.basename(uproject_path).split('.')[0] uprojects.append( dict( uproject_path = uproject_path, ue4_path = ue4_linux, log_file = 'log/linux_%s.log' % uproject_name ), ) for uproject_path in mac_uprojects: uproject_name = os.path.basename(uproject_path).split('.')[0] uprojects.append( dict( uproject_path = uproject_path, ue4_path = ue4_mac, log_file = 'log/mac_%s.log' % uproject_name ), ) if __name__ == '__main__': for uproject in uprojects: uproject_path = uproject['uproject_path'] if not os.path.isfile(uproject_path): print("Can not find uproject file %s, skip this project" % uproject_path) continue cmd = [ 'python', 'build.py', '--UE4', uproject['ue4_path'], # '--output', uproject['output_folder'], uproject['uproject_path'] ] print(cmd) subprocess.call(cmd, stdout = open(uproject['log_file'], 'w')) with open(uproject['log_file']) as f: lines = f.readlines() print(''.join(lines[-10:])) # Print the last few lines
[((18, 4, 18, 97), 'os.path.expanduser', 'os.path.expanduser', ({(18, 23, 18, 96): '"""~/workspace/uprojects/UE4RealisticRendering/RealisticRendering.uproject"""'}, {}), "(\n '~/workspace/uprojects/UE4RealisticRendering/RealisticRendering.uproject')", False, 'import subprocess, os\n'), ((19, 4, 19, 107), 'os.path.expanduser', 'os.path.expanduser', ({(19, 23, 19, 106): '"""~/workspace/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject"""'}, {}), "(\n '~/workspace/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject'\n )", False, 'import subprocess, os\n'), ((20, 4, 20, 107), 'os.path.expanduser', 'os.path.expanduser', ({(20, 23, 20, 106): '"""~/workspace/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject"""'}, {}), "(\n '~/workspace/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject'\n )", False, 'import subprocess, os\n'), ((21, 4, 21, 107), 'os.path.expanduser', 'os.path.expanduser', ({(21, 23, 21, 106): '"""~/workspace/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject"""'}, {}), "(\n '~/workspace/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject'\n )", False, 'import subprocess, os\n'), ((22, 4, 22, 79), 'os.path.expanduser', 'os.path.expanduser', ({(22, 23, 22, 78): '"""~/workspace/uprojects/UE4UrbanCity/UrbanCity.uproject"""'}, {}), "('~/workspace/uprojects/UE4UrbanCity/UrbanCity.uproject')", False, 'import subprocess, os\n'), ((26, 4, 26, 99), 'os.path.expanduser', 'os.path.expanduser', ({(26, 23, 26, 98): '"""~/workspace/UnrealEngine/Templates/FP_FirstPerson/FP_FirstPerson.uproject"""'}, {}), "(\n '~/workspace/UnrealEngine/Templates/FP_FirstPerson/FP_FirstPerson.uproject'\n )", False, 'import subprocess, os\n'), ((27, 4, 27, 84), 'os.path.expanduser', 'os.path.expanduser', ({(27, 23, 27, 83): '"""~/uprojects/RealisticRendering/RealisticRendering.uproject"""'}, {}), "('~/uprojects/RealisticRendering/RealisticRendering.uproject'\n )", False, 'import subprocess, os\n'), ((28, 4, 28, 97), 'os.path.expanduser', 'os.path.expanduser', ({(28, 23, 28, 96): '"""~/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject"""'}, {}), "(\n '~/uprojects/UE4ArchinteriorsVol2Scene1/ArchinteriorsVol2Scene1.uproject')", False, 'import subprocess, os\n'), ((29, 4, 29, 97), 'os.path.expanduser', 'os.path.expanduser', ({(29, 23, 29, 96): '"""~/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject"""'}, {}), "(\n '~/uprojects/UE4ArchinteriorsVol2Scene2/ArchinteriorsVol2Scene2.uproject')", False, 'import subprocess, os\n'), ((30, 4, 30, 97), 'os.path.expanduser', 'os.path.expanduser', ({(30, 23, 30, 96): '"""~/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject"""'}, {}), "(\n '~/uprojects/UE4ArchinteriorsVol2Scene3/ArchinteriorsVol2Scene3.uproject')", False, 'import subprocess, os\n'), ((31, 4, 31, 69), 'os.path.expanduser', 'os.path.expanduser', ({(31, 23, 31, 68): '"""~/uprojects/UE4UrbanCity/UrbanCity.uproject"""'}, {}), "('~/uprojects/UE4UrbanCity/UrbanCity.uproject')", False, 'import subprocess, os\n'), ((70, 15, 70, 44), 'os.path.isfile', 'os.path.isfile', ({(70, 30, 70, 43): 'uproject_path'}, {}), '(uproject_path)', False, 'import subprocess, os\n'), ((37, 20, 37, 51), 'os.path.basename', 'os.path.basename', ({(37, 37, 37, 50): 'uproject_path'}, {}), '(uproject_path)', False, 'import subprocess, os\n'), ((47, 20, 47, 51), 'os.path.basename', 'os.path.basename', ({(47, 37, 47, 50): 'uproject_path'}, {}), '(uproject_path)', False, 'import subprocess, os\n'), ((57, 20, 57, 51), 'os.path.basename', 'os.path.basename', ({(57, 37, 57, 50): 'uproject_path'}, {}), '(uproject_path)', False, 'import subprocess, os\n')]
NeonJarbas/skill-ddg
__init__.py
48476ad650e72f68ee7e96dd92c6d18f841ce6ec
# 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 ovos_utils.gui import can_use_gui from adapt.intent import IntentBuilder from mycroft.skills.common_query_skill import CommonQuerySkill, CQSMatchLevel from mycroft.skills.core import intent_handler from neon_solver_ddg_plugin import DDGSolver class DuckDuckGoSkill(CommonQuerySkill): def __init__(self): super().__init__() self.duck = DDGSolver() # for usage in tell me more / follow up questions self.idx = 0 self.results = [] self.image = None # intents @intent_handler("search_duck.intent") def handle_search(self, message): query = message.data["query"] summary = self.ask_the_duck(query) if summary: self.speak_result() else: self.speak_dialog("no_answer") @intent_handler(IntentBuilder("DuckMore").require("More"). require("DuckKnows")) def handle_tell_more(self, message): """ Follow up query handler, "tell me more".""" # query = message.data["DuckKnows"] # data, related_queries = self.duck.get_infobox(query) # TODO maybe do something with the infobox data ? self.speak_result() # common query def CQS_match_query_phrase(self, utt): summary = self.ask_the_duck(utt) if summary: self.idx += 1 # spoken by common query return (utt, CQSMatchLevel.GENERAL, summary, {'query': utt, 'image': self.image, 'answer': summary}) def CQS_action(self, phrase, data): """ If selected show gui """ self.display_ddg(data["answer"], data["image"]) # duck duck go api def ask_the_duck(self, query): # context for follow up questions self.set_context("DuckKnows", query) self.idx = 0 self.results = self.duck.long_answer(query, lang=self.lang) self.image = self.duck.get_image(query) if self.results: return self.results[0]["summary"] def display_ddg(self, summary=None, image=None): if not can_use_gui(self.bus): return image = image or \ self.image or \ "https://github.com/JarbasSkills/skill-ddg/raw/master/ui/logo.png" if image.startswith("/"): image = "https://duckduckgo.com" + image self.gui['summary'] = summary or "" self.gui['imgLink'] = image self.gui.show_page("DuckDelegate.qml", override_idle=60) def speak_result(self): if self.idx + 1 > len(self.results): self.speak_dialog("thats all") self.remove_context("DuckKnows") self.idx = 0 else: self.display_ddg(self.results[self.idx]["summary"], self.results[self.idx]["img"]) self.speak(self.results[self.idx]["summary"]) self.idx += 1 def create_skill(): return DuckDuckGoSkill()
[((30, 5, 30, 41), 'mycroft.skills.core.intent_handler', 'intent_handler', ({(30, 20, 30, 40): '"""search_duck.intent"""'}, {}), "('search_duck.intent')", False, 'from mycroft.skills.core import intent_handler\n'), ((23, 20, 23, 31), 'neon_solver_ddg_plugin.DDGSolver', 'DDGSolver', ({}, {}), '()', False, 'from neon_solver_ddg_plugin import DDGSolver\n'), ((73, 15, 73, 36), 'ovos_utils.gui.can_use_gui', 'can_use_gui', ({(73, 27, 73, 35): 'self.bus'}, {}), '(self.bus)', False, 'from ovos_utils.gui import can_use_gui\n'), ((39, 20, 39, 45), 'adapt.intent.IntentBuilder', 'IntentBuilder', ({(39, 34, 39, 44): '"""DuckMore"""'}, {}), "('DuckMore')", False, 'from adapt.intent import IntentBuilder\n')]
LAL/openstack-lease-it
openstack_lease_it/openstack_lease_it/settings.py
4ff983911825eac886fa6f76d6efc25225a698b7
""" Django settings for openstack_lease_it project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import ast import logging from openstack_lease_it.config import GLOBAL_CONFIG, load_config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load configuration load_config() # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = GLOBAL_CONFIG['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = ast.literal_eval(GLOBAL_CONFIG['DJANGO_DEBUG']) # ALLOWED_HOSTS secure django app access ALLOWED_HOSTS = [] # A email as format must match this regular expression # If you not understand, please EMAIL_REGEXP = r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\.-]+\.[A-Za-z]*$" # Application definition INSTALLED_APPS = ( 'openstack_auth', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'openstack_lease_it', 'lease_it', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'openstack_lease_it.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'openstack_lease_it.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True DEFAULT_CHARSET = 'utf-8' # We use memcached as cache backend SESSION_ENGINE = 'django.contrib.sessions.backends.cache' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '{MEMCACHED_HOST}:{MEMCACHED_PORT}'.format(**GLOBAL_CONFIG), } } SESSION_COOKIE_SECURE = False SESSION_TIMEOUT = 1800 # A token can be near the end of validity when a page starts loading, and # invalid during the rendering which can cause errors when a page load. # TOKEN_TIMEOUT_MARGIN defines a time in seconds we retrieve from token # validity to avoid this issue. You can adjust this time depending on the # performance of the infrastructure. TOKEN_TIMEOUT_MARGIN = 100 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = '/' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' if GLOBAL_CONFIG['BACKEND_PLUGIN'] == 'Openstack': # UserId on django-openstack_auth need specific User model AUTH_USER_MODEL = 'openstack_auth.User' # Define keystone URL for authentification OPENSTACK_KEYSTONE_URL = GLOBAL_CONFIG['OS_AUTH_URL'] # We use keystone v3 API OPENSTACK_API_VERSIONS = { "identity": GLOBAL_CONFIG['OS_IDENTITY_API_VERSION'], } # We use multidomain OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT = True # We load Openstack_auth backend AUTHENTICATION_BACKENDS = ( 'openstack_auth.backend.KeystoneBackend', 'django.contrib.auth.backends.ModelBackend', ) else: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) # Configure logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(levelname)s %(asctime)s: %(message)s' }, }, 'handlers': { 'django': { 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'class': 'logging.FileHandler', 'filename': os.path.join(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'django.log'), 'formatter': 'simple' }, 'main': { 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'class': 'logging.FileHandler', 'filename': os.path.join(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'main.log'), 'formatter': 'simple' }, 'notification': { 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'class': 'logging.FileHandler', 'filename': os.path.join(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'notification.log'), 'formatter': 'simple' }, 'instances': { 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'class': 'logging.FileHandler', 'filename': os.path.join(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'instances.log'), 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['django'], 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'propagate': True, }, 'main': { 'handlers': ['main'], 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'propagate': True, }, 'notification': { 'handlers': ['notification'], 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'propagate': True, }, 'instances': { 'handlers': ['instances'], 'level': GLOBAL_CONFIG['DJANGO_LOGLEVEL'], 'propagate': True, }, }, } LOGGER = logging.getLogger('main') LOGGER_NOTIFICATION = logging.getLogger('notification') LOGGER_INSTANCES = logging.getLogger('instances')
[((23, 0, 23, 13), 'openstack_lease_it.config.load_config', 'load_config', ({}, {}), '()', False, 'from openstack_lease_it.config import GLOBAL_CONFIG, load_config\n'), ((29, 8, 29, 55), 'ast.literal_eval', 'ast.literal_eval', ({(29, 25, 29, 54): "GLOBAL_CONFIG['DJANGO_DEBUG']"}, {}), "(GLOBAL_CONFIG['DJANGO_DEBUG'])", False, 'import ast\n'), ((211, 9, 211, 34), 'logging.getLogger', 'logging.getLogger', ({(211, 27, 211, 33): '"""main"""'}, {}), "('main')", False, 'import logging\n'), ((212, 22, 212, 55), 'logging.getLogger', 'logging.getLogger', ({(212, 40, 212, 54): '"""notification"""'}, {}), "('notification')", False, 'import logging\n'), ((213, 19, 213, 49), 'logging.getLogger', 'logging.getLogger', ({(213, 37, 213, 48): '"""instances"""'}, {}), "('instances')", False, 'import logging\n'), ((20, 43, 20, 68), 'os.path.abspath', 'os.path.abspath', ({(20, 59, 20, 67): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((88, 16, 88, 52), 'os.path.join', 'os.path.join', ({(88, 29, 88, 37): 'BASE_DIR', (88, 39, 88, 51): '"""db.sqlite3"""'}, {}), "(BASE_DIR, 'db.sqlite3')", False, 'import os\n'), ((165, 24, 165, 82), 'os.path.join', 'os.path.join', ({(165, 37, 165, 67): "GLOBAL_CONFIG['DJANGO_LOGDIR']", (165, 69, 165, 81): '"""django.log"""'}, {}), "(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'django.log')", False, 'import os\n'), ((171, 24, 171, 80), 'os.path.join', 'os.path.join', ({(171, 37, 171, 67): "GLOBAL_CONFIG['DJANGO_LOGDIR']", (171, 69, 171, 79): '"""main.log"""'}, {}), "(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'main.log')", False, 'import os\n'), ((177, 24, 177, 88), 'os.path.join', 'os.path.join', ({(177, 37, 177, 67): "GLOBAL_CONFIG['DJANGO_LOGDIR']", (177, 69, 177, 87): '"""notification.log"""'}, {}), "(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'notification.log')", False, 'import os\n'), ((183, 24, 183, 85), 'os.path.join', 'os.path.join', ({(183, 37, 183, 67): "GLOBAL_CONFIG['DJANGO_LOGDIR']", (183, 69, 183, 84): '"""instances.log"""'}, {}), "(GLOBAL_CONFIG['DJANGO_LOGDIR'], 'instances.log')", False, 'import os\n')]
vishalbelsare/rigl
rigl/experimental/jax/pruning/pruning.py
f18abc7d82ae3acc6736068408a0186c9efa575c
# coding=utf-8 # Copyright 2021 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Functions for pruning FLAX masked models.""" import collections from typing import Any, Callable, Mapping, Optional, Union import flax import jax.numpy as jnp from rigl.experimental.jax.pruning import masked def weight_magnitude(weights): """Creates weight magnitude-based saliencies, given a weight matrix.""" return jnp.absolute(weights) def prune( model, pruning_rate, saliency_fn = weight_magnitude, mask = None, compare_fn = jnp.greater): """Returns a mask for a model where the params in each layer are pruned using a saliency function. Args: model: The model to create a pruning mask for. pruning_rate: The fraction of lowest magnitude saliency weights that are pruned. If a float, the same rate is used for all layers, otherwise if it is a mapping, it must contain a rate for all masked layers in the model. saliency_fn: A function that returns a float number used to rank the importance of individual weights in the layer. mask: If the model has an existing mask, the mask will be applied before pruning the model. compare_fn: A pairwise operator to compare saliency with threshold, and return True if the saliency indicates the value should not be masked. Returns: A pruned mask for the given model. """ if not mask: mask = masked.simple_mask(model, jnp.ones, masked.WEIGHT_PARAM_NAMES) if not isinstance(pruning_rate, collections.Mapping): pruning_rate_dict = {} for param_name, _ in masked.iterate_mask(mask): # Get the layer name from the parameter's full name/path. layer_name = param_name.split('/')[-2] pruning_rate_dict[layer_name] = pruning_rate pruning_rate = pruning_rate_dict for param_path, param_mask in masked.iterate_mask(mask): split_param_path = param_path.split('/') layer_name = split_param_path[-2] param_name = split_param_path[-1] # If we don't have a pruning rate for the given layer, don't mask it. if layer_name in pruning_rate and mask[layer_name][param_name] is not None: param_value = model.params[layer_name][ masked.MaskedModule.UNMASKED][param_name] # Here any existing mask is first applied to weight matrix. # Note: need to check explicitly is not None for np array. if param_mask is not None: saliencies = saliency_fn(param_mask * param_value) else: saliencies = saliency_fn(param_value) # TODO: Use partition here (partial sort) instead of sort, # since it's O(N), not O(N log N), however JAX doesn't support it. sorted_param = jnp.sort(jnp.abs(saliencies.flatten())) # Figure out the weight magnitude threshold. threshold_index = jnp.round(pruning_rate[layer_name] * sorted_param.size).astype(jnp.int32) threshold = sorted_param[threshold_index] mask[layer_name][param_name] = jnp.array( compare_fn(saliencies, threshold), dtype=jnp.int32) return mask
[((29, 9, 29, 30), 'jax.numpy.absolute', 'jnp.absolute', ({(29, 22, 29, 29): 'weights'}, {}), '(weights)', True, 'import jax.numpy as jnp\n'), ((66, 32, 66, 57), 'rigl.experimental.jax.pruning.masked.iterate_mask', 'masked.iterate_mask', ({(66, 52, 66, 56): 'mask'}, {}), '(mask)', False, 'from rigl.experimental.jax.pruning import masked\n'), ((56, 11, 56, 73), 'rigl.experimental.jax.pruning.masked.simple_mask', 'masked.simple_mask', ({(56, 30, 56, 35): 'model', (56, 37, 56, 45): 'jnp.ones', (56, 47, 56, 72): 'masked.WEIGHT_PARAM_NAMES'}, {}), '(model, jnp.ones, masked.WEIGHT_PARAM_NAMES)', False, 'from rigl.experimental.jax.pruning import masked\n'), ((60, 25, 60, 50), 'rigl.experimental.jax.pruning.masked.iterate_mask', 'masked.iterate_mask', ({(60, 45, 60, 49): 'mask'}, {}), '(mask)', False, 'from rigl.experimental.jax.pruning import masked\n'), ((88, 24, 89, 52), 'jax.numpy.round', 'jnp.round', ({(88, 34, 89, 51): 'pruning_rate[layer_name] * sorted_param.size'}, {}), '(pruning_rate[layer_name] * sorted_param.size)', True, 'import jax.numpy as jnp\n')]
hanzzhu/chadle
venv/Lib/site-packages/dash_bootstrap_components/_components/CardLink.py
ac1d63b0410bb43f3fab362bb00abfc2e8790b9d
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class CardLink(Component): """A CardLink component. Use card link to add consistently styled links to your cards. Links can be used like buttons, external links, or internal Dash style links. Keyword arguments: - children (a list of or a singular dash component, string or number; optional): The children of this component. - id (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across all of the components in an app. - className (string; optional): Often used with CSS to style elements with common properties. - external_link (boolean; optional): If True, the browser will treat this as an external link, forcing a page refresh at the new location. If False, this just changes the location without triggering a page refresh. Use this if you are observing dcc.Location, for instance. Defaults to True for absolute URLs and False otherwise. - href (string; optional): URL of the resource to link to. - key (string; optional): A unique identifier for the component, used to improve performance by React.js while rendering components See https://reactjs.org/docs/lists-and-keys.html for more info. - loading_state (dict; optional): Object that holds the loading state object coming from dash-renderer. `loading_state` is a dict with keys: - component_name (string; optional): Holds the name of the component that is loading. - is_loading (boolean; optional): Determines if the component is loading or not. - prop_name (string; optional): Holds which property is loading. - n_clicks (number; default 0): An integer that represents the number of times that this element has been clicked on. - n_clicks_timestamp (number; default -1): An integer that represents the time (in ms since 1970) at which n_clicks changed. This can be used to tell which button was changed most recently. - style (dict; optional): Defines CSS styles which will override styles previously set. - target (string; optional): Target attribute to pass on to the link. Only applies to external links.""" @_explicitize_args def __init__(self, children=None, id=Component.UNDEFINED, style=Component.UNDEFINED, className=Component.UNDEFINED, key=Component.UNDEFINED, href=Component.UNDEFINED, external_link=Component.UNDEFINED, n_clicks=Component.UNDEFINED, n_clicks_timestamp=Component.UNDEFINED, loading_state=Component.UNDEFINED, target=Component.UNDEFINED, **kwargs): self._prop_names = ['children', 'id', 'className', 'external_link', 'href', 'key', 'loading_state', 'n_clicks', 'n_clicks_timestamp', 'style', 'target'] self._type = 'CardLink' self._namespace = 'dash_bootstrap_components' self._valid_wildcard_attributes = [] self.available_properties = ['children', 'id', 'className', 'external_link', 'href', 'key', 'loading_state', 'n_clicks', 'n_clicks_timestamp', 'style', 'target'] self.available_wildcard_properties = [] _explicit_args = kwargs.pop('_explicit_args') _locals = locals() _locals.update(kwargs) # For wildcard attrs args = {k: _locals[k] for k in _explicit_args if k != 'children'} for k in []: if k not in args: raise TypeError( 'Required argument `' + k + '` was not specified.') super(CardLink, self).__init__(children=children, **args)
[]
antfootAlex/HanLP
plugins/hanlp_demo/hanlp_demo/zh/tf/train/train_ctb9_pos_electra.py
e8044b27ae1de54b9070db08549853d3ca8271e2
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-28 23:15 from hanlp.components.taggers.transformers.transformer_tagger_tf import TransformerTaggerTF from tests import cdroot cdroot() tagger = TransformerTaggerTF() save_dir = 'data/model/pos/ctb9_electra_small_zh_epoch_20' tagger.fit('data/pos/ctb9/train.tsv', 'data/pos/ctb9/test.tsv', save_dir, transformer='hfl/chinese-electra-small-discriminator', max_seq_length=130, warmup_steps_ratio=0.1, epochs=20, learning_rate=5e-5) tagger.load(save_dir) print(tagger(['我', '的', '希望', '是', '希望', '和平'])) tagger.evaluate('data/pos/ctb9/test.tsv', save_dir=save_dir) print(f'Model saved in {save_dir}')
[((7, 0, 7, 8), 'tests.cdroot', 'cdroot', ({}, {}), '()', False, 'from tests import cdroot\n'), ((8, 9, 8, 30), 'hanlp.components.taggers.transformers.transformer_tagger_tf.TransformerTaggerTF', 'TransformerTaggerTF', ({}, {}), '()', False, 'from hanlp.components.taggers.transformers.transformer_tagger_tf import TransformerTaggerTF\n')]
Wedding-APIs-System/Backend-APi
src/app/main.py
5a03be5f36ce8ca7e3abba2d64b63c55752697f3
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api import landing, login, attendance_confirmation from sql_app.database import orm_connection app = FastAPI(title="Sergio's wedding backend API", description="REST API which serves login, attendance confirmation and other features", version="1.0",) origins = [ "*" # "http://190.96.140.12:5500", # "68.251.63.208" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(landing.router) app.include_router(login.router) app.include_router(attendance_confirmation.router) @app.get("/ping") async def pong(): return {"ping": "pong!"}
[((7, 6, 9, 19), 'fastapi.FastAPI', 'FastAPI', (), '', False, 'from fastapi import FastAPI\n')]
NextGenTechBar/twandora
tests/test_pydora/test_utils.py
f626717a5580f82250bbe66d4ebc357e0882382c
from unittest import TestCase from pandora.client import APIClient from pandora.errors import InvalidAuthToken, ParameterMissing from pandora.models.pandora import Station, AdItem, PlaylistItem from pandora.py2compat import Mock, patch from pydora.utils import iterate_forever class TestIterateForever(TestCase): def setUp(self): self.transport = Mock(side_effect=[InvalidAuthToken(), None]) self.client = APIClient(self.transport, None, None, None, None) self.client._authenticate = Mock() def test_handle_missing_params_exception_due_to_missing_ad_tokens(self): with patch.object(APIClient, 'get_playlist') as get_playlist_mock: with patch.object(APIClient, 'register_ad', side_effect=ParameterMissing("ParameterMissing")): station = Station.from_json(self.client, {'stationToken': 'token_mock'}) ad_mock = AdItem.from_json(self.client, {'station_id': 'id_mock'}) get_playlist_mock.return_value=iter([ad_mock]) station_iter = iterate_forever(station.get_playlist) next_track = next(station_iter) self.assertEqual(ad_mock, next_track) def test_reraise_missing_params_exception(self): with patch.object(APIClient, 'get_playlist', side_effect=ParameterMissing("ParameterMissing")) as get_playlist_mock: with self.assertRaises(ParameterMissing): station = Station.from_json(self.client, {'stationToken': 'token_mock'}) track_mock = PlaylistItem.from_json(self.client, {'token': 'token_mock'}) get_playlist_mock.return_value=iter([track_mock]) station_iter = iterate_forever(station.get_playlist) next(station_iter)
[((14, 22, 14, 71), 'pandora.client.APIClient', 'APIClient', ({(14, 32, 14, 46): 'self.transport', (14, 48, 14, 52): 'None', (14, 54, 14, 58): 'None', (14, 60, 14, 64): 'None', (14, 66, 14, 70): 'None'}, {}), '(self.transport, None, None, None, None)', False, 'from pandora.client import APIClient\n'), ((15, 36, 15, 42), 'pandora.py2compat.Mock', 'Mock', ({}, {}), '()', False, 'from pandora.py2compat import Mock, patch\n'), ((18, 13, 18, 52), 'pandora.py2compat.patch.object', 'patch.object', ({(18, 26, 18, 35): 'APIClient', (18, 37, 18, 51): '"""get_playlist"""'}, {}), "(APIClient, 'get_playlist')", False, 'from pandora.py2compat import Mock, patch\n'), ((21, 26, 21, 88), 'pandora.models.pandora.Station.from_json', 'Station.from_json', ({(21, 44, 21, 55): 'self.client', (21, 57, 21, 87): "{'stationToken': 'token_mock'}"}, {}), "(self.client, {'stationToken': 'token_mock'})", False, 'from pandora.models.pandora import Station, AdItem, PlaylistItem\n'), ((22, 26, 22, 82), 'pandora.models.pandora.AdItem.from_json', 'AdItem.from_json', ({(22, 43, 22, 54): 'self.client', (22, 56, 22, 81): "{'station_id': 'id_mock'}"}, {}), "(self.client, {'station_id': 'id_mock'})", False, 'from pandora.models.pandora import Station, AdItem, PlaylistItem\n'), ((25, 31, 25, 68), 'pydora.utils.iterate_forever', 'iterate_forever', ({(25, 47, 25, 67): 'station.get_playlist'}, {}), '(station.get_playlist)', False, 'from pydora.utils import iterate_forever\n'), ((34, 30, 34, 92), 'pandora.models.pandora.Station.from_json', 'Station.from_json', ({(34, 48, 34, 59): 'self.client', (34, 61, 34, 91): "{'stationToken': 'token_mock'}"}, {}), "(self.client, {'stationToken': 'token_mock'})", False, 'from pandora.models.pandora import Station, AdItem, PlaylistItem\n'), ((35, 33, 35, 93), 'pandora.models.pandora.PlaylistItem.from_json', 'PlaylistItem.from_json', ({(35, 56, 35, 67): 'self.client', (35, 69, 35, 92): "{'token': 'token_mock'}"}, {}), "(self.client, {'token': 'token_mock'})", False, 'from pandora.models.pandora import Station, AdItem, PlaylistItem\n'), ((38, 35, 38, 72), 'pydora.utils.iterate_forever', 'iterate_forever', ({(38, 51, 38, 71): 'station.get_playlist'}, {}), '(station.get_playlist)', False, 'from pydora.utils import iterate_forever\n'), ((13, 43, 13, 61), 'pandora.errors.InvalidAuthToken', 'InvalidAuthToken', ({}, {}), '()', False, 'from pandora.errors import InvalidAuthToken, ParameterMissing\n'), ((31, 65, 31, 101), 'pandora.errors.ParameterMissing', 'ParameterMissing', ({(31, 82, 31, 100): '"""ParameterMissing"""'}, {}), "('ParameterMissing')", False, 'from pandora.errors import InvalidAuthToken, ParameterMissing\n'), ((19, 68, 19, 104), 'pandora.errors.ParameterMissing', 'ParameterMissing', ({(19, 85, 19, 103): '"""ParameterMissing"""'}, {}), "('ParameterMissing')", False, 'from pandora.errors import InvalidAuthToken, ParameterMissing\n')]
mdlama/pydstool
PyDSTool/PyCont/BifPoint.py
3d298e908ff55340cd3612078508be0c791f63a8
""" Bifurcation point classes. Each class locates and processes bifurcation points. * _BranchPointFold is a version based on BranchPoint location algorithms * BranchPoint: Branch process is broken (can't find alternate branch -- see MATCONT notes) Drew LaMar, March 2006 """ from __future__ import absolute_import, print_function from .misc import * from PyDSTool.common import args from .TestFunc import DiscreteMap, FixedPointMap from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, \ subtract, divide, transpose, eye, real, imag, \ conjugate, average from scipy import optimize, linalg from numpy import dot as matrixmultiply from numpy import array, float, complex, int, float64, complex64, int32, \ zeros, divide, subtract, reshape, argsort, nonzero ##### _classes = ['BifPoint', 'BPoint', 'BranchPoint', 'FoldPoint', 'HopfPoint', 'BTPoint', 'ZHPoint', 'CPPoint', 'BranchPointFold', '_BranchPointFold', 'DHPoint', 'GHPoint', 'LPCPoint', 'PDPoint', 'NSPoint', 'SPoint'] __all__ = _classes ##### class BifPoint(object): def __init__(self, testfuncs, flagfuncs, label='Bifurcation', stop=False): self.testfuncs = [] self.flagfuncs = [] self.found = [] self.label = label self.stop = stop self.data = args() if not isinstance(testfuncs, list): testfuncs = [testfuncs] if not isinstance(flagfuncs, list): flagfuncs = [flagfuncs] self.testfuncs.extend(testfuncs) self.flagfuncs.extend(flagfuncs) self.tflen = len(self.testfuncs) def locate(self, P1, P2, C): pointlist = [] for i, testfunc in enumerate(self.testfuncs): if self.flagfuncs[i] == iszero: for ind in range(testfunc.m): X, V = testfunc.findzero(P1, P2, ind) pointlist.append((X,V)) X = average([point[0] for point in pointlist], axis=0) V = average([point[1] for point in pointlist], axis=0) C.Corrector(X,V) return X, V def process(self, X, V, C): data = args() data.X = todict(C, X) data.V = todict(C, V) self.found.append(data) def info(self, C, ind=None, strlist=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] if C.verbosity >= 1: print(self.label + ' Point found ') if C.verbosity >= 2: print('========================== ') for n, i in enumerate(ind): print(n, ': ') Xd = self.found[i].X for k, j in Xd.items(): print(k, ' = ', j) print('') if hasattr(self.found[i], 'eigs'): print('Eigenvalues = \n') for x in self.found[i].eigs: print(' (%f,%f)' % (x.real, x.imag)) print('\n') if strlist is not None: for string in strlist: print(string) print('') class SPoint(BifPoint): """Special point that represents user-selected free parameter values.""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'S', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) self.info(C, -1) return True class BPoint(BifPoint): """Special point that represents boundary of computational domain.""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'B', stop=stop) def locate(self, P1, P2, C): # Find location that triggered testfunc and initialize testfunc to that index val1 = (P1[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P1[0]) val2 = (P2[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P2[0]) ind = nonzero(val1*val2 < 0) self.testfuncs[0].ind = ind self.testfuncs[0].func = self.testfuncs[0].one X, V = BifPoint.locate(self, P1, P2, C) # Set testfunc back to monitoring all self.testfuncs[0].ind = None self.testfuncs[0].func = self.testfuncs[0].all return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class BranchPoint(BifPoint): """May only work for EquilibriumCurve ... (needs fixing)""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def __locate_newton(self, X, C): """x[0:self.dim] = (x,alpha) x[self.dim] = beta x[self.dim+1:2*self.dim] = p """ J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords) J_params = C.CorrFunc.jac(X[0:C.dim], C.params) return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \ matrixmultiply(transpose(J_coords),X[C.dim+1:]), \ matrixmultiply(transpose(X[C.dim+1:]),J_params), \ matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1] def locate(self, P1, P2, C): # Initiliaze p vector to eigenvector with smallest eigenvalue X, V = P1 X2, V2 = P2 J_coords = C.CorrFunc.jac(X, C.coords) W, VL = linalg.eig(J_coords, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] p = real(VL[:,ind]) initpoint = zeros(2*C.dim, float) initpoint[0:C.dim] = X initpoint[C.dim+1:] = p X = optimize.fsolve(self.__locate_newton, initpoint, C) self.data.psi = X[C.dim+1:] X = X[0:C.dim] V = 0.5*(V+V2) return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) singular = True perpvec = r_[1,zeros(C.dim-1)] d = 1 while singular and d <= C.dim: try: v0 = linalg.solve(r_[c_[J_coords, J_params], [perpvec]], \ r_[zeros(C.dim-1),1]) except: perpvec = r_[0., perpvec[0:(C.dim-1)]] d += 1 else: singular = False if singular: raise PyDSTool_ExistError("Problem in _compute: Failed to compute tangent vector.") v0 /= linalg.norm(v0) V = sign([x for x in v0 if abs(x) > 1e-8][0])*v0 A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] V1 = real(VR[:,W0[0]]) H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class FoldPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'LP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) # Compute normal form coefficient # NOTE: These are for free when using bordering technique!) # NOTE: Does not agree with MATCONT output! (if |p| = |q| = 1, then it does) J_coords = C.CorrFunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) minW = min(abs(W)) ind = [(abs(eig) < minW+1e-8) and (abs(eig) > minW-1e-8) for eig in W].index(True) p, q = real(VL[:,ind]), real(VR[:,ind]) p /= matrixmultiply(p,q) B = C.CorrFunc.hess(X, C.coords, C.coords) self.found[-1].a = abs(0.5*matrixmultiply(p,[bilinearform(B[i,:,:], q, q) for i in range(B.shape[0])])) self.found[-1].eigs = W numzero = len([eig for eig in W if abs(eig) < 1e-4]) if numzero > 1: if C.verbosity >= 2: print('Fold-Fold!\n') del self.found[-1] return False elif numzero == 0: if C.verbosity >= 2: print('False positive!\n') del self.found[-1] return False if C.verbosity >= 2: print('\nChecking...') print(' |q| = %f' % linalg.norm(q)) print(' <p,q> = %f' % matrixmultiply(p,q)) print(' |Aq| = %f' % linalg.norm(matrixmultiply(J_coords,q))) print(' |transpose(A)p| = %f\n' % linalg.norm(matrixmultiply(transpose(J_coords),p))) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('a = ' + repr(self.found[i].a)) BifPoint.info(self, C, ind, strlist) class HopfPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'H', stop=stop) def process(self, X, V, C): """Tolerance for eigenvalues a possible problem when checking for neutral saddles.""" BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) # Check for neutral saddles found = False for i in range(len(eigs)): if abs(imag(eigs[i])) < 1e-5: for j in range(i+1,len(eigs)): if C.verbosity >= 2: if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5: print('Fold-Fold point found in Hopf!\n') elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5: print('Neutral saddle found!\n') elif abs(real(eigs[i])) < 1e-5: for j in range(i+1, len(eigs)): if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5: found = True w = abs(imag(eigs[i])) if imag(eigs[i]) > 0: p = conjugate(LV[:,j])/linalg.norm(LV[:,j]) q = RV[:,i]/linalg.norm(RV[:,i]) else: p = conjugate(LV[:,i])/linalg.norm(LV[:,i]) q = RV[:,j]/linalg.norm(RV[:,j]) if not found: del self.found[-1] return False direc = conjugate(1/matrixmultiply(conjugate(p),q)) p = direc*p # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4]) #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \ # w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q)))) self.found[-1].w = w self.found[-1].l1 = firstlyapunov(X, C.CorrFunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('w = ' + repr(self.found[i].w)) strlist.append('l1 = ' + repr(self.found[i].l1)) BifPoint.info(self, C, ind, strlist) # Codimension-2 bifurcations class BTPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BT', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W if C.verbosity >= 2: if C.CorrFunc.testfunc.data.B.shape[1] == 2: b = matrixmultiply(transpose(J_coords), C.CorrFunc.testfunc.data.w[:,0]) c = matrixmultiply(J_coords, C.CorrFunc.testfunc.data.v[:,0]) else: b = C.CorrFunc.testfunc.data.w[:,0] c = C.CorrFunc.testfunc.data.v[:,0] print('\nChecking...') print(' <b,c> = %f' % matrixmultiply(transpose(b), c)) print('\n') self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class ZHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'ZH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class CPPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'CP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) B = C.CorrFunc.sysfunc.hess(X, C.coords, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) q = C.CorrFunc.testfunc.data.C/linalg.norm(C.CorrFunc.testfunc.data.C) p = C.CorrFunc.testfunc.data.B/matrixmultiply(transpose(C.CorrFunc.testfunc.data.B),q) self.found[-1].eigs = W a = 0.5*matrixmultiply(transpose(p), reshape([bilinearform(B[i,:,:], q, q) \ for i in range(B.shape[0])],(B.shape[0],1)))[0][0] if C.verbosity >= 2: print('\nChecking...') print(' |a| = %f' % a) print('\n') self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class BranchPointFold(BifPoint): """Check Equilibrium.m in MATCONT""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) pind = self.testfuncs[0].pind # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] #A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] tmp = real(VR[:,W0[0]]) V1 = r_[tmp[:-1], 0, 0] V1[len(tmp)-1+pind] = tmp[-1] """NEED TO FIX THIS!""" H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) # c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) # c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) # c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) # beta = 1 # alpha = -1*c22/(2*c12) # V1 = alpha*V + beta*V1 # V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = None self.found[-1].par = C.freepars[self.testfuncs[0].pind] # self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] #for n, i in enumerate(ind): # strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ # tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class _BranchPointFold(BifPoint): """Check Equilibrium.m in MATCONT""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def __locate_newton(self, X, C): """Note: This is redundant!! B is a column of A!!! Works for now, though...""" pind = self.testfuncs[0].pind J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords) J_params = C.CorrFunc.jac(X[0:C.dim], C.params) A = c_[J_coords, J_params[:,pind]] B = J_params[:,pind] return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \ matrixmultiply(transpose(A),X[C.dim+1:]), \ matrixmultiply(transpose(X[C.dim+1:]),B), \ matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1] def locate(self, P1, P2, C): # Initiliaze p vector to eigenvector with smallest eigenvalue X, V = P1 pind = self.testfuncs[0].pind J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] W, VL = linalg.eig(A, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] p = real(VL[:,ind]) initpoint = zeros(2*C.dim, float) initpoint[0:C.dim] = X initpoint[C.dim+1:] = p X = optimize.fsolve(self.__locate_newton, initpoint, C) self.data.psi = X[C.dim+1:] X = X[0:C.dim] return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) pind = self.testfuncs[0].pind # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] #A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] tmp = real(VR[:,W0[0]]) V1 = r_[tmp[:-1], 0, 0] V1[len(tmp)-1+pind] = tmp[-1] """NEED TO FIX THIS!""" H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = None self.found[-1].par = C.freepars[self.testfuncs[0].pind] self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] #for n, i in enumerate(ind): # strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ # tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class DHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'DH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class GHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'GH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) # Check for neutral saddles found = False for i in range(len(eigs)): if abs(imag(eigs[i])) < 1e-5: for j in range(i+1,len(eigs)): if C.verbosity >= 2: if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5: print('Fold-Fold point found in Hopf!\n') elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5: print('Neutral saddle found!\n') elif abs(real(eigs[i])) < 1e-5: for j in range(i+1, len(eigs)): if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5: found = True w = abs(imag(eigs[i])) if imag(eigs[i]) > 0: p = conjugate(LV[:,j]/linalg.norm(LV[:,j])) q = RV[:,i]/linalg.norm(RV[:,i]) else: p = conjugate(LV[:,i]/linalg.norm(LV[:,i])) q = RV[:,j]/linalg.norm(RV[:,j]) if not found: del self.found[-1] return False direc = conjugate(1/matrixmultiply(conjugate(p),q)) p = direc*p # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4]) #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \ # w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q)))) self.found[-1].w = w self.found[-1].l1 = firstlyapunov(X, C.CorrFunc.sysfunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('w = ' + repr(self.found[i].w)) strlist.append('l1 = ' + repr(self.found[i].l1)) BifPoint.info(self, C, ind, strlist) # Discrete maps class LPCPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'LPC', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) strlist.append('Test function #2: ' + repr(self.testfuncs[1](X,V)[0])) BifPoint.info(self, C, ind, strlist) class PDPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'PD', stop=stop) def process(self, X, V, C): """Do I need to compute the branch, or will it always be in the direction of freepar = constant?""" BifPoint.process(self, X, V, C) F = DiscreteMap(C.sysfunc, period=2*C.sysfunc.period) FP = FixedPointMap(F) J_coords = FP.jac(X, C.coords) J_params = FP.jac(X, C.params) # Locate branch of double period map W, VL = linalg.eig(J_coords, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] psi = real(VL[:,ind]) A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = argsort([abs(eig) for eig in W])[0] V1 = real(VR[:,W0]) H = FP.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) J_coords = C.sysfunc.jac(X, C.coords) W = linalg.eig(J_coords, right=0) self.found[-1].eigs = W self.found[-1].branch_period = 2*C.sysfunc.period self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('Period doubling branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ tocoords(C, self.found[i].branch)))) BifPoint.info(self, C, ind, strlist) class NSPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'NS', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.sysfunc.jac(X, C.coords) eigs, VL, VR = linalg.eig(J_coords, left=1, right=1) # Check for nonreal multipliers found = False for i in range(len(eigs)): for j in range(i+1,len(eigs)): if abs(imag(eigs[i])) > 1e-10 and \ abs(imag(eigs[j])) > 1e-10 and \ abs(eigs[i]*eigs[j] - 1) < 1e-5: found = True if not found: del self.found[-1] return False self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind)
[((39, 20, 39, 26), 'PyDSTool.common.args', 'args', ({}, {}), '()', False, 'from PyDSTool.common import args\n'), ((59, 12, 59, 62), 'numpy.average', 'average', (), '', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((60, 12, 60, 62), 'numpy.average', 'average', (), '', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((66, 15, 66, 21), 'PyDSTool.common.args', 'args', ({}, {}), '()', False, 'from PyDSTool.common import args\n'), ((119, 14, 119, 36), 'numpy.nonzero', 'nonzero', ({(119, 22, 119, 35): 'val1 * val2 < 0'}, {}), '(val1 * val2 < 0)', False, 'from numpy import array, float, complex, int, float64, complex64, int32, zeros, divide, subtract, reshape, argsort, nonzero\n'), ((173, 16, 173, 53), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((175, 12, 175, 27), 'numpy.real', 'real', ({(175, 17, 175, 26): 'VL[:, (ind)]'}, {}), '(VL[:, (ind)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((177, 20, 177, 41), 'numpy.zeros', 'zeros', ({(177, 26, 177, 33): '2 * C.dim', (177, 35, 177, 40): 'float'}, {}), '(2 * C.dim, float)', False, 'from numpy import array, float, complex, int, float64, complex64, int32, zeros, divide, subtract, reshape, argsort, nonzero\n'), ((181, 12, 181, 63), 'scipy.optimize.fsolve', 'optimize.fsolve', ({(181, 28, 181, 48): 'self.__locate_newton', (181, 50, 181, 59): 'initpoint', (181, 61, 181, 62): 'C'}, {}), '(self.__locate_newton, initpoint, C)', False, 'from scipy import optimize, linalg\n'), ((213, 14, 213, 29), 'scipy.linalg.norm', 'linalg.norm', ({(213, 26, 213, 28): 'v0'}, {}), '(v0)', False, 'from scipy import optimize, linalg\n'), ((217, 16, 217, 29), 'scipy.linalg.eig', 'linalg.eig', ({(217, 27, 217, 28): 'A'}, {}), '(A)', False, 'from scipy import optimize, linalg\n'), ((219, 13, 219, 30), 'numpy.real', 'real', ({(219, 18, 219, 29): 'VR[:, (W0[0])]'}, {}), '(VR[:, (W0[0])])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((229, 14, 229, 29), 'scipy.linalg.norm', 'linalg.norm', ({(229, 26, 229, 28): 'V1'}, {}), '(V1)', False, 'from scipy import optimize, linalg\n'), ((269, 20, 269, 57), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((273, 13, 273, 32), 'numpy.dot', 'matrixmultiply', ({(273, 28, 273, 29): 'p', (273, 30, 273, 31): 'q'}, {}), '(p, q)', True, 'from numpy import dot as matrixmultiply\n'), ((325, 23, 325, 58), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((394, 20, 394, 57), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((432, 20, 432, 57), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((460, 20, 460, 57), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((504, 16, 504, 29), 'scipy.linalg.eig', 'linalg.eig', ({(504, 27, 504, 28): 'A'}, {}), '(A)', False, 'from scipy import optimize, linalg\n'), ((506, 14, 506, 31), 'numpy.real', 'real', ({(506, 19, 506, 30): 'VR[:, (W0[0])]'}, {}), '(VR[:, (W0[0])])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((579, 16, 579, 46), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((581, 12, 581, 27), 'numpy.real', 'real', ({(581, 17, 581, 26): 'VL[:, (ind)]'}, {}), '(VL[:, (ind)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((583, 20, 583, 41), 'numpy.zeros', 'zeros', ({(583, 26, 583, 33): '2 * C.dim', (583, 35, 583, 40): 'float'}, {}), '(2 * C.dim, float)', False, 'from numpy import array, float, complex, int, float64, complex64, int32, zeros, divide, subtract, reshape, argsort, nonzero\n'), ((587, 12, 587, 63), 'scipy.optimize.fsolve', 'optimize.fsolve', ({(587, 28, 587, 48): 'self.__locate_newton', (587, 50, 587, 59): 'initpoint', (587, 61, 587, 62): 'C'}, {}), '(self.__locate_newton, initpoint, C)', False, 'from scipy import optimize, linalg\n'), ((605, 16, 605, 29), 'scipy.linalg.eig', 'linalg.eig', ({(605, 27, 605, 28): 'A'}, {}), '(A)', False, 'from scipy import optimize, linalg\n'), ((607, 14, 607, 31), 'numpy.real', 'real', ({(607, 19, 607, 30): 'VR[:, (W0[0])]'}, {}), '(VR[:, (W0[0])])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((620, 14, 620, 29), 'scipy.linalg.norm', 'linalg.norm', ({(620, 26, 620, 28): 'V1'}, {}), '(V1)', False, 'from scipy import optimize, linalg\n'), ((658, 23, 658, 58), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((684, 23, 684, 58), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((754, 20, 754, 57), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((792, 16, 792, 53), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((794, 14, 794, 29), 'numpy.real', 'real', ({(794, 19, 794, 28): 'VL[:, (ind)]'}, {}), '(VL[:, (ind)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((797, 16, 797, 29), 'scipy.linalg.eig', 'linalg.eig', ({(797, 27, 797, 28): 'A'}, {}), '(A)', False, 'from scipy import optimize, linalg\n'), ((799, 13, 799, 27), 'numpy.real', 'real', ({(799, 18, 799, 26): 'VR[:, (W0)]'}, {}), '(VR[:, (W0)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((809, 14, 809, 29), 'scipy.linalg.norm', 'linalg.norm', ({(809, 26, 809, 28): 'V1'}, {}), '(V1)', False, 'from scipy import optimize, linalg\n'), ((812, 12, 812, 41), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((846, 23, 846, 60), 'scipy.linalg.eig', 'linalg.eig', (), '', False, 'from scipy import optimize, linalg\n'), ((272, 15, 272, 30), 'numpy.real', 'real', ({(272, 20, 272, 29): 'VL[:, (ind)]'}, {}), '(VL[:, (ind)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((272, 32, 272, 47), 'numpy.real', 'real', ({(272, 37, 272, 46): 'VR[:, (ind)]'}, {}), '(VR[:, (ind)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((462, 39, 462, 78), 'scipy.linalg.norm', 'linalg.norm', ({(462, 51, 462, 77): 'C.CorrFunc.testfunc.data.C'}, {}), '(C.CorrFunc.testfunc.data.C)', False, 'from scipy import optimize, linalg\n'), ((401, 20, 401, 77), 'numpy.dot', 'matrixmultiply', ({(401, 35, 401, 43): 'J_coords', (401, 45, 401, 76): 'C.CorrFunc.testfunc.data.v[:, (0)]'}, {}), '(J_coords, C.CorrFunc.testfunc.data.v[:, (0)])', True, 'from numpy import dot as matrixmultiply\n'), ((463, 54, 463, 91), 'numpy.transpose', 'transpose', ({(463, 64, 463, 90): 'C.CorrFunc.testfunc.data.B'}, {}), '(C.CorrFunc.testfunc.data.B)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((198, 23, 198, 37), 'numpy.zeros', 'zeros', ({(198, 29, 198, 36): '(C.dim - 1)'}, {}), '(C.dim - 1)', False, 'from numpy import array, float, complex, int, float64, complex64, int32, zeros, divide, subtract, reshape, argsort, nonzero\n'), ((293, 33, 293, 47), 'scipy.linalg.norm', 'linalg.norm', ({(293, 45, 293, 46): 'q'}, {}), '(q)', False, 'from scipy import optimize, linalg\n'), ((294, 35, 294, 54), 'numpy.dot', 'matrixmultiply', ({(294, 50, 294, 51): 'p', (294, 52, 294, 53): 'q'}, {}), '(p, q)', True, 'from numpy import dot as matrixmultiply\n'), ((330, 19, 330, 32), 'numpy.imag', 'imag', ({(330, 24, 330, 31): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((353, 43, 353, 55), 'numpy.conjugate', 'conjugate', ({(353, 53, 353, 54): 'p'}, {}), '(p)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((400, 35, 400, 54), 'numpy.transpose', 'transpose', ({(400, 45, 400, 53): 'J_coords'}, {}), '(J_coords)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((689, 19, 689, 32), 'numpy.imag', 'imag', ({(689, 24, 689, 31): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((712, 43, 712, 55), 'numpy.conjugate', 'conjugate', ({(712, 53, 712, 54): 'p'}, {}), '(p)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((162, 33, 162, 52), 'numpy.transpose', 'transpose', ({(162, 43, 162, 51): 'J_coords'}, {}), '(J_coords)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((163, 33, 163, 55), 'numpy.transpose', 'transpose', ({(163, 43, 163, 54): 'X[C.dim + 1:]'}, {}), '(X[C.dim + 1:])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((295, 46, 295, 72), 'numpy.dot', 'matrixmultiply', ({(295, 61, 295, 69): 'J_coords', (295, 70, 295, 71): 'q'}, {}), '(J_coords, q)', True, 'from numpy import dot as matrixmultiply\n'), ((337, 21, 337, 34), 'numpy.real', 'real', ({(337, 26, 337, 33): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((406, 50, 406, 62), 'numpy.transpose', 'transpose', ({(406, 60, 406, 61): 'b'}, {}), '(b)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((467, 31, 467, 43), 'numpy.transpose', 'transpose', ({(467, 41, 467, 42): 'p'}, {}), '(p)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((564, 33, 564, 45), 'numpy.transpose', 'transpose', ({(564, 43, 564, 44): 'A'}, {}), '(A)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((565, 33, 565, 55), 'numpy.transpose', 'transpose', ({(565, 43, 565, 54): 'X[C.dim + 1:]'}, {}), '(X[C.dim + 1:])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((696, 21, 696, 34), 'numpy.real', 'real', ({(696, 26, 696, 33): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((164, 33, 164, 55), 'numpy.transpose', 'transpose', ({(164, 43, 164, 54): 'X[C.dim + 1:]'}, {}), '(X[C.dim + 1:])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((296, 74, 296, 93), 'numpy.transpose', 'transpose', ({(296, 84, 296, 92): 'J_coords'}, {}), '(J_coords)', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((566, 33, 566, 55), 'numpy.transpose', 'transpose', ({(566, 43, 566, 54): 'X[C.dim + 1:]'}, {}), '(X[C.dim + 1:])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((852, 23, 852, 36), 'numpy.imag', 'imag', ({(852, 28, 852, 35): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((853, 23, 853, 36), 'numpy.imag', 'imag', ({(853, 28, 853, 35): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((204, 37, 204, 51), 'numpy.zeros', 'zeros', ({(204, 43, 204, 50): 'C.dim - 1'}, {}), '(C.dim - 1)', False, 'from numpy import array, float, complex, int, float64, complex64, int32, zeros, divide, subtract, reshape, argsort, nonzero\n'), ((341, 32, 341, 45), 'numpy.imag', 'imag', ({(341, 37, 341, 44): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((342, 27, 342, 40), 'numpy.imag', 'imag', ({(342, 32, 342, 39): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((700, 32, 700, 45), 'numpy.imag', 'imag', ({(700, 37, 700, 44): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((701, 27, 701, 40), 'numpy.imag', 'imag', ({(701, 32, 701, 39): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((339, 27, 339, 40), 'numpy.real', 'real', ({(339, 32, 339, 39): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((343, 32, 343, 50), 'numpy.conjugate', 'conjugate', ({(343, 42, 343, 49): 'LV[:, (j)]'}, {}), '(LV[:, (j)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((343, 51, 343, 71), 'scipy.linalg.norm', 'linalg.norm', ({(343, 63, 343, 70): 'LV[:, (j)]'}, {}), '(LV[:, (j)])', False, 'from scipy import optimize, linalg\n'), ((344, 40, 344, 60), 'scipy.linalg.norm', 'linalg.norm', ({(344, 52, 344, 59): 'RV[:, (i)]'}, {}), '(RV[:, (i)])', False, 'from scipy import optimize, linalg\n'), ((346, 32, 346, 50), 'numpy.conjugate', 'conjugate', ({(346, 42, 346, 49): 'LV[:, (i)]'}, {}), '(LV[:, (i)])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((346, 51, 346, 71), 'scipy.linalg.norm', 'linalg.norm', ({(346, 63, 346, 70): 'LV[:, (i)]'}, {}), '(LV[:, (i)])', False, 'from scipy import optimize, linalg\n'), ((347, 40, 347, 60), 'scipy.linalg.norm', 'linalg.norm', ({(347, 52, 347, 59): 'RV[:, (j)]'}, {}), '(RV[:, (j)])', False, 'from scipy import optimize, linalg\n'), ((698, 27, 698, 40), 'numpy.real', 'real', ({(698, 32, 698, 39): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((703, 40, 703, 60), 'scipy.linalg.norm', 'linalg.norm', ({(703, 52, 703, 59): 'RV[:, (i)]'}, {}), '(RV[:, (i)])', False, 'from scipy import optimize, linalg\n'), ((706, 40, 706, 60), 'scipy.linalg.norm', 'linalg.norm', ({(706, 52, 706, 59): 'RV[:, (j)]'}, {}), '(RV[:, (j)])', False, 'from scipy import optimize, linalg\n'), ((335, 33, 335, 46), 'numpy.imag', 'imag', ({(335, 38, 335, 45): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((339, 57, 339, 70), 'numpy.real', 'real', ({(339, 62, 339, 69): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((339, 73, 339, 86), 'numpy.real', 'real', ({(339, 78, 339, 85): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((694, 33, 694, 46), 'numpy.imag', 'imag', ({(694, 38, 694, 45): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((698, 57, 698, 70), 'numpy.real', 'real', ({(698, 62, 698, 69): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((698, 73, 698, 86), 'numpy.real', 'real', ({(698, 78, 698, 85): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((702, 50, 702, 70), 'scipy.linalg.norm', 'linalg.norm', ({(702, 62, 702, 69): 'LV[:, (j)]'}, {}), '(LV[:, (j)])', False, 'from scipy import optimize, linalg\n'), ((705, 50, 705, 70), 'scipy.linalg.norm', 'linalg.norm', ({(705, 62, 705, 69): 'LV[:, (i)]'}, {}), '(LV[:, (i)])', False, 'from scipy import optimize, linalg\n'), ((335, 63, 335, 76), 'numpy.real', 'real', ({(335, 68, 335, 75): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((335, 79, 335, 92), 'numpy.real', 'real', ({(335, 84, 335, 91): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((694, 63, 694, 76), 'numpy.real', 'real', ({(694, 68, 694, 75): 'eigs[i]'}, {}), '(eigs[i])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n'), ((694, 79, 694, 92), 'numpy.real', 'real', ({(694, 84, 694, 91): 'eigs[j]'}, {}), '(eigs[j])', False, 'from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, subtract, divide, transpose, eye, real, imag, conjugate, average\n')]
OmenApps/marion
src/marion/marion/urls/__init__.py
f501674cafbd91f0bbad7454e4dcf3527cf4445e
"""Urls for the marion application""" from django.urls import include, path from rest_framework import routers from .. import views router = routers.DefaultRouter() router.register(r"requests", views.DocumentRequestViewSet) urlpatterns = [ path("", include(router.urls)), ]
[((9, 9, 9, 32), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ({}, {}), '()', False, 'from rest_framework import routers\n'), ((13, 13, 13, 33), 'django.urls.include', 'include', ({(13, 21, 13, 32): 'router.urls'}, {}), '(router.urls)', False, 'from django.urls import include, path\n')]
TanKingsley/pyxll-jupyter
setup.py
4f7b3eb361079b74683d89340dfff9576fb2ff41
""" PyXLL-Jupyter This package integrated Jupyter notebooks into Microsoft Excel. To install it, first install PyXLL (see https://www.pyxll.com). Briefly, to install PyXLL do the following:: pip install pyxll pyxll install Once PyXLL is installed then installing this package will add a button to the PyXLL ribbon toolbar that will start a Jupyter notebook browser as a custom task pane in Excel. To install this package use:: pip install pyxll_jupyter """ from setuptools import setup, find_packages from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name="pyxll_jupyter", description="Adds Jupyter notebooks to Microsoft Excel using PyXLL.", long_description=long_description, long_description_content_type='text/markdown', version="0.1.11", packages=find_packages(), include_package_data=True, package_data={ "pyxll_jupyter": [ "pyxll_jupyter/resources/ribbon.xml", "pyxll_jupyter/resources/jupyter.png", ] }, project_urls={ "Source": "https://github.com/pyxll/pyxll-jupyter", "Tracker": "https://github.com/pyxll/pyxll-jupyter/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: Microsoft :: Windows" ], entry_points={ "pyxll": [ "modules = pyxll_jupyter.pyxll:modules", "ribbon = pyxll_jupyter.pyxll:ribbon" ] }, install_requires=[ "pyxll >= 5.0.0", "jupyter >= 1.0.0", "PySide2" ] )
[((25, 30, 25, 52), 'os.path.dirname', 'path.dirname', ({(25, 43, 25, 51): '__file__'}, {}), '(__file__)', False, 'from os import path\n'), ((26, 10, 26, 48), 'os.path.join', 'path.join', ({(26, 20, 26, 34): 'this_directory', (26, 36, 26, 47): '"""README.md"""'}, {}), "(this_directory, 'README.md')", False, 'from os import path\n'), ((36, 13, 36, 28), 'setuptools.find_packages', 'find_packages', ({}, {}), '()', False, 'from setuptools import setup, find_packages\n')]
albi23/Pyra
board/views.py
1c1ceece15d55cd0e0ecf41d7224683b93b72555
from typing import List from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic, View from board.forms import SignUpForm from .const import BOARD_VIEW_COLUMN_COUNT from .models import Board, Priority, Membership, Contribution from .models import Task @login_required def index(request): board_col, row_count = Board.objects.get_user_split_boards(request.user, BOARD_VIEW_COLUMN_COUNT) context = { 'board_col': board_col, 'row_count': row_count } return render(request, 'index.html', context) @login_required def board(request, board_id): _board = Board.objects.get(id=board_id) todo_tasks: List[Task] = Task.objects.filter(board=_board, status='TODO') doing_tasks = Task.objects.filter(board=_board, status='DOING') done_tasks = Task.objects.filter(board=_board, status='DONE') context = { 'board': _board, 'todo_tasks': todo_tasks, 'doing_tasks': doing_tasks, 'done_tasks': done_tasks, 'user': request.user, } return render(request, 'board.html', context) @login_required def update_task_state(request): if request.method == "POST": task_id = request.POST['task_id'] new_state = request.POST['new_state'] this_task = Task.objects.get(id=task_id) this_task.status = new_state this_task.save() return JsonResponse({"success": True}) class SignUp(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy('login') template_name = 'signup.html' class CreateBoard(View): def post(self, request): name = request.POST['name'] description = request.POST['description'] if name: new_board = Board.objects.create( name=name, description=description, ) Membership.objects.create( board=new_board, user=request.user, role=Membership.Role.SUPER_USER ) return JsonResponse({"success": True}) return JsonResponse({"success": False}) class CreateTask(View): def post(self, request): title = request.POST['title'] description = request.POST['description'] status = request.POST['status'] priority = int(request.POST['priority']) board_id = int(request.POST['board_id']) if title and request.user in Board.objects.get(id=board_id).members.all(): Task.objects.create( title=title, description=description, status=status, priority=Priority.choices[-int(priority) - 1][0], created_by=request.user, board_id=board_id ) return JsonResponse({"success": True}) return JsonResponse({"success": False}) class CreateBoardMembership(View): def post(self, request): username = request.POST['username'] board_id = int(request.POST['board_id']) if username and board_id: try: user = User.objects.get(username=username) except User.DoesNotExist: return JsonResponse( status=404, data={'message': 'User doesn\'t exist'} ) try: membership = Membership.objects.get(board=board_id, user=user.id) except Membership.DoesNotExist: membership = None if membership is not None: return JsonResponse( status=400, data={'message': 'user already added'} ) Membership.objects.create( user=user, board_id=board_id ) return JsonResponse({'message': 'success'}) return JsonResponse( status=400, data={'message': 'username or board_id can\'t be empty'} ) def parse_priority(value: str): choices = Priority.choices for i in range(0, len(choices)): if value == choices[i][1].lower(): return choices[i][0] @login_required def update_task(request): this_task = Task.objects.get(id=request.POST['id']) this_task.title = request.POST['title'] this_task.description = request.POST['description'] this_task.status = request.POST['status'] this_task.priority = parse_priority(request.POST['priority'].lower()) this_task.save() assigned_user_id = request.POST['user'] if assigned_user_id: Contribution.objects.create( task=this_task, user_id=assigned_user_id, ) return JsonResponse({"success": True}) @login_required def get_available_users(request): users = User.objects.filter( membership__board_id=request.GET['board'] ).exclude( contribution__task_id=request.GET['task'] ) response_users = list(map( lambda user: { 'id': user.id, 'username': user.username }, users )) return JsonResponse({'users': response_users}) @login_required def delete_task(request): if request.method.POST['task']: task = Task.objects.get(id=request.method.GET['task']) if request.user in task.board.members.all(): task.delete() return JsonResponse({"success": True}) return JsonResponse({"success": False})
[((24, 11, 24, 49), 'django.shortcuts.render', 'render', ({(24, 18, 24, 25): 'request', (24, 27, 24, 39): '"""index.html"""', (24, 41, 24, 48): 'context'}, {}), "(request, 'index.html', context)", False, 'from django.shortcuts import render\n'), ((42, 11, 42, 49), 'django.shortcuts.render', 'render', ({(42, 18, 42, 25): 'request', (42, 27, 42, 39): '"""board.html"""', (42, 41, 42, 48): 'context'}, {}), "(request, 'board.html', context)", False, 'from django.shortcuts import render\n'), ((54, 11, 54, 42), 'django.http.JsonResponse', 'JsonResponse', ({(54, 24, 54, 41): "{'success': True}"}, {}), "({'success': True})", False, 'from django.http import JsonResponse\n'), ((59, 18, 59, 39), 'django.urls.reverse_lazy', 'reverse_lazy', ({(59, 31, 59, 38): '"""login"""'}, {}), "('login')", False, 'from django.urls import reverse_lazy\n'), ((170, 11, 170, 42), 'django.http.JsonResponse', 'JsonResponse', ({(170, 24, 170, 41): "{'success': True}"}, {}), "({'success': True})", False, 'from django.http import JsonResponse\n'), ((188, 11, 188, 50), 'django.http.JsonResponse', 'JsonResponse', ({(188, 24, 188, 49): "{'users': response_users}"}, {}), "({'users': response_users})", False, 'from django.http import JsonResponse\n'), ((198, 11, 198, 43), 'django.http.JsonResponse', 'JsonResponse', ({(198, 24, 198, 42): "{'success': False}"}, {}), "({'success': False})", False, 'from django.http import JsonResponse\n'), ((82, 15, 82, 47), 'django.http.JsonResponse', 'JsonResponse', ({(82, 28, 82, 46): "{'success': False}"}, {}), "({'success': False})", False, 'from django.http import JsonResponse\n'), ((106, 15, 106, 47), 'django.http.JsonResponse', 'JsonResponse', ({(106, 28, 106, 46): "{'success': False}"}, {}), "({'success': False})", False, 'from django.http import JsonResponse\n'), ((141, 15, 144, 9), 'django.http.JsonResponse', 'JsonResponse', (), '', False, 'from django.http import JsonResponse\n'), ((80, 19, 80, 50), 'django.http.JsonResponse', 'JsonResponse', ({(80, 32, 80, 49): "{'success': True}"}, {}), "({'success': True})", False, 'from django.http import JsonResponse\n'), ((104, 19, 104, 50), 'django.http.JsonResponse', 'JsonResponse', ({(104, 32, 104, 49): "{'success': True}"}, {}), "({'success': True})", False, 'from django.http import JsonResponse\n'), ((139, 19, 139, 55), 'django.http.JsonResponse', 'JsonResponse', ({(139, 32, 139, 54): "{'message': 'success'}"}, {}), "({'message': 'success'})", False, 'from django.http import JsonResponse\n'), ((175, 12, 177, 5), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', (), '', False, 'from django.contrib.auth.models import User\n'), ((197, 19, 197, 50), 'django.http.JsonResponse', 'JsonResponse', ({(197, 32, 197, 49): "{'success': True}"}, {}), "({'success': True})", False, 'from django.http import JsonResponse\n'), ((117, 23, 117, 58), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', (), '', False, 'from django.contrib.auth.models import User\n'), ((130, 23, 133, 17), 'django.http.JsonResponse', 'JsonResponse', (), '', False, 'from django.http import JsonResponse\n'), ((119, 23, 122, 17), 'django.http.JsonResponse', 'JsonResponse', (), '', False, 'from django.http import JsonResponse\n')]
lazmond3/pylib-instagram-type
setup.py
9683a7fb1dad9b1a770a3f98317f1cde1085f0a7
# -*- coding: utf-8 -*- # Learn more: https://github.com/kennethreitz/setup.py from setuptools import setup, find_packages import os with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() def take_package_name(name): if name.startswith("-e"): return name[name.find("=")+1:name.rfind("-")] else: return name.strip() def load_requires_from_file(filepath): with open(filepath) as fp: return [take_package_name(pkg_name) for pkg_name in fp.readlines()] setup( name='lazmond3-pylib-instagram-type', version='1.0.8', description='update from 1.0.8: hasattr: 1.0.7: medias 複数, str get multiple + init.py', long_description=readme, author='lazmond3', author_email='[email protected]', url='https://github.com/lazmond3/pylib-instagram-type.git', install_requires=["lazmond3-pylib-debug"], license=license, packages=find_packages(exclude=('tests', 'docs')), test_suite='tests' )
[((37, 13, 37, 53), 'setuptools.find_packages', 'find_packages', (), '', False, 'from setuptools import setup, find_packages\n')]
arush15june/wagtail-torchbox
tbx/core/migrations/0111_move_sign_up_form_into_new_app.py
c4d06e096c72bd8007975dc016133024f9d27fab
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-01-15 22:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wagtailsearchpromotions', '0002_capitalizeverbose'), ('wagtailcore', '0040_page_draft_title'), ('wagtailredirects', '0006_redirect_increase_max_length'), ('wagtailforms', '0003_capitalizeverbose'), ('torchbox', '0110_rename_blogpagetaglist_to_tag'), ] database_operations = [ migrations.AlterModelTable('SignUpFormPageResponse', 'sign_up_form_signupformpageresponse'), migrations.AlterModelTable('SignUpFormPage', 'sign_up_form_signupformpage'), migrations.AlterModelTable('SignUpFormPageBullet', 'sign_up_form_signupformpagebullet'), migrations.AlterModelTable('SignUpFormPageLogo', 'sign_up_form_signupformpagelogo'), migrations.AlterModelTable('SignUpFormPageQuote', 'sign_up_form_signupformpagequote'), ] state_operations = [ migrations.RemoveField( model_name='signupformpage', name='call_to_action_image', ), migrations.RemoveField( model_name='signupformpage', name='email_attachment', ), migrations.RemoveField( model_name='signupformpage', name='page_ptr', ), migrations.RemoveField( model_name='signupformpagebullet', name='page', ), migrations.RemoveField( model_name='signupformpagelogo', name='logo', ), migrations.RemoveField( model_name='signupformpagelogo', name='page', ), migrations.RemoveField( model_name='signupformpagequote', name='page', ), migrations.DeleteModel( name='SignUpFormPageResponse', ), migrations.DeleteModel( name='SignUpFormPage', ), migrations.DeleteModel( name='SignUpFormPageBullet', ), migrations.DeleteModel( name='SignUpFormPageLogo', ), migrations.DeleteModel( name='SignUpFormPageQuote', ), ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations, ) ]
[((19, 8, 19, 99), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', ({(19, 35, 19, 59): '"""SignUpFormPageResponse"""', (19, 61, 19, 98): '"""sign_up_form_signupformpageresponse"""'}, {}), "('SignUpFormPageResponse',\n 'sign_up_form_signupformpageresponse')", False, 'from django.db import migrations\n'), ((20, 8, 20, 83), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', ({(20, 35, 20, 51): '"""SignUpFormPage"""', (20, 53, 20, 82): '"""sign_up_form_signupformpage"""'}, {}), "('SignUpFormPage', 'sign_up_form_signupformpage')", False, 'from django.db import migrations\n'), ((21, 8, 21, 95), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', ({(21, 35, 21, 57): '"""SignUpFormPageBullet"""', (21, 59, 21, 94): '"""sign_up_form_signupformpagebullet"""'}, {}), "('SignUpFormPageBullet',\n 'sign_up_form_signupformpagebullet')", False, 'from django.db import migrations\n'), ((22, 8, 22, 91), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', ({(22, 35, 22, 55): '"""SignUpFormPageLogo"""', (22, 57, 22, 90): '"""sign_up_form_signupformpagelogo"""'}, {}), "('SignUpFormPageLogo',\n 'sign_up_form_signupformpagelogo')", False, 'from django.db import migrations\n'), ((23, 8, 23, 93), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable', ({(23, 35, 23, 56): '"""SignUpFormPageQuote"""', (23, 58, 23, 92): '"""sign_up_form_signupformpagequote"""'}, {}), "('SignUpFormPageQuote',\n 'sign_up_form_signupformpagequote')", False, 'from django.db import migrations\n'), ((27, 8, 30, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((31, 8, 34, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((35, 8, 38, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((39, 8, 42, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((43, 8, 46, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((47, 8, 50, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((51, 8, 54, 9), 'django.db.migrations.RemoveField', 'migrations.RemoveField', (), '', False, 'from django.db import migrations\n'), ((55, 8, 57, 9), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', (), '', False, 'from django.db import migrations\n'), ((58, 8, 60, 9), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', (), '', False, 'from django.db import migrations\n'), ((61, 8, 63, 9), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', (), '', False, 'from django.db import migrations\n'), ((64, 8, 66, 9), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', (), '', False, 'from django.db import migrations\n'), ((67, 8, 69, 9), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', (), '', False, 'from django.db import migrations\n'), ((73, 8, 76, 9), 'django.db.migrations.SeparateDatabaseAndState', 'migrations.SeparateDatabaseAndState', (), '', False, 'from django.db import migrations\n')]