How to use iter_classes method in avocado

Best Python code snippet using avocado_python

exp2..py

Source:exp2..py Github

copy

Full Screen

1# from typing_extensions import ParamSpec2import numpy as np3import matplotlib.pyplot as plt4from mpl_toolkits.mplot3d import Axes3D5 6def dist(v_A, v_B):7 """8 判断两个节点之间的一维距离9 :param v_A: A 二维向量10 :param v_B: B 二维向量11 :return: 一维距离12 """13 return np.sqrt(np.power((v_A[0] - v_B[0]), 2) + np.power((v_A[1] - v_B[1]), 2))14 15def node_factory(N, R, r, energy=50):16 """17 生成N个节点的拓扑网络18 :param N: 网络中节点个数19 :param R: 圆形拓扑半径20 :para r: 通信半径范围,超出此范围为某簇的孤立节点21 :param selected_flag: 标志:是否被选择为簇首-->初始化为022 :param energy: 能量23 :return: 节点集合nodes=[[x,y,e],[x,y,e]...]24 """25 nodes = []26 selected_flag = []27 iso = []28 # 中心sink节点29 sinknode = [0, 0, energy]30 nodes.append(sinknode)31 selected_flag.append(0)32 33 # 随机生成圆形拓扑网络34 i = 035 while i < N-1:36 # 在1*1矩阵生成[x,y]坐标37 node = [np.random.uniform(-1, 1)*R, np.random.uniform(-1, 1)*R, energy]38 if dist(node, sinknode) < R and dist(node, sinknode) > r:39 nodes.append(node)40 selected_flag.append(0)41 iso.append(1)42 i = i + 143 elif dist(node, sinknode) < R and dist(node, sinknode) < r:44 nodes.append(node)45 selected_flag.append(0)46 iso.append(0)47 i = i + 148 49 return nodes, selected_flag, iso50 51 52def sel_heads(r, nodes, flags):53 """54 使用leach协议,选取簇头(注意这里还没有开始进入正式的分簇,这里只选了簇头)55 :param r: 轮数56 :param nodes: 节点列表57 :param flags: 选择标志58 :param P: 比例因子59 :return: 簇首列表heads,簇成员列表members60 """61 # 阈值函数 Tn 使用leach计算62 P = 0.25 * (200 / len(nodes))63 Tn = P / (1 - P * (r % (1 / P)))64 heads = [] # 簇首列表65 members = [] # 簇成员列表66 n_head = 0 # 本轮簇首数67 rands = [np.random.random() for _ in range(len(nodes))] # 对每个节点生成对应的随机数,用于筛选簇头68 69 # 遍历随机数列表,选取簇首70 for i in range(len(nodes)):71 # 随机数低于阈值-->选为簇首72 if rands[i] <= Tn:73 flags[i] = 174 heads.append(nodes[i])75 n_head += 176 # 随机数高于阈值77 else:78 members.append(nodes[i])79 80 return heads, members81 82 83def classify(nodes, flag, r, mode=1, k=20):84 """85 对网络进行簇分类86 :param nodes: 节点列表87 :param flag: 节点标记88 :param mode: 0-->显示图片(死亡节点不显示) 1-->显示结束轮数89 :param k: 轮数90 :return: 簇分类结果列表 classes[[类1..],[类2...],......] [类1...簇首...簇成员]91 """92 # 能量损耗模型的参数93 b = 2400 # 比特数94 e_elec = 5*np.power(10., -9)*10095 e_fs = 10*np.power(10., -12)*10096 e_mp = 0.0013*np.power(10., -12)*10097 d_0 = 4.0 # 阈值98 # k轮的有效集合: 无死亡节点99 iter_classes = []100 # 是否已有节点能量为0101 e_is_empty = 0102 103 # 迭代r轮104 for r in range(k):105 # mode1: 若无死亡节点 继续迭代106 if e_is_empty == 0:107 # 获取簇首列表,簇成员列表108 heads, members = sel_heads(r,nodes,flag)109 110 # 建立簇类的列表111 if len(heads) == 0:112 break113 classes = [[] for _ in range(len(heads))]114 115 # 将簇首作为首节点添加到聚类列表中116 for i in range(len(heads)):117 classes[i].append(heads[i])118 119 # 簇分类:遍历节点node120 for member in members:121 122 # 选取距离最小的节点123 dist_min = 100000124 125 # 判断和每个簇首的距离126 for i in range(len(heads)):127 128 dist_heads = dist(member, heads[i])129 130 # 找到距离最小的簇头对应的heads下标i131 if dist_heads < dist_min:132 dist_min = dist_heads133 head_cla = i134 if dist_min==1:135 print("本轮没有簇首!")136 break137 # 添加到距离最小的簇首对应的聚类列表中138 classes[head_cla].append(member)139 140 # 正式的数据传输过程,使用能量消耗模型141 if int(member[2]) > 0 and int(heads[head_cla][2]) > 0:142 if dist_min < d_0:143 member[2] -= e_elec*b+e_fs*b*dist_min144 else:145 member[2] -= e_elec*b+e_mp*b*dist_min146 147 if dist([member[0], member[1]], [heads[head_cla][0], heads[head_cla][1]]) <= r:148 heads[head_cla][2] -= e_elec*b149 else:150 pass151 # heads[head_cla][2] -= e_elec*b152 else:153 e_is_empty = mode154 # break155 iter_classes.append(classes)156 157 else:158 print("第", r, "轮能量耗尽")159 break160 161 return iter_classes162 163 164def show_plt(classes, R, r):165 """166 显示分类图167 :param classes: [[类1...],[类2...]....]-->[簇首,成员,成员...]168 :param R: 圆形拓扑半径169 :para r: 通信半径范围,超出此范围为某簇的孤立节点170 :return:171 """172 fig = plt.figure()173 ax1 = plt.gca()174 175 # 设置标题176 ax1.set_title('WSN2')177 # 设置X轴标签178 plt.xlabel('X')179 # 设置Y轴标签180 plt.ylabel('Y')181 182 # 簇内的显示点图标及连线颜色,以得到较好的显示结果183 icon = ['o', '*', '.', 'x', '+', 's']184 color = ['b', 'g', 'c', 'y', 'm']185 186 x, y, e = [], [], []187 # 对不同的簇进行不同的显示,以得到较好的显示结果188 for i in range(len(classes)):189 centor = classes[i][0]190 x.append(centor[0])191 y.append(centor[1])192 e.append(centor[2])193 for point in classes[i]:194 if point[2] > 0 and dist(centor, point) < r:195 ax1.plot([centor[0], point[0]], [centor[1], point[1]], c=color[i % 5], marker=icon[i % 5], alpha=0.4)196 elif point[2] > 0 and dist(centor, point) > r:197 ax1.plot([centor[0], point[0]], [centor[1], point[1]], c='r', marker=icon[i % 5], alpha=0.4)198 else:199 pass200 a, b = (0., 0.)201 theta = np.arange(0, 2*np.pi, 0.01)202 x = a + R * np.cos(theta)203 y = b + R * np.sin(theta)204 plt.plot(x, y, 'y')205 # 显示206 plt.show()207 208def show_eninfo(iter_classes):209 fig = plt.figure()210 ax1 = Axes3D(fig)211 lastclass = iter_classes[-1]212 x, y, e = [], [], []213 # 将所有节点的剩余能量统计起来,用于后续能量三维图的显示214 for i in range(len(lastclass)):215 for point in lastclass[i]:216 x.append(point[0])217 y.append(point[1])218 e.append(point[2])219 # 需要进行数据类型转换list->ndarray,才能进行三维图像的显示220 x = np.array(x)221 y = np.array(y)222 e = np.array(e)223 # 显示三维图像224 print(f"各节点能量的标准差: {np.std(e):.4f}")225 ax1.plot_trisurf(x, y, e, cmap='rainbow')226 plt.show()227def run():228 """229 1、输入节点个数N230 2、node_factory(N,energy): 生成N个节点的列表,节点的能量初始化为energy231 3、classify(nodes,mode=1,k=100): 进行簇分类,返回所有簇的列表232 mode=0: 当节点死亡不停止,进行k次迭代,显示k张图,图中已死亡节点不标记233 mode=1: 当节点死亡停止,记录第一个节点死亡时的轮数,显示无死亡节点的图234 4、show_plt(classes): 迭代每次聚类结果,显示连线图235 :return:236 """237 # N = int(input("请输入节点个数:"))238 N = 300239 R = 20240 r = 5241 # 获取初始节点列表242 nodes, flag, iso = node_factory(N, R, r, energy=5)243 # 对节点列表进行簇分类,mode为模式 2种244 iter_classes = classify(nodes,flag, r, mode=1, k=200)245 # 迭代每次聚类结果,显示连线图246 for classes in iter_classes:247 # 显示分类结果248 show_plt(classes, R, r)249 show_eninfo(iter_classes)250if __name__ == '__main__':...

Full Screen

Full Screen

clustering.py

Source:clustering.py Github

copy

Full Screen

1'''2 * @Author: zhikunch 3 * @Date: 2021-03-19 20:39:28 4 * @Last Modified by: zhikunch5 * @Last Modified time: 2021-03-19 20:43:396 '''7 # devide users into several clusters following leach protocal8import numpy as np9import matplotlib.pyplot as plt10def dist(v_A, v_B):11 """12 判断两个节点之间的距离13 :param v_A: A 二维向量14 :param v_B: B 二维向量15 :return: 距离16 """17 return np.sqrt(np.power((v_A[0] - v_B[0]), 2) + np.power((v_A[1] - v_B[1]), 2))18def node_factory(N):19 """20 生成N个节点的集合21 :param N:节点的数目22 :param nodes: 节点的集合23 :param selected_flag: 标志,是否被选择为簇首-->初始化为024 :return: 节点集合nodes=[[x,y],[x,y]...] + 标志 flag25 """26 nodes = []27 selected_flag = []28 for i in range(0, N):29 # 1*1生成[x,y]坐标30 node = [np.random.random(),np.random.random()]31 # print("生成的节点为:",node)32 nodes.append(node)33 # 初始化对应标志为034 selected_flag.append(0)35 return nodes, selected_flag36def sel_heads(r, nodes, flags):37 """38 根据阈值选取簇头节点39 :param r: 轮数40 :param nodes:节点列表41 :param flags:选择标志42 :param P:比例因子43 :return:簇首列表heads,簇成员列表members44 """45 # 阈值函数Tn使用leach计算46 P = 0.1 * (100 / len(nodes))47 Tn = P / (1 - P * (r % (1/P)))48 49 # 簇首列表50 heads = []51 # 成员列表52 members = []53 # 本轮簇首数54 n_head = 055 56 # 对每个节点生成对应的随机数57 rands = [np.random.random() for _ in range(len(nodes))]58 59 # 遍历随机数列表,选取簇首60 for i in range(len(nodes)):61 # 若此节点未被选择为簇首62 if flags[i] == 0:63 # 随机数低于阈值-->选为簇首64 if rands[i] <= Tn:65 flags[i] = 166 heads.append(nodes[i])67 n_head += 168 # 随机数高于阈值69 else:70 members.append(nodes[i])71 # 若此节点已经被选择过72 else:73 members.append(nodes[i])74 75# print("簇首为:", len(heads),"个")76# print("簇成员为:",len(members),"个")77 78 return heads, members79def classify(nodes, flag, k=1):80 """81 进行簇分类82 :param nodes:节点列表83 :param flag:节点标记84 :param k:轮数85 :return:簇分类结果列表 classes[[类1..],[类2..],......] [类1...簇首...簇成员]86 """87 # k轮的集合88 global head_cla89 iter_classes = []90 # 迭代r轮91 for r in range(k):92 # 获取簇首列表,簇成员列表93 heads, members = sel_heads(r, nodes, flag)94 95 # 建立簇类的列表96 classes = [[] for _ in range(len(heads))]97 98 # 将簇首作为首节点添加到聚类列表中99 for i in range(len(heads)):100 classes[i].append(heads[i])101 ch = np.argwhere(np.array(nodes) == heads[i])[0][0]102 print("head:",ch)103 # 簇分类:遍历节点node104 for n in range(len(members)):105 # 选取距离最小的节点106 dist_min = 1107 108 for i in range(len(heads)):109 dist_heads = dist(members[n], heads[i])110 111 # 找到距离最小的簇头对应的heads下标i112 if dist_heads < dist_min:113 dist_min = dist_heads114 head_cla = i115 # 0 个簇首的情况116 if dist_min == 1:117 print("本轮没有簇首!")118 break119 # 添加到距离最小的簇首对应的聚类列表中120 classes[head_cla].append(members[n])121 122 iter_classes.append(classes)123 # dict124 dict_clusters = {j:{} for j in range(len(iter_classes[0]))}125 for j in range(len(iter_classes[0])):126 # print(len(iter_classes[0][j]))127 idx = []128 for jj in range(len(iter_classes[0][j])):129 idx.append(np.argwhere(np.array(nodes)==iter_classes[0][j][jj])[0][0])130 dict_clusters[j] = idx131 return iter_classes, dict_clusters132def show_plt(classes):133 """134 显示分类图135 :param classes:[[类1..],[类2..],....]-->[簇首,成员,成员...]136 : return: 137 """138 fig = plt.figure()139 ax1 = plt.gca()140 141 ax1.set_title('WSN1')142 plt.xlabel('X')143 plt.ylabel('Y')144 145 icon = ['o','*','.','x','+','s']146 color = ['r','b','g','c','y','m']147 148 # 对每个簇分类列表进行show149 for i in range(len(classes)):150 centor = classes[i][0]151 for point in classes[i]:152 ax1.plot([centor[0],point[0]],[centor[1],point[1]], c=color[i % 6], marker=icon[i % 5],alpha=0.4)153 plt.show()154def run_leach(cluster_num):155 """156 1、输入节点数N157 2、node_factory(N):生成N个节点的列表158 3、classify(nodes, flags, k=10):进行k轮簇分类,flag标记的节点不再成为簇首,返回所有簇159 4、show_plt(classes):迭代每次聚类结果,显示连线图160 return:161 """162 N=100163 # 获取初始节点列表,选择标志列表164 nodes, flags = node_factory(N)165 # 对节点列表进行簇分类,k为迭代轮数166 iter_classes, dict_clusters = classify(nodes, flags, k=1)167 168 # for classes in iter_classes:169 # show_plt(classes)170 return dict_clusters171if __name__ == '__main__':172 clusters = run_leach()173 # print(len(classes[0]))...

Full Screen

Full Screen

jarjar

Source:jarjar Github

copy

Full Screen

...6parser = argparse.ArgumentParser(description='jarjar')7parser.add_argument("jarsa")8parser.add_argument("jarsb")9args = parser.parse_args()10def iter_classes(jarname, jar):11 with zipfile.ZipFile(jar, 'r') as zip:12 for name in zip.namelist():13 if name.endswith('.class'):14 yield jarname, name15def iter_jars(top):16 if os.path.isdir(top):17 for root, dirs, files in os.walk(top):18 for name in files:19 if name.endswith(".jar"):20 yield from iter_classes(name, os.path.join(root, name))21 elif top.endswith('.zip'):22 with zipfile.ZipFile(top, 'r') as zip:23 for name in zip.namelist():24 if name.endswith('.jar'):25 with zip.open(name, 'r') as jar:26 yield from iter_classes(os.path.basename(name), jar)27 elif top.endswith('.jar'):28 yield from iter_classes(os.path.basename(top), top)29 else:30 raise NotImplementedError31def scan_jars(top):32 class2jars = defaultdict(set);33 for jarname, classname in iter_jars(top):34 class2jars[classname].add(jarname)35 return class2jars36a = scan_jars(args.jarsa)37b = scan_jars(args.jarsb)38intersection = set(a.keys()) & set(b.keys())39if not intersection:40 print("no overlap")41for cls in intersection:42 print(f"{cls} is duplicated")...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful