Best Python code snippet using pytest
out_Guide_posts_locking_assemble.py
Source:out_Guide_posts_locking_assemble.py
1import win32com.client as win322import global_var as gvar34def out_Guide_posts_locking_assemble(outer_Guiding_data): # å¤å°æ±èºæ 5 (M) = out_Guide_posts_down_locking_assemble(outer_Guiding_data) # ä¸æ¨¡åº§èºæ 6 # hide_1()7 (N) = out_Guide_posts_down_pin_assemble(outer_Guiding_data) # ä¸æ¨¡åº§åé·8 # hide_2()9 out_Guide_posts_up_locking_assemble(M,outer_Guiding_data) # ä¸æ¨¡åº§èºæ 10 # # hide_3()11 out_Guide_posts_up_pin_assemble(N,outer_Guiding_data) # ä¸æ¨¡åº§åé·12 # # hide_4()13 catapp = win32.Dispatch('CATIA.Application')14 document = catapp.ActiveDocument15 product1 = document.Product16 products1 = product1.Products17 product1.Update()181920def out_Guide_posts_down_locking_assemble(outer_Guiding_data):21 catapp = win32.Dispatch('CATIA.Application')22 document = catapp.ActiveDocument23 product1 = document.Product24 products1 = product1.Products25 # if outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYJP":26 # a = "CB_6"27 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYJP":28 # a = "CB_8"29 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYJP":30 # a = "CB_10"31 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYJP":32 # a = "CB_10"33 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYJP":34 # a = "CB_12"35 # elif outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYKP":36 # a = "CB_8"37 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYKP":38 # a = "CB_8"39 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYKP":40 # a = "CB_10"41 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYKP":42 # a = "CB_10"43 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYKP":44 # a = "CB_12"45 M = 046 # =====================èºæ å¤æ·(æå°)===============================47 selection1 = document.Selection48 selection1.Clear()49 selection1.Search("Name=" + str(outer_Guiding_data[4][1]) + "*")50 N = selection1.Count51 selection1.Clear()52 # =====================èºæ å¤æ·(æå°)===============================53 for g in range(1, 4 + 1):54 for i in range(1, 4 + 1):55 M += 156 # ================å¯å
¥æªæ¡================57 arrayOfVariantOfBSTR1 = [0]58 arrayOfVariantOfBSTR1[0] = gvar.save_path + str(outer_Guiding_data[4][1]) + ".CATPart"59 products1Variant = products160 products1Variant.AddComponentsFromFiles(arrayOfVariantOfBSTR1, "All")61 # ================å¯å
¥æªæ¡================62 constraints1 = product1.Connections("CATIAConstraints")63 # ================é²è¡ææ================64 reference1 = product1.CreateReferenceFromName(65 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(66 g) + "/!Product1/" + str(outer_Guiding_data[3][1]) + "_down." + str(g) + "/")67 constraint1 = constraints1.AddMonoEltCst(0, reference1)68 reference2 = product1.CreateReferenceFromName(69 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(70 g) + "/!Locking_point_" + str(i))71 reference3 = product1.CreateReferenceFromName(72 "Product1/" + str(outer_Guiding_data[4][1]) + "." + str(M) + "/!Start_Point")73 constraint2 = constraints1.AddBiEltCst(2, reference2, reference3)74 reference4 = product1.CreateReferenceFromName(75 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(76 g) + "/!Locking_dir_point_" + str(i))77 reference5 = product1.CreateReferenceFromName(78 "Product1/" + str(outer_Guiding_data[4][1]) + "." + str(M) + "/!End_Point")79 constraint3 = constraints1.AddBiEltCst(2, reference4, reference5)80 # ================é²è¡ææ================81 return M828384def out_Guide_posts_down_pin_assemble(outer_Guiding_data):85 catapp = win32.Dispatch('CATIA.Application')86 document = catapp.ActiveDocument87 product1 = document.Product88 products1 = product1.Products89 # if outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYJP":90 # a = "CB_6"91 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYJP":92 # a = "CB_8"93 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYJP":94 # a = "CB_10"95 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYJP":96 # a = "CB_10"97 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYJP":98 # a = "CB_12"99 # elif outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYKP":100 # a = "CB_8"101 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYKP":102 # a = "CB_8"103 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYKP":104 # a = "CB_10"105 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYKP":106 # a = "CB_10"107 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYKP":108 # a = "CB_12"109 N = 0110 # =====================pinå¤æ·(æå°)===============================111 selection1 = document.Selection112 selection1.Clear()113 selection1.Search("Name=" + str(outer_Guiding_data[5][1]))114 N = selection1.Count115 selection1.Clear()116 # =====================pinå¤æ·(æå°)===============================117 for g in range(1, 4 + 1):118 for i in range(1, 2 + 1):119 N += 1120 # ================å¯å
¥æªæ¡================121 arrayOfVariantOfBSTR1 = [0]122 arrayOfVariantOfBSTR1[0] = gvar.save_path + str(outer_Guiding_data[5][1]) + ".CATPart"123 products1Variant = products1124 products1Variant.AddComponentsFromFiles(arrayOfVariantOfBSTR1, "All")125 # ================å¯å
¥æªæ¡================126 constraints1 = product1.Connections("CATIAConstraints")127 # ================é²è¡ææ================128 reference1 = product1.CreateReferenceFromName(129 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(130 g) + "/!Product1" + str(outer_Guiding_data[3][1]) + "_" + str(131 outer_Guiding_data[1][1]) + "_down." + str(g) + "/")132 constraint1 = constraints1.AddMonoEltCst(0, reference1)133 reference2 = product1.CreateReferenceFromName(134 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(135 g) + "/!Pin_point_" + str(i))136 reference3 = product1.CreateReferenceFromName(137 "Product1/" + str(outer_Guiding_data[5][1]) + "." + str(N) + "/!Start_Point")138 constraint2 = constraints1.AddBiEltCst(2, reference2, reference3)139 reference4 = product1.CreateReferenceFromName(140 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_down." + str(141 g) + "/!Pin_dir_point_" + str(i))142 # reference5 = product1.CreateReferenceFromName(143 # "Product1/" + str(outer_Guiding_data[5][1]) + "." + str(N) + "/!End_Point")144 # constraint3 = constraints1.AddBiEltCst(1, reference4, reference5)145146 # WordCount_PinLength = len(outer_Guiding_data[5][1])147 # for j in range(0, WordCount_PinLength):148 # word = outer_Guiding_data51[j] # æåPin_data[2][1]ä¸çå¼149 # if word == "1":150 # length2 = constraint3.dimension151 # if WordCount_PinLength < 14:152 # k = 2153 # else:154 # k = 3155 # if int(int(outer_Guiding_data51[j + 3:20]) - 30) < 0:156 # length2.Value = int((int(outer_Guiding_data51[j + k:10]) - 30) * -1)157 # else:158 # length2.Value = int(int(outer_Guiding_data51[j + k:10]) - 30)159 # ================é²è¡ææ================160 return N161162163def out_Guide_posts_up_locking_assemble(M,outer_Guiding_data):164 catapp = win32.Dispatch('CATIA.Application')165 document = catapp.ActiveDocument166 product1 = document.Product167 products1 = product1.Products168 # if outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYJP":169 # a = "CB_10"170 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYJP":171 # a = "CB_10"172 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYJP":173 # a = "CB_12"174 # elif outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYJP":175 # a = "CB_8"176 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYJP":177 # a = "CB_8"178 # elif outer_Guiding_data(1, 1) ==32 and outer_Guiding_data(3, 1) == "MYKP":179 # a = "CB_810"180 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYKP":181 # a = "CB_10"182 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYKP":183 # a = "CB_12"184 # =====================èºæ å¤æ·(æå°)===============================185 # selection1 = document.Selection186 # selection1.Clear()187 # selection1.Search("Name=" + str(outer_Guiding_data[4][2]) + "*")188 # M = selection1.Count189 # selection1.Clear()190 # =====================èºæ å¤æ·(æå°)===============================191 for g in range(1, 4 + 1):192 for i in range(1, 4 + 1):193 M += 1194 # ================å¯å
¥æªæ¡================195 arrayOfVariantOfBSTR1 = [0]196 arrayOfVariantOfBSTR1[0] = gvar.save_path + str(outer_Guiding_data[4][2]) + ".CATPart"197 products1Variant = products1198 products1Variant.AddComponentsFromFiles(arrayOfVariantOfBSTR1, "All")199 # ================å¯å
¥æªæ¡================200 constraints1 = product1.Connections("CATIAConstraints")201 # ================é²è¡ææ================202 reference1 = product1.CreateReferenceFromName(203 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(204 g) + "/!Product1" + str(outer_Guiding_data[3][1]) + "_" + str(205 outer_Guiding_data[1][1]) + "_up." + str(g) + "/")206 constraint1 = constraints1.AddMonoEltCst(0, reference1)207 reference2 = product1.CreateReferenceFromName(208 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(209 g) + "/!Locking_point_" + str(i))210 reference3 = product1.CreateReferenceFromName(211 "Product1/" + str(outer_Guiding_data[4][2]) + "." + str(M) + "/!Start_Point")212 constraint2 = constraints1.AddBiEltCst(2, reference2, reference3)213 reference4 = product1.CreateReferenceFromName(214 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(215 g) + "/!Locking_dir_point_" + str(i))216 reference5 = product1.CreateReferenceFromName(217 "Product1/" + str(outer_Guiding_data[4][2]) + "." + str(M) + "/!End_Point")218 constraint3 = constraints1.AddBiEltCst(2, reference4, reference5)219 # ================é²è¡ææ================220 # product1.Update()221222223def out_Guide_posts_up_pin_assemble(N,outer_Guiding_data):224 catapp = win32.Dispatch('CATIA.Application')225 document = catapp.ActiveDocument226 product1 = document.Product227 products1 = product1.Products228 # if outer_Guiding_data(1, 1) == 20 and outer_Guiding_data(3, 1) == "MYJP":229 # a = "MSTM_6"230 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYJP":231 # a = "MSTM_8"232 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYJP":233 # a = "MSTM_8"234 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYJP":235 # a = "MSTM_8"236 # elif outer_Guiding_data(1, 1) == 50 and outer_Guiding_data(3, 1) == "MYJP":237 # a = "MSTM_10"238 # elif outer_Guiding_data(1, 1) ==20 and outer_Guiding_data(3, 1) == "MYKP":239 # a = "MSTM_8"240 # elif outer_Guiding_data(1, 1) == 25 and outer_Guiding_data(3, 1) == "MYKP":241 # a = "MSTM_8"242 # elif outer_Guiding_data(1, 1) == 32 and outer_Guiding_data(3, 1) == "MYKP":243 # a = "MSTM_8"244 # elif outer_Guiding_data(1, 1) == 38 and outer_Guiding_data(3, 1) == "MYKP":245 # a = "MSTM_10"246 # elif outer_Guiding_data(1, 1) == and outer_Guiding_data(3, 1) == "MYKP":247 # a = "MSTM_10"248 # =====================pinå¤æ·(æå°)===============================249 # selection1 = document.Selection250 # selection1.Clear()251 # selection1.Search("Name=*" + str(outer_Guiding_data[4][2]) + ".*")252 # N = selection1.Count253 # selection1.Clear()254 # =====================pinå¤æ·(æå°)===============================255 for g in range(1, 4 + 1):256 for i in range(1, 2 + 1):257 N += 1258 # ================å¯å
¥æªæ¡================259 arrayOfVariantOfBSTR1 = [0]260 arrayOfVariantOfBSTR1[0] = gvar.save_path + str(outer_Guiding_data[5][2]) + ".CATPart"261 products1Variant = products1262 products1Variant.AddComponentsFromFiles(arrayOfVariantOfBSTR1, "All")263 # ================å¯å
¥æªæ¡================264 constraints1 = product1.Connections("CATIAConstraints")265 # ================é²è¡ææ================266 reference1 = product1.CreateReferenceFromName(267 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(268 g) + "/!Product1" + str(outer_Guiding_data[3][1]) + "_" + str(269 outer_Guiding_data[1][1]) + "_up." + str(g) + "/")270 constraint1 = constraints1.AddMonoEltCst(0, reference1)271 reference2 = product1.CreateReferenceFromName(272 "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(273 g) + "/!Pin_point_" + str(i))274 reference3 = product1.CreateReferenceFromName(275 "Product1/" + str(outer_Guiding_data[5][2]) + "." + str(N) + "/!Start_Point")276 constraint2 = constraints1.AddBiEltCst(2, reference2, reference3)277 # reference4 = product1.CreateReferenceFromName(278 # "Product1/" + str(outer_Guiding_data[3][1]) + "_" + str(outer_Guiding_data[1][1]) + "_up." + str(279 # g) + "/!Pin_dir_point_" + str(i))280 # reference5 = product1.CreateReferenceFromName(281 # "Product1/" + str(outer_Guiding_data[5][2]) + "." + str(N) + "/!End_Point")282 # constraint3 = constraints1.AddBiEltCst(1, reference4, reference5)283 # WordCount_PinLength = len(outer_Guiding_data[5][2])284 # for j in range(0, WordCount_PinLength):285 # word = outer_Guiding_data51[j] # æåPin_data[2][1]ä¸çå¼286 # if word == "1":287 # length2 = constraint3.dimension288 # if WordCount_PinLength < 14:289 # k = 2290 # else:291 # k = 3292 # if int(int(outer_Guiding_data51[j + 3:20]) - 30) < 0:293 # length2.Value = int((int(outer_Guiding_data51[j + k:10]) - 30) * -1)294 # else:295 # length2.Value = int(int(outer_Guiding_data51[j + k:10]) - 30)296 # ================é²è¡ææ================297 # product1.Update()298299300def hide1():301 catapp = win32.Dispatch('CATIA.Application')302303304def hide2():305 catapp = win32.Dispatch('CATIA.Application')306307308def hide3():309 catapp = win32.Dispatch('CATIA.Application')310311312def hide4():
...
ragged_merge_dims_op_test.py
Source:ragged_merge_dims_op_test.py
1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for RaggedTensor.merge_dims."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19from absl.testing import parameterized20from tensorflow.python.eager import context21from tensorflow.python.framework import test_util22from tensorflow.python.ops import array_ops23from tensorflow.python.ops.ragged import ragged_factory_ops24from tensorflow.python.platform import googletest25from tensorflow.python.util import nest26@test_util.run_all_in_graph_and_eager_modes27class RaggedMergeDimsOpTest(test_util.TensorFlowTestCase,28 parameterized.TestCase):29 @parameterized.named_parameters([30 {31 'testcase_name': '2DAxis0To1',32 'rt': [[1, 2], [], [3, 4, 5]],33 'outer_axis': 0,34 'inner_axis': 1,35 'expected': [1, 2, 3, 4, 5],36 },37 {38 'testcase_name': '3DAxis0To1',39 'rt': [[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]],40 'outer_axis': 0,41 'inner_axis': 1,42 'expected': [[1, 2], [], [3, 4, 5], [6], [7, 8], []],43 },44 {45 'testcase_name': '3DAxis1To2',46 'rt': [[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]],47 'outer_axis': 1,48 'inner_axis': 2,49 'expected': [[1, 2, 3, 4, 5], [6, 7, 8]],50 },51 {52 'testcase_name': '3DAxis0To2',53 'rt': [[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]],54 'outer_axis': 0,55 'inner_axis': 2,56 'expected': [1, 2, 3, 4, 5, 6, 7, 8],57 },58 {59 'testcase_name': '3DAxis0To1WithDenseValues',60 'rt': [[[1, 2], [3, 4], [5, 6]], [[7, 8]]],61 'ragged_ranks': (1, 2),62 'outer_axis': 0,63 'inner_axis': 1,64 'expected': [[1, 2], [3, 4], [5, 6], [7, 8]],65 },66 {67 'testcase_name': '3DAxis1To2WithDenseValues',68 'rt': [[[1, 2], [3, 4], [5, 6]], [[7, 8]]],69 'ragged_ranks': (1, 2),70 'outer_axis': 1,71 'inner_axis': 2,72 'expected': [[1, 2, 3, 4, 5, 6], [7, 8]],73 },74 {75 'testcase_name': '4DAxis0To1',76 'rt': [[[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]], [[[9], [0]]]],77 'outer_axis': 0,78 'inner_axis': 1,79 'expected': [[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []], [[9], [0]]],80 },81 {82 'testcase_name': '4DAxis1To2',83 'rt': [[[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]], [[[9], [0]]]],84 'outer_axis': 1,85 'inner_axis': 2,86 'expected': [[[1, 2], [], [3, 4, 5], [6], [7, 8], []], [[9], [0]]],87 },88 {89 'testcase_name': '4DAxis2To3',90 'rt': [[[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]], [[[9], [0]]]],91 'outer_axis': 2,92 'inner_axis': 3,93 'expected': [[[1, 2, 3, 4, 5], [6, 7, 8]], [[9, 0]]],94 },95 {96 'testcase_name': '4DAxis1To3',97 'rt': [[[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]], [[[9], [0]]]],98 'outer_axis': 1,99 'inner_axis': 3,100 'expected': [[1, 2, 3, 4, 5, 6, 7, 8], [9, 0]],101 },102 {103 'testcase_name': '4DAxis1ToNeg1',104 'rt': [[[[1, 2], [], [3, 4, 5]], [[6], [7, 8], []]], [[[9], [0]]]],105 'outer_axis': 1,106 'inner_axis': -1,107 'expected': [[1, 2, 3, 4, 5, 6, 7, 8], [9, 0]],108 },109 {110 'testcase_name': '4DAxis1To2WithDenseValues',111 'rt': [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]]]],112 'ragged_ranks': (1, 2, 3),113 'outer_axis': 1,114 'inner_axis': 2,115 'expected': [[[1, 2], [3, 4], [5, 6], [7, 8]], [[9, 10], [11, 12]]],116 },117 {118 'testcase_name': '4DAxis2To3WithDenseValues',119 'rt': [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]]]],120 'ragged_ranks': (1, 2, 3),121 'outer_axis': 2,122 'inner_axis': 3,123 'expected': [[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12]]],124 },125 {126 'testcase_name': '4DAxis1To3WithDenseValues',127 'rt': [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]]]],128 'ragged_ranks': (1, 2, 3),129 'outer_axis': 1,130 'inner_axis': 3,131 'expected': [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12]],132 },133 {134 'testcase_name': '5DAxis2To3WithDenseValues',135 'rt': [[[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]],136 [[[[9, 10], [11, 12]]]]],137 'ragged_ranks': (1, 2, 3, 4),138 'outer_axis': 2,139 'inner_axis': 3,140 'expected': [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],141 [[[9, 10], [11, 12]]]],142 },143 {144 'testcase_name': '5DAxis3To4WithDenseValues',145 'rt': [[[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]],146 [[[[9, 10], [11, 12]]]]],147 'ragged_ranks': (1, 2, 3, 4),148 'outer_axis': 3,149 'inner_axis': 4,150 'expected': [[[[1, 2, 3, 4]], [[5, 6, 7, 8]]], [[[9, 10, 11, 12]]]],151 },152 {153 'testcase_name': '5DAxis1To3WithDenseValues',154 'rt': [[[[[1, 2], [3, 4]]], [[[5, 6], [7, 8]]]],155 [[[[9, 10], [11, 12]]]]],156 'ragged_ranks': (1, 2, 3, 4),157 'outer_axis': 1,158 'inner_axis': 3,159 'expected': [[[1, 2], [3, 4], [5, 6], [7, 8]], [[9, 10], [11, 12]]],160 },161 ]) # pyformat: disable162 def testRaggedMergeDims(self,163 rt,164 outer_axis,165 inner_axis,166 expected,167 ragged_ranks=(None,)):168 for ragged_rank in ragged_ranks:169 x = ragged_factory_ops.constant(rt, ragged_rank=ragged_rank)170 # Check basic behavior.171 actual = x.merge_dims(outer_axis, inner_axis)172 self.assertAllEqual(expected, actual)173 if outer_axis >= 0 and inner_axis >= 0:174 self.assertEqual(actual.shape.rank,175 x.shape.rank - (inner_axis - outer_axis))176 # Check behavior with negative axis.177 if outer_axis >= 0 and inner_axis >= 0:178 actual_with_neg_axis = x.merge_dims(outer_axis - x.shape.rank,179 inner_axis - x.shape.rank)180 self.assertAllEqual(expected, actual_with_neg_axis)181 # Check behavior with placeholder input (no shape info).182 if (not context.executing_eagerly() and outer_axis >= 0 and183 inner_axis >= 0):184 x_with_placeholders = nest.map_structure(185 lambda t: array_ops.placeholder_with_default(t, None),186 x,187 expand_composites=True)188 actual_with_placeholders = x_with_placeholders.merge_dims(189 outer_axis, inner_axis)190 self.assertAllEqual(expected, actual_with_placeholders)191 @parameterized.parameters([192 {193 'rt': [[1]],194 'outer_axis': {},195 'inner_axis': 1,196 'exception': TypeError,197 'message': 'outer_axis must be an int',198 },199 {200 'rt': [[1]],201 'outer_axis': 1,202 'inner_axis': {},203 'exception': TypeError,204 'message': 'inner_axis must be an int',205 },206 {207 'rt': [[1]],208 'outer_axis': 1,209 'inner_axis': 3,210 'exception': ValueError,211 'message': 'inner_axis=3 out of bounds: expected -2<=inner_axis<2',212 },213 {214 'rt': [[1]],215 'outer_axis': 1,216 'inner_axis': -3,217 'exception': ValueError,218 'message': 'inner_axis=-3 out of bounds: expected -2<=inner_axis<2',219 },220 {221 'rt': [[1]],222 'outer_axis': 0,223 'inner_axis': 0,224 'exception': ValueError,225 'message': 'Expected outer_axis .* to be less than inner_axis .*',226 },227 {228 'rt': [[1]],229 'outer_axis': 1,230 'inner_axis': 0,231 'exception': ValueError,232 'message': 'Expected outer_axis .* to be less than inner_axis .*',233 },234 {235 'rt': [[1]],236 'outer_axis': -1,237 'inner_axis': -2,238 'exception': ValueError,239 'message': 'Expected outer_axis .* to be less than inner_axis .*',240 },241 {242 'rt': [[1]],243 'outer_axis': 1,244 'inner_axis': -1,245 'exception': ValueError,246 'message': 'Expected outer_axis .* to be less than inner_axis .*',247 },248 ]) # pyformat: disable249 def testRaggedMergeDimsError(self,250 rt,251 outer_axis,252 inner_axis,253 exception,254 message=None,255 ragged_rank=None):256 x = ragged_factory_ops.constant(rt, ragged_rank=ragged_rank)257 with self.assertRaisesRegexp(exception, message):258 self.evaluate(x.merge_dims(outer_axis, inner_axis))259if __name__ == '__main__':...
maml.py
Source:maml.py
1import functools2import constants3import jax4import jax.numpy as jnp5import matplotlib.pyplot as plt6import sinusoidal_task_distribution7from jax.experimental import optimizers, stax8class MAML:9 def __init__(10 self,11 key,12 optimiser_type: str,13 lr: float,14 task_distribution,15 network_specification,16 ):17 self._key = key18 self._task_distribution = task_distribution19 (20 optimiser_initialiser,21 optimiser_update,22 get_parameters,23 ) = self._setup_optimiser(optimiser_type=optimiser_type, lr=lr)24 network_forward, network_parameters = self._setup_network(25 network_specification=network_specification26 )27 self._optimiser_state = optimiser_initialiser(network_parameters)28 def loss_function(parameters, inputs, labels):29 predictions = network_forward(parameters, inputs)30 return jnp.mean((predictions - labels) ** 2)31 def inner_loop(parameters, x, y):32 # get inner loop optimiser33 # (34 # optimiser_initialiser,35 # optimiser_update,36 # get_parameters,37 # ) = self._setup_optimiser(optimiser_type="adam", lr=0.001)38 # optimiser_state = optimiser_initialiser(parameters)39 gradients = jax.grad(loss_function)(parameters, x, y)40 # updated_optimiser_state = optimiser_update(0, gradients, optimiser_state)41 # updated_parameters = get_parameters(updated_optimiser_state)42 # import pdb43 # pdb.set_trace()44 # return updated_parameters45 inner_sgd_fn = lambda g, state: (state - 0.01 * g)46 return jax.tree_multimap(inner_sgd_fn, gradients, parameters)47 def compute_meta_loss(parameters, x_inner, y_inner, x_outer, y_outer):48 updated_parameters = inner_loop(49 parameters=parameters, x=x_inner, y=y_inner50 )51 loss = loss_function(updated_parameters, x_outer, y_outer)52 return loss53 def compute_batch_meta_loss(54 parameters, batch_x_inner, batch_y_inner, batch_x_outer, batch_y_outer55 ):56 task_losses = jax.vmap(functools.partial(compute_meta_loss, parameters))(57 batch_x_inner, batch_y_inner, batch_x_outer, batch_y_outer58 )59 batch_meta_loss = jnp.mean(task_losses)60 return batch_meta_loss61 def step(epoch: int, optimiser_state, inner_x, inner_y, outer_x, outer_y):62 parameters = get_parameters(optimiser_state)63 gradients = jax.grad(compute_batch_meta_loss)(64 parameters, inner_x, inner_y, outer_x, outer_y65 )66 batch_meta_loss = compute_batch_meta_loss(67 parameters, inner_x, inner_y, outer_x, outer_y68 )69 return (70 optimiser_update(epoch, gradients, optimiser_state),71 batch_meta_loss,72 )73 self._get_parameters = get_parameters74 self._network_forward = network_forward75 self._inner_loop = inner_loop76 self._step = jax.jit(step)77 def _setup_optimiser(self, optimiser_type: str, lr: float):78 if optimiser_type == constants.ADAM:79 init, update, get_params = optimizers.adam(step_size=lr)80 return init, update, get_params81 def _setup_network(self, network_specification):82 input_dimension = network_specification[constants.INPUT_DIM]83 layer_specifications = network_specification[constants.LAYER_SPECIFICATIONS]84 layers = []85 for layer_specification in layer_specifications:86 layer_type = list(layer_specification.keys())[0]87 layer_info = list(layer_specification.values())[0]88 if layer_type == constants.LINEAR:89 layer = stax.Dense(layer_info[constants.OUTPUT_DIM])90 layers.append(layer)91 activation_type = layer_info.get(constants.ACTIVATION)92 if activation_type is not None:93 if activation_type == constants.RELU:94 activation = stax.Relu95 layers.append(activation)96 init, forward = stax.serial(*layers)97 _, params = init(self._key, (-1, input_dimension))98 return forward, params99 def _fine_tune(self, parameters, x, y, adaptation_steps):100 fine_tuned_parameters = []101 updated_parameters = parameters102 fine_tuned_parameters.append(updated_parameters)103 for i in range(adaptation_steps):104 updated_parameters = self._inner_loop(updated_parameters, x, y)105 fine_tuned_parameters.append(updated_parameters)106 return fine_tuned_parameters107 def _get_data_batch_from_tasks(self, tasks, batch_size: int):108 batch_x_inner = []109 batch_y_inner = []110 batch_x_outer = []111 batch_y_outer = []112 for task in tasks:113 x_inner, y_inner = task.sample_data(114 key=self._key, num_datapoints=batch_size115 )116 x_outer, y_outer = task.sample_data(117 key=self._key, num_datapoints=batch_size118 )119 batch_x_inner.append(x_inner)120 batch_y_inner.append(y_inner)121 batch_x_outer.append(x_outer)122 batch_y_outer.append(y_outer)123 return (124 jnp.stack(batch_x_inner),125 jnp.stack(batch_y_inner),126 jnp.stack(batch_x_outer),127 jnp.stack(batch_y_outer),128 )129 def train(self, epochs: int, num_tasks: int, batch_size: int):130 meta_losses = []131 for i in range(epochs):132 task_sample = self._task_distribution.sample(133 key=self._key, num_tasks=num_tasks134 )135 (136 batch_x_inner,137 batch_y_inner,138 batch_x_outer,139 batch_y_outer,140 ) = self._get_data_batch_from_tasks(141 tasks=task_sample, batch_size=batch_size142 )143 self._optimiser_state, meta_loss = self._step(144 epoch=i,145 optimiser_state=self._optimiser_state,146 inner_x=batch_x_inner,147 inner_y=batch_y_inner,148 outer_x=batch_x_outer,149 outer_y=batch_y_outer,150 )151 meta_losses.append(meta_loss)152 if i % 100 == 0:153 print(f"{i}: {meta_loss}")154 return meta_losses155 def test(156 self,157 num_evaluations: int,158 num_examples: int,159 num_adaptation_steps: int,160 plot: bool,161 ):162 evaluation_tasks = self._task_distribution.sample(163 key=self._key, num_tasks=num_evaluations164 )165 trained_parameters = self._get_parameters(self._optimiser_state)166 for i, task in enumerate(evaluation_tasks):167 x, y = task.sample_data(key=self._key, num_datapoints=num_examples)168 adapted_parameters = self._fine_tune(169 trained_parameters, x, y, num_adaptation_steps170 )171 if plot:172 self._plot_evaluation(x, y, task, adapted_parameters, f"{i}_test.pdf")173 def _plot_evaluation(self, x, y, task, adapted_parameters, save_name):174 fig = plt.figure()175 plt.scatter(x, y)176 x_range = jnp.linspace(-5, 5, 100).reshape(-1, 1)177 plt.plot(x_range, task(x_range), label="ground truth")178 for i, parameters in enumerate(adapted_parameters):179 regression = self._network_forward(parameters, x_range)180 plt.plot(x_range, regression, label=f"{i} tuning")181 plt.legend()182 fig.savefig(save_name)183def forward(inputs):184 mlp = hk.Sequential(185 [hk.Linear(40), jax.nn.relu, hk.Linear(40), jax.nn.relu, hk.Linear(1)]186 )187 prediction = mlp(inputs)188 return prediction189if __name__ == "__main__":190 task_distribution = sinusoidal_task_distribution.SinusoidalTaskDistribution(191 x_range=(-5, 5), amplitude_range=(0.1, 5), phase_range=(0, jnp.pi)192 )193 network_specification = {194 "input_dim": 1,195 "layer_specifications": [196 {"linear": {"output_dim": 40, "activation": "relu"}},197 {"linear": {"output_dim": 40, "activation": "relu"}},198 {"linear": {"output_dim": 1}},199 ],200 }201 rng = jax.random.PRNGKey(0)202 maml = MAML(203 key=rng,204 task_distribution=task_distribution,205 optimiser_type="adam",206 lr=0.001,207 network_specification=network_specification,208 )209 meta_losses = maml.train(10000, 5, 5)210 fig = plt.figure()211 plt.plot(range(len(meta_losses)), meta_losses)212 plt.xlabel("epochs")213 plt.ylabel("meta loss")214 fig.savefig("losses.pdf")...
summary_test.py
Source:summary_test.py
1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15from __future__ import absolute_import16from __future__ import division17from __future__ import print_function18from six.moves import xrange # pylint: disable=redefined-builtin19from tensorflow.core.framework import summary_pb220from tensorflow.python.framework import constant_op21from tensorflow.python.framework import meta_graph22from tensorflow.python.framework import ops23from tensorflow.python.ops import array_ops24from tensorflow.python.ops import variables25from tensorflow.python.platform import test26from tensorflow.python.summary import summary as summary_lib27class ScalarSummaryTest(test.TestCase):28 def testScalarSummary(self):29 with self.test_session() as s:30 i = constant_op.constant(3)31 with ops.name_scope('outer'):32 im = summary_lib.scalar('inner', i)33 summary_str = s.run(im)34 summary = summary_pb2.Summary()35 summary.ParseFromString(summary_str)36 values = summary.value37 self.assertEqual(len(values), 1)38 self.assertEqual(values[0].tag, 'outer/inner')39 self.assertEqual(values[0].simple_value, 3.0)40 def testScalarSummaryWithFamily(self):41 with self.test_session() as s:42 i = constant_op.constant(7)43 with ops.name_scope('outer'):44 im1 = summary_lib.scalar('inner', i, family='family')45 self.assertEquals(im1.op.name, 'outer/family/inner')46 im2 = summary_lib.scalar('inner', i, family='family')47 self.assertEquals(im2.op.name, 'outer/family/inner_1')48 sm1, sm2 = s.run([im1, im2])49 summary = summary_pb2.Summary()50 summary.ParseFromString(sm1)51 values = summary.value52 self.assertEqual(len(values), 1)53 self.assertEqual(values[0].tag, 'family/outer/family/inner')54 self.assertEqual(values[0].simple_value, 7.0)55 summary.ParseFromString(sm2)56 values = summary.value57 self.assertEqual(len(values), 1)58 self.assertEqual(values[0].tag, 'family/outer/family/inner_1')59 self.assertEqual(values[0].simple_value, 7.0)60 def testSummarizingVariable(self):61 with self.test_session() as s:62 c = constant_op.constant(42.0)63 v = variables.Variable(c)64 ss = summary_lib.scalar('summary', v)65 init = variables.global_variables_initializer()66 s.run(init)67 summ_str = s.run(ss)68 summary = summary_pb2.Summary()69 summary.ParseFromString(summ_str)70 self.assertEqual(len(summary.value), 1)71 value = summary.value[0]72 self.assertEqual(value.tag, 'summary')73 self.assertEqual(value.simple_value, 42.0)74 def testImageSummary(self):75 with self.test_session() as s:76 i = array_ops.ones((5, 4, 4, 3))77 with ops.name_scope('outer'):78 im = summary_lib.image('inner', i, max_outputs=3)79 summary_str = s.run(im)80 summary = summary_pb2.Summary()81 summary.ParseFromString(summary_str)82 values = summary.value83 self.assertEqual(len(values), 3)84 tags = sorted(v.tag for v in values)85 expected = sorted('outer/inner/image/{}'.format(i) for i in xrange(3))86 self.assertEqual(tags, expected)87 def testImageSummaryWithFamily(self):88 with self.test_session() as s:89 i = array_ops.ones((5, 2, 3, 1))90 with ops.name_scope('outer'):91 im = summary_lib.image('inner', i, max_outputs=3, family='family')92 self.assertEquals(im.op.name, 'outer/family/inner')93 summary_str = s.run(im)94 summary = summary_pb2.Summary()95 summary.ParseFromString(summary_str)96 values = summary.value97 self.assertEqual(len(values), 3)98 tags = sorted(v.tag for v in values)99 expected = sorted('family/outer/family/inner/image/{}'.format(i)100 for i in xrange(3))101 self.assertEqual(tags, expected)102 def testHistogramSummary(self):103 with self.test_session() as s:104 i = array_ops.ones((5, 4, 4, 3))105 with ops.name_scope('outer'):106 summ_op = summary_lib.histogram('inner', i)107 summary_str = s.run(summ_op)108 summary = summary_pb2.Summary()109 summary.ParseFromString(summary_str)110 self.assertEqual(len(summary.value), 1)111 self.assertEqual(summary.value[0].tag, 'outer/inner')112 def testHistogramSummaryWithFamily(self):113 with self.test_session() as s:114 i = array_ops.ones((5, 4, 4, 3))115 with ops.name_scope('outer'):116 summ_op = summary_lib.histogram('inner', i, family='family')117 self.assertEquals(summ_op.op.name, 'outer/family/inner')118 summary_str = s.run(summ_op)119 summary = summary_pb2.Summary()120 summary.ParseFromString(summary_str)121 self.assertEqual(len(summary.value), 1)122 self.assertEqual(summary.value[0].tag, 'family/outer/family/inner')123 def testAudioSummary(self):124 with self.test_session() as s:125 i = array_ops.ones((5, 3, 4))126 with ops.name_scope('outer'):127 aud = summary_lib.audio('inner', i, 0.2, max_outputs=3)128 summary_str = s.run(aud)129 summary = summary_pb2.Summary()130 summary.ParseFromString(summary_str)131 values = summary.value132 self.assertEqual(len(values), 3)133 tags = sorted(v.tag for v in values)134 expected = sorted('outer/inner/audio/{}'.format(i) for i in xrange(3))135 self.assertEqual(tags, expected)136 def testAudioSummaryWithFamily(self):137 with self.test_session() as s:138 i = array_ops.ones((5, 3, 4))139 with ops.name_scope('outer'):140 aud = summary_lib.audio('inner', i, 0.2, max_outputs=3, family='family')141 self.assertEquals(aud.op.name, 'outer/family/inner')142 summary_str = s.run(aud)143 summary = summary_pb2.Summary()144 summary.ParseFromString(summary_str)145 values = summary.value146 self.assertEqual(len(values), 3)147 tags = sorted(v.tag for v in values)148 expected = sorted('family/outer/family/inner/audio/{}'.format(i)149 for i in xrange(3))150 self.assertEqual(tags, expected)151 def testSummaryNameConversion(self):152 c = constant_op.constant(3)153 s = summary_lib.scalar('name with spaces', c)154 self.assertEqual(s.op.name, 'name_with_spaces')155 s2 = summary_lib.scalar('name with many $#illegal^: characters!', c)156 self.assertEqual(s2.op.name, 'name_with_many___illegal___characters_')157 s3 = summary_lib.scalar('/name/with/leading/slash', c)158 self.assertEqual(s3.op.name, 'name/with/leading/slash')159 def testSummaryWithFamilyMetaGraphExport(self):160 with ops.name_scope('outer'):161 i = constant_op.constant(11)162 summ = summary_lib.scalar('inner', i)163 self.assertEquals(summ.op.name, 'outer/inner')164 summ_f = summary_lib.scalar('inner', i, family='family')165 self.assertEquals(summ_f.op.name, 'outer/family/inner')166 metagraph_def, _ = meta_graph.export_scoped_meta_graph(export_scope='outer')167 with ops.Graph().as_default() as g:168 meta_graph.import_scoped_meta_graph(metagraph_def, graph=g,169 import_scope='new_outer')170 # The summaries should exist, but with outer scope renamed.171 new_summ = g.get_tensor_by_name('new_outer/inner:0')172 new_summ_f = g.get_tensor_by_name('new_outer/family/inner:0')173 # However, the tags are unaffected.174 with self.test_session() as s:175 new_summ_str, new_summ_f_str = s.run([new_summ, new_summ_f])176 new_summ_pb = summary_pb2.Summary()177 new_summ_pb.ParseFromString(new_summ_str)178 self.assertEquals('outer/inner', new_summ_pb.value[0].tag)179 new_summ_f_pb = summary_pb2.Summary()180 new_summ_f_pb.ParseFromString(new_summ_f_str)181 self.assertEquals('family/outer/family/inner',182 new_summ_f_pb.value[0].tag)183if __name__ == '__main__':...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!