input
stringlengths
2.65k
237k
output
stringclasses
1 value
import sys, os import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm import learningHelper as lh import datetime # sageconv from typing import Union, Tuple from torch_geometric.typing import OptPairTensor, Adj, Size from torch import Tensor from torch.nn import Linear import torch.nn.functional as F from torch_sparse import SparseTensor, matmul from torch_geometric.nn.conv import MessagePassing class SAGEConv(MessagePassing): r"""The GraphSAGE operator from the `"Inductive Representation Learning on Large Graphs" <https://arxiv.org/abs/1706.02216>`_ paper .. math:: \mathbf{x}^{\prime}_i = \mathbf{W}_1 \mathbf{x}_i + \mathbf{W_2} \cdot \mathrm{mean}_{j \in \mathcal{N(i)}} \mathbf{x}_j Args: in_channels (int or tuple): Size of each input sample. A tuple corresponds to the sizes of source and target dimensionalities. out_channels (int): Size of each output sample. normalize (bool, optional): If set to :obj:`True`, output features will be :math:`\ell_2`-normalized, *i.e.*, :math:`\frac{\mathbf{x}^{\prime}_i} {\| \mathbf{x}^{\prime}_i \|_2}`. (default: :obj:`False`) bias (bool, optional): If set to :obj:`False`, the layer will not learn an additive bias. (default: :obj:`True`) **kwargs (optional): Additional arguments of :class:`torch_geometric.nn.conv.MessagePassing`. """ def __init__(self, in_channels: Union[int, Tuple[int, int]], out_channels: int, edge_in_channels: int, normalize: bool = False, bias: bool = True, **kwargs): # yapf: disable super(SAGEConv, self).__init__(aggr='mean', **kwargs) self.in_channels = in_channels self.edge_in_channels = edge_in_channels self.out_channels = out_channels self.normalize = normalize if isinstance(in_channels, int): in_channels = (in_channels, in_channels) self.lin_l = Linear(in_channels[0], out_channels, bias=bias) self.lin_r = Linear(in_channels[1], out_channels, bias=False) self.lin_e = Linear(edge_in_channels, in_channels[0], bias=bias) self.reset_parameters() def reset_parameters(self): self.lin_l.reset_parameters() self.lin_r.reset_parameters() self.lin_e.reset_parameters() def propagate(self, edge_index: Adj, size: Size = None, **kwargs): r"""The initial call to start propagating messages. Args: adj (Tensor or SparseTensor): A :obj:`torch.LongTensor` or a :obj:`torch_sparse.SparseTensor` that defines the underlying graph connectivity/message passing flow. :obj:`edge_index` holds the indices of a general (sparse) assignment matrix of shape :obj:`[N, M]`. If :obj:`edge_index` is of type :obj:`torch.LongTensor`, its shape must be defined as :obj:`[2, num_messages]`, where messages from nodes in :obj:`edge_index[0]` are sent to nodes in :obj:`edge_index[1]` (in case :obj:`flow="source_to_target"`). If :obj:`edge_index` is of type :obj:`torch_sparse.SparseTensor`, its sparse indices :obj:`(row, col)` should relate to :obj:`row = edge_index[1]` and :obj:`col = edge_index[0]`. The major difference between both formats is that we need to input the *transposed* sparse adjacency matrix into :func:`propagate`. size (tuple, optional): The size :obj:`(N, M)` of the assignment matrix in case :obj:`edge_index` is a :obj:`LongTensor`. If set to :obj:`None`, the size will be automatically inferred and assumed to be quadratic. This argument is ignored in case :obj:`edge_index` is a :obj:`torch_sparse.SparseTensor`. (default: :obj:`None`) **kwargs: Any additional data which is needed to construct and aggregate messages, and to update node embeddings. """ size = self.__check_input__(edge_index, size) # # Run "fused" message and aggregation (if applicable). # if (isinstance(edge_index, SparseTensor) and self.fuse # and not self.__explain__): # coll_dict = self.__collect__(self.__fused_user_args__, edge_index, # size, kwargs) # # msg_aggr_kwargs = self.inspector.distribute( # 'message_and_aggregate', coll_dict) # out = self.message_and_aggregate(edge_index, **msg_aggr_kwargs) # # update_kwargs = self.inspector.distribute('update', coll_dict) # return self.update(out, **update_kwargs) # Otherwise, run both functions in separation. if isinstance(edge_index, Tensor) or not self.fuse: coll_dict = self.__collect__(self.__user_args__, edge_index, size, kwargs) msg_kwargs = self.inspector.distribute('message', coll_dict) out = self.message(**msg_kwargs) # For `GNNExplainer`, we require a separate message and aggregate # procedure since this allows us to inject the `edge_mask` into the # message passing computation scheme. if self.__explain__: edge_mask = self.__edge_mask__.sigmoid() # Some ops add self-loops to `edge_index`. We need to do the # same for `edge_mask` (but do not train those). if out.size(self.node_dim) != edge_mask.size(0): loop = edge_mask.new_ones(size[0]) edge_mask = torch.cat([edge_mask, loop], dim=0) assert out.size(self.node_dim) == edge_mask.size(0) out = out * edge_mask.view([-1] + [1] * (out.dim() - 1)) aggr_kwargs = self.inspector.distribute('aggregate', coll_dict) out = self.aggregate(out, **aggr_kwargs) update_kwargs = self.inspector.distribute('update', coll_dict) return self.update(out, **update_kwargs) def forward(self, x: Union[Tensor, OptPairTensor], edge_attr: Tensor, edge_index: Adj, size: Size = None) -> Tensor: """""" if isinstance(x, Tensor): x: OptPairTensor = (x, x) # lin_l is W2 and should be filtered by an edge network shared for all edges but different per layer # propagate_type: (x: OptPairTensor) edge_attr = self.lin_e(edge_attr) out = self.propagate(edge_index, x=x, edge_attr=edge_attr, size=size) out = self.lin_l(out) # lin_r is W1 and does not need to be modified x_r = x[1] if x_r is not None: out += self.lin_r(x_r) if self.normalize: out = F.normalize(out, p=2., dim=-1) return out, edge_attr def message(self, x_j: Tensor, edge_attr: Tensor) -> Tensor: # TODO: maybe simply return MLP(edge_features) \hadamard x_j, where # and return should also be MLP(edge_features) for outputting edge labels with dim=1 for last edge_MLP out_channel return x_j*edge_attr def message_and_aggregate(self, adj_t: SparseTensor, x: OptPairTensor) -> Tensor: adj_t = adj_t.set_value(None, layout=None) return matmul(adj_t, x[0], reduce=self.aggr) def __repr__(self): return '{}(in:{}, edge_in:{}, edge_out:{}, out:{})'.format(self.__class__.__name__, self.in_channels, self.edge_in_channels, self.in_channels, self.out_channels) class SurfaceNet(nn.Module): def __init__(self, n_node_features, clf): super(SurfaceNet, self).__init__() # necessary for all classes extending the module class self.clf = clf self.n_classes = 2 self.n_node_feat = n_node_features self.convs = torch.nn.ModuleList() self.convs.append(SAGEConv(self.n_node_feat, self.clf.training.model_params[0], 2)) self.convs.append(SAGEConv(self.clf.training.model_params[0], self.clf.training.model_params[1], self.n_node_feat)) for i in range(len(self.clf.training.model_params)-2): self.convs.append(SAGEConv(self.clf.training.model_params[i+1], self.clf.training.model_params[i+2], self.clf.training.model_params[i], normalize=False)) self.num_layers = len(self.convs) if(self.clf.training.model_name[-1] == "+"): self.out_net = nn.Sequential(nn.ReLU(True), nn.Linear(self.clf.training.model_params[-1], 128), nn.ReLU(True), nn.Linear(128, 2)) ####################################################### ##################### TRAIN FORWARD ################### ####################################################### def forward(self, data_all): # produces final embedding batch per batch """ the forward function producing the embeddings for each cell of 'input' input = [n_batch, input_feat, n_channels=1] float array: input features output = [n_batch, n_class, n_channels=1] float array: cell class scores """ if(self.clf.features.normalization_feature and not self.clf.features.keep_normalization_feature): x=data_all.x[data_all.n_id, 1:].to(self.clf.temp.device) # put this batch on gpu else: x=data_all.x[data_all.n_id, :].to(self.clf.temp.device) # put this batch on gpu edge_attr = data_all.edge_attr for i in range(self.num_layers): edge_index, e_id, size = data_all.adjs[i] # TODO: first try the dumb version where edge_attr is not updated and goes always from # dim(edge_features) to dim(self.convs[i].in_channels) new_edge_attr = torch.zeros([data_all.edge_attr.shape[0], self.convs[i].in_channels],device=self.clf.temp.device) x,new_edge_attr[e_id] = self.convs[i]((x, x[:size[1]]), edge_attr[e_id,:self.convs[i].edge_in_channels].to(self.clf.temp.device), edge_index.to(self.clf.temp.device)) edge_attr = new_edge_attr if i != self.num_layers - 1: x = F.relu(x) edge_attr = F.relu(edge_attr) # x = F.dropout(x, p=0.5, training=self.training) torch.cuda.empty_cache() if(self.clf.training.model_name[-1] == "+"): x = F.relu(x) x = self.out_net(x) # self.clf.temp.memory.append(lh.get_gpu_memory(self.clf.temp.device)) return x ####################################################### ################## INFERENCE FORWARDS ################# ####################################################### def inference_batch_layer(self, x_all, batch_loader): # produces embeddings layer by layer, batch per batch # subgraph sampling necessary # needed when full graph does not fit in memory if (self.clf.training.loss == "kl"): x_out = torch.zeros([x_all.size()[0], 2], dtype=torch.float32, requires_grad=False).to('cpu') elif (self.clf.training.loss == "mse"): x_out = torch.zeros([x_all.size()[0], 1], dtype=torch.float32, requires_grad=False).to('cpu') else: print("{} is not a valid loss. choose either kl or mse".format(self.clf.training.loss)) sys.exit(1) if (self.clf.features.normalization_feature and not self.clf.features.keep_normalization_feature): x_all = x_all[:, 1:] # do not put it on gpu yet, because they will be used batch by batch # Compute representations of nodes layer by layer, using *all* # available edges. This leads to faster computation in contrast to # immediately computing the final representations of each batch. for batch_size, n_id, adjs in tqdm(batch_loader, ncols=50): x = x_all[n_id, :].to(self.clf.temp.device) for i in range(self.num_layers): edge_index, _, size = adjs[i] x = self.convs[i]((x, x[:size[1]]), edge_index.to(self.clf.temp.device)) if i != self.num_layers - 1: x = F.relu(x) # torch.cuda.empty_cache() # self.clf.temp.memory.append(lh.get_gpu_memory(self.clf.temp.device)) x_out[n_id[:batch_size]] = x.to('cpu') if(self.clf.training.model_name[-1] == "+"): x = F.relu(x_out.to(self.clf.temp.device)) x = self.out_net(x) else: x = x_out.to(self.clf.temp.device) self.clf.temp.memory.append(lh.get_gpu_memory(self.clf.temp.device)) return x def inference_layer_batch(self, data_all, batch_loader): # produces embeddings layer by layer, batch per batch # subgraph sampling necessary # needed when full graph does not fit in memory if (self.clf.features.normalization_feature and not self.clf.features.keep_normalization_feature): x_all = data_all.x[:, 1:] # do not put it on gpu yet, because they will be used batch by batch # Compute representations of nodes layer by layer, using *all* # available edges. This leads to faster computation in contrast to # immediately computing the final representations of each batch. for i in tqdm(range(self.num_layers), ncols=50): xs = [] for batch_size, n_id, adj in batch_loader: edge_index, _, size = adj # get adjacencies of current layer / hop x = x_all[n_id].to(self.clf.temp.device) x_target = x[:size[1]] x = self.convs[i]((x, x_target), edge_index.to(self.clf.temp.device)) if i != self.num_layers - 1: x = F.relu(x) # torch.cuda.empty_cache() # self.clf.temp.memory.append(lh.get_gpu_memory(self.clf.temp.device)) xs.append(x.cpu()) x_all = torch.cat(xs, dim=0) if(self.clf.training.model_name[-1] == "+"): x = F.relu(x_all.to(self.clf.temp.device)) x = self.out_net(x) else: x = x_all.to(self.clf.temp.device) self.clf.temp.memory.append(lh.get_gpu_memory(self.clf.temp.device)) return x def inference_layer(self, data_all): # produces embeddings layer by layer directly for the whole graph # no subgraph sampling necessary # only works if full graph fits in memory
import struct import sys import timeit import threading import pdb import bpy import mathutils import os.path from bpy.props import * from bpy_extras.image_utils import load_image from ast import literal_eval as make_tuple from math import sqrt from math import atan2 import re import bmesh def openclose(file): oc = file.read(4) if (oc == (b'\x4D\x01\x00\x00')): return 2 elif oc == (b'\x2B\x02\x00\x00'): # print('}') return 0 elif oc == (b'\xbc\x01\x00\x00'): #print('BC01') return 3 elif oc == (b'\xde\x00\00\00'): print ('EOF') return 1 else: print(str(file.tell())) print (str(oc)) print('brackets error') #sys.exit() raise Exception() def onebyte(file): return (file.read(1)) def readName(file): objName = file.read(32) if (objName[0] == 0): objName = "empty name" #objname = "Untitled_0x" + str(hex(file.tell()-36)) else: objName = (objName.decode("cp1251").rstrip('\0')) return objName class type05: name_fmt = '32c' byte1 = 'c' byte3 = '3c' def __init__(self,file): self.name = file.read(struct.calcsize(self.name_fmt)).decode("utf-8") _s = file.read(struct.calcsize(self.byte1)) self.byte1 = struct.unpack(self.byte1,_s) _s = file.read(struct.calcsize(self.byte3)) self.byte3 = struct.unpack(self.byte3,_s) class type15: byte1 = 'c' byte1_2 = 'c' byte4 = '4c' byte3 = '3c' def __init__(self,file): self.byte1 = onebyte(file) file.seek(3,1) # _s = file.read(struct.calcsize(self.byte4)) # self.byte4 = struct.unpack(self.byte4,_s) self.byte1_2 = onebyte(file) # кол-во вложеных обьектов 25 _s = file.read(struct.calcsize(self.byte3)) self.byte3 = struct.unpack(self.byte3,_s) class coords3: def __init__(self, file): self.v = struct.unpack("<3f", file.read(12)) class quat: fmt = 'ffff' def __init__(self, file): _s = file.read(struct.calcsize(self.fmt)) self.v = struct.unpack(self.fmt, _s) # Quats are stored x,y,z,w - this fixes it self.v = [self.v[-1], self.v[0], self.v[1], self.v[2]] def Triangulate(faces): print('faces: '+str(faces)) faces_new = [] for t in range(len(faces)-2): faces_new.extend([faces[t],faces[t+1],faces[t+2]]) # if t%2 ==0: # faces_new.extend([faces[t],faces[t+1],faces[t+2]]) # else: # faces_new.extend([faces[t+2],faces[t+1],faces[t]]) # if ((format == 0) or (format == 16) or (format == 1)): # faces_new.extend([faces[t+2],faces[t+1],faces[0]]) # else: # faces_new.extend([faces[t+2],faces[t+1],faces[t]]) print('faces new: '+str(faces_new)) return faces_new def MakePolyOk(faces): faces1 = [] face = [] for j in range(len(faces)): if (j%2 == 0): faces1.append(faces[j]) else: face.append(faces[j]) faces = face faces1.reverse() faces.extend(faces1) return faces def parse_plm(input_file, color_format): with open (input_file,'r+b') as file: struct.unpack('<i',file.read(4))[0] #== 5065808: data_len = struct.unpack('<i',file.read(4))[0] ##### PALT ##### PALT = struct.unpack('<i',file.read(4))[0] #if PALT == 1414283600: #print("PALT") #else: #print("something went wrong") # sys.exit() PALT_len = struct.unpack('<i',file.read(4))[0] colors_list = [] for i in range(PALT_len): #print("COLOR " + str(i)) R = 0 G = 0 B = 0 R_dat = struct.unpack('<b',file.read(1))[0] if (R_dat <= 1): R = 255 + R_dat else: R = R_dat G_dat = struct.unpack('<b',file.read(1))[0] if (G_dat <= -1): G = 255 + G_dat else: G = G_dat B_dat = struct.unpack('<b',file.read(1))[0] if (B_dat <= -1): B = 255 + B_dat else: B = B_dat #print("R: " + str(R) + "G: " + str(G) + "B: " + str(B)) #print("R: " + str(R_dat) + "G: " + str(G_dat) + "B: " + str(B_dat)) #print("") col_1 = 0 col_2 = 0 col_3 = 0 if (color_format[0] == "R"): col_1 = R elif (color_format[0] == "G"): col_1 = G elif (color_format[0] == "B"): col_1 = B if (color_format[1] == "R"): col_2 = R elif (color_format[1] == "G"): col_2 = G elif (color_format[1] == "B"): col_2 = B if (color_format[2] == "R"): col_3 = R elif (color_format[2] == "G"): col_3 = G elif (color_format[2] == "B"): col_3 = B colors_list.append( (col_1, col_2, col_3) ) return colors_list def parse_pro(input_file, colors_list): with open (input_file,'r') as file: #read all lines first pro = file.readlines() file.close() # you may also want to remove whitespace characters like `\n` at the end of each line pro = [x.strip() for x in pro] #print(pro) ##### TEXTUREFILES ##### texturefiles_index = pro.index([i for i in pro if "TEXTUREFILES" in i][0]) texturefiles_num = int(re.search(r'\d+', pro[texturefiles_index]).group()) texturefiles = [] for i in range(texturefiles_num): texturefiles.append(pro[texturefiles_index + 1 + i].split(".")[0]) # так как texturefiles_index = номер строки, где написано "TEXTUREFILES", сами текстуры на одну строку ниже # split нужен для того, чтобы убрать всё, что после точки - например, ".txr noload" #print("len texfiles: " + str(len(texturefiles))) ##### MATERIALS ##### materials_index = pro.index([i for i in pro if "MATERIALS" in i][0]) materials_num = int(re.search(r'\d+', pro[materials_index]).group()) materials = [] for i in range(materials_num): materials.append(pro[materials_index + 1 + i]) # тоже самое, так как materials_index = номер строки, где написано "MATERIALS", сами материалы на одну строку ниже ##### Параметры материалов (col %d) ##### material_colors = [] for i in range(materials_num): colNum_str = str(re.findall(r'col\s+\d+', materials[i])) colNum = 0 if (colNum_str != "[]"): colNum_final = str(re.findall(r'\d+', colNum_str[2:-2]))[2:-2] #print(texNum_final) colNum = int(colNum_final) #[5:-2] нужно чтобы убрать ['tex и '], например: ['tex 10'] -> 10 material_colors.append(str(colors_list[colNum])) else: material_colors.append("[]") ##### Параметры материалов (tex %d) ##### material_textures = [] for i in range(materials_num): texNum_str = str(re.findall(r't\wx\s+\d+', materials[i])) # t\wx - так как помимо tex, ещё бывает ttx texNum = 0 if (texNum_str != "[]"): texNum_final = str(re.findall(r'\d+', texNum_str[2:-2]))[2:-2] #print(texNum_final) texNum = int(texNum_final) #[5:-2] нужно чтобы убрать ['tex и '], например: ['tex 10'] -> 10 material_textures.append(texturefiles[texNum-1]) else: material_textures.append(material_colors[i]) #for k in range(materials_num): # print(materials[k] + " ---> " + material_textures[k]) return material_textures def read(file, context, op, filepath, search_tex_names, textures_format, color_format, tex_path): if file.read(3) == b'b3d': print ("correct file"); else: print ("b3d error") file.seek(21,1); Imgs = [] math = [] #texr = [] if (search_tex_names == True): colors_list = parse_plm(file.name[:-3] + "plm", color_format) material_textures = parse_pro(file.name[:-3] + "pro", colors_list) #print(material_textures) for i in range(struct.unpack('<i',file.read(4))[0]): #Imgs.append(file.read(32).decode("utf-8").rstrip('\0')) SNImg = file.read(32).decode("utf-8").rstrip('\0') #читаю имя #PImg = (filepath.rsplit('\\',1)[0] +'\\txr\\' +SNImg+'.tga') #полный путь ####################################################### if (search_tex_names == True): if (material_textures[i][0] == "("): PImg = (material_textures[i]) elif (material_textures[i][0] == "["): PImg = ("(255, 255, 255)") else: PImg = (filepath.rsplit('\\',1)[0] + "\\" + material_textures[i] + "." + textures_format) else: PImg = (filepath.rsplit('\\',1)[0] +'\\txr\\' +SNImg + "." + textures_format) #print (PImg) if (search_tex_names == True): if os.path.isfile(PImg): img = bpy.data.images.load(PImg) else: img = bpy.data.images.new(SNImg,1,1) if (material_textures[i][0] == "("): PImg = (material_textures[i]) R = (float((PImg[1:-1].split(", "))[0])) / 255 G = (float((PImg[1:-1].split(", "))[1])) / 255 B = (float((PImg[1:-1].split(", "))[2])) / 255 img.pixels = (B, G, R, 1.0) img.filepath_raw = (filepath.rsplit('\\',1)[0] + tex_path + "\\" + SNImg + "." + textures_format) img.file_format = textures_format.upper() img.save() else: print ('no '+PImg+' image') else: if os.path.isfile(PImg): img = bpy.data.images.load(PImg) else: PImg = (filepath.rsplit('\\',1)[0] +'\\txr\\' +SNImg[4:]+'.tga') #полный путь if os.path.isfile(PImg): img = bpy.data.images.load(PImg) else: img = bpy.data.images.new(SNImg,1,1) print ('no '+PImg+' image') #print(img.pixels) #name="Untitled", width=1024, height=1024, color=(0.0, 0.0, 0.0, 1.0), alpha=True, generated_type='BLANK', float=False, gen_context='NONE', use_stereo_3d=False #print ('no '+PImg+' image') #print(PImg[1:-1].split(", ")) #print(int((PImg[1:-1].split(", "))[0])) #print(int((PImg[1:-1].split(", "))[1])) #print(int((PImg[1:-1].split(", "))[2])) #if (search_tex_names == False): # PImg = (filepath.rsplit('\\',1)[0] +'\\txr\\' +SNImg+'.tga') #полный путь ##################################################################### #PImg = (filepath.rsplit('\\',1)[0] +'\\txr\\' +SNImg[4:]+'.tga') #? #if os.path.isfile(PImg): # img = bpy.data.images.load(PImg) #else: # img = bpy.data.images.new(SNImg,1,1)#bpy.data.images.new(SNImg,1,1) # print ('no '+PImg+' image') #print ('no '+PImg+' image') Imgs.append(img) #print(Imgs) tex = bpy.data.textures.new(SNImg,'IMAGE') tex.use_preview_alpha = True tex.image = img #bpy.data.images[i] mat = bpy.data.materials.new(SNImg) mat.texture_slots.add() mat.texture_slots[0].uv_layer = 'UVmap' mat.texture_slots[0].texture = tex mat.texture_slots[0].use_map_alpha = True math.append(mat) file.seek(4,1) ex = 0 i = 0 lvl = 0 cnt = 0 coords25 = [] coords23 = [] vertexes = [] normals = [] format = 0 # b3dObj = 0 uv = [] b3dObj = bpy.data.objects.new(os.path.basename(op.properties.filepath),None) context.scene.objects.link(b3dObj) objString = [os.path.basename(op.properties.filepath)] while ex!=1: #if (file.tell()>23281193): # break ex = openclose(file) if ex == 0: #print('-') del objString[-1] #objString = objString[:-1] lvl-=1 #print((objString)) #print('eob') #continue elif ex == 1: print(str(cnt)) file.close() break elif ex == 3: continue elif ex == 2: #print ('+') lvl+=1 objName = readName(file) type = struct.unpack("<i",file.read(4))[0] #print (str(type)) print(objName + ", type: " + str(type) + ", pos: " + str(file.tell())) if (type == 0): qu = quat(file).v objString.append(os.path.basename(op.properties.filepath)) ff = file.seek(28,1) elif (type == 1): cnt+=1 #b3dObj.append( b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 1 b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True b3dObj['2 name'] = file.read(32).decode("cp1251").rstrip('\0') b3dObj['3 name'] = file.read(32).decode("cp1251").rstrip('\0') b3dObj['pos'] = str(file.tell()) elif (type == 2): #контейнер хз cnt+=1 #b3dObj.append( b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 2 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v struct.unpack("<4fi",file.read(20)) elif (type == 3): # cnt+=1 #b3dObj.append( b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 3 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v struct.unpack("<i",file.read(4)) elif (type == 4): #похоже на контейнер 05 совмещенный с 12 cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 4 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v str(file.read(32).decode("utf-8")).rstrip('\0') struct.unpack("<i7fi",file.read(36)) elif (type==5): #общий контейнер #object = type05(file) cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 5 b3dObj['pos'] = str(file.tell()) b3dObj['node_x'] = struct.unpack("<f",file.read(4))[0] b3dObj['node_y'] = struct.unpack("<f",file.read(4))[0] b3dObj['node_z'] = struct.unpack("<f",file.read(4))[0] b3dObj['node_radius'] = struct.unpack("<f",file.read(4))[0] b3dObj['add_name'] = readName(file) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) file.seek(4,1) #b3dObj.hide = True elif (type == 6): vertexes = [] uv = [] cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 6 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v readName(file) readName(file) num = struct.unpack("<i",file.read(4))[0] for i in range (num): vertexes.append(struct.unpack("<3f",file.read(12))) uv.append(struct.unpack("<2f",file.read(8))) struct.unpack("<i",file.read(4))[0] elif (type == 7): #25? xyzuv TailLight? похоже на "хвост" движения mesh format = 0; coords25 = [] vertexes = [] uv = [] cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 7 b3dObj.parent = context.scene.objects[objString[-1]] #b3dObj.hide = True qu = quat(file).v str(struct.unpack("<8f",file.read(32))) #0-0 num = struct.unpack("<i",file.read(4))[0] for i in range(num): vertexes.append(struct.unpack("<3f",file.read(12))) uv.append(struct.unpack("<2f",file.read(8))) #((struct.unpack("<f",file.read(4))[0], 1 - struct.unpack("<f",file.read(4))[0])) #str(struct.unpack("<5f",file.read(20))) str(struct.unpack("<i",file.read(4))[0]) context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) elif (type == 8): #тоже фейсы face faces = [] faces_all = [] uvs = [] texnum = 0 cnt+=1 b3dMesh = (bpy.data.meshes.new(objName)) b3dObj=bpy.data.objects.new(objName, b3dMesh) b3dObj['block_type'] = '8' b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] #b3dObj.hide = True qu = coords3(file).v #b3dObj.location = qu file.read(4) num = struct.unpack("<i",file.read(4))[0] for i in range(num): faces = [] faces_new = [] format = struct.unpack("<i",file.read(4))[0] struct.unpack("<fi",file.read(8)) texnum = struct.unpack("i",file.read(4))[0] num1 = struct.unpack("<i",file.read(4))[0] if ((format == 178) or (format == 50)): for j in range(num1): faces.append(struct.unpack("<i",file.read(4))[0]) struct.unpack("<5f",file.read(20)) elif ((format == 176) or (format == 48)or (format == 179)or (format == 51)): for j in range(num1): faces.append(struct.unpack("<i",file.read(4))[0]) struct.unpack("<3f",file.read(12)) elif ((format == 3) or (format == 2) or (format == 131)): for j in range(num1): faces.append(struct.unpack("<i",file.read(4))[0]) struct.unpack("<2f",file.read(8)) elif format == 177: for j in range(num1): faces.append(struct.unpack("<i",file.read(4))[0]) struct.unpack("<f",file.read(4)) else: for j in range(num1): faces.append(struct.unpack("<i",file.read(4))[0]) #print ('faces: '+str(faces)) for t in range(len(faces)-2): if t%2 ==0: faces_new.append([faces[t],faces[t+1],faces[t+2]]) else: if ((format == 0) or (format == 16) or (format == 1)): faces_new.append([faces[t+2],faces[t+1],faces[0]]) else: faces_new.append([faces[t+2],faces[t+1],faces[t]]) uvs.append((uv[faces_new[t][0]],uv[faces_new[t][1]],uv[faces_new[t][2]])) faces_all.extend(faces_new) #print(str(faces_all)) #pdb.set_trace() Ev = threading.Event() Tr = threading.Thread(target=b3dMesh.from_pydata, args = (vertexes,[],faces_all)) Tr.start() Ev.set() Tr.join() uvMesh = b3dMesh.uv_textures.new() imgMesh = math[texnum].texture_slots[0].texture.image.size[0] uvMesh.name = 'default' uvLoop = b3dMesh.uv_layers[0] uvsMesh = [] #print('uvs: ',str(uvs)) for i, texpoly in enumerate(uvMesh.data): texpoly.image = Imgs[texnum] poly = b3dMesh.polygons[i] for j,k in enumerate(poly.loop_indices): uvsMesh = [uvs[i][j][0],1 - uvs[i][j][1]] uvLoop.data[k].uv = uvsMesh mat = b3dMesh.materials.append(math[texnum]) context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) elif (type == 9): cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 9 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v str(quat(file).v) #print file.seek(4,1) elif (type == 10): #контейнер, хз о чем cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 10 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v quat(file) (onebyte(file)) file.seek(3,1) elif (type == 11): cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 11 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) qu = quat(file).v #printwrite(writefile,tab1+'block 11 XYZW: '+str(qu)) file.seek(32,1) #printwrite(writefile,tab1+str(struct.unpack("<8f",file.read(32)))) file.seek(4,1) #printwrite(writefile, tab1+'child: '+str(struct.unpack("<i",file.read(4))[0])) elif (type == 12): cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 12 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v file.read(28) elif (type == 13): cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 13 b3dObj['pos'] = str(file.tell()) b3dObj.parent = context.scene.objects[objString[-1]] context.scene.objects.link(b3dObj) objString.append(context.scene.objects[0].name) #b3dObj.hide = True qu = quat(file).v num = [] coords = [] num = struct.unpack("3i",file.read(12)) #printwrite(writefile,tab1+str(num)) for i in range(num[-1]): coords.append(struct.unpack("f",file.read(4))[0]) if num[-1]>0: pass #printwrite(writefile,tab1+'0d Coords: '+str(coords)) elif (type == 14): #sell_ ? #cnt+=1 #b3dObj = bpy.data.objects.new(objName, None) #b3dObj['block_type'] = 14 #b3dObj['pos'] = str(file.tell()) #b3dObj.parent = context.scene.objects[objString[-1]] #context.scene.objects.link(b3dObj) #objString.append(context.scene.objects[0].name) #b3dObj.hide = True #qu = quat(file).v #file.seek(24, 1) #var = struct.unpack("<i",file.read(4))[0] #print(str(file.tell())) #if var !=0: # file.seek(len(objName), 1) #file.seek(4, 1) #file.seek(17,1) #file.seek(11,1)#0-0 cnt+=1 b3dObj = bpy.data.objects.new(objName, None) b3dObj['block_type'] = 14 b3dObj['pos'] =
user_alert infos for particular user with alerts. Parameters: :param alert_infos: alert_infos list for particular user :param user: user details format is list type: [(<userIndicator>, <userValue>)] Returns: :return: parsed alerts """ # Initialize user_alerts list user_alerts = list() last_run_user_alert_hash_digest = self._last_run_hash_digests.get(GC_RM_USER_ALERTS, list()) curr_run_user_alert_hash_digest = list() for alert_info in alert_infos: # Create 'cef' type artifact for individual user alert by adding corresponding user infos with alert infos user_alert = { "userIndicator": user[0][0], "userValue": user[0][1], "alertName": alert_info.get("name", ""), "sourceProduct": alert_info.get("sourceProduct", ""), "timestamp": alert_info.get("timestamp", ""), "rawLog": alert_info.get("rawLog", ""), "uri": alert_info.get("uri", [""])[0], "udmEvent": alert_info.get("udmEvent") } # Check if the user_alert was already fetched and ingested in the previous run if not self._check_last_run_hash(last_run_user_alert_hash_digest, curr_run_user_alert_hash_digest, user_alert): user_alerts.append(user_alert) self._last_run_hash_digests[GC_RM_USER_ALERTS] = curr_run_user_alert_hash_digest return user_alerts def _parse_user_alerts_response(self, response): """Parse response of alerts with given ingestion asset configuration parameters. Parameters: :param response: object of alerts API call Returns: :return: parsed user alerts results """ # Initialize alerts results user_alerts_results = list() # If response is not dictionary type if not isinstance(response, dict): return user_alerts_results # Fetch user_alerts from the response user_alerts = response.get('userAlerts', []) if not user_alerts: return user_alerts_results self.debug_print(f"Total user alerts fetched: {len(user_alerts)}") for user_alert in user_alerts: # Initialize results list results = list() # Fetch user information user = list(user_alert.get('user', {}).items()) if not user: # Not received any kind of user details in the user with user_alerts dictionary # Hence marking userIndicator and userValue as empty string user = [("", "")] try: # Parse user_alerts infos for particular user results = self._parse_user_alert_info(user_alert.get('alertInfos', []), user) except Exception as e: self.debug_print(f"Exception occurred while parsing user_alerts response. Error: {str(e)}") self.debug_print(f"Ignoring user_alert infos for userIndicator: '{user[0][0]}' and userValue: '{user[0][1]}'") # Add user_alerts into final results user_alerts_results.extend(results) self.debug_print(f"Total parsed user alerts after deduplication: {len(user_alerts_results)}") return user_alerts_results def _parse_alert_info(self, alert_infos, asset): """Parse alert infos for particular asset with alerts. Parameters: :param alert_infos: alert_infos list for particular asset :param asset: asset details format is list type: [(<assetIndicator>, <assetValue>)] Returns: :return: parsed alerts """ # Initialize alerts list alerts = list() last_run_alert_hash_digest = self._last_run_hash_digests.get(GC_RM_ASSET_ALERTS, list()) curr_run_alert_hash_digest = list() for alert_info in alert_infos: # Ignore alerts which alert has configured severity to ingest if self._alerts_severity and alert_info.get('severity', '').lower() not in self._alerts_severity: self.debug_print(f"Ignored alert: {alert_info.get('name', '')} " f"which has severity: {alert_info.get('severity', '')}") continue # Create 'cef' type artifact for individual alert by adding corresponding asset infos with alert infos alert = { "assetIndicator": asset[0][0], "assetValue": asset[0][1], "alertName": alert_info.get("name", ""), "sourceProduct": alert_info.get("sourceProduct", ""), "severity": alert_info.get("severity", ""), "timestamp": alert_info.get("timestamp", ""), "rawLog": alert_info.get("rawLog", ""), "uri": alert_info.get("uri", [""])[0], "udmEvent": alert_info.get("udmEvent") } # Check if the alert was already fetched and ingested in the previous run if not self._check_last_run_hash(last_run_alert_hash_digest, curr_run_alert_hash_digest, alert): alerts.append(alert) self._last_run_hash_digests[GC_RM_ASSET_ALERTS] = curr_run_alert_hash_digest return alerts def _parse_alerts_response(self, response): """Parse response of alerts with given ingestion asset configuration parameters. Parameters: :param response: object of alerts API call Returns: :return: parsed asset alerts results """ # Initialize alerts results alerts_results = list() # If response is not dictionary type if not isinstance(response, dict): return alerts_results # Fetch alerts from the response alerts = response.get('alerts', []) if not alerts: return alerts_results self.debug_print(f"Total asset alerts fetched: {len(alerts)}") for alert in alerts: # Initialize results list results = list() # Fetch asset information asset = list(alert.get('asset', {}).items()) if not asset: # Not received any kind of asset details in the asset with alerts dictionary # Hence marking assetIndicator and assetValue as empty string asset = [("", "")] try: # Parse alerts infos for particular asset results = self._parse_alert_info(alert.get('alertInfos', []), asset) except Exception as e: self.debug_print(f"Exception occurred while parsing alerts response. Error: {str(e)}") self.debug_print(f"Ignoring alert infos for assetIndicator: '{asset[0][0]}' and assetValue: '{asset[0][1]}'") # Add alerts into final results alerts_results.extend(results) self.debug_print(f"Total parsed asset alerts after deduplication: {len(alerts_results)}") return alerts_results def _parse_ioc_info(self, ioc, artifact): """Parse alert infos for particular asset with alerts. Parameters: :param ioc: IoC domain match :param artifact: asset details format is list type: [(<artifactIndicator>, <artifactValue>)] Returns: :return: parsed ioc result """ # Initialize list of IoCs information sources = list() severity = list() category = list() confidence_str = list() confidence_int = list() # Parse information from received IoC sources for source in ioc.get('sources', []): sources.append(source.get('source', '')) confidence_str.append(source.get('confidenceScore', {}).get('normalizedConfidenceScore', 'unknown')) confidence_int.append(source.get('confidenceScore', {}).get('intRawConfidenceScore', 0)) severity.append(source.get('rawSeverity', '')) category.append(source.get('category', '')) # Convert intRawConfidenceScore to str type from int type try: confidence_int = list(map(lambda x: str(x), confidence_int)) except Exception as e: self.debug_print(f"Error occurred while converting intRawConfidenceScore value to 'str' type from 'int' type. " f"Error: {str(e)}") self.debug_print(f"Ignoring intRawConfidenceScore value from all the sources for IoC domain: {artifact[0][1]}") # Ignore all the intRawConfidenceScore confidence_int = list() # Remove empty string values from the list of different sources details sources = list(filter(None, sources)) confidence_str = list(filter(None, confidence_str)) confidence_int = list(filter(None, confidence_int)) severity = list(filter(None, severity)) category = list(filter(None, category)) # Create parsed IoC parsed_ioc = { 'artifactIndicator': artifact[0][0], 'artifactValue': artifact[0][1], 'sources': ", ".join(sources), 'normalizedConfidenceScore': ", ".join(confidence_str), 'intRawConfidenceScore': ", ".join(confidence_int), 'rawSeverity': ", ".join(severity), 'category': ", ".join(category), 'iocIngestTime': ioc.get("iocIngestTime", ""), 'firstSeenTime': ioc.get("firstSeenTime", ""), 'lastSeenTime': ioc.get("lastSeenTime", ""), 'uri': ioc.get('uri', [''])[0], 'rawJSON': json.dumps(ioc), 'data': ioc } return parsed_ioc def _parse_iocs_response(self, response): """Parse response of iocs with given ingestion asset configuration parameters. Parameters: :param response: response dictionary of IoCs API call Returns: :return: parsed iocs results """ # Initialize alerts results iocs_results = list() # If response is not dictionary type if not isinstance(response, dict): return iocs_results # Fetch alerts from the response iocs = response.get('response', {}).get('matches', []) if not iocs: return iocs_results self.debug_print(f"Total IoCs fetched: {len(iocs)}") for ioc in iocs: # Initialize result variable result = None # Fetch asset information artifact = list(ioc.get('artifact', {}).items()) if not artifact: # Not received any artifact information for IoC domain matches # Hence marking artifactIndicator and artifactValue as empty string artifact = [("", "")] try: # Ingest only IoC domain matches if artifact[0][0] != "domainName": self.debug_print("Ignore as retrieved IoCs is not domain matches") self.debug_print(f"Received IoC artifactIndicator is {artifact[0][0]}") continue # Parse IoC information result = self._parse_ioc_info(ioc, artifact) except Exception as e: self.debug_print(f"Exception occurred while parsing IoCs response. Error: {str(e)}") self.debug_print(f"Ignoring IoC match for artifactIndicator: " f"'{artifact[0][0]}' and artifactValue: '{artifact[0][1]}'") # Add alerts into final results if result: iocs_results.append(result) self.debug_print(f"Total IoC domain matches parsed: {len(iocs_results)}") return iocs_results def _parse_collection_elements(self, collection_elements): """Parse Collection Elements to fetch the detections. Parameters: :param collection_elements: a list of dictionaries obtained from the detections response Returns: :return: parsed list of events """ parsed_events = list() try: for element in collection_elements: label = element.get("label") refs = element.get("references") for ref in refs: event = dict() event.update(ref) event['label'] = label parsed_events.append(event) except Exception as e: self.debug_print(f"Error occurred while parsing the collectionEvents. Error: {str(e)}") self.debug_print("Returning the partially parsed events") return parsed_events return parsed_events def _parse_detections_response(self, response, run_mode): """Parse response of detections with given ingestion asset configuration parameters. Parameters: :param response: response dictionary of Detections API call :param run_mode: run_mode to differentiate ALERTING and NOT_ALERTING detections Returns: :return: parsed detections results """ # Initialize alerts results parsed_detections = list() # If response is not dictionary type if not isinstance(response, dict): return parsed_detections # Fetch alerts from the response detections = response.get('detections', []) if not detections: return parsed_detections self.debug_print(f"Total {run_mode} detections fetched: {len(detections)}") invalid_rule_ids = response.get('invalid_rule_ids', []) rule_ids_with_partial_detections = response.get('rule_ids_with_partial_detections', []) if invalid_rule_ids: invalid_rule_ids_str = list(map(lambda invalid_rule: invalid_rule['rule_id'], invalid_rule_ids)) invalid_rule_ids_str = ', '.join(invalid_rule_ids_str) self.debug_print(f"Following Rule ID(s) are not valid:\n{invalid_rule_ids_str}") self.debug_print("No detections were fetched for them") self.save_progress(f"Following Rule ID(s) are not valid:\n{invalid_rule_ids_str}") self.save_progress("No detections were fetched for them") if rule_ids_with_partial_detections: map_func = lambda rule_ids_with_partial_detection: rule_ids_with_partial_detection['rule_id'] rule_ids_with_partial_detections_str = list(map(map_func, rule_ids_with_partial_detections)) rule_ids_with_partial_detections_str = ', '.join(rule_ids_with_partial_detections_str) self.debug_print(f"Detections maybe missing for the following Rule ID(s):\n{rule_ids_with_partial_detections_str}") self.debug_print(GC_RATE_LIMIT_EXCEEDED) self.save_progress(f"Detections maybe missing for the following Rule ID(s):\n{rule_ids_with_partial_detections_str}") self.save_progress(GC_RATE_LIMIT_EXCEEDED) last_run_detections_hash_digest = self._last_run_hash_digests.get(run_mode, list()) curr_run_detections_hash_digest = list() for detection_info in detections: # Check if the detection was already fetched and ingested in the previous run if self._check_last_run_hash(last_run_detections_hash_digest, curr_run_detections_hash_digest, detection_info): continue collection_elements = detection_info.get("collectionElements", []) # Fetch asset information detection_details = detection_info.get('detection', [{}])[0] detection = { "detectionId": detection_info.get("id", ""), "detectionType": detection_info.get("type", GC_DEFAULT_DETECTION_TYPE), "ruleId": detection_details.get("ruleId", ""),
+ m.x2831 + m.x2981 == 1) m.c3133 = Constraint(expr= m.x132 + m.x282 + m.x432 + m.x582 + m.x732 + m.x882 + m.x1032 + m.x1182 + m.x1332 + m.x1482 + m.x1632 + m.x1782 + m.x1932 + m.x2082 + m.x2232 + m.x2382 + m.x2532 + m.x2682 + m.x2832 + m.x2982 == 1) m.c3134 = Constraint(expr= m.x133 + m.x283 + m.x433 + m.x583 + m.x733 + m.x883 + m.x1033 + m.x1183 + m.x1333 + m.x1483 + m.x1633 + m.x1783 + m.x1933 + m.x2083 + m.x2233 + m.x2383 + m.x2533 + m.x2683 + m.x2833 + m.x2983 == 1) m.c3135 = Constraint(expr= m.x134 + m.x284 + m.x434 + m.x584 + m.x734 + m.x884 + m.x1034 + m.x1184 + m.x1334 + m.x1484 + m.x1634 + m.x1784 + m.x1934 + m.x2084 + m.x2234 + m.x2384 + m.x2534 + m.x2684 + m.x2834 + m.x2984 == 1) m.c3136 = Constraint(expr= m.x135 + m.x285 + m.x435 + m.x585 + m.x735 + m.x885 + m.x1035 + m.x1185 + m.x1335 + m.x1485 + m.x1635 + m.x1785 + m.x1935 + m.x2085 + m.x2235 + m.x2385 + m.x2535 + m.x2685 + m.x2835 + m.x2985 == 1) m.c3137 = Constraint(expr= m.x136 + m.x286 + m.x436 + m.x586 + m.x736 + m.x886 + m.x1036 + m.x1186 + m.x1336 + m.x1486 + m.x1636 + m.x1786 + m.x1936 + m.x2086 + m.x2236 + m.x2386 + m.x2536 + m.x2686 + m.x2836 + m.x2986 == 1) m.c3138 = Constraint(expr= m.x137 + m.x287 + m.x437 + m.x587 + m.x737 + m.x887 + m.x1037 + m.x1187 + m.x1337 + m.x1487 + m.x1637 + m.x1787 + m.x1937 + m.x2087 + m.x2237 + m.x2387 + m.x2537 + m.x2687 + m.x2837 + m.x2987 == 1) m.c3139 = Constraint(expr= m.x138 + m.x288 + m.x438 + m.x588 + m.x738 + m.x888 + m.x1038 + m.x1188 + m.x1338 + m.x1488 + m.x1638 + m.x1788 + m.x1938 + m.x2088 + m.x2238 + m.x2388 + m.x2538 + m.x2688 + m.x2838 + m.x2988 == 1) m.c3140 = Constraint(expr= m.x139 + m.x289 + m.x439 + m.x589 + m.x739 + m.x889 + m.x1039 + m.x1189 + m.x1339 + m.x1489 + m.x1639 + m.x1789 + m.x1939 + m.x2089 + m.x2239 + m.x2389 + m.x2539 + m.x2689 + m.x2839 + m.x2989 == 1) m.c3141 = Constraint(expr= m.x140 + m.x290 + m.x440 + m.x590 + m.x740 + m.x890 + m.x1040 + m.x1190 + m.x1340 + m.x1490 + m.x1640 + m.x1790 + m.x1940 + m.x2090 + m.x2240 + m.x2390 + m.x2540 + m.x2690 + m.x2840 + m.x2990 == 1) m.c3142 = Constraint(expr= m.x141 + m.x291 + m.x441 + m.x591 + m.x741 + m.x891 + m.x1041 + m.x1191 + m.x1341 + m.x1491 + m.x1641 + m.x1791 + m.x1941 + m.x2091 + m.x2241 + m.x2391 + m.x2541 + m.x2691 + m.x2841 + m.x2991 == 1) m.c3143 = Constraint(expr= m.x142 + m.x292 + m.x442 + m.x592 + m.x742 + m.x892 + m.x1042 + m.x1192 + m.x1342 + m.x1492 + m.x1642 + m.x1792 + m.x1942 + m.x2092 + m.x2242 + m.x2392 + m.x2542 + m.x2692 + m.x2842 + m.x2992 == 1) m.c3144 = Constraint(expr= m.x143 + m.x293 + m.x443 + m.x593 + m.x743 + m.x893 + m.x1043 + m.x1193 + m.x1343 + m.x1493 + m.x1643 + m.x1793 + m.x1943 + m.x2093 + m.x2243 + m.x2393 + m.x2543 + m.x2693 + m.x2843 + m.x2993 == 1) m.c3145 = Constraint(expr= m.x144 + m.x294 + m.x444 + m.x594 + m.x744 + m.x894 + m.x1044 + m.x1194 + m.x1344 + m.x1494 + m.x1644 + m.x1794 + m.x1944 + m.x2094 + m.x2244 + m.x2394 + m.x2544 + m.x2694 + m.x2844 + m.x2994 == 1) m.c3146 = Constraint(expr= m.x145 + m.x295 + m.x445 + m.x595 + m.x745 + m.x895 + m.x1045 + m.x1195 + m.x1345 + m.x1495 + m.x1645 + m.x1795 + m.x1945 + m.x2095 + m.x2245 + m.x2395 + m.x2545 + m.x2695 + m.x2845 + m.x2995 == 1) m.c3147 = Constraint(expr= m.x146 + m.x296 + m.x446 + m.x596 + m.x746 + m.x896 + m.x1046 + m.x1196 + m.x1346 + m.x1496 + m.x1646 + m.x1796 + m.x1946 + m.x2096 + m.x2246 + m.x2396 + m.x2546 + m.x2696 + m.x2846 + m.x2996 == 1) m.c3148 = Constraint(expr= m.x147 + m.x297 + m.x447 + m.x597 + m.x747 + m.x897 + m.x1047 + m.x1197 + m.x1347 + m.x1497 + m.x1647 + m.x1797 + m.x1947 + m.x2097 + m.x2247 + m.x2397 + m.x2547 + m.x2697 + m.x2847 + m.x2997 == 1) m.c3149 = Constraint(expr= m.x148 + m.x298 + m.x448 + m.x598 + m.x748 + m.x898 + m.x1048 + m.x1198 + m.x1348 + m.x1498 + m.x1648 + m.x1798 + m.x1948 + m.x2098 + m.x2248 + m.x2398 + m.x2548 + m.x2698 + m.x2848 + m.x2998 == 1) m.c3150 = Constraint(expr= m.x149 + m.x299 + m.x449 + m.x599 + m.x749 + m.x899 + m.x1049 + m.x1199 + m.x1349 + m.x1499 + m.x1649 + m.x1799 + m.x1949 + m.x2099 + m.x2249 + m.x2399 + m.x2549 + m.x2699 + m.x2849 + m.x2999 == 1) m.c3151 = Constraint(expr= m.x150 + m.x300 + m.x450 + m.x600 + m.x750 + m.x900 + m.x1050 + m.x1200 + m.x1350 + m.x1500 + m.x1650 + m.x1800 + m.x1950 + m.x2100 + m.x2250 + m.x2400 + m.x2550 + m.x2700 + m.x2850 + m.x3000 == 1) m.c3152 = Constraint(expr=m.x1*m.x1 - m.x3021*m.b3001 <= 0) m.c3153 = Constraint(expr=m.x2*m.x2 - m.x3022*m.b3001 <= 0) m.c3154 = Constraint(expr=m.x3*m.x3 - m.x3023*m.b3001 <= 0) m.c3155 = Constraint(expr=m.x4*m.x4 - m.x3024*m.b3001 <= 0) m.c3156 = Constraint(expr=m.x5*m.x5 - m.x3025*m.b3001 <= 0) m.c3157 = Constraint(expr=m.x6*m.x6 - m.x3026*m.b3001 <= 0) m.c3158 = Constraint(expr=m.x7*m.x7 - m.x3027*m.b3001 <= 0) m.c3159 = Constraint(expr=m.x8*m.x8 - m.x3028*m.b3001 <= 0) m.c3160 = Constraint(expr=m.x9*m.x9 - m.x3029*m.b3001 <= 0) m.c3161 = Constraint(expr=m.x10*m.x10 - m.x3030*m.b3001 <= 0) m.c3162 = Constraint(expr=m.x11*m.x11 - m.x3031*m.b3001 <= 0) m.c3163 = Constraint(expr=m.x12*m.x12 - m.x3032*m.b3001 <= 0) m.c3164 = Constraint(expr=m.x13*m.x13 - m.x3033*m.b3001 <= 0) m.c3165 = Constraint(expr=m.x14*m.x14 - m.x3034*m.b3001 <= 0) m.c3166 = Constraint(expr=m.x15*m.x15 - m.x3035*m.b3001 <= 0) m.c3167 = Constraint(expr=m.x16*m.x16 - m.x3036*m.b3001 <= 0) m.c3168 = Constraint(expr=m.x17*m.x17 - m.x3037*m.b3001 <= 0) m.c3169 = Constraint(expr=m.x18*m.x18 - m.x3038*m.b3001 <= 0) m.c3170 = Constraint(expr=m.x19*m.x19 - m.x3039*m.b3001 <= 0) m.c3171 = Constraint(expr=m.x20*m.x20 - m.x3040*m.b3001 <= 0) m.c3172 = Constraint(expr=m.x21*m.x21 - m.x3041*m.b3001 <= 0) m.c3173 = Constraint(expr=m.x22*m.x22 - m.x3042*m.b3001 <= 0) m.c3174 = Constraint(expr=m.x23*m.x23 - m.x3043*m.b3001 <= 0) m.c3175 = Constraint(expr=m.x24*m.x24 - m.x3044*m.b3001 <= 0) m.c3176 = Constraint(expr=m.x25*m.x25 - m.x3045*m.b3001 <= 0) m.c3177 = Constraint(expr=m.x26*m.x26 - m.x3046*m.b3001 <= 0) m.c3178 = Constraint(expr=m.x27*m.x27 - m.x3047*m.b3001 <= 0) m.c3179 = Constraint(expr=m.x28*m.x28 - m.x3048*m.b3001 <= 0) m.c3180 = Constraint(expr=m.x29*m.x29 - m.x3049*m.b3001 <= 0) m.c3181 = Constraint(expr=m.x30*m.x30 - m.x3050*m.b3001 <= 0) m.c3182 = Constraint(expr=m.x31*m.x31 - m.x3051*m.b3001 <= 0) m.c3183 = Constraint(expr=m.x32*m.x32 - m.x3052*m.b3001 <= 0) m.c3184 = Constraint(expr=m.x33*m.x33 - m.x3053*m.b3001 <= 0) m.c3185 = Constraint(expr=m.x34*m.x34 - m.x3054*m.b3001 <= 0) m.c3186 = Constraint(expr=m.x35*m.x35 - m.x3055*m.b3001 <= 0) m.c3187 = Constraint(expr=m.x36*m.x36 - m.x3056*m.b3001 <= 0) m.c3188 = Constraint(expr=m.x37*m.x37 - m.x3057*m.b3001 <= 0) m.c3189 = Constraint(expr=m.x38*m.x38 - m.x3058*m.b3001 <= 0) m.c3190 = Constraint(expr=m.x39*m.x39 - m.x3059*m.b3001 <= 0) m.c3191 = Constraint(expr=m.x40*m.x40 - m.x3060*m.b3001 <= 0) m.c3192 = Constraint(expr=m.x41*m.x41 - m.x3061*m.b3001 <= 0) m.c3193 = Constraint(expr=m.x42*m.x42 - m.x3062*m.b3001 <= 0) m.c3194 = Constraint(expr=m.x43*m.x43 - m.x3063*m.b3001 <= 0) m.c3195 = Constraint(expr=m.x44*m.x44 - m.x3064*m.b3001 <= 0) m.c3196 = Constraint(expr=m.x45*m.x45 - m.x3065*m.b3001 <= 0) m.c3197 = Constraint(expr=m.x46*m.x46 - m.x3066*m.b3001 <= 0) m.c3198 = Constraint(expr=m.x47*m.x47 - m.x3067*m.b3001 <= 0) m.c3199 = Constraint(expr=m.x48*m.x48 - m.x3068*m.b3001 <= 0) m.c3200 = Constraint(expr=m.x49*m.x49 - m.x3069*m.b3001 <= 0) m.c3201 = Constraint(expr=m.x50*m.x50 - m.x3070*m.b3001 <= 0) m.c3202 = Constraint(expr=m.x51*m.x51 - m.x3071*m.b3001 <= 0) m.c3203 = Constraint(expr=m.x52*m.x52 - m.x3072*m.b3001 <= 0) m.c3204 = Constraint(expr=m.x53*m.x53 - m.x3073*m.b3001 <= 0) m.c3205 = Constraint(expr=m.x54*m.x54 - m.x3074*m.b3001 <= 0) m.c3206 = Constraint(expr=m.x55*m.x55 - m.x3075*m.b3001 <= 0) m.c3207 = Constraint(expr=m.x56*m.x56 - m.x3076*m.b3001 <= 0) m.c3208 = Constraint(expr=m.x57*m.x57 - m.x3077*m.b3001 <= 0) m.c3209 = Constraint(expr=m.x58*m.x58 - m.x3078*m.b3001 <= 0) m.c3210 = Constraint(expr=m.x59*m.x59 - m.x3079*m.b3001 <= 0) m.c3211 = Constraint(expr=m.x60*m.x60 - m.x3080*m.b3001 <= 0) m.c3212 = Constraint(expr=m.x61*m.x61 - m.x3081*m.b3001 <= 0) m.c3213 = Constraint(expr=m.x62*m.x62 - m.x3082*m.b3001 <= 0) m.c3214 = Constraint(expr=m.x63*m.x63 - m.x3083*m.b3001 <= 0) m.c3215 = Constraint(expr=m.x64*m.x64 - m.x3084*m.b3001 <= 0) m.c3216 = Constraint(expr=m.x65*m.x65 - m.x3085*m.b3001 <= 0) m.c3217 = Constraint(expr=m.x66*m.x66 - m.x3086*m.b3001 <= 0) m.c3218 = Constraint(expr=m.x67*m.x67 - m.x3087*m.b3001 <= 0) m.c3219 = Constraint(expr=m.x68*m.x68 - m.x3088*m.b3001 <= 0) m.c3220 = Constraint(expr=m.x69*m.x69 - m.x3089*m.b3001 <= 0) m.c3221 = Constraint(expr=m.x70*m.x70 - m.x3090*m.b3001 <= 0) m.c3222 = Constraint(expr=m.x71*m.x71 - m.x3091*m.b3001 <= 0) m.c3223 = Constraint(expr=m.x72*m.x72 - m.x3092*m.b3001 <= 0) m.c3224 = Constraint(expr=m.x73*m.x73 - m.x3093*m.b3001 <= 0) m.c3225 = Constraint(expr=m.x74*m.x74 - m.x3094*m.b3001 <= 0) m.c3226 = Constraint(expr=m.x75*m.x75 - m.x3095*m.b3001 <= 0) m.c3227 = Constraint(expr=m.x76*m.x76 - m.x3096*m.b3001 <= 0) m.c3228 =
"▁Alte": 26872, "▁Criminal": 26873, "▁cyn": 26874, "▁sty": 26875, "Wie": 26876, "cente": 26877, "elim": 26878, "fut": 26879, "habita": 26880, "haq": 26881, "kulam": 26882, "rur": 26883, "tekin": 26884, "ʊ": 26885, "▁17.00": 26886, "▁Bilo": 26887, "▁Kunde": 26888, "▁Mulla": 26889, "▁Norden": 26890, "▁Pediatri": 26891, "▁Sonne": 26892, "▁incomp": 26893, "▁kul": 26894, "▁δ": 26895, ".08.2017": 26896, "HTML": 26897, "RUN": 26898, "gica": 26899, "jeva": 26900, "mā": 26901, "ohemi": 26902, "serva": 26903, "suar": 26904, "trek": 26905, "tuar": 26906, "▁Dhe": 26907, "▁SoundCloud": 26908, "▁available": 26909, "▁gou": 26910, "▁schlecht": 26911, "▁vene": 26912, "UDA": 26913, "bilo": 26914, "cía": 26915, "mbana": 26916, "ník": 26917, "venir": 26918, "zli": 26919, "”.": 26920, "▁Belgium": 26921, "▁Frieden": 26922, "▁Trainer": 26923, "▁location": 26924, "師": 26925, "dame": 26926, "▁13.00": 26927, "▁Joaquim": 26928, "▁Literatur": 26929, "▁Lotto": 26930, "▁Premi": 26931, "▁antar": 26932, "▁picture": 26933, "青": 26934, "Consult": 26935, "alala": 26936, "ará": 26937, "fusion": 26938, "png": 26939, "reach": 26940, "shte": 26941, "tı": 26942, "éri": 26943, "▁Demand": 26944, "▁Democracy": 26945, "▁Javascript": 26946, "▁Persona": 26947, "▁Tanga": 26948, "▁Voll": 26949, "▁Wys": 26950, "▁ela": 26951, "▁festiv": 26952, "▁minutes": 26953, "▁mozzarella": 26954, "▁question": 26955, "▁sida": 26956, "戦": 26957, "政": 26958, "Krist": 26959, "Yahoo": 26960, "ikke": 26961, "inot": 26962, "kapi": 26963, "kiel": 26964, "legia": 26965, "muni": 26966, "nomina": 26967, "wic": 26968, "yada": 26969, "▁9:00": 26970, "▁Basketball": 26971, "▁Edvard": 26972, "▁Legg": 26973, "▁MEDI": 26974, "▁command": 26975, "▁hag": 26976, "▁lume": 26977, "▁sv": 26978, "BAR": 26979, "BAS": 26980, "Jak": 26981, "handa": 26982, "hovo": 26983, "jj": 26984, "malle": 26985, "mbak": 26986, "meti": 26987, "niti": 26988, "puli": 26989, "vane": 26990, "ÉP": 26991, "▁Gomb": 26992, "▁Naud": 26993, "▁Nebo": 26994, "▁Sungai": 26995, "▁Tradition": 26996, "▁firm": 26997, "▁spring": 26998, "▁teams": 26999, "의": 27000, "Diagnos": 27001, "NEL": 27002, "añ": 27003, "ceni": 27004, "gast": 27005, "igt": 27006, "ipun": 27007, "kuna": 27008, "obs": 27009, "piac": 27010, "plata": 27011, "zyc": 27012, "▁(35)": 27013, "▁Senat": 27014, "▁canta": 27015, "▁dat": 27016, "▁jambo": 27017, "▁kom": 27018, "▁lec": 27019, "▁points": 27020, "▁sari": 27021, "▁sme": 27022, "▁turk": 27023, "▁Δ": 27024, "PAK": 27025, "avad": 27026, "cident": 27027, "deild": 27028, "logia": 27029, "mmin": 27030, "pret": 27031, "punt": 27032, "unii": 27033, "yasa": 27034, "ños": 27035, "ılı": 27036, "ście": 27037, "▁Kek": 27038, "▁Señor": 27039, "▁Zuid": 27040, "▁ergo": 27041, "▁hawa": 27042, "▁reality": 27043, "▁scale": 27044, "▁skype": 27045, "Esta": 27046, "condi": 27047, "ischen": 27048, "schule": 27049, "▁Does": 27050, "▁ESO": 27051, "▁Escuela": 27052, "▁Odense": 27053, "▁Period": 27054, "▁Rece": 27055, "▁Wam": 27056, "▁Wett": 27057, "▁emer": 27058, "▁hope": 27059, "▁jihad": 27060, "▁magazine": 27061, "▁refresh": 27062, "▁techno": 27063, "部": 27064, "Date": 27065, "HEN": 27066, "close": 27067, "kni": 27068, "▁Gourmet": 27069, "▁Mahendra": 27070, "▁Mikko": 27071, "▁comic": 27072, "▁dig": 27073, "▁dol": 27074, "▁dub": 27075, "▁economic": 27076, "▁education": 27077, "▁frig": 27078, "▁marginal": 27079, "▁soc": 27080, "▁transport": 27081, "▁wer": 27082, "▁yogurt": 27083, "▁zur": 27084, "お": 27085, "九": 27086, "達": 27087, "bahar": 27088, "gyel": 27089, "museum": 27090, "θ": 27091, "▁gol": 27092, "▁kao": 27093, "▁mean": 27094, "▁mut": 27095, "▁ora": 27096, "▁psa": 27097, "▁salt": 27098, "▁stro": 27099, "fler": 27100, "lki": 27101, "▁Ceza": 27102, "▁Ft": 27103, "▁Timbalan": 27104, "▁crash": 27105, "▁mall": 27106, "▁nema": 27107, "ミ": 27108, "的": 27109, "莊": 27110, "Mae": 27111, "jt": 27112, "▁Astronomi": 27113, "▁bras": 27114, "▁dela": 27115, "▁growth": 27116, "▁idea": 27117, "▁tuan": 27118, "06.2017": 27119, "halle": 27120, "malt": 27121, "sisi": 27122, "▁Indica": 27123, "▁Podle": 27124, "▁Punto": 27125, "▁rag": 27126, "▁steel": 27127, "レ": 27128, "LIC": 27129, "SOFT": 27130, "kaj": 27131, "pate": 27132, "terne": 27133, "tso": 27134, "▁Brü": 27135, "▁Für": 27136, "▁broad": 27137, "▁combat": 27138, "▁false": 27139, "▁going": 27140, "▁less": 27141, "▁sibi": 27142, "▁testo": 27143, "▁wir": 27144, "え": 27145, "Roz": 27146, "YAMA": 27147, "boll": 27148, "itud": 27149, "lić": 27150, "praz": 27151, "stamine": 27152, "stum": 27153, "▁COME": 27154, "▁DEL": 27155, "▁Déc": 27156, "▁Ziya": 27157, "▁spo": 27158, "대": 27159, "AGO": 27160, "LIMA": 27161, "imos": 27162, "mui": 27163, "pung": 27164, "sites": 27165, "voli": 27166, "▁Apartments": 27167, "▁Essay": 27168, "▁Haug": 27169, "▁Kampf": 27170, "▁Sort": 27171, "▁kor": 27172, "▁leder": 27173, "▁receive": 27174, "▁upon": 27175, "LOG": 27176, "amini": 27177, "ifying": 27178, "scul": 27179, "sidor": 27180, "ğü": 27181, "γ": 27182, "▁ELS": 27183, "▁Forex": 27184, "▁Lice": 27185, "▁Tomás": 27186, "▁mali": 27187, "▁sama": 27188, "良": 27189, "DDD": 27190, "fod": 27191, "pust": 27192, "sump": 27193, "timi": 27194, "wp": 27195, "zón": 27196, "▁Caso": 27197, "▁Mikl": 27198, "▁Onda": 27199, "▁Tomar": 27200, "▁disk": 27201, "▁journal": 27202, "▁sonde": 27203, "▁spe": 27204, "▁Ş": 27205, "rebro": 27206, "utis": 27207, "å": 27208, "▁Ahli": 27209, "▁STEP": 27210, "▁Symbol": 27211, "▁Zá": 27212, "▁billion": 27213, "▁glad": 27214, "▁hij": 27215, "▁vaga": 27216, "▁valida": 27217, "▁vivi": 27218, "鄭": 27219, "evro": 27220, "guna": 27221, "laka": 27222, "raste": 27223, "rés": 27224, "surat": 27225, "▁Australi": 27226, "▁Biskup": 27227, "▁Inspiration": 27228, "▁Nowy": 27229, "▁fine": 27230, "▁swa": 27231, "▁tres": 27232, "ナ": 27233, "UZU": 27234, "chair": 27235, "dod": 27236, "houd": 27237, "hā": 27238, "itatis": 27239, "ütz": 27240, "▁Evita": 27241, "▁Fett": 27242, "▁Lég": 27243, "▁Norm": 27244, "▁Reykjavík": 27245, "▁bh": 27246, "▁due": 27247, "▁era": 27248, "▁kat": 27249, "▁tarta": 27250, "▁tortu": 27251, "心": 27252, "Atom": 27253, "Ev": 27254, "SUM": 27255, "ZK": 27256, "ipari": 27257, "klage": 27258, "ranta": 27259, "sag": 27260, "sinin": 27261, "м": 27262, "▁Crven": 27263, "▁Juta": 27264, "▁Rako": 27265, "▁Taal": 27266, "▁blanc": 27267, "▁glass": 27268, "▁str": 27269, "agit": 27270, "expert": 27271, "genera": 27272, "puta": 27273, "reis": 27274, "▁ANG": 27275, "▁Farma": 27276, "▁Leif": 27277, "▁MEN": 27278, "▁Nuestra": 27279, "▁gha": 27280, "▁haha": 27281, "▁mountain": 27282, "▁solitari": 27283, "▁systems": 27284, "た": 27285, "者": 27286, "9001": 27287, "EEL": 27288, "baw": 27289, "hér": 27290, "tiere": 27291, "āna": 27292, "▁Nõ": 27293, "▁Piemonte": 27294, "▁court": 27295, "▁propo": 27296, "▁regal": 27297, "▁spec": 27298, "▁wheel": 27299, "宋": 27300, "aider": 27301, "espace": 27302, "kati": 27303, "lds": 27304, "magn": 27305, "tool": 27306, "в": 27307, "▁Islamic": 27308, "▁NHL": 27309, "▁Oor": 27310, "▁Powered": 27311, "▁Schedule": 27312, "▁anni": 27313, "▁decora": 27314, "▁facto": 27315, "▁spiral": 27316, "ロ": 27317, "OLL": 27318, "angal": 27319, "centa": 27320, "ecchia": 27321, "minibus": 27322, "profil": 27323, "short": 27324, "uß": 27325, "▁Brot": 27326, "▁Nieuw": 27327, "▁OMG": 27328, "▁Rett": 27329, "▁Sare": 27330, "▁alter": 27331, "▁compound": 27332, "▁kong": 27333, "▁mah": 27334, "▁moro": 27335, "▁opp": 27336, "bih": 27337, "cija": 27338, "financ": 27339, "ihin": 27340, "lanan": 27341, "nej": 27342, "olt": 27343, "rej": 27344, "toris": 27345, "valla": 27346, "voje": 27347, "üzü": 27348, "▁Goud": 27349, "▁Neem": 27350, "▁Swami": 27351, "▁kop": 27352, "▁ped": 27353, "▁rever": 27354, "▁sauna": 27355, "▁stipula": 27356, "朝": 27357, "Histori": 27358, "PPT": 27359, "haku": 27360, "kı": 27361, "tím": 27362, "▁Advertising": 27363, "▁Karne": 27364, "▁Kuka": 27365, "▁Kunst": 27366, "▁Summa": 27367, "▁atom": 27368, "▁figure": 27369, "▁joy": 27370, "▁regular": 27371, "じ": 27372, "通": 27373, "Contact": 27374, "digi": 27375, "disk": 27376, "dyr": 27377, "dzin": 27378, "jski": 27379, "mutat": 27380, "ously": 27381, "pasa": 27382, "utama": 27383, "ə": 27384, "▁Abstract": 27385, "▁Bekas": 27386, "▁Kalmar": 27387, "▁Mw": 27388, "▁Nuo": 27389, "▁modu": 27390, "▁total": 27391, "IKA": 27392, "eket": 27393, "ovou": 27394, "▁14.00": 27395, "▁Bulan": 27396, "▁Città": 27397, "▁Galerie": 27398, "▁arms": 27399, "▁bran": 27400, "▁chill": 27401, "▁coach": 27402, "▁father": 27403, "▁soon": 27404, "INK": 27405, "RUM": 27406, "dza": 27407, "inya": 27408, "konda": 27409, "mates": 27410, "ndung": 27411, "slov": 27412, "unni": 27413, "vah": 27414, "μ": 27415, "▁Cem": 27416, "▁Compl": 27417, "▁Srebr": 27418, "▁Zdrav": 27419, "▁bora": 27420, "▁glaci": 27421, "▁krat": 27422, "▁meet": 27423, "▁mulle": 27424, "▁ready": 27425, "▁thermo": 27426, "洞": 27427, "DEV": 27428, "Europe": 27429, "JU": 27430, "Nie": 27431, "kolo": 27432, "ktor": 27433, "lank": 27434, "marks": 27435, "rapan": 27436, "ravi": 27437, "unan": 27438, "▁Foi": 27439, "▁Gj": 27440, "▁Orbán": 27441, "▁Sdn": 27442, "▁Toll": 27443, "▁champ": 27444, "▁escu": 27445, "▁mae": 27446, "▁pipe": 27447, "▁silver": 27448, "▁sou": 27449, "信": 27450, "BAL": 27451, "ingan": 27452, "▁SMP": 27453, "▁blood": 27454, "▁custom": 27455, "▁ensi": 27456, "▁problem": 27457, "▁saga": 27458, "▁ungu": 27459, "▁Şen": 27460, "zle": 27461, "zwi": 27462, "ët": 27463, "ий": 27464, "▁(34)": 27465, "▁(45)": 27466, "▁Escort": 27467, "▁Hanif": 27468, "▁Inform": 27469, "▁MGA": 27470, "▁adam": 27471, "▁cale": 27472, "▁gue": 27473, "▁inside": 27474, "▁lacinia": 27475, "▁smoothie": 27476, "▁span": 27477, "▁vicina": 27478, "承": 27479, "黃": 27480, "EDO": 27481, "HANA": 27482, "LAG": 27483, "OON": 27484, "Ref": 27485, "hapur": 27486, "hotmail": 27487, "intele": 27488, "krieg": 27489, "messu": 27490, "process": 27491, "warm": 27492, "▁COMP": 27493, "▁Guardia": 27494, "▁Mapa": 27495, "▁Riba": 27496, "▁aqui": 27497, "▁ct": 27498, "▁jen": 27499, "▁yourself": 27500, "思": 27501, "Hôtel": 27502, "aber": 27503, "ecund": 27504, "snes": 27505, "▁Barcelo": 27506, "▁Bible": 27507, "▁Fue": 27508, "▁Mā": 27509, "▁Ulf": 27510, "▁Václav": 27511,
""" Copyright 2020 The OneFlow 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 oneflow as flow import oneflow._oneflow_internal from oneflow.python.nn.module import Module from oneflow.python.oneflow_export import oneflow_export, experimental_api from oneflow.python.framework.tensor import register_tensor_op from typing import Optional def _softmax_need_transpose(x, axis): assert type(axis) is int dim_num = len(x.shape) assert dim_num >= 2 if axis < 0: axis += dim_num assert axis >= 0 assert axis < dim_num need_transpose = False permute = list(range(dim_num)) if axis != dim_num - 1: need_transpose = True permute[axis] = permute[-1] permute[-1] = axis return need_transpose, permute @oneflow_export("nn.ReLU") @experimental_api class ReLU(Module): r"""Applies the rectified linear unit function element-wise: :math:`\text{ReLU}(x) = (x)^+ = \max(0, x)` Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np m = flow.nn.ReLU() arr = np.random.randn(2, 3, 4, 5) input = flow.Tensor(arr) output = m(input) # equal to np.maximum(0, arr) """ def __init__(self): super().__init__() self._op = flow.builtin_op("relu").Input("in").Output("out").Build() def forward(self, x): res = self._op(x)[0] return res @oneflow_export("nn.Tanh") @experimental_api class Tanh(Module): r"""This operator computes the hyperbolic tangent value of Tensor. The equation is: .. math:: out = \frac{e^x-e^{-x}}{e^x+e^{-x}} Args: x (oneflow.Tensor): A Tensor Returns: oneflow.Tensor: The result Tensor For example: .. code-block:: python import oneflow.experimental as flow import numpy as np x = np.array([-1, 0, 1]).astype(np.float32) input = flow.Tensor(x) tanh = flow.nn.Tanh() out = tanh(input).numpy() # out [-0.7615942 0. 0.7615942] """ def __init__(self): super().__init__() self._op = flow.builtin_op("tanh").Input("x").Output("y").Build() def forward(self, x): res = self._op(x)[0] return res @oneflow_export("tanh") @register_tensor_op("tanh") @experimental_api def tanh_op(x): r"""This operator computes the hyperbolic tangent value of Tensor. The equation is: .. math:: out = \frac{e^x-e^{-x}}{e^x+e^{-x}} Args: x (oneflow.Tensor): A Tensor Returns: oneflow.Tensor: The result Tensor For example: .. code-block:: python import oneflow as flow import numpy as np x = np.array([-1, 0, 1]).astype(np.float32) input = flow.Tensor(x) tanh = flow.nn.Tanh() out = tanh(input).numpy() # out [-0.7615942 0. 0.7615942] """ return Tanh()(x) @oneflow_export("nn.GELU") @experimental_api class GELU(Module): r"""Gelu activation operator. The equation is: .. math:: out = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) Args: x (oneflow.Tensor): Input Tensor Returns: oneflow.Tensor: A Tensor. For example: .. code-block:: python import oneflow.experimental as flow import numpy as np import oneflow.typing as tp x = np.array([-0.5, 0, 0.5]).astype(np.float32) input = flow.Tensor(x) gelu = flow.nn.GELU() out = gelu(input) # out [-0.15426877, 0., 0.34573123] """ def __init__(self): super().__init__() self._op = flow.builtin_op("gelu").Input("in").Output("out").Build() def forward(self, x): res = self._op(x)[0] return res @oneflow_export("gelu") @register_tensor_op("gelu") @experimental_api def gelu_op(x): r"""Gelu activation operator. The equation is: .. math:: out = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) Args: x (oneflow.Tensor): Input Tensor Returns: oneflow.Tensor: A Tensor. For example: .. code-block:: python import oneflow.experimental as flow import numpy as np import oneflow.typing as tp x = np.array([-0.5, 0, 0.5]).astype(np.float32) input = flow.Tensor(x) gelu = flow.nn.GELU() out = gelu(input) # out [-0.15426877, 0., 0.34573123] """ return GELU()(x) @oneflow_export("nn.Sigmoid") @experimental_api class Sigmoid(Module): r"""Applies the element-wise function: .. math:: \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)} Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np x = flow.Tensor( np.array( [ [0.81733328, 0.43621480, 0.10351428], [-1.15555191, -0.67776406, 0.27372134], ] ) ) m = flow.nn.Sigmoid() # or y = flow.sigmoid(x) y = m(x) # [[0.69366997, 0.60735673, 0.52585548], # [0.23947647, 0.33676055, 0.56800622]] """ def __init__(self): super().__init__() self._op = flow.builtin_op("sigmoid").Input("in").Output("out").Build() def forward(self, x): return self._op(x)[0] @oneflow_export("sigmoid") @register_tensor_op("sigmoid") @experimental_api def sigmoid_op(x): r"""Applies the element-wise function: .. math:: \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)} Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np x = flow.Tensor( np.array( [ [0.81733328, 0.43621480, 0.10351428], [-1.15555191, -0.67776406, 0.27372134], ] ) ) y = x.sigmoid() # [[0.69366997, 0.60735673, 0.52585548], # [0.23947647, 0.33676055, 0.56800622]] """ return Sigmoid()(x) @oneflow_export("nn.Softmax") @experimental_api class Softmax(Module): def __init__(self, dim: Optional[int] = None): super().__init__() self.axis = -1 if dim is None else dim self._op = flow.builtin_op("softmax").Input("in").Output("out").Build() self._transpose_op = ( flow.builtin_op("transpose") .Input("input") .Output("output") .Attr("perm", []) .Build() ) def forward(self, x): need_transpose, permute = _softmax_need_transpose(x, self.axis) if need_transpose: x = self._transpose_op(x, perm=permute)[0] res = self._op(x)[0] if need_transpose: res = self._transpose_op(res, perm=permute)[0] return res @oneflow_export("softmax") @register_tensor_op("softmax") @experimental_api def softmax_op(tensor, dim=None): r"""Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1. Softmax is defined as: .. math:: \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} When the input Tensor is a sparse tensor then the unspecifed values are treated as ``-inf``. Shape: - Input: :math:`(*)` where `*` means, any number of additional dimensions - Output: :math:`(*)`, same shape as the input Returns: a Tensor of the same dimension and shape as the input with values in the range [0, 1] Args: dim (int): A dimension along which Softmax will be computed (so every slice along dim will sum to 1). For example: .. code-block:: python import oneflow as flow import numpy as np m = flow.nn.Softmax(dim = 2) x = flow.Tensor( np.array( [[[[-0.46716809, 0.40112534, 0.61984003], [-1.31244969, -0.42528763, 1.47953856]]], [[[ 1.02978742, -0.49383053, 1.88214159], [ 1.35351622, -1.46251285, -1.40751374]]]] ) ) y = m(x) # [[[[0.6995764 0.6955959 0.29740235] # [0.3004236 0.30440408 0.7025977 ]]] # [[[0.4197673 0.7248568 0.96407217] # [0.58023274 0.27514324 0.03592779]]]] """ return Softmax(dim)(tensor) @oneflow_export("nn.LogSoftmax") @experimental_api class LogSoftmax(Module): r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional input Tensor. The LogSoftmax formulation can be simplified as: .. math:: \text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right) Args: dim (int): A dimension along which LogSoftmax will be computed. Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np m = flow.nn.LogSoftmax(dim=1) x = flow.Tensor( np.array( [[ 0.4296, -1.1957, 2.5463], [ 1.2552, -1.5747, 0.6923]] ) ) y = m(x) # [[-2.251349 -3.8766491 -0.13464898] # [-0.48770458 -3.3176045 -1.0506046 ]] """ def __init__( self, dim: Optional[int] = 1, ): super().__init__() self.dim = dim self._op = ( flow.builtin_op("transpose") .Input("input") .Output("output") .Attr("perm", []) .Build() ) def __setstate__(self, state): self.__dict__.update(state) if not hasattr(self, "dim"): self.dim = None def forward(self, x): need_transpose, permute = _softmax_need_transpose(x, self.dim) if need_transpose: x = self._op(x, perm=permute)[0] x = x.softmax() res = x.log() if need_transpose: res = self._op(res, perm=permute)[0] return res def extra_repr(self): return "dim={dim}".format(dim=self.dim) @oneflow_export("nn.Hardtanh") @experimental_api class Hardtanh(Module): r""" Applies the HardTanh function element-wise HardTanh is defined as: .. math:: \text{HardTanh}(x) = \begin{cases} 1 & \text{ if } x > 1 \\ -1 & \text{ if } x < -1 \\ x & \text{ otherwise } \\ \end{cases} The range of the linear region :math:`[-1, 1]` can be adjusted using :attr:`min_val` and :attr:`max_val`. Args: min_val: minimum value of the linear region range. Default: -1 max_val: maximum value of the linear region range. Default: 1 inplace: can optionally do the operation in-place. Default: ``False`` Keyword arguments :attr:`min_value` and :attr:`max_value` have been deprecated in favor of :attr:`min_val` and :attr:`max_val`. Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow m = flow.nn.Hardtanh() arr = np.random.randn(2, 3, 4, 5) x = flow.Tensor(arr) out = m(x) """ def __init__( self, min_val: float = -1, max_val: float = 1, inplace: bool = False, min_value: Optional[float] = None, max_value: Optional[float] =
deepCopySeq(self.checkRamp(ramp)) self.lengthRamp = len(ramp) if self.lengthRamp > self.height : self.height = self.lengthRamp #print "self.height 2", self.height self.numOfRampValues.set(self.lengthRamp) self.linesPerRampValue = self.height / float(self.lengthRamp) self.resizeCanvases(self.height) self.guiRamp = ramp if self.labels is not None: self.adjustGuiLabels(self.lengthRamp) self.drawRampCanvases(drawRamp=drawRamp) else: #print "guiRamp" self.lengthRamp = len(ramp) if self.lengthRamp > self.height : self.height = self.lengthRamp #print "self.height 3", self.height #self.numOfRampValues.set(self.lengthRamp) self.linesPerRampValue = self.height / float(self.lengthRamp) self.resizeCanvases(self.height) #self.guiRamp = guiRamp if self.labels is not None: self.adjustGuiLabels(self.lengthRamp) self.drawRampCanvases(drawRamp=drawRamp) # Update the OpenGL ramp self.ogl_cmw.ramp = deepCopySeq(self.guiRamp) self.ogl_cmw.tkRedraw() if self.continuousUpdate.get(): self.configureCmap(cfgCmap=cfgCmap) def configure(self, name=None, ramp=None, geoms=None, legend=None, labels=None, mini='not passed', maxi='not passed', viewer=None, updateGui=True, pushRamp=True, **kw): #print "ColorMapGUI.configure", mini, maxi ColorMap.configure(self, name=name, ramp=ramp, labels=labels, mini=mini, maxi=maxi) if ramp is not None: ramp = self.ramp if labels is not None: labels = self.labels # because it was just set in the configure self.configureGui(ramp=ramp, labels=labels, geoms=geoms, legend=legend, viewer=viewer, updateGui=updateGui, pushRamp=pushRamp, **kw) def configureGui(self, name=None, ramp=None, labels=None, geoms=None, legend=None, viewer=None, updateGui=True, pushRamp=True, #guiRamp=None, theGivenRampIsTheGuiRamp=False, **kw): """Configure the colormapGui with the given values. """ if (ramp is not None) and (theGivenRampIsTheGuiRamp is False): # The ramp is new put has not been pushed onto the history # stack yet self.currentOnStack = False # When pushRamp is True this new ramp is pushed on the stack if pushRamp: self.pushRamp() if labels is not None and self.labels is not None: #print "labels", labels #import traceback;traceback.print_stack() self.labelsComboBox.delete(0,'end') for label in labels: self.labelsComboBox.insert(0, str(label) ) if geoms is not None and len(geoms): self.geoms.update(geoms) if viewer is not None and viewer != self.viewer: self.SetViewer(viewer) if self.name != self.legend.name: self.nameVar.set(self.legend.name) self.rename_cb() # if a legend is specified then set self.legend if legend is not None: self.legend = legend # Then update the legend with the given values if self.legend is not None: cmlOptions = {'ramp':self.ramp} # Need to update the legendValues as well cmlOptions['mini'] = self.mini cmlOptions['maxi'] = self.maxi if hasattr(self, 'showLegendVar'): cmlOptions['visible'] = self.showLegendVar.get() apply(self.legend.Set, (), cmlOptions) if updateGui: self.update(ramp=ramp, mini=self.mini, maxi=self.maxi, cfgCmap=False, theGivenRampIsTheGuiRamp=theGivenRampIsTheGuiRamp, ) def Map(self, values, mini='not passed', maxi='not passed'): col = ColorMap.Map(self, values, mini=mini, maxi=maxi) if self.legend is not None: cmlOptions = {'ramp':self.ramp} # Need to update the legendValues with the value that where just used cmlOptions['mini'] = self.lastMini cmlOptions['maxi'] = self.lastMaxi if hasattr(self, 'showLegendVar'): cmlOptions['visible'] = self.showLegendVar.get() apply(self.legend.Set, (), cmlOptions) return col def configureCmap(self, cfgCmap=True): """ This method configures the associated cmap with the GUI new values. """ if self.cmapCompToReset is not None: self.resetComp(self.cmapCompToReset) self.cmapCompToReset = None cfgCmap = False self.cmapCurrent = True if self.cmapResetAll is True: self.reset() self.cmapResetAll = False cfgCmap = False self.cmapCurrent = True if self.nbStepBack != 0: if self.nbStepBack == len(self.history): cfgCmap = False self.cmapCurrent = True self.popRamp(-self.nbStepBack) self.nbStepBack = 0 if cfgCmap: # if self.allowRename: # name = self.nametk.get() # else: # name=None # donnot update the cmap if already current... if self.cmapCurrent: ramp=None else: ramp = deepCopySeq(self.guiRamp) self.configure(ramp=ramp, mini=self.guiMini, maxi=self.guiMaxi) if self.legend is not None: if self.legend.viewer: self.tk.call(self.legend.viewer.currentCamera._w, 'makecurrent') self.legend.RedoDisplayList() self.legend.viewer.Redraw() self.cmapCurrent = True if self.labels is not None: self.labels = deepCopySeq(self.guiLabels) #print "self.labels", self.labels # Then will call the callbacks with the new cmap values. self.callCallbacks() def drawRampCanvases(self, event=None, drawRamp=True): """draw all ramp canvases """ #print "drawRampCanvases" # update Ramp self.currentHue = range(self.lengthRamp) self.currentSat = range(self.lengthRamp) if drawRamp: for v in self.idList: self.deleteCanvasLines(v) self.setRightXVals(v) var = self.currentCanvasVar.get() self.currentValues = self.rightXVals[var] self.drawHue() self.drawSaturation() self.drawValue() self.drawOpacity() ################################################################# ### MOUSE CALLBACKS ################################################################# def mouseUp(self, event=None): self.cmapCurrent=False self.update(drawRamp=False) def mouseDown(self, event): j = self.canvasStart # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object Y = min(j+self.height-1, event.y) x = min(self.width, event.x) x = max(self.xoffset, x) if Y < j: Y = j y = int ( (Y-j) / self.linesPerRampValue) if y < 0: y = 0 self.startx = x self.startY = Y self.starty = y self.updateCurTk(event) c = self.currentCanvas lineIndex = self.lengthRamp-1-y line = self.currentLines[lineIndex] col, graybitmap = self.getColor(x, lineIndex) #y newline = c.create_rectangle( j, y*self.linesPerRampValue+j, 1+x,#+j, (1+y)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline #update self.guiRamp self.updateRGBMap(x, lineIndex) #update rightXVals self.currentValues[lineIndex] = x c.delete(line) def mouseMotion(self, event): j = self.canvasStart # canvas x and y take the screen coords from the event and translate # them into the coordinate system of the canvas object # x,y are float #x = self.canvasHue.canvasx(event.x) #y = self.canvasHue.canvasy(event.y) # event.x, event.y are same as x,y but int Y = min(j+self.height-1, event.y) x = min(self.width, event.x) x = max(self.xoffset, x) if Y < j: Y = j y = int ( (Y-j) / self.linesPerRampValue) if y < 0: y = 0 elif self.startx is None: self.mouseDown(event) c = self.currentCanvas if self.startY == Y: lineIndex = self.lengthRamp-1-y #print "lineIndex 0 ...", lineIndex line = self.currentLines[lineIndex] col, graybitmap = self.getColor(x, lineIndex) newline = c.create_rectangle( j, y*self.linesPerRampValue+j, 1+x,#+j, (1+y)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline c.delete(line) self.currentValues[lineIndex] = x self.updateRGBMap(x, lineIndex) else: # we need to interpolate for all y's between self.starty and y dx = x-self.startx dy = Y-self.startY rat = float(dx)/float(dy) if Y > self.startY: for Yl in range(self.startY, Y+1): yl = int ( (Yl-j) / self.linesPerRampValue) ddx = int(rat*(Yl-self.startY)) + self.startx lineIndex = self.lengthRamp-1-yl #print "lineIndex 1 ...", lineIndex line = self.currentLines[lineIndex] col, graybitmap = self.getColor(ddx, lineIndex) newline = c.create_rectangle( j, yl*self.linesPerRampValue+j, 1+ddx,#+j, (yl+1)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline c.delete(line) self.currentValues[lineIndex] = ddx self.updateRGBMap(ddx, lineIndex) else: for Yl in range(self.startY, Y-1, -1): yl = int ( (Yl-j) / self.linesPerRampValue) ddx = int(rat*(Yl-self.startY)) + self.startx lineIndex = self.lengthRamp-1-yl #print "lineIndex 2 ...", lineIndex line = self.currentLines[lineIndex] col, graybitmap = self.getColor(ddx, lineIndex) newline = c.create_rectangle( j, yl*self.linesPerRampValue+j, 1+ddx,#+j, (1+yl)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline c.delete(line) self.currentValues[lineIndex] = ddx self.updateRGBMap(ddx, lineIndex) self.startY = Y self.startx = x # this flushes the output, making sure that # the rectangle makes it to the screen # before the next event is handled self.update_idletasks() self.updateCurTk(event) def mouseDownRight(self, event): j = self.canvasStart Y = min(j+self.height-1, event.y) x = min(self.width, event.x) x = max(self.xoffset, x) if Y < j: Y = j y = int ( (Y-j) / self.linesPerRampValue) if y < 0: y = 0 self.startx = x self.startY = Y self.starty = y def mouseMotionRight(self, event): j = self.canvasStart Y = min(j+self.height-1, event.y) x = min(self.width, event.x) x = max(self.xoffset, x) if Y < j: Y = j y = int ( (Y-j) / self.linesPerRampValue) if y < 0: y = 0 elif self.startx is None: self.mouseDown(event) c = self.currentCanvas if self.straightLine is not None: c.delete(self.straightLine[0]) c.delete(self.straightLine[1]) dy = Y-self.startY if abs(dy) < (self.linesPerRampValue/2): return straightLineBlack = c.create_line( self.startx,#+j, (self.starty+.5)*self.linesPerRampValue+j, x,#+j, (y+.5)*self.linesPerRampValue+j, fill='black', width=3) straightLineWhite = c.create_line( self.startx,#+j, (self.starty+.5)*self.linesPerRampValue+j, x,#+j, (y+.5)*self.linesPerRampValue+j, fill='white', width=1) self.straightLine = [straightLineBlack, straightLineWhite] self.update_idletasks() self.updateCurTk(event) def mouseUpRight(self, event=None): j = self.canvasStart c = self.currentCanvas if self.straightLine is not None: c.delete(self.straightLine[0]) c.delete(self.straightLine[1]) Y = min(j+self.height-1, event.y) x = min(self.width, event.x) x = max(self.xoffset, x) if Y < j: Y = j y = int ( (Y-j) / self.linesPerRampValue) if y < 0: y = 0 elif self.startx is None: self.mouseDown(event) dx = x-self.startx dY = Y-self.startY dy = y-self.starty if abs(dY) < (self.linesPerRampValue/2): return rat = float(dx)/float(dy) if y > self.starty: for yl in range(self.starty, y+1): ddx = int(rat*(yl-self.starty)) + self.startx lineIndex = self.lengthRamp-1-yl line = self.currentLines[lineIndex] col, graybitmap = self.getColor(ddx, lineIndex) newline = c.create_rectangle( j, yl*self.linesPerRampValue+j, 1+ddx,#+j, (yl+1)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline c.delete(line) self.currentValues[lineIndex] = ddx self.updateRGBMap(ddx, lineIndex) else: for yl in range(self.starty, y-1, -1): ddx = int(rat*(yl-self.starty)) + self.startx lineIndex = self.lengthRamp-1-yl line = self.currentLines[lineIndex] col, graybitmap = self.getColor(ddx, lineIndex) newline = c.create_rectangle( j, yl*self.linesPerRampValue+j, 1+ddx,#+j, (yl+1)*self.linesPerRampValue+j, outline='', fill=col, stipple=graybitmap) self.currentLines[lineIndex] = newline c.delete(line) self.currentValues[lineIndex] = ddx self.updateRGBMap(ddx, lineIndex) self.starty = y self.startY = Y self.startx = x # this flushes the output, making
<gh_stars>10-100 from base64 import b64decode import glob import gzip import zlib import re import flask import dash_ngl import dash from dash.dependencies import Input, Output, State from dash.dash import no_update import dash_html_components as html import dash_core_components as dcc import dash_bootstrap_components as dbc f_app = flask.Flask(__name__) app = dash.Dash( __name__, server=f_app, external_stylesheets=[dbc.themes.BOOTSTRAP] ) app.css.config.serve_locally = True # Preset colors for the shown molecules color_list = [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999', ] representations = [ 'axes', 'axes+box', 'backbone', 'ball+stick', 'cartoon', 'helixorient', 'hyperball', 'licorice', 'line', 'ribbon', 'rope', 'spacefill', 'surface', 'trace', 'tube', 'unitcell', ] # PDB examples pdbs_list = [ 'MPRO', 'PLPR', 'NSP2', 'NSP4', 'NSP6', '1PNK', '1KMQ', '5L73', '4GWM', '3L9P', '6CHG', '3K8P', '2MRU', '1BNA', '6NZK', '6OHW', ] # Placeholder which is loaded if no molecule is selected data_dict = { 'uploaded': False, 'selectedValue': 'placeholder', 'resetView': False, 'chain': 'ALL', 'aaRange': 'ALL', 'chosen': {'atoms': '', 'residues': ''}, 'color': '#e41a1c', 'filename': 'placeholder', 'ext': '', 'config': {'type': '', 'input': ''}, } # user input triggered error messages: input_wrong = 'wrong input make sure it matches that format: \ pdbID1.chain:start-end_pdbID2.chain:start-end' mols2colors_missmatch = 'more molecules selected as chain colors defined \ add a extra color in the view tab and try again' # Canvas container to display the structures component_id = 'nglViewer' viewer = html.Div( id='ngl-biomolecule-viewer', children=[dash_ngl.DashNgl(id=component_id, data=[data_dict])], ) about_html = [ html.H4(className='what-is', children='What is Ngl Molecule Viewer?'), html.P( 'Ngl Molecule Viewer is a visualizer that allows you' ' to view biomolecules in multiple representations.' ), html.P( 'You can select a preloaded structure, or upload your own,' ' in the "Data" tab. Supported formats: .pdb(.gz) / .cif(.gz) ' ), html.P( 'Additionally you can show multiple structures and (or) specify a chain/' ' residues range / highlight Cα of chosen residues or single atoms.' ), html.P( 'In the "View" tab, you can change the style of the viewer.' ' Like the background color, the chain colors, the render quality etc.' ' On top you can change the molecular representation.' ), ] regexp = [ '^([A-Za-z0-9]{4})', '(.[a-zA-Z])?', '([:][0-9-]+)?', '[@]?([a0-9,]+)?' ] data_tab = [ html.Div(className='app-controls-name', children='Select structure'), dcc.Dropdown( id='pdb-dropdown', clearable=False, options=[{'label': k, 'value': k} for k in pdbs_list], placeholder='Select a molecule', ), html.Br(), html.Div( children=[ html.P( 'Show multiple structures and (or) \ specify a chain/ residues range/ \ highlight chosen residues/ atoms', style={'fontSize': '10pt'}, ) ] ), dbc.Input( id='pdb-string', className='mb-3', placeholder='pdbID1.chain:start-end_pdbID2.chain:start-end', value='6CHG.A:1-450@a50,a100,a150_3K8P.D', type='text', pattern="^[A-Za-z0-9]{4}([A-Za-z0-9-@,_.:]+)?", debounce=True ), html.Br(), html.Button('submit', id='btn-pdbString'), html.Button('reset view', id='btn-resetView'), html.Br(), html.Div( title='Upload biomolecule to view here', className='app-controls-block', id='ngl-upload-container', children=[ dcc.Upload( id='ngl-upload-data', className='control-upload', children=html.Div( ['Drag and drop or click to upload (multiple) pdb/cif file(s).'] ), # Allow multiple files to be uploaded multiple=True, ), # html.Div(id='uploaded-files', children=html.Div([''])), html.Div(id='warning_div', children=html.Div([''])), ], ), html.Div(id='ngl-data-info'), ] view_tab = [ html.Div( title='select molecule style', className='app-controls-block', id='ngl-mols-style', children=[ html.P('Style', style={'fontWeight': 'bold', 'marginBottom': '10px'}), dcc.Dropdown( id='molecules-representation-style', options=[{'label': e, 'value': e.lower()} for e in representations], placeholder='select molecule style', value=['cartoon', 'axes+box'], multi=True, ), ], ), html.Div( title='show molecules side by side', className='app-controls-block', id='ngl-mols-sideByside', children=[ html.P('if multiple molecules show them side by side?', style={'fontWeight': 'bold', 'marginBottom': '10px'}), dcc.RadioItems( id='sideByside-selector', options=[ {'label': 'Yes (mols cannot be moved/rotated independently)', 'value':'True'}, {'label': 'No (move/rotate mols independently by ctrl)', 'value':'False'}, ], value='False' ), ], ), html.Div( title='set molecules x-axis spacing', className='app-controls-block', id='ngl-mols-spacing', children=[ html.P( 'x-axis spacing (if side by side yes)', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Input( id='molecules-xaxis-spacing', placeholder='set x-axis spacing', value=100, ), ], ), html.P('To apply the settings go back to data and submit again'), # modifying the chain colors only works when individual chains are displayed html.Div( title='set chain color', className='app-controls-block', id='ngl-mols-color', children=[ html.P( 'Chain colors', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Input(id='molecules-chain-color', value=','.join(color_list)), ], ), html.Div( title='set chosen atoms color', className='app-controls-block', id='ngl-atom-color', children=[ html.P( 'Chosen atoms Color', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Input(id='chosen-atoms-color', value='#808080'), ], ), html.Div( title='set chosen atoms radius', className='app-controls-block', id='ngl-atom-radius', children=[ html.P( 'Chosen atoms radius', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Input(id='chosen-atoms-radius', value='1.1'), ], ), html.Div( title='select background color', className='app-controls-block', id='ngl-style-color', children=[ html.P( 'Background color', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Dropdown( id='stage-bg-color', options=[{'label': e, 'value': e.lower()} for e in ['black', 'white']], value='white', ), ], ), html.Div( title='Camera settings', className='app-controls-block', id='ngl-selection-display', children=[ html.P( 'Camera settings', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Dropdown( id='stage-camera-type', options=[ {'label': e.capitalize(), 'value': e} for e in ['perspective', 'orthographic'] ], value='perspective', ), ], ), html.Div( title='select render quality', className='app-controls-block', id='ngl-style', children=[ html.P( 'Render quality', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Dropdown( id='stage-render-quality', options=[ {'label': e, 'value': e.lower()} for e in ['auto', 'low', 'medium', 'high'] ], value='auto', ), ], ), ] download_tab = [ html.Button('Download Image', id='btn-downloadImage'), html.Div( title='antialias', className='app-controls-block', id='ngl-image-antialias', children=[ html.P('antialias', style={'fontWeight': 'bold', 'marginBottom': '10px'},), dcc.Dropdown( id='image-antialias', options=[{'label': c, 'value': c} for c in ['Yes', 'No']], value='Yes', ), ], ), html.Div( title='trim', className='app-controls-block', id='ngl-image-trim', children=[ html.P('trim', style={'fontWeight': 'bold', 'marginBottom': '10px'}), dcc.Dropdown( id='image-trim', options=[{'label': c, 'value': c} for c in ['Yes', 'No']], value='Yes', ), ], ), html.Div( title='transparent', className='app-controls-block', id='ngl-image-transparent', children=[ html.P( 'transparent', style={'fontWeight': 'bold', 'marginBottom': '10px'}, ), dcc.Dropdown( id='image-transparent', options=[{'label': c, 'value': c} for c in ['Yes', 'No']], value='Yes', ), ], ), ] htmls = [('About', 'what-is', about_html), ('Data', 'upload-select', data_tab), ('View', 'view-options', view_tab), ('Download', 'download-options', download_tab)] tabs = html.Div( id='ngl-control-tabs', className='control-tabs', children=[ dcc.Tabs( id='ngl-tabs', value='what-is', children=[ dcc.Tab( label=l, value=v, children=html.Div(className='control-tab', children=h), ) for l, v, h in htmls ], ), ], ) # LAYOUT app.layout = html.Div( id='main-page', children=[ # looses the data when the browser/tab closes. dcc.Store(id='uploaded-files', storage_type='session'), html.Div( id='app-page-header', children=[html.H1('Ngl Molecule Viewer')], style={'background': '#e7625f', 'color': 'white'}, ), html.Div( id='app-page-content', children=[ html.Div( id='ngl-body', className='app-body', children=[ tabs, viewer # using dcc.Loading leads to remounting with every selection change # dcc.Loading(viewer), ], ), ], ), ], ) def createDict( selection, chain, aa_range, highlight_dic, color, filename, ext, contents, resetView=False, uploaded=False, ): print('create dic') print(highlight_dic) return { 'filename': filename, 'ext': ext, 'selectedValue': selection, 'chain': chain, 'aaRange': aa_range, 'chosen': highlight_dic, 'color': color, 'config': {'type': 'text/plain', 'input': contents}, 'resetView': resetView, 'uploaded': uploaded, } def getHighlights(string, sep, atom_indicator): print('getHighlights') residues_list = [] atoms_list = [] str_, _str = string.split(sep) for e in _str.split(','): if atom_indicator in e: atoms_list.append(e.replace(atom_indicator, '')) else: residues_list.append(e) print(atoms_list) print(residues_list) return (str_, {'atoms': ','.join(atoms_list), 'residues': ','.join(residues_list)}) # Helper function to load structures from local storage def getLocalData(selection, pdb_id, color, uploadedFiles, resetView=False): print('getLocalData') print (color) chain = 'ALL' aa_range = 'ALL' highlight_dic = {'atoms': '', 'residues': ''} highlights_sep = '@' atom_indicator = 'a' ### replace all this if statements with a regex # and then get value for each group # pdb = regex group (1) # chain = regex group (2) # aa_range = regex_group(3) # Check if only one chain should be shown if '.' in pdb_id: pdb_id, chain = pdb_id.split('.') # Check if only a specified amino acids range should be shown: if ':' in chain: chain, aa_range = chain.split(':') # Check if atoms should be highlighted if highlights_sep in aa_range: aa_range, highlight_dic = getHighlights( aa_range, highlights_sep, atom_indicator ) else: if highlights_sep in chain: chain, highlight_dic = getHighlights( chain, highlights_sep, atom_indicator ) # print ('highlight_dic') # print (highlight_dic) if pdb_id not in pdbs_list: if pdb_id in uploadedFiles: print('Already uploaded') # print(files[:-1].split(',')) fname = [i for i in uploadedFiles[:-1].split(',') if pdb_id in i][0] print(fname) content = '' return createDict( selection, chain, aa_range, highlight_dic, color, fname, fname.split('.')[1], content, resetView, uploaded=False, ) return data_dict # get path to protein structure fname = [f for f in glob.glob('data/' + pdb_id + '.*')][0] if 'gz' in fname: ext = fname.split('.')[-2] with gzip.open(fname, 'r') as f: content = f.read().decode('UTF-8') else: ext = fname.split('.')[-1] with open(fname, 'r') as f: content = f.read() filename = fname.split('/')[-1] return createDict( selection, chain, aa_range, highlight_dic, color, filename, ext, content, resetView, uploaded=False, ) # Helper function to load structures from uploaded content def getUploadedData(uploaded_content): data = [] uploads = [] ext = 'pdb' chain = 'ALL' aa_range = 'ALL' highlight_dic = {'atoms': '', 'residues': ''} for i, content in enumerate(uploaded_content): content_type, content = str(content).split(',') if 'gzip' in content_type: content = zlib.decompress(b64decode(content), zlib.MAX_WBITS | 16) else: content = b64decode(content) content = content.decode('UTF-8') pdb_id = content.split('\n')[0].split()[-1] if 'data_' in pdb_id: pdb_id = pdb_id.split('_')[1] ext = 'cif' print(pdb_id) filename = pdb_id + '.' + ext uploads.append(filename) data.append( createDict( pdb_id, chain, aa_range, highlight_dic, color_list[i], filename, ext, content, resetView=False, uploaded=True, ) ) return data, uploads # CB viewport @app.callback( [ Output(component_id, 'data'), Output(component_id, 'molStyles'), Output('pdb-dropdown', 'options'), Output('uploaded-files', 'data'), Output('pdb-dropdown', 'placeholder'),
from inspect import cleandoc import pathlib from mlinspect import PipelineInspector from mlinspect.utils import get_project_root import os from mlinspect.utils import store_timestamp import time # ########################################### FOR THE SIMPLE OP BENCHMARK ############################################## class Join: """ Code for simple join. """ @staticmethod def get_name(): return "Join" @staticmethod def get_pandas_code(path_1, path_2, join_attr, na_val="?"): pandas_code = cleandoc(f""" df1 = pandas.read_csv(r\"{path_1}\", na_values=[\"{na_val}\"]) df2 = pandas.read_csv(r\"{path_2}\", na_values=[\"{na_val}\"]) result = df1.merge(df2, on=['{join_attr}']) """) return pandas_code @staticmethod def get_sql_code(ds_1, ds_2, join_attr): sql_code = cleandoc(f""" SELECT * FROM {ds_1} INNER JOIN {ds_2} ON {ds_1}.{join_attr} = {ds_2}.{join_attr} """) return sql_code class Projection: """ Won't be used!! """ @staticmethod def get_name(): return "Projection" @staticmethod def get_pandas_code(path, attr, na_val="?"): pandas_code = cleandoc(f""" df = pandas.read_csv(r\"{path}\", na_values=[\"{na_val}\"]) result = df[[\"{attr}\"]] """) return pandas_code @staticmethod def get_sql_code(ds, attr): sql_code = cleandoc(f""" SELECT count({attr}) FROM {ds} """) return sql_code class Selection: """ Code for selection benchmark, with aggregation. """ @staticmethod def get_name(): return "Selection" @staticmethod def get_pandas_code(path, attr, cond="", value="", na_val="?"): pandas_code = cleandoc(f""" df = pandas.read_csv(r\"{path}\", na_values=[\"{na_val}\"]) result = df.loc[lambda df: (df['{attr}'] {cond} {value}), :] """) return pandas_code @staticmethod def get_sql_code(ds, attr, cond="", value=""): sql_code = cleandoc(f""" SELECT * FROM {ds} WHERE {attr} {cond} {value} """) return sql_code class GroupBy: """ Code for group by benchmark. """ @staticmethod def get_name(): return "GroupBy" @staticmethod def get_pandas_code(path, attr1, attr2, op, na_val="?"): pandas_code = cleandoc(f""" df = pandas.read_csv(r\"{path}\", na_values=[\"{na_val}\"]) complications = df.groupby('{attr1}').agg(mean_complications=('{attr2}', '{op}')) """) return pandas_code @staticmethod def get_sql_code(ds, attr1, attr2, op): # Here we don't need a count, as smoker is boolean and we will only need to print 3 values: null, True, False sql_code = cleandoc(f""" SELECT {attr1}, {op}({attr2}) FROM {ds} GROUP BY {attr1} """) return sql_code # ###################################################################################################################### # ########################################### FOR THE PURE PIPELINE BENCHMARK ########################################## def get_healthcare_pipe_code(path_patients=None, path_histories=None, only_pandas=False, include_training=True): if path_patients is None or path_histories is None: path_patients = os.path.join(str(get_project_root()), "example_pipelines", "healthcare", "patients.csv") path_histories = os.path.join(str(get_project_root()), "example_pipelines", "healthcare", "histories.csv") setup_code = cleandoc(""" import warnings import os import pandas as pd from mlinspect.utils import get_project_root """) test_code = cleandoc(f""" COUNTIES_OF_INTEREST = ['county2', 'county3'] patients = pd.read_csv('{path_patients}', na_values='') histories = pd.read_csv('{path_histories}', na_values='') data = patients.merge(histories, on=['ssn']) complications = data.groupby('age_group') \ .agg(mean_complications=('complications', 'mean')) data = data.merge(complications, on=['age_group']) data['label'] = data['complications'] > 1.2 * data['mean_complications'] data = data[['smoker', 'last_name', 'county', 'num_children', 'race', 'income', 'label']] data = data[data['county'].isin(COUNTIES_OF_INTEREST)] """) if not only_pandas: setup_code += "\n" + cleandoc(""" from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, StandardScaler from example_pipelines.healthcare.healthcare_utils import MyW2VTransformer, MyKerasClassifier, create_model """) training_part = cleandoc(""" neural_net = MyKerasClassifier(build_fn=create_model, epochs=10, batch_size=1, verbose=0) pipeline = Pipeline([ ('features', featurisation), ('learner', neural_net) ]) train_data, test_data = train_test_split(data) model = pipeline.fit(train_data, train_data['label']) print("Mean accuracy: " + str(model.score(test_data, test_data['label'])) ) """) test_code += "\n" + cleandoc(""" impute_and_one_hot_encode = Pipeline([ ('impute', SimpleImputer(strategy='most_frequent')), ('encode', OneHotEncoder(sparse=False, handle_unknown='ignore')) ]) featurisation = ColumnTransformer(transformers=[ ("impute_and_one_hot_encode", impute_and_one_hot_encode, ['smoker', 'county', 'race']), # ('word2vec', MyW2VTransformer(min_count=2), ['last_name']), ('numeric', StandardScaler(), ['num_children', 'income']), ], remainder='drop') """) + "\n" + training_part if not include_training: test_code = test_code.replace(training_part, "result = featurisation.fit_transform(data)") return setup_code + "\n", test_code def get_compas_pipe_code(compas_train=None, compas_test=None, only_pandas=False, include_training=True): if compas_train is None or compas_test is None: compas_train = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "compas", "compas_train.csv") compas_test = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "compas", "compas_test.csv") setup_code = cleandoc(""" import os import pandas as pd from mlinspect.utils import get_project_root """) test_code = cleandoc(f""" train_data = pd.read_csv(r\"{compas_train}\", na_values='', index_col=0) test_data = pd.read_csv(r\"{compas_test}\", na_values='', index_col=0) train_data = train_data[ ['sex', 'dob', 'age', 'c_charge_degree', 'race', 'score_text', 'priors_count', 'days_b_screening_arrest', 'decile_score', 'is_recid', 'two_year_recid', 'c_jail_in', 'c_jail_out']] test_data = test_data[ ['sex', 'dob', 'age', 'c_charge_degree', 'race', 'score_text', 'priors_count', 'days_b_screening_arrest', 'decile_score', 'is_recid', 'two_year_recid', 'c_jail_in', 'c_jail_out']] train_data = train_data[(train_data['days_b_screening_arrest'] <= 30) & (train_data['days_b_screening_arrest'] >= -30)] train_data = train_data[train_data['is_recid'] != -1] train_data = train_data[train_data['c_charge_degree'] != "O"] train_data = train_data[train_data['score_text'] != 'N/A'] train_data = train_data.replace('Medium', "Low") test_data = test_data.replace('Medium', "Low") """) if not only_pandas: setup_code += "\n" + cleandoc(""" from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, KBinsDiscretizer, label_binarize """) training_part = cleandoc(""" pipeline = Pipeline([ ('features', featurizer), ('classifier', LogisticRegression()) ]) pipeline.fit(train_data, train_labels.ravel()) print(pipeline.score(test_data, test_labels.ravel())) """) test_code += "\n" + cleandoc(""" train_labels = label_binarize(train_data['score_text'], classes=['High', 'Low']) test_labels = label_binarize(test_data['score_text'], classes=['High', 'Low']) impute1_and_onehot = Pipeline([('imputer1', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) impute2_and_bin = Pipeline([('imputer2', SimpleImputer(strategy='mean')), ('discretizer', KBinsDiscretizer(n_bins=4, encode='ordinal', strategy='uniform'))]) featurizer = ColumnTransformer(transformers=[ ('impute1_and_onehot', impute1_and_onehot, ['is_recid']), ('impute2_and_bin', impute2_and_bin, ['age']) ]) """) + "\n" + training_part if not include_training: test_code = test_code.replace(training_part, "result = featurizer.fit_transform(train_data)") return setup_code + "\n", test_code def get_compas_pipe_code_with_timestamps(compas_train=None, compas_test=None, only_pandas=False, include_training=True, engine_name=""): engine_name = f"\"{engine_name}\"" if compas_train is None or compas_test is None: compas_train = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "compas", "compas_train.csv") compas_test = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "compas", "compas_test.csv") setup_code = cleandoc(""" import os import pandas as pd from mlinspect.utils import get_project_root, store_timestamp import time """) test_code = cleandoc(f""" t0 = time.time() train_data = pd.read_csv(r\"{compas_train}\", na_values='', index_col=0) store_timestamp("LOAD CSV 1", time.time() - t0, {engine_name}) t0 = time.time() test_data = pd.read_csv(r\"{compas_test}\", na_values='', index_col=0) store_timestamp("LOAD CSV 2", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data[ ['sex', 'dob', 'age', 'c_charge_degree', 'race', 'score_text', 'priors_count', 'days_b_screening_arrest', 'decile_score', 'is_recid', 'two_year_recid', 'c_jail_in', 'c_jail_out']] store_timestamp("PROJECT TRAIN", time.time() - t0, {engine_name}) t0 = time.time() test_data = test_data[ ['sex', 'dob', 'age', 'c_charge_degree', 'race', 'score_text', 'priors_count', 'days_b_screening_arrest', 'decile_score', 'is_recid', 'two_year_recid', 'c_jail_in', 'c_jail_out']] store_timestamp("PROJECT TEST", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data[(train_data['days_b_screening_arrest'] <= 30) & (train_data['days_b_screening_arrest'] >= -30)] store_timestamp("SELECT TRAIN 1", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data[train_data['is_recid'] != -1] store_timestamp("SELECT TRAIN 2", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data[train_data['c_charge_degree'] != "O"] store_timestamp("SELECT TRAIN 3", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data[train_data['score_text'] != 'N/A'] store_timestamp("SELECT TRAIN 4", time.time() - t0, {engine_name}) t0 = time.time() train_data = train_data.replace('Medium', "Low") store_timestamp("REPLACE TRAIN", time.time() - t0, {engine_name}) t0 = time.time() test_data = test_data.replace('Medium', "Low") store_timestamp("REPLACE TEST", time.time() - t0, {engine_name}) """) if not only_pandas: setup_code += "\n" + cleandoc(""" from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, KBinsDiscretizer, label_binarize """) training_part = cleandoc(f""" t0 = time.time() pipeline = Pipeline([ ('features', featurizer), ('classifier', LogisticRegression()) ]) pipeline.fit(train_data, train_labels.ravel()) store_timestamp("PIPELINE+MODEL FIT", time.time() - t0, {engine_name}) t0 = time.time() print(pipeline.score(test_data, test_labels.ravel())) store_timestamp("PIPELINE+MODEL SCORE", time.time() - t0, {engine_name}) """) test_code += "\n" + cleandoc(f""" t0 = time.time() train_labels = label_binarize(train_data['score_text'], classes=['High', 'Low']) store_timestamp("BINARIZE TRAIN", time.time() - t0, {engine_name}) t0 = time.time() test_labels = label_binarize(test_data['score_text'], classes=['High', 'Low']) store_timestamp("BINARIZE TEST", time.time() - t0, {engine_name}) impute1_and_onehot = Pipeline([('imputer1', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) impute2_and_bin = Pipeline([('imputer2', SimpleImputer(strategy='mean')), ('discretizer', KBinsDiscretizer(n_bins=4, encode='ordinal', strategy='uniform'))]) featurizer = ColumnTransformer(transformers=[ ('impute1_and_onehot', impute1_and_onehot, ['is_recid']), ('impute2_and_bin', impute2_and_bin, ['age']) ]) """) + "\n" + training_part if not include_training: test_code = test_code.replace(training_part, "result = featurizer.fit_transform(train_data)") return setup_code + "\n", test_code def get_adult_simple_pipe_code(train=None, only_pandas=False, include_training=True): if train is None: train = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "adult_complex", "adult_train.csv") setup_code = cleandoc(""" import os import pandas as pd """) test_code = cleandoc(f""" train_file = r\"{train}\" raw_data = pd.read_csv(train_file, na_values='', index_col=0) data = raw_data.dropna() """) if not only_pandas: setup_code += "\n" + cleandoc(""" from sklearn import compose, tree, pipeline from sklearn import preprocessing """) training_part = cleandoc(""" income_pipeline = pipeline.Pipeline([ ('features', feature_transformation), ('classifier', tree.DecisionTreeClassifier()) ]) income_pipeline.fit(data, labels) """) test_code += "\n" + cleandoc(""" labels = preprocessing.label_binarize(data['income-per-year'], classes=['>50K', '<=50K']) feature_transformation = compose.ColumnTransformer(transformers=[ ('categorical', preprocessing.OneHotEncoder(handle_unknown='ignore'), ['education', 'workclass']), ('numeric', preprocessing.StandardScaler(), ['age', 'hours-per-week']) ]) """) + "\n" + training_part if not include_training: test_code = test_code.replace(training_part, "result = feature_transformation.fit_transform(data)") return setup_code + "\n", test_code def get_adult_complex_pipe_code(train=None, test=None, only_pandas=False, include_training=True): if train is None or test is None: train = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "adult_complex", "adult_train.csv") test = os.path.join(str(get_project_root()), "test", "monkeypatchingSQL", "pipelines_for_tests", "adult_complex", "adult_test.csv") setup_code = cleandoc(""" import os import pandas as pd from sklearn import preprocessing """) test_code = cleandoc(f""" train_file = r\"{train}\" train_data = pd.read_csv(train_file, na_values='', index_col=0) test_file = r\"{test}\" test_data = pd.read_csv(test_file, na_values='', index_col=0) train_labels = preprocessing.label_binarize(train_data['income-per-year'], classes=['>50K', '<=50K']) test_labels = preprocessing.label_binarize(test_data['income-per-year'], classes=['>50K', '<=50K']) """) if not only_pandas: setup_code +=
# -*- coding: utf-8 -*- """ Created on Tue Mar 29 12:31:30 2022 @author: LENOVO """ import biosteam as bst import thermosteam as tmo import numpy as np from chaospy import distributions as shape import biosteam as bst import numpy as np # All units are explicitly defined here for transparency and easy reference # Naming conventions: # D = Distillation column # M = Mixer # E = Multi effect evaporator # C = Crystalliser # H = Heat exchange # L = Liquid-liquid extraction unit (Multi stage Mixer settlers) # P = Pump (including conveying belt) # R = Reactor # S = Splitter (including solid/liquid separator) # T = Tank or bin for storage # U = Other units # PS = Process specificiation, not physical units, but for adjusting streams # MT = Mixing Tank # Processes: # 100: Conversion # 200: PrimarySeparation # 300: SecondarySeparation # 400: Wastewater # 500: Facilities #Defining chemicals #ref:lactic acid code #Chemicals used Water = tmo.Chemical('Water') #New chemical #FFA = C18H34O2 #C18H34O2 + CH3OH → C19H36O2 + H2O #FAME (C19H36O2) #WCO #C27H54O2 + 3CH3OH → C3H8O3 ​+ ​FAME #Triglyceride considered is triolein #all_chemicals.set_synonym('Tripalmitin' ,'Oil1') # Oil2 = tmo.Chemical() Oil2 = tmo.Chemical('TAG', search_ID='122-32-7', phase = 'l') Oil2.copy_models_from(tmo.Chemical('Water'), ['mu']) Oil2.Hf = -1607.83*1000 Glycerol = tmo.Chemical('Glycerol', search_ID='56-81-5') Glycerol_missing_properties = Glycerol.get_missing_properties() Furfural = tmo.Chemical('Furfural') Furfural_missing_properties = Furfural.get_missing_properties() for i in Glycerol_missing_properties: try: Glycerol.copy_models_from(Furfural,[i]) except: pass CaO = tmo.Chemical('Calcium_oxide', phase = 's') Calcium_Sulphate = tmo.Chemical('Calcium_Sulphate', phase = 's') all_chemicals = tmo.Chemicals(['Water', 'Sulphuric_acid', 'Sodium_Hydroxide', 'Oleic_acid', #'Tripalmitin', 'Methyl_oleate', 'Methanol', Oil2, CaO, Calcium_Sulphate, #'Methyl_palmitate', '112-62-9', Glycerol, ]) all_chemicals.compile() all_chemicals.show() all_chemicals.set_synonym('Oleic_acid' ,'FFA') all_chemicals.set_synonym('56-81-5' ,'Glycerol') all_chemicals.set_synonym('122-32-7' ,'Oil2') #all_chemicals.set_synonym('Methyl_palmitate' ,'fame1') all_chemicals.set_synonym('112-62-9' ,'fame2') ##############################Settings#########################################3 bst.settings.set_thermo(all_chemicals) bst.Stream.display_units.flow = 'kg/hr' bst.Stream.display_units.composition = True GWP = 'GWP 100yr' bst.settings.define_impact_indicator(key=GWP, units='kg*CO2e') Calcium_oxide = bst.Chemical('Calcium_oxide') Calcium_oxide.at_state('s') ### TODO.xxx Calcium_oxide.V.add_model(1e-6) #############################UNITS############################################# class PReactor(bst.BatchBioreactor): _N_ins = 1 _N_outs = 1 @property def effluent(self): return self.outs[0] @effluent.setter def effluent(self,effluent): self.outs[0]=effluent def __init__(self, ID='', ins=None, outs=(), thermo=None, tau=None, N=None, V=None, T= 65 + 275, P=101325, Nmin=2, Nmax=36): bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo, tau = tau , N = N, V = V, T = T, P = P ,Nmin = Nmin , Nmax = Nmax) self.PR_conversion = 0.999 def _setup(self): self.reactions = tmo.SeriesReaction([ tmo.Rxn('Oleic_acid + Methanol -> Methyl_oleate + Water ', 'Oleic_acid', X = self.PR_conversion ) ]) # def _cost(self): # density_in_kg_per_m3 = 913 # batch_vol = self.design_results['Reactor volume'] * self.V_wf # R = (batch_vol/(0.002))**0.33 #here 2 is 2L # N2 = 600*((1/R)**(2/3)) # D2 = 0.4*((batch_vol*4/3.14)**0.33) # Np = 1.27 # power = Np * density_in_kg_per_m3*(N2**3)*(D2**5) # self.power_utility(power) def _run(self): feed = self.ins[0] effluent = self.outs[0] effluent.copy_like(feed) self.reactions(effluent) effluent.T = self.T effluent.P = self.P # Calcium oxide addition for Glycerol recovery class Glycerol_recovery(bst.BatchBioreactor): _N_ins = 1 _N_outs = 1 @property def effluent(self): return self.outs[0] @effluent.setter def effluent(self,effluent): self.outs[0]=effluent def __init__(self, ID='', ins=None, outs=(), thermo=None, tau=None, N=None, V=None, T= 60 + 275, P=101325, Nmin=2, Nmax=36): bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo, tau = tau , N = N, V = V, T = T, P = P ,Nmin = Nmin , Nmax = Nmax) def _setup(self): self.reactions = tmo.SeriesReaction([ tmo.Rxn('Calcium_oxide + Sulphuric_acid -> Calcium_Sulphate + Water', 'Sulphuric_acid', X = 0.999)]) # def _cost(self): # density_in_kg_per_m3 = 873.9 # batch_vol = self.design_results['Reactor volume'] * self.V_wf # R = (batch_vol/(0.002))**0.33 #here 2 is 2L # N2 = 600*((1/R)**(2/3)) # D2 = 0.4*((batch_vol*4/3.14)**0.33) # Np = 1.27 # power = Np * density_in_kg_per_m3*(N2**3)*(D2**5) # self.power_utility(power) def _run(self): feed = self.ins[0] effluent = self.outs[0] effluent.copy_like(feed) self.reactions(effluent) effluent.T = self.T effluent.P = self.P # Transesterification reactor class TReactor(bst.BatchBioreactor): _N_ins = 1 _N_outs = 1 @property def effluent(self): return self.outs[0] @effluent.setter def effluent(self,effluent): self.outs[0]=effluent def __init__(self, ID='', ins=None, outs=(), thermo=None, tau=None, N=None, V=None, T= 60 + 275, P=101325, Nmin=2, Nmax=36): bst.BatchBioreactor.__init__(self, ID, ins, outs, thermo, tau = tau , N = N, V = V, T = T, P = P ,Nmin = Nmin , Nmax = Nmax) self.TR_conversion = 0.999 def _setup(self): self.reactions = tmo.ParallelReaction([ # tmo.Rxn('Tripalmitin + 3Methanol -> Methyl_palmitate + Glycerol', # 'Tripalmitin', # X = 0.9), tmo.Rxn('Oil2 + 3Methanol -> Methyl_oleate + Glycerol', 'Oil2', X = self.TR_conversion) ]) # def _cost(self): # density_in_kg_per_m3 = 913 # batch_vol = self.design_results['Reactor volume'] * self.V_wf # R = (batch_vol/(0.002))**0.33 #here 2 is 2L # N2 = 600*((1/R)**(2/3)) # D2 = 0.4*((batch_vol*4/3.14)**0.33) # Np = 1.27 # power = Np * density_in_kg_per_m3*(N2**3)*(D2**5) # self.power_utility(power) def _run(self): feed = self.ins[0] effluent = self.outs[0] effluent.copy_like(feed) self.reactions(effluent) effluent.T = self.T effluent.P = self.P ############################ STREAMS ########################################## WCO_range = [4947,5038,5128, 5219,5310,5400, 5491,5581,5672, 5763,5853,5944, 6035,6125,6216, 6307,6397,6488, 6579,6669] GWP_obtained = [68.03354950443708, -18.60145643725397,] Total_Collected_WCO = 6669 #Three values 4800,5525,6475 FFA = tmo.Chemical('Oleic_acid') # Oil1 = tmo.Chemical('Tripalmitin') Oil2 = all_chemicals['Oil2'] # FFA content is 6% of the total Oil Collected_WCO = bst.Stream('Collected_WCO', #Oil1 = 940/2 , Oil2 = 940, FFA = 60, units = 'kg/hr') # http://dx.doi.org/10.17576/jkukm-2018-si1(2)-10 Collected_WCO.set_total_flow(Total_Collected_WCO, units='kg/hr') Fresh_water = bst.Stream('Fresh_water') Washed_WCO = bst.Stream('Washed_WCO') #TODO.xxx change this depending on the scale up ratios Fresh_Methanol_1 = bst.Stream('Methanol1') Fresh_Methanol_2 = bst.Stream('Methanol2') Fresh_Sulacid = bst.Stream('Sulphuric_acid') Fresh_Glycerol = bst.Stream('Glycerol') Recycled_Methanol = bst.Stream('Recycled_Methanol') Fresh_CaO = bst.Stream('Fresh_CaO') # Calcium_Sulphate = bst.Chemical('Calcium_Sulphate') Calcium_Sulphate.at_state('s') Calcium_Sulphate.V.add_model(1e-6) Reuse_Calcium_Sulphate = bst.Stream('Reuse_Calcium_Sulphate') ############################# SYSTEMS ########################################## #Tank to store Collected WCO and Water T101 = bst.StorageTank('T101_WCO', ins = (Collected_WCO), outs = 'WCO_to_pump') # P101 = bst.Pump('P101_WCO', # ins = T101-0, # outs = 'WCO_for_waterwash') T102 = bst.StorageTank('T102_Water', ins = Fresh_water, outs = 'Washing_water_to_pump') P102 = bst.Pump('P102_Water', ins = T102-0, outs = 'water_for_wash') # T103 = bst.MixTank('T103_Methanol', # ins = (Fresh_Methanol), # outs = 'Methanol_to_pump') # #TODO.xxx Check # P103 = bst.Pump('P103_Methanol', # ins = T103-0, # outs ='Methanol_to_reactor') # M103_Methanol = bst.Mixer('M103_Methanol_mixing', # ins = (Fresh_Methanol_1,Fresh_Methanol_2), # outs = ('Methanol_to_splitter')) # S1031 = bst.Splitter('S1031', # ins = M103_Methanol-0, # outs = ('Methanol_for_pretreatment', # 'Methanol_for_transesterification'), # split = 0.5) T104 = bst.StorageTank('T104_Sulacid', ins = Fresh_Sulacid, outs='Sulacid_to_pump') P104 = bst.Pump('P104_Sulacid', ins = T104-0, outs='Sulacid_to_reactor') T105 = bst.StorageTank('T105_Glycerol', ins = Fresh_Glycerol, outs = 'Glycerol_to_pump') P105 = bst.Pump('P105_Glycerol', P = 110300, ins = T105-0, outs = 'Glycerol_to_scrubber') # T106 = bst.StorageTank('T106_CaO', # ins = Fresh_CaO, # vessel_type='Field erected', # outs = 'CaO_to_pump') # P106 = bst.Pump('P106_CaO', # ins = Fresh_CaO, # outs = 'CaO_for_deacidification') #############################SYTEMS AND UNITS######################## #Mixtank to mix WCO and water M101 = bst.MixTank('M101', ins = (T101-0,P102-0), outs = 'Mixedfeed_for_waterwashing' ) @M101.add_specification(run=True) def adjust_Washing_water_flow(): Fresh_water.imass['Water'] = 10 * Collected_WCO.F_mass #Splitter to seperate the water slurry from the effluent #Considers 2% loss of oil S101 = bst.units.Splitter('S101', ins=M101-0, outs=('Water_slurry', 'WCO_pretreatment', ), split={'Water': 1, 'Oleic_acid': 0, #'Oil1': 0.01, 'Oil2': 0.02, }) #Mixer to mix all the streams before adding the stream to the reactor M102 = bst.Mixer('M102', ins = (S101-1,Fresh_Methanol_1,P104-0), outs = 'mixedfeed_to_pretreatment') Sul_acid_ratio = 0.0015 ####################################################################### @M102.add_specification(run=True) def adjust_methanol(): b = S101.ins[0].imass['Oleic_acid'] Fresh_Methanol_1.imass['Methanol'] = 3*b Fresh_Sulacid.imass['Sulphuric_acid'] = Sul_acid_ratio * S101.outs[1].F_mass #Reactor for the first esterification to reduce FFA content #Assumes 90% conversion R101 = PReactor('R101', ins = M102.outs[0], outs = 'feed_to_Glycerol_scrubber', N = 4, T = 48.5 + 273.15, P = 400000, tau = 2 ) #Glycerol scrubber to scrub Sulacid, Methanol and Water L101_H = bst.units.HXutility('L101_H', ins = R101-0, outs ='feed_to_Glycerol_scrubber', T = 65+273) L101 = bst.MultiStageMixerSettlers('L101_Glycerol_scrubber', ins = (L101_H-0,P105-0), outs=('Methanol_extract', 'raffinate_with_pretreated_WCO', ), N_stages = 2, ) @L101.add_specification(run=True) def adjust_glycerol(): b = M102.outs[0].imass['Methanol'] Fresh_Glycerol.imass['Glycerol'] = 0.547*b #Methanol recovery D101 = bst.units.ShortcutColumn('D101', ins = L101-0, outs = ('Recycled_methanol', 'Glycerol_for_recovery'), LHK = ('Methanol','Water'), k = 2, P = 90000, #P = 101325./20, Lr = 0.99, Hr = 0.99, partial_condenser= False, ) @D101.add_specification def D101_spec(): oil_mol = D101.ins[0].imol['122-32-7'] D101.ins[0].imol['122-32-7'] = 0 D101._run() # D101.ins[0].imol['122-32-7'] = oil_mol # D101.outs[1].imol['122-32-7'] = oil_mol M103 = bst.Mixer('M103', ins = (D101-1, Fresh_CaO), outs = 'mixedfeed_for_deacidification' ) @M103.add_specification(run = True) def adjust_CaO(): c = D101.outs[1].imass['Sulphuric_acid'] print(c) # P106.outs[0].imass['Calcium_oxide'] = 5.4*c Fresh_CaO.imass['Calcium_oxide'] = 5.4*c v_for_Calcium_sulphate_prod = 1.2* M103.outs[0].F_vol #5.4 Kg of CaO/Kg of Sul acid R102 = Glycerol_recovery('R102', ins = M103-0, outs='effluent_to_splitter', T = 50 + 273.15, tau = 3, N = 3 ) # Splitter to remove Calcium sulphate S103 = bst.units.Splitter('S103', R102-0, ['Reuse_Calcium_Sulphate', 'Glycerol_for_recovery'], split={'Calcium_Sulphate': 1, 'Methanol': 0, 'Glycerol': 0, 'Sulphuric_acid': 0, 'Calcium_oxide': 0, 'Water': 0,} ) T107 = bst.StorageTank('T107_Calcium_Sulphate', ins = S103-0, outs ='co_product_CaSO4') #Reactor for transesterification M104 = bst.Mixer('M104', ins = (L101-1,D101-0,Fresh_Methanol_2), outs = 'feed_to_transesterification') R103 = TReactor('R103', ins = M104.outs[0], outs = 'mixedfeed_to_biodiesel_rectification', T = 50 + 273.15, tau = 4, N = 3 ) @M104.add_specification(run = True) def adjust_methanol_for_transesterification(): b = M104.ins[0].imass['Oil2'] + M104.ins[1].imass['Oil2'] #M104.ins[0].imass['Tripalmitin'] + M104.ins[1].imass['Tripalmitin'] + a =
<filename>cuppa/dependencies/boost/boost_builder.py # Copyright <NAME> 2011-2018 # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) #------------------------------------------------------------------------------- # Boost Builder #------------------------------------------------------------------------------- import os import six # SCons Imports from SCons.Script import File, Flatten # Cuppa Imports import cuppa.build_platform from cuppa.output_processor import IncrementalSubProcess from cuppa.colourise import as_info, as_notice, colour_items from cuppa.log import logger # Boost Imports from cuppa.dependencies.boost.bjam import BjamOutputProcessor, BuildBjam, bjam_exe, bjam_command from cuppa.dependencies.boost.configjam import WriteToolsetConfigJam from cuppa.dependencies.boost.library_naming import stage_directory, variant_name, static_library_name, shared_library_name, extract_library_name_from_path from cuppa.dependencies.boost.library_dependencies import add_dependent_libraries _prebuilt_boost_libraries = { 'action': {}, 'emitter': {}, 'builder': {} } _bjam_invocations = {} # NOTE: We want to take advantage of the ability to parallelise BJAM calls when building boost. # However a number of aspects of how BJAM is executed are not "thread-safe" - that is # concurrent calls to BJAM to build libraries that will touch the same folders or files # on disk will result in spurious build failures. To address this issues we attempt to do # two things: # # 1. We minimise the number of calls to BJAM by tracking the which libraries are being # built and re-use targets when a BJAM call exists that will perform the build. This # is the purpose of the `_prebuilt_boost_libraries` dictionary. We only really need # to track the libraries in the `buildber` sub-dict but the libraries as known to the # `action` and `emitter` are also tracked to help with logging and diagnostics. # # By performing this tracking we can re-use library targets when building the dependency # tree and minimise unneeded calls to BJAM. We do this across a whole sconstruct file # as typically multiple sconscript files will make the same calls to build the same # libraries and if we are executing Scons in parallel mode using `--parallel` on the # cuppa commandline then those invocations of BJAM will potentially execute in parallel. # # 2. We serialise calls to BJAM because concurrent calls to BJAM that build targets # touching the same areas of disk with spuriously fail. Since we will use sufficient # cores to maximise the opportunity to execute builds in parallel when invoking BJAM we # will, on average, not suffer any loss of processing opportuinty. In other words we # can avoid hitting the build failures while still benefitting from executing a parallel # build. This is the purpose of the `_bjam_invocations` dict. With this we track all # invocations to BJAM and use a Requires() rule to force an ordering at the dependency # tree level. # # Here is an example of BJAM code in Boost that cannot reliably function concurrently. From # 'tools/build/src/util/path.jam': # # --------------------------------------------------------------------------------- # rule makedirs ( path ) # { # local result = true ; # local native = [ native $(path) ] ; # if ! [ exists $(native) ] # { # if [ makedirs [ parent $(path) ] ] # { # if ! [ MAKEDIR $(native) ] # { # import errors ; # errors.error "Could not create directory '$(path)'" ; # result = ; # } # } # } # return $(result) ; # } # --------------------------------------------------------------------------------- # # This should be written as: # # --------------------------------------------------------------------------------- # rule makedirs ( path ) # { # local result = true ; # local native = [ native $(path) ] ; # if ! [ exists $(native) ] # { # if [ makedirs [ parent $(path) ] ] # { # if ! [ MAKEDIR $(native) ] # { # if ! [ exists $(native) ] # { # import errors ; # errors.error "Could not create directory '$(path)'" ; # result = ; # } # } # } # } # return $(result) ; # } # --------------------------------------------------------------------------------- # # This change is needed as makedirs might fail because the directly already exists, perhaps # because a concurrent invocation of BJAM created it between the call to exists and makedirs def _lazy_update_library_list( env, emitting, libraries, prebuilt_libraries, add_dependents, linktype, boost, stage_dir ): def build_with_library_name( library ): if library == 'log_setup': return 'log' elif library in { 'prg_exec_monitor', 'test_exec_monitor', 'unit_test_framework' }: return 'test' else: return library if add_dependents: if not emitting: libraries = set( build_with_library_name(l) for l in add_dependent_libraries( boost, linktype, libraries ) ) else: libraries = add_dependent_libraries( boost, linktype, libraries ) if not stage_dir in prebuilt_libraries: logger.trace( "Lazy update libraries list for [{}] to [{}]".format( as_info(stage_dir), colour_items(str(l) for l in libraries) ) ) prebuilt_libraries[ stage_dir ] = set( libraries ) else: logger.trace( "Lazy read libraries list for [{}]: libraries are [{}]".format( as_info(stage_dir), colour_items(str(l) for l in libraries) ) ) libraries = [ l for l in libraries if l not in prebuilt_libraries[ stage_dir ] ] prebuilt_libraries[ stage_dir ].update( libraries ) return libraries class BoostLibraryAction(object): def __init__( self, env, stage_dir, libraries, add_dependents, linktype, boost, verbose_build, verbose_config ): self._env = env sconstruct_id = env['sconstruct_path'] global _prebuilt_boost_libraries if sconstruct_id not in _prebuilt_boost_libraries['action']: _prebuilt_boost_libraries['action'][sconstruct_id] = {} logger.trace( "Current Boost build [{}] has the following build variants [{}]".format( as_info(sconstruct_id), colour_items(_prebuilt_boost_libraries['action'][sconstruct_id].keys()) ) ) logger.debug( "Requested libraries [{}]".format( colour_items( libraries ) ) ) self._linktype = linktype self._variant = variant_name( self._env['variant'].name() ) self._target_arch = env['target_arch'] self._toolchain = env['toolchain'] self._stage_dir = stage_dir self._libraries = _lazy_update_library_list( env, False, libraries, _prebuilt_boost_libraries['action'][sconstruct_id], add_dependents, linktype, boost, self._stage_dir ) logger.debug( "Required libraries [{}]".format( colour_items( self._libraries ) ) ) self._location = boost.local() self._verbose_build = verbose_build self._verbose_config = verbose_config self._job_count = env['job_count'] self._parallel = env['parallel'] self._threading = True def __call__( self, target, source, env ): if not self._libraries: return None args = bjam_command( env, self._location, self._toolchain, self._libraries, self._variant, self._target_arch, self._linktype, self._stage_dir, self._verbose_build, self._verbose_config, self._job_count, self._parallel ) processor = BjamOutputProcessor( env, self._verbose_build, self._verbose_config, self._toolchain ) returncode = IncrementalSubProcess.Popen( processor, args, cwd=self._location ) summary = processor.summary( returncode ) if summary: print( summary ) if returncode: return returncode return None class BoostLibraryEmitter(object): def __init__( self, env, stage_dir, libraries, add_dependents, linktype, boost ): self._env = env sconstruct_id = env['sconstruct_path'] global _prebuilt_boost_libraries if sconstruct_id not in _prebuilt_boost_libraries['emitter']: _prebuilt_boost_libraries['emitter'][sconstruct_id] = {} logger.trace( "Current Boost build [{}] has the following build variants [{}]".format( as_info(sconstruct_id), colour_items(_prebuilt_boost_libraries['emitter'][sconstruct_id].keys()) ) ) self._stage_dir = stage_dir logger.debug( "Requested libraries [{}]".format( colour_items( libraries ) ) ) self._libraries = _lazy_update_library_list( env, True, libraries, _prebuilt_boost_libraries['emitter'][sconstruct_id], add_dependents, linktype, boost, self._stage_dir ) logger.debug( "Required libraries [{}]".format( colour_items( self._libraries ) ) ) self._location = boost.local() self._boost = boost self._threading = True self._linktype = linktype self._variant = variant_name( self._env['variant'].name() ) self._toolchain = env['toolchain'] def __call__( self, target, source, env ): for library in self._libraries: filename = None if self._linktype == 'static': filename = static_library_name( env, library, self._toolchain, self._boost.version(), self._variant, self._threading ) else: filename = shared_library_name( env, library, self._toolchain, self._boost.full_version(), self._variant, self._threading ) built_library_path = os.path.join( self._location, self._stage_dir, 'lib', filename ) logger.trace( "Emit Boost library [{}] to [{}]".format( as_notice(library), as_notice(built_library_path) ) ) node = File( built_library_path ) target.append( node ) return target, source class BoostLibraryBuilder(object): def __init__( self, boost, add_dependents, verbose_build, verbose_config ): self._boost = boost self._add_dependents = add_dependents self._verbose_build = verbose_build self._verbose_config = verbose_config def __call__( self, env, target, source, libraries, linktype ): sconstruct_id = env['sconstruct_path'] global _prebuilt_boost_libraries if sconstruct_id not in _prebuilt_boost_libraries['builder']: _prebuilt_boost_libraries['builder'][sconstruct_id] = {} global _bjam_invocations if sconstruct_id not in _bjam_invocations: _bjam_invocations[sconstruct_id] = [] logger.trace( "Build Dir = [{}]".format( as_info( env['build_dir'] ) ) ) logger.trace( "Requested libraries = [{}]".format( colour_items( libraries ) ) ) variant = variant_name( env['variant'].name() ) target_arch = env['target_arch'] toolchain = env['toolchain'] stage_dir = stage_directory( toolchain, variant, target_arch, toolchain.abi_flag(env) ) variant_key = stage_dir logger.trace( "Prebuilt Libraries Variant Key = [{}]".format( as_notice( variant_key ) ) ) library_action = BoostLibraryAction ( env, stage_dir, libraries, self._add_dependents, linktype, self._boost, self._verbose_build, self._verbose_config ) library_emitter = BoostLibraryEmitter( env, stage_dir, libraries, self._add_dependents, linktype, self._boost ) logger.trace( "Action Prebuilt Libraries for [{}] = {}".format( as_info( variant_key ), colour_items( _prebuilt_boost_libraries['action'][sconstruct_id][variant_key] ) ) ) logger.trace( "Emitter Prebuilt Libraries for [{}] = {}".format( as_info( variant_key ), colour_items( _prebuilt_boost_libraries['emitter'][sconstruct_id][variant_key] ) ) ) env.AppendUnique( BUILDERS = { 'BoostLibraryBuilder' : env.Builder( action=library_action, emitter=library_emitter ) } ) built_libraries = env.BoostLibraryBuilder( target, source ) built_libraries_map = { extract_library_name_from_path(l):l for l in built_libraries } logger.trace( "Libraries to be built = [{}]".format( colour_items( built_libraries_map.keys() ) ) ) if not variant_key in _prebuilt_boost_libraries['builder'][sconstruct_id]: _prebuilt_boost_libraries['builder'][sconstruct_id][ variant_key ] = {} logger.trace( "Variant sources = [{}]".format( colour_items( _prebuilt_boost_libraries['builder'][sconstruct_id][ variant_key ].keys() ) ) ) required_libraries = add_dependent_libraries( self._boost, linktype, libraries ) logger.trace( "Required libraries = [{}]".format( colour_items( required_libraries ) ) ) unbuilt_libraries = False new_libraries = [] for library in required_libraries: if library in _prebuilt_boost_libraries['builder'][sconstruct_id][
<reponame>cvandeplas/plaso #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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. """Script to update prebuilt versions of the dependencies.""" import argparse import glob import logging import os import platform import re import subprocess import sys import urllib2 if platform.system() == 'Windows': import wmi class DownloadHelper(object): """Class that helps in downloading a project.""" def __init__(self): """Initializes the build helper.""" super(DownloadHelper, self).__init__() self._cached_url = u'' self._cached_page_content = '' def DownloadPageContent(self, download_url): """Downloads the page content from the URL and caches it. Args: download_url: the URL where to download the page content. Returns: The page content if successful, None otherwise. """ if not download_url: return if self._cached_url != download_url: url_object = urllib2.urlopen(download_url) if url_object.code != 200: return self._cached_page_content = url_object.read() self._cached_url = download_url return self._cached_page_content def DownloadFile(self, download_url): """Downloads a file from the URL and returns the filename. The filename is extracted from the last part of the URL. Args: download_url: the URL where to download the file. Returns: The filename if successful also if the file was already downloaded or None on error. """ _, _, filename = download_url.rpartition(u'/') if not os.path.exists(filename): logging.info(u'Downloading: {0:s}'.format(download_url)) url_object = urllib2.urlopen(download_url) if url_object.code != 200: return file_object = open(filename, 'wb') file_object.write(url_object.read()) file_object.close() return filename class GoogleCodeDownloadHelper(DownloadHelper): """Class that helps in downloading a Google Code project.""" def GetGoogleCodeDownloadsUrl(self, project_name): """Retrieves the Download URL from the Google Code project page. Args: project_name: the name of the project. Returns: The downloads URL or None on error. """ download_url = u'https://code.google.com/p/{0:s}/'.format(project_name) page_content = self.DownloadPageContent(download_url) if not page_content: return # The format of the project downloads URL is: # https://googledrive.com/host/{random string}/ expression_string = ( u'<a href="(https://googledrive.com/host/[^/]*/)"[^>]*>Downloads</a>') matches = re.findall(expression_string, page_content) if not matches or len(matches) != 1: return return matches[0] def GetPackageDownloadUrls(self, google_drive_url): """Retrieves the package downloads URL for a given URL. Args: google_drive_url: the Google Drive URL. Returns: A list of package download URLs. """ page_content = self.DownloadPageContent(google_drive_url) if not page_content: return # The format of the project download URL is: # /host/{random string}/3rd%20party/{sub directory}/{filename} expression_string = u'/host/[^/]+/3rd%20party/[^/">]+/[^">]+' matches = re.findall(expression_string, page_content) for match_index in range(0, len(matches)): matches[match_index] = u'https://googledrive.com{0:s}'.format( matches[match_index]) return matches def Download(self, download_url): """Downloads the project for a given project name and version. Args: download_url: the download URL. Returns: The filename if successful also if the file was already downloaded or None on error. """ return self.DownloadFile(download_url) def CompareVersions(first_version_list, second_version_list): """Compares two lists containing version parts. Note that the version parts can contain alpha numeric characters. Args: first_version_list: the first list of version parts. second_version_list: the second list of version parts. Returns: 1 if the first is larger than the second, -1 if the first is smaller than the second, or 0 if the first and second are equal. """ first_version_list_length = len(first_version_list) second_version_list_length = len(second_version_list) for index in range(0, first_version_list_length): if index >= second_version_list_length: return 1 if first_version_list[index] > second_version_list[index]: return 1 elif first_version_list[index] < second_version_list[index]: return -1 if first_version_list_length < second_version_list_length: return -1 return 0 def Main(): args_parser = argparse.ArgumentParser(description=( u'Installs the latest versions of libyal packages in the current ' u'directory.')) _ = args_parser.parse_args() operating_system = platform.system() cpu_architecture = platform.machine().lower() linux_name = None if operating_system == u'Darwin': # TODO: determine OSX version if cpu_architecture != u'x86_64': logging.error(u'CPU architecture: {0:s} not supported.'.format( cpu_architecture)) # Note that the sub directory should be URL encoded. sub_directory = u'macosx%2010.9' noarch_sub_directory = None elif operating_system == u'Linux': linux_name, linux_version, _ = platform.linux_distribution() if linux_name == u'Fedora' and linux_version == u'20': if cpu_architecture != u'x86_64': logging.error(u'CPU architecture: {0:s} not supported.'.format( cpu_architecture)) sub_directory = u'fedora20-x86_64' noarch_sub_directory = u'fedora20-noarch' elif linux_name == u'Ubuntu' and linux_version == u'12.04': if cpu_architecture == u'i686': sub_directory = u'ubuntu12.04-i386' noarch_sub_directory = u'ubuntu12.04-all' elif cpu_architecture == u'x86_64': sub_directory = u'ubuntu12.04-amd64' noarch_sub_directory = u'ubuntu12.04-all' else: logging.error(u'CPU architecture: {0:s} not supported.'.format( cpu_architecture)) else: logging.error(u'Linux variant: {0:s} {1:s} not supported.'.format( linux_name, linux_version)) elif operating_system == u'Windows': if cpu_architecture == u'x86': sub_directory = u'win32-vs2008' elif cpu_architecture == u'amd64': sub_directory = u'win-amd64-vs2010' else: logging.error(u'CPU architecture: {0:s} not supported.'.format( cpu_architecture)) noarch_sub_directory = None else: logging.error(u'Operating system: {0:s} not supported.'.format( operating_system)) return False download_helper = GoogleCodeDownloadHelper() google_drive_url = download_helper.GetGoogleCodeDownloadsUrl(u'plaso') package_urls = download_helper.GetPackageDownloadUrls( u'{0:s}/3rd%20party/{1:s}'.format(google_drive_url, sub_directory)) if noarch_sub_directory: noarch_package_urls = download_helper.GetPackageDownloadUrls( u'{0:s}/3rd%20party/{1:s}'.format( google_drive_url, noarch_sub_directory)) package_urls.extend(noarch_package_urls) dependencies_directory = u'dependencies' if not os.path.exists(dependencies_directory): os.mkdir(dependencies_directory) os.chdir(dependencies_directory) package_filenames = {} package_versions = {} for package_url in package_urls: _, _, package_filename = package_url.rpartition(u'/') if package_filename.endswith(u'.deb'): name, _, version = package_filename.partition(u'_') # Ignore devel and tools DEB packages. if name.endswith(u'-dev') or name.endswith(u'-tools'): continue if name.endswith(u'-python'): package_prefix = name name, _, _ = name.partition(u'-') else: package_prefix = u'{0:s}_'.format(name) version, _, _ = version.partition(u'-') elif package_filename.endswith(u'.dmg'): name, _, version = package_filename.partition(u'-') version, _, _ = version.partition(u'.dmg') package_prefix = name elif package_filename.endswith(u'.msi'): name, _, version = package_filename.partition(u'-') version, _, _ = version.partition(u'.win') package_prefix = name elif package_filename.endswith(u'.rpm'): name, _, version = package_filename.partition(u'-') # Ignore debuginfo, devel and tools RPM packages. if (version.startswith(u'debuginfo') or version.startswith(u'devel') or version.startswith(u'tools')): continue # Ignore the sleuthkit tools RPM package. if name == u'sleuthkit' and not version.startswith(u'libs'): continue package_prefix, _, version = version.partition(u'-') version, _, _ = version.partition(u'-') package_prefix = u'{0:s}-{1:s}'.format(name, package_prefix) else: # Ignore all other file exensions. continue version = version.split(u'.') if name == u'pytsk': last_part = version.pop() version.extend(last_part.split(u'-')) if name not in package_versions: compare_result = 1 else: compare_result = CompareVersions(version, package_versions[name]) if compare_result > 0: package_filenames[name] = package_filename package_versions[name] = version if not os.path.exists(package_filename): filenames = glob.glob(u'{0:s}*'.format(package_prefix)) for filename in filenames: print u'Removing: {0:s}'.format(filename) os.remove(filename) print u'Downloading: {0:s}'.format(package_filename) _ = download_helper.Download(package_url) os.chdir(u'..') if operating_system == u'Darwin': result = True command = u'/usr/sbin/pkgutil --packages' print 'Running: "{0:s}"'.format(command) process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) if process.returncode is None: packages, _ = process.communicate() else: packages = '' if process.returncode != 0: logging.error(u'Running: "{0:s}" failed.'.format(command)) return False for package_name in packages.split('\n'): if not package_name: continue if (package_name.startswith(u'com.google.code.p.') or package_name.startswith(u'org.python.pypi.') or package_name.startswith(u'net.sourceforge.projects.')): if package_name.startswith(u'com.google.code.p.'): name = package_name[18:] elif package_name.startswith(u'org.python.pypi.'): name = package_name[16:] elif package_name.startswith(u'net.sourceforge.projects.'): name = package_name[25:] # Detect the PackageMaker naming convention. if name.endswith(u'.pkg'): _, _, sub_name = name[:-4].rpartition(u'.') is_package_maker_pkg = True else: is_package_maker_pkg = False name, _, _ = name.partition(u'.') if name in package_versions: # Determine the package version. command = u'/usr/sbin/pkgutil --pkg-info {0:s}'.format(package_name) print 'Running: "{0:s}"'.format(command) process = subprocess.Popen( command, stdout=subprocess.PIPE, shell=True) if process.returncode is None: package_info, _ = process.communicate() else: package_info = '' if process.returncode != 0: logging.error(u'Running: "{0:s}" failed.'.format(command)) result = False continue location = None version = None volume = None for attribute in package_info.split('\n'): if attribute.startswith(u'location: '): _, _, location = attribute.rpartition(u'location: ') elif attribute.startswith(u'version: '): _, _, version = attribute.rpartition(u'version: ') elif attribute.startswith(u'volume: '): _, _, volume = attribute.rpartition(u'volume: ') version = version.split(u'.') if name not in package_versions: compare_result = 1 # TODO: handle pytsk. else: compare_result = CompareVersions(version, package_versions[name]) if compare_result >= 0: # The latest or newer version is already installed. del package_versions[name] if compare_result < 0: # Determine the files in the package. command = u'/usr/sbin/pkgutil --files {0:s}'.format(package_name) print 'Running: "{0:s}"'.format(command) process = subprocess.Popen( command, stdout=subprocess.PIPE, shell=True) if process.returncode is None: package_files, _ = process.communicate() else: package_files = '' if process.returncode != 0: logging.error(u'Running: "{0:s}" failed.'.format(command)) result = False continue directories = [] files = [] for filename in package_files.split('\n'): if is_package_maker_pkg: filename = u'{0:s}{1:s}/{2:s}/{3:s}'.format( volume, location, sub_name, filename) else: filename = u'{0:s}{1:s}'.format(location, filename) if os.path.isdir(filename): directories.append(filename) else: files.append(filename) print 'Removing: {0:s} {1:s}'.format(name, version) for filename in files: if os.path.exists(filename): os.remove(filename) for filename in directories: if os.path.exists(filename): try: os.rmdir(filename) except OSError: # Ignore directories that are not empty. pass command =
# Generated by Django 2.1.1 on 2019-05-08 09:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('rbac', '0001_initial'), ] operations = [ migrations.CreateModel( name='Account', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=32, verbose_name='用户名')), ('passwd', models.CharField(max_length=64, verbose_name='密码')), ('email', models.EmailField(blank=True, max_length=32, null=True, verbose_name='邮箱')), ('brief', models.CharField(blank=True, max_length=64, null=True, verbose_name='学员简介')), ('education', models.IntegerField(blank=True, choices=[(0, '大专'), (1, '本科'), (2, '研究生'), (3, '博士'), (4, '硕士'), (5, '其他')], null=True, verbose_name='学历')), ('career', models.CharField(blank=True, max_length=32, null=True, verbose_name='目前职业/最近一次从事职业')), ('balance', models.IntegerField(default=0, verbose_name='账户余额')), ('level', models.IntegerField(choices=[(0, '管理员'), (1, '导师'), (2, '学员'), (3, '非学员')], default=3, verbose_name='用户等级')), ('date', models.DateTimeField(auto_now_add=True, verbose_name='注册日期')), ('roles', models.ManyToManyField(blank=True, to='rbac.Role', verbose_name='所属角色')), ], options={ 'verbose_name': '用户表', 'verbose_name_plural': 'DB_Account', 'db_table': 'DB_Account', }, ), migrations.CreateModel( name='Admins', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='管理组')), ], options={ 'verbose_name': '管理组表', 'verbose_name_plural': 'DB_Admins', 'db_table': 'DB_Admins', }, ), migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32, verbose_name='文章标题')), ('content', models.TextField(verbose_name='文章正文')), ('date', models.DateTimeField(auto_now_add=True, verbose_name='发布日期')), ], options={ 'verbose_name': '资讯文章', 'verbose_name_plural': 'DB_Article', 'db_table': 'DB_Article', }, ), migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32, verbose_name='课程分类名')), ], options={ 'verbose_name': '课程分类', 'verbose_name_plural': 'DB_Category', 'db_table': 'DB_Category', }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('object_id', models.PositiveIntegerField(blank=True, null=True)), ('comment_date', models.DateField(auto_now_add=True)), ('content', models.CharField(max_length=1024, verbose_name='评论内容')), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='评论用户')), ('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'verbose_name': '评论', 'verbose_name_plural': 'DB_Comment', 'db_table': 'DB_Comment', }, ), migrations.CreateModel( name='CommonQuestion', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('object_id', models.PositiveIntegerField()), ('question', models.CharField(max_length=64, verbose_name='问题')), ('answer', models.CharField(max_length=512, verbose_name='答案')), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'verbose_name': '常见问题', 'verbose_name_plural': 'DB_CommonQuestion', 'db_table': 'DB_CommonQuestion', }, ), migrations.CreateModel( name='ConsultRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('note', models.TextField(verbose_name='跟进内容')), ('date', models.DateField(auto_now_add=True, verbose_name='跟进日期')), ], options={ 'verbose_name': '导师跟进记录表', 'verbose_name_plural': 'DB_ConsultRecord', 'db_table': 'DB_ConsultRecord', }, ), migrations.CreateModel( name='Coupon', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=64, verbose_name='活动名')), ('brief', models.TextField(blank=True, max_length=128, null=True, verbose_name='优惠券介绍')), ('coupon_type', models.SmallIntegerField(choices=[(0, '通用券'), (1, '抵扣券'), (2, '满减券')], default=0, help_text='通用券为全局优惠券,其他则为专项券')), ('count', models.IntegerField(verbose_name='优惠券张数,发放一次立即更新该字段')), ('equal_money', models.IntegerField(blank=True, default=0, null=True, verbose_name='优惠券等值货币')), ('off_percent', models.PositiveIntegerField(blank=True, default=100, help_text='仅在折扣券使用', null=True, verbose_name='折扣券百分比')), ('minimum_consume', models.FloatField(blank=True, default=0, help_text='仅在满减券使用', null=True, verbose_name='最低消费')), ('grant_begin_time', models.DateTimeField(verbose_name='活动领取开始时间')), ('grant_end_time', models.DateTimeField(verbose_name='活动领取结束时间')), ('start_time', models.DateTimeField(blank=True, null=True, verbose_name='优惠券有效期开始时间')), ('end_time', models.DateTimeField(blank=True, null=True, verbose_name='优惠券有效期结束时间')), ('period', models.PositiveIntegerField(blank=True, default=0, null=True, verbose_name='优惠券有效期(天)')), ('date', models.DateTimeField(auto_now_add=True, help_text='即用户实际领取优惠券生效的时间', verbose_name='生效时间')), ('object_id', models.PositiveIntegerField(blank=True, help_text='有值代表专项优惠券,没有值代表通用券', null=True, verbose_name='绑定的课程对象')), ('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'verbose_name': '优惠券规则', 'verbose_name_plural': 'DB_Coupon', 'db_table': 'DB_Coupon', }, ), migrations.CreateModel( name='CouponDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.CharField(max_length=64, unique=True, verbose_name='优惠券流水记录')), ('status', models.IntegerField(choices=[(0, '未使用'), (1, '已使用'), (2, '已过期')], default=0)), ('get_time', models.DateTimeField(verbose_name='用户领取时间')), ('use_time', models.DateTimeField(blank=True, null=True, verbose_name='用户使用时间')), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='优惠券拥有者')), ('coupon', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Coupon')), ], options={ 'verbose_name': '用户优惠券领取使用记录表', 'verbose_name_plural': 'DB_CouponDetail', 'db_table': 'DB_CouponDetail', }, ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32, verbose_name='课程标题')), ('course_img', models.ImageField(blank=True, help_text='填写一个cdn外链地址即可', null=True, upload_to='course/%Y-%m', verbose_name='课程图片')), ('status', models.SmallIntegerField(choices=[(0, '预售中'), (1, '开设中'), (2, '已下架')], verbose_name='课程状态')), ('difficult', models.SmallIntegerField(choices=[(0, '初级'), (1, '中级'), (2, '高级')], default=0, verbose_name='课程难度')), ('course_type', models.SmallIntegerField(choices=[(0, '付费'), (1, '免费'), (2, 'VIP专享'), (3, '学位课程')], verbose_name='课程类型')), ('release_date', models.DateField(blank=True, null=True, verbose_name='发布日期')), ('order', models.IntegerField(help_text='从上一个课程开始', verbose_name='课程顺序')), ('study_number', models.IntegerField(help_text='只要有人买,立即更新该字段', verbose_name='学习人数')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Category', verbose_name='课程分类')), ], options={ 'verbose_name': '课程', 'verbose_name_plural': 'DB_Course', 'db_table': 'DB_Course', }, ), migrations.CreateModel( name='CourseChapter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('chapter', models.SmallIntegerField(default=1, verbose_name='第几章')), ('title', models.CharField(max_length=32, verbose_name='章节名称')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_chapters', to='generic.Course', verbose_name='课程')), ], options={ 'verbose_name': '课程章节', 'verbose_name_plural': 'DB_CourseChapter', 'db_table': 'DB_CourseChapter', }, ), migrations.CreateModel( name='CourseDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('lesson', models.IntegerField(default=7, verbose_name='总课时')), ('slogan', models.CharField(blank=True, max_length=64, null=True, verbose_name='课程口号')), ('brief', models.CharField(max_length=128, verbose_name='简介')), ('why_study', models.CharField(max_length=1024, verbose_name='为什么学习')), ('point', models.CharField(max_length=512, verbose_name='课程安排,能学到的知识点')), ('harvest', models.CharField(max_length=1024, verbose_name='学完对我的职业生涯影响')), ('feature', models.CharField(max_length=512, verbose_name='课程特点')), ('prerequisite', models.TextField(max_length=1024, verbose_name='课程先修条件')), ('object_person', models.CharField(max_length=128, verbose_name='面向人群')), ('course_review', models.FloatField(blank=True, null=True, verbose_name='课程评分')), ('course', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='generic.Course')), ('recommend_course', models.ManyToManyField(related_name='recommend_by', to='generic.Course', verbose_name='推荐课程')), ], options={ 'verbose_name': '课程详情', 'verbose_name_plural': 'DB_CourseDetail', 'db_table': 'DB_CourseDetail', }, ), migrations.CreateModel( name='CourseLesson', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32, verbose_name='课时名称')), ('order', models.SmallIntegerField(help_text='每三个隔开排序,方便以后更新课程插入', verbose_name='课时顺序')), ('course_lesson_type', models.SmallIntegerField(choices=[(0, '视频'), (1, '文档'), (2, '练习题')], default=0, verbose_name='课时类型')), ('free_trail', models.BooleanField(default=False, verbose_name='是否可试看')), ('lesson_link', models.CharField(blank=True, help_text='如果是文档,需要给链接', max_length=255, null=True, verbose_name='课程链接')), ('chapter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_lesson', to='generic.CourseChapter', verbose_name='课程章节')), ], options={ 'verbose_name': '课时', 'verbose_name_plural': 'DB_CourseLesson', 'db_table': 'DB_CourseLesson', }, ), migrations.CreateModel( name='CourseOutline', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=128, verbose_name='大纲名')), ('order', models.SmallIntegerField(default=1, verbose_name='大纲顺序')), ('content', models.TextField(max_length=2048, verbose_name='大纲内容')), ('course_detail', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_outline', to='generic.CourseDetail')), ], options={ 'verbose_name': '课程大纲', 'verbose_name_plural': 'DB_CourseOutline', 'db_table': 'DB_CourseOutline', }, ), migrations.CreateModel( name='Degree', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32, verbose_name='学位课程名')), ('aims', models.CharField(max_length=1024, verbose_name='培养目标')), ('core', models.CharField(max_length=1024, verbose_name='核心优势')), ('serving', models.CharField(max_length=1024, verbose_name='特色服务')), ], options={ 'verbose_name': '学位表', 'verbose_name_plural': 'DB_Degree', 'db_table': 'DB_Degree', }, ), migrations.CreateModel( name='Homework', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField(blank=True, null=True, verbose_name='作业内容')), ('title', models.CharField(blank=True, max_length=32, null=True, verbose_name='作业标题')), ('chapter', models.ManyToManyField(to='generic.CourseChapter', verbose_name='课程章节')), ('courses', models.ManyToManyField(to='generic.Course', verbose_name='课程')), ], options={ 'verbose_name': '作业情况', 'verbose_name_plural': 'DB_Homework', 'db_table': 'DB_Homework', }, ), migrations.CreateModel( name='HomeworkDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.IntegerField(choices=[(1, '作业未发布'), (2, '学生未提交'), (3, '讲师未批改'), (4, '讲师已批改-合格'), (5, '讲师已批改-不合格')], default=2)), ('file', models.FileField(blank=True, null=True, upload_to='homework/%Y-%m-%d/', verbose_name='作业文件')), ('critic', models.TextField(blank=True, null=True, verbose_name='作业批语')), ('homework', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='generic.Homework', verbose_name='作业')), ], options={ 'verbose_name': '作业详情', 'verbose_name_plural': 'DB_HomeworkDetail', 'db_table': 'DB_HomeworkDetail', }, ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('payment_type', models.SmallIntegerField(choices=[(0, '支付宝'), (1, '微信'), (2, '余额支付'), (3, '优惠吗'), (4, '银行卡支付')], verbose_name='付款类型')), ('payment_number', models.IntegerField(blank=True, null=True, verbose_name='支付第三方流水号')), ('order_nubmer', models.CharField(blank=True, max_length=128, null=True, verbose_name='订单号')), ('payment_amount', models.FloatField(verbose_name='实付金额')), ('status', models.SmallIntegerField(choices=[(0, '交易成功'), (1, '待支付'), (2, '退费申请中'), (3, '已退费'), (4, '主动取消'), (5, '超时取消')], verbose_name='订单状态')), ('date', models.DateTimeField(auto_now_add=True, verbose_name='订单生成时间')), ('pay_time', models.DateTimeField(blank=True, null=True, verbose_name='付款时间')), ('cancel_time', models.DateTimeField(blank=True, null=True, verbose_name='订单取消时间')), ('assess_status', models.IntegerField(choices=[(0, '未评价'), (1, '已评价'), (2, '已追评')], default=0)), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='下单用户')), ], options={ 'verbose_name': '订单表', 'verbose_name_plural': 'DB_Order', 'db_table': 'DB_Order', }, ), migrations.CreateModel( name='OrderDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('original_price', models.FloatField(blank=True, null=True, verbose_name='课程原价')), ('price', models.FloatField(blank=True, null=True, verbose_name='折后价格')), ('valid_period_display', models.CharField(blank=True, max_length=32, null=True, verbose_name='有效期在订单页显示')), ('valid_period', models.PositiveIntegerField(blank=True, null=True, verbose_name='课程有效期(days)')), ('memo', models.CharField(blank=True, max_length=255, null=True, verbose_name='订单交易备注')), ('transaction_type', models.SmallIntegerField(choices=[(0, '收入'), (1, '支出'), (2, '退款'), (3, '提现')], default=1, verbose_name='交易类型')), ('transaction_number', models.CharField(blank=True, max_length=128, null=True, unique=True, verbose_name='流水号')), ('product', models.CharField(blank=True, help_text='如果是支出和退款一定写入购买的商品', max_length=2048, null=True, verbose_name='商品名')), ('object_id', models.PositiveIntegerField(blank=True, null=True)), ('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType', verbose_name='关联普通课程或学位')), ('order', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='generic.Order')), ], options={ 'verbose_name': '账单详细', 'verbose_name_plural': 'DB_OrderDetail', 'db_table': 'DB_OrderDetail', }, ), migrations.CreateModel( name='PaymentRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pay_type', models.IntegerField(choices=[(1, '报名费'), (2, '学费'), (3, '退学'), (4, '其他')], default=1, verbose_name='费用类型')), ('paid_fee', models.FloatField(default=0, verbose_name='金额')), ('apply_date', models.DateTimeField(auto_now_add=True, verbose_name='申请日期')), ('confirm_status', models.IntegerField(choices=[(1, '申请中'), (2, '已确认'), (3, '已驳回')], default=1, verbose_name='确认状态')), ('confirm_date', models.DateTimeField(blank=True, null=True, verbose_name='确认日期')), ('note', models.TextField(blank=True, null=True, verbose_name='备注')), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='客户')), ('confirm_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='confirms', to='generic.Admins', verbose_name='审批人')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Course', verbose_name='申请课程')), ], options={ 'verbose_name': '缴费申请表', 'verbose_name_plural': 'DB_PaymentRecord', 'db_table': 'DB_PaymentRecord', }, ), migrations.CreateModel( name='PricePolicy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('object_id', models.PositiveIntegerField(verbose_name='课程对象')), ('valid_period', models.SmallIntegerField(choices=[(1, '1天'), (3, '3天'), (7, '1周'), (14, '2周'), (30, '1个月'), (60, '2个月'), (90, '3个月'), (120, '4个月'), (150, '5个月'), (180, '6个月'), (210, '12个月'), (540, '18个月'), (720, '24个月'), (722, '24个月'), (723, '24个月')], verbose_name='课程有效期')), ('price', models.FloatField(verbose_name='课程价格')), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], options={ 'verbose_name': '价格策略表', 'verbose_name_plural': 'DB_PricePolicy', 'db_table': 'DB_PricePolicy', }, ), migrations.CreateModel( name='ScoreRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField(verbose_name='理由')), ('score', models.IntegerField(help_text='违纪扣分写负值,表现邮寄加分写正值', verbose_name='分值')), ('student', models.ForeignKey(limit_choices_to={'level': 2}, on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='学生')), ], options={ 'verbose_name': '积分记录', 'verbose_name_plural': 'DB_ScoreRecord', 'db_table': 'DB_ScoreRecord', }, ), migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('qq', models.CharField(blank=True, max_length=32, null=True, verbose_name='QQ号')), ('mobile', models.CharField(blank=True, max_length=32, null=True, verbose_name='手机号')), ('emergency_contract', models.CharField(blank=True, max_length=32, null=True, verbose_name='紧急联系人电话')), ('student_status', models.IntegerField(choices=[(1, '申请中'), (2, '在学'), (3, '毕业'), (4, '退学'), (5, '非学员')], default=1, verbose_name='学员状态')), ('score', models.IntegerField(default=100, verbose_name='积分')), ('memo', models.TextField(blank=True, max_length=255, null=True, verbose_name='备注')), ('account', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='学员信息')), ('courses', models.ManyToManyField(blank=True, to='generic.Course', verbose_name='已买课程')), ], options={ 'verbose_name': '学生表', 'verbose_name_plural': 'DB_Student', 'db_table': 'DB_Student', }, ), migrations.CreateModel( name='StudyQuestion', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question', models.TextField(verbose_name='提问内容')), ('answer', models.TextField(blank=True, null=True, verbose_name='回答内容')), ('question_date', models.DateTimeField(auto_now_add=True, verbose_name='提问日期')), ('answer_date', models.DateTimeField(blank=True, null=True, verbose_name='回答日期')), ('student', models.ForeignKey(limit_choices_to={'level': 2}, on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='提问学生')), ], options={ 'verbose_name': '问题表', 'verbose_name_plural': 'DB_StudyQuestion', 'db_table': 'DB_StudyQuestion', }, ), migrations.CreateModel( name='StudyRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.IntegerField(choices=[(1, '未学习'), (2, '已学习')], default=1)), ('course_lesson', models.ManyToManyField(to='generic.CourseLesson', verbose_name='课时')), ('student', models.ManyToManyField(to='generic.Student', verbose_name='学生')), ], options={ 'verbose_name': '学员学习进度', 'verbose_name_plural': 'DB_StudyRecord', 'db_table': 'DB_StudyRecord', }, ), migrations.CreateModel( name='Teacher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=32, verbose_name='讲师姓名')), ('title', models.CharField(max_length=64, verbose_name='讲师头衔')), ('teacher_img', models.ImageField(blank=True, null=True, upload_to='teacher/', verbose_name='头像')), ('brief', models.CharField(max_length=128, verbose_name='讲师简介')), ], options={ 'verbose_name': '讲师表', 'verbose_name_plural': 'DB_Teacher', 'db_table': 'DB_Teacher', }, ), migrations.CreateModel( name='TradeRecord', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.FloatField(verbose_name='使用账户余额')), ('balance', models.FloatField(verbose_name='账户余额')), ('date', models.DateTimeField(auto_now_add=True, verbose_name='交易时间')), ('user_address', models.CharField(blank=True, max_length=512, null=True, verbose_name='收获地址')), ('memo', models.CharField(blank=True, max_length=128, null=True, verbose_name='交易备注')), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='用户')), ('order', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='generic.Order', verbose_name='账单')), ], options={ 'verbose_name': '余额交易记录', 'verbose_name_plural': 'DB_TradeRecord', 'db_table': 'DB_TradeRecord', }, ), migrations.CreateModel( name='Tutor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='generic.Account', verbose_name='导师信息')), ], options={ 'verbose_name': '导师表', 'verbose_name_plural': 'DB_Tutor', 'db_table': 'DB_Tutor', }, ), migrations.AddField( model_name='studyquestion', name='tutor', field=models.ForeignKey(limit_choices_to={'account__level': 1}, on_delete=django.db.models.deletion.CASCADE, to='generic.Tutor', verbose_name='导师'), ), migrations.AddField( model_name='student', name='tutor', field=models.ForeignKey(blank=True, help_text='这个字段由管理员填写分配', null=True, on_delete=django.db.models.deletion.CASCADE, to='generic.Tutor',
''' Created on Oct 5, 2011 @author: grant provides python methods to perform generate isosurfaces using marching cubes or marching tetrahedrons ''' import numpy, time from TriModel import TriModel edgeTable = [ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 ] triTable = [[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1], [3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1], [3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1], [3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1], [9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1], [1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1], [9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1], [2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1], [8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1], [9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1], [4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1], [3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1], [1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1], [4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1], [4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1], [9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1], [1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1], [5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1], [2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1], [9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1], [0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1], [2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1], [10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1], [4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1], [5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1], [5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1], [9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1], [0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1], [1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1], [10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1], [8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1], [2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1], [7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1], [9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1], [2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1], [11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1], [9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1], [5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1], [11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1], [11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [1, 8, 3, 1, 9, 8, 5, 10, 6, -1,
<gh_stars>0 import gc import unittest from hecuba import config, StorageNumpy import uuid import numpy as np from storage.api import getByID from time import time as timer import random class StorageNumpyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.old = config.execution_name config.execution_name = "StorageNumpyTest".lower() @classmethod def tearDownClass(cls): #config.session.execute("DROP KEYSPACE IF EXISTS {}".format(config.execution_name), timeout=60) config.execution_name = cls.old # Create a new keyspace per test def setUp(self): self.ksp = config.execution_name pass def tearDown(self): pass table = 'numpy_test' def test_init_empty(self): tablename = None base_array = np.arange(4096).reshape((64, 64)) storage_id = None basic_init = StorageNumpy(base_array) self.assertTrue(np.array_equal(basic_init, base_array)) complete_init = StorageNumpy(base_array, storage_id, tablename) self.assertTrue(np.array_equal(complete_init, base_array)) def test_types_in_memory(self): base_array = np.arange(256) for typecode in np.typecodes['Integer']: typed_array = StorageNumpy(base_array.astype(typecode)) self.assertTrue(np.array_equal(typed_array, base_array.astype(typecode))) for typecode in np.typecodes['UnsignedInteger']: typed_array = StorageNumpy(base_array.astype(typecode)) self.assertTrue(np.array_equal(typed_array, base_array.astype(typecode))) def test_reconstruct(self): base_array = np.arange(256) tablename = self.ksp + '.' + "test_reconstruct" typecode = 'mytype' niter = 2 for _ in range(niter): # Build array and store typed_array = StorageNumpy(base_array, tablename) self.assertTrue(np.array_equal(typed_array, base_array)) typed_array.sync() # Flush values to cassandra # Load array typed_array = StorageNumpy(None, tablename) self.assertTrue(np.allclose(typed_array, base_array)) typed_array.delete_persistent() def test_types_persistence(self): base_array = np.arange(256) tablename = self.ksp + '.' + "test_types_persistence" for typecode in np.typecodes['Integer']: if typecode == 'p': # TODO For now skip arrays made of pointers pass typed_array = StorageNumpy(base_array.astype(typecode), tablename) self.assertTrue(np.array_equal(typed_array, base_array.astype(typecode))) typed_array.sync() # Flush values to cassandra typed_array = StorageNumpy(None, tablename) self.assertTrue(np.allclose(typed_array, base_array.astype(typecode))) typed_array.delete_persistent() for typecode in np.typecodes['UnsignedInteger']: if typecode == 'P': # TODO For now skip arrays made of pointers pass typed_array = StorageNumpy(base_array.astype(typecode), tablename) self.assertTrue(np.allclose(typed_array, base_array.astype(typecode))) typed_array.sync() # Flush values to cassandra typed_array = StorageNumpy(None, tablename) self.assertTrue(np.allclose(typed_array, base_array.astype(typecode))) typed_array.delete_persistent() def test_read_all(self): nelem = 2 ** 21 elem_dim = 2 ** 7 base_array = np.arange(nelem).reshape((elem_dim, elem_dim, elem_dim)) casted = StorageNumpy(input_array=base_array, name="test_read_all") casted.sync() # Flush values to cassandra test_numpy = np.arange(nelem).reshape((elem_dim, elem_dim, elem_dim)) casted = StorageNumpy(name="test_read_all") chunk = casted[slice(None, None, None)] self.assertTrue(np.allclose(chunk.view(np.ndarray), test_numpy)) casted.delete_persistent() def test_numpy_reserved_5d_read_all(self): nelem = 100000 elem_dim = 10 base_array = np.arange(nelem).reshape((elem_dim, elem_dim, elem_dim, elem_dim, elem_dim)) casted = StorageNumpy(input_array=base_array, name="test_5d_read_all") casted.sync() # Flush values to cassandra test_numpy = np.arange(nelem).reshape((elem_dim, elem_dim, elem_dim, elem_dim, elem_dim)) casted = StorageNumpy(name="test_5d_read_all") chunk = casted[slice(None, None, None)] self.assertTrue(np.allclose(chunk.view(np.ndarray), test_numpy)) casted.delete_persistent() def test_explicit_construct(self): # From an explicit constructor - e.g. InfoArray(): # obj is None # (we're in the middle of the InfoArray.__new__ # constructor, and self.info will be set when we return to # InfoArray.__new__) basic_init = StorageNumpy() def test_view_cast(self): # From view casting - e.g arr.view(InfoArray): # obj is arr # (type(obj) can be InfoArray) base_array = np.arange(4096).reshape((64, 64)) view_cast = base_array.view(StorageNumpy) def test_new_from_template(self): # From new-from-template - e.g infoarr[:3] # type(obj) is InfoArray base_array = np.arange(4096).reshape((64, 64)) basic_init = StorageNumpy(base_array) new_from_template = basic_init[:32] def test_new2_from_template(self): # From new-from-template - e.g infoarr[:3] # type(obj) is InfoArray base_array = np.arange(4096).reshape((64, 64)) basic_init = StorageNumpy(base_array) new_from_template = basic_init[32:] def test_get_subarray(self): base = np.arange(8 * 8 * 4).reshape((8, 8, 4)) hecu_p = StorageNumpy(input_array=base, name='test_get_subarray') hecu_p.sync() # Flush values to cassandra hecu_r2 = StorageNumpy(name="test_get_subarray") res = hecu_r2[:3, :2] sum = res.sum() res = hecu_r2[:3, :2] avg = res.mean() self.assertGreater(sum, 0) self.assertGreater(avg, 0) def test_slicing_3d(self): base = np.arange(8 * 8 * 4).reshape((8, 8, 4)) hecu = StorageNumpy(input_array=base, name='test_slicing_3d') res_hecu = hecu[6:7, 4:] res = base[6:7, 4:] self.assertTrue(np.array_equal(res, res_hecu)) hecu.sync() # Flush values to cassandra hecu = StorageNumpy(name="test_slicing_3d") res_hecu = hecu[6:7, 4:] self.assertTrue(np.array_equal(res, res_hecu)) hecu.delete_persistent() def test_slicing_ndims(self): import random ndims = 10 max_elements = 2048 for dims in range(1, ndims): elem_per_dim = int(max_elements ** (1 / dims)) select = (slice(random.randint(0, elem_per_dim)),) * dims base = np.arange(elem_per_dim ** dims).reshape((elem_per_dim,) * dims) hecu = StorageNumpy(input_array=base, name='test_slicing_ndims') res_hecu = hecu[select] res = base[select] self.assertTrue(np.array_equal(res, res_hecu)) hecu.sync() # Flush values to cassandra hecu = StorageNumpy(name="test_slicing_ndims") res_hecu = hecu[select] res = base[select] self.assertTrue(np.array_equal(res, res_hecu)) hecu.delete_persistent() del res_hecu del hecu def test_slice_ops(self): obj = np.arange(8 * 8 * 8).reshape((8, 8, 8)) hecu = StorageNumpy(input_array=obj, name='test_slice_ops') hecu_sub = hecu[:2, 3:, 4:] sum = hecu_sub.sum() self.assertGreater(sum, 0) description = repr(hecu_sub) self.assertIsInstance(description, str) hecu.delete_persistent() def test_slice_ops2(self): obj = np.arange(8 * 8 * 8).reshape((8, 8, 8)) hecu = StorageNumpy(input_array=obj, name='test_slice_ops2') hecu_sub = hecu[:2, 3:, 4:] hecu_sub2 = hecu_sub[:1, 2:, 3:] sum = hecu_sub2.sum() self.assertGreater(sum, 0) description = repr(hecu_sub2) self.assertIsInstance(description, str) hecu.delete_persistent() def test_slice_from_numpy_array(self): obj = np.arange(8 * 8 * 8).reshape((8, 8, 8)) hecu = StorageNumpy(input_array=obj, name='test_slice_numpy') l = np.array((0,1)) hecu_sub = hecu[l] #Access using an array of indexes # FIXME add more testing, currently if it does not segfault, then it works sum = hecu_sub.sum() self.assertEqual(sum, obj[l].sum()) hecu.delete_persistent() def test_iter_numpy(self): obj = np.arange(8 * 8 * 8).reshape((8, 8, 8)) hecu = StorageNumpy(input_array=obj, name='test_iter_numpy') acc = 0 for i in hecu: acc = acc + 1 hecu_sub = hecu[:2, 3:, 4:] acc2 = 0 for i in hecu_sub: acc2 = acc2 + 1 self.assertGreater(acc, acc2) hecu.delete_persistent() def test_assign_slice(self): base = np.arange(8 * 8 * 4).reshape((8, 8, 4)) hecu_p = StorageNumpy(input_array=base, name='test_assign_slice') sub_hecu = hecu_p[:2, 3:] sub_hecu[0][2:] = 0 hecu_p.sync() # Flush values to cassandra hecu_p_load = StorageNumpy(name="test_assign_slice") rep = repr(hecu_p_load) self.assertIsInstance(rep, str) # StorageNumpy in memory and in database should share data load_sub_arr = hecu_p_load[:] self.assertFalse(np.array_equal(load_sub_arr, np.arange(8 * 8 * 4).reshape((8, 8, 4)))) self.assertTrue(np.array_equal(sub_hecu, hecu_p_load[:2, 3:])) # Clean up hecu_p_load.delete_persistent() def test_assign_element(self): base = np.arange(8 * 8 * 4).reshape((8, 8, 4)) hecu_p = StorageNumpy(input_array=base, name='test_assign_element') sub_hecu = hecu_p[:2, 3:] sub_hecu[0][1][0] = 0 hecu_p.sync() hecu_p_load = StorageNumpy(name="test_assign_element") rep = repr(hecu_p_load) self.assertIsInstance(rep, str) load_sub_arr = hecu_p_load[:] self.assertFalse(np.array_equal(load_sub_arr, np.arange(8 * 8 * 4).reshape((8, 8, 4)))) sub_hecu_load = hecu_p_load[:2, 3:] self.assertTrue(sub_hecu_load[0][1][0] == 0) # Clean up hecu_p_load.delete_persistent() def test_load_2_dif_clusters_same_instance(self): base = np.arange(50 * 50).reshape((50, 50)) hecu_p = StorageNumpy(input_array=base, name='load_2_clustrs_same_inst') hecu_p.sync() # Flush values to cassandra hecu_p_load = StorageNumpy(name="load_2_clustrs_same_inst") hecu_p_load[0:1, 0:1] self.assertTrue(np.array_equal(hecu_p_load[40:50, 40:50], base[40:50, 40:50])) def test_split_by_rows(self): """ Tests iterating through the rows of the Hecuba array """ bn, bm = (1, 10) x = np.arange(100).reshape(10, -1) blocks = [] for i in range(0, x.shape[0], bn): row = [x[i: i + bn, j: j + bm] for j in range(0, x.shape[1], bm)] blocks.append(row) data = StorageNumpy(input_array=x, name="test_split_by_rows") data.sync() # Flush values to cassandra for i, chunk in enumerate(data.np_split(block_size=(bn, bm))): storage_id = chunk.storage_id chunk.sync() #Flush data del chunk chunk = getByID(storage_id) self.assertTrue(np.array_equal(list(chunk), blocks[i])) self.assertEqual(i + 1, len(blocks)) def test_split_by_columns(self): """ Tests iterating through the columns of the Hecuba array """ bn, bm = (10, 1) x = np.arange(100).reshape(10, -1) blocks = [] for i in range(0, x.shape[0], bn): row = [x[i: i + bn, j: j + bm] for j in range(0, x.shape[1], bm)] blocks.append(row) data = StorageNumpy(input_array=x, name="test_split_by_columns") data.sync() # Flush values to cassandra for i, chunk in enumerate(data.np_split(block_size=(bn, bm))): storage_id = chunk.storage_id chunk.sync() #Flush data del chunk chunk = getByID(storage_id) self.assertTrue(np.array_equal(list(chunk), blocks[i])) self.assertEqual(i + 1, len(blocks)) def test_split_rows_and_columns(self): bn, bm = (2, 1) x = np.arange(100).reshape(10, -1) blocks = [] for i in range(0, x.shape[0], bn): row = [x[i: i + bn, j: j + bm] for j in range(0, x.shape[1], bm)] blocks.append(row) data = StorageNumpy(input_array=x, name="test_split_rows_and_columns") data.sync() # Flush values to cassandra for i, chunk in enumerate(data.np_split(block_size=(bn, bm))): storage_id = chunk.storage_id chunk.sync() #Flush data del chunk chunk = getByID(storage_id) self.assertTrue(np.array_equal(list(chunk), blocks[i])) self.assertEqual(i + 1, len(blocks)) @unittest.skip("np_split is not maintained...") def test_split_already_persistent(self): bn, bm = (2, 1) x = np.arange(100).reshape(10, -1) blocks = [] for i in range(0, x.shape[0], bn): row = [x[i: i + bn, j: j + bm] for j in range(0, x.shape[1], bm)] blocks.append(row) data = StorageNumpy(input_array=x, name="test_split_already_persistent") data.sync() # Flush values to cassandra for i, chunk in enumerate(data.np_split(block_size=(bn, bm))): storage_id = chunk.storage_id chunk.sync() #Flush data del chunk chunk = getByID(storage_id) self.assertTrue(np.array_equal(list(chunk), blocks[i])) del data gc.collect() data = StorageNumpy(name="test_split_already_persistent") self.assertTrue(np.array_equal(list(data), x)) for i, chunk in enumerate(data.np_split(block_size=(bn, bm))): storage_id = chunk.storage_id chunk.sync() #Flush data del chunk chunk = getByID(storage_id) self.assertTrue(np.array_equal(list(chunk), blocks[i])) self.assertEqual(i + 1, len(blocks)) def test_storagenumpy_copy_memory(self): #''' #Check that the memory from a StorageNumpy does not share original array #''' n = np.arange(12).reshape(3,4) s1 = StorageNumpy(n, "test_storagenumpy_copy_memory") # StorageNumpy s1 and n should NOT share memory s1[0][0] = 42 self.assertTrue(not np.array_equal(s1, n)) s1[0][0] = n[0][0] # Undo n[2][2] = 666 self.assertTrue(not np.array_equal(s1, n)) # Clean up s1.delete_persistent() def test_storagenumpy_from_storagenumpy(self):
# coding: utf-8 """ Automated Tool for Optimized Modelling (ATOM) Author: Mavs Description: Unit tests for basetrainer.py """ from unittest.mock import patch import pytest from mlflow.tracking.fluent import ActiveRun from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score, make_scorer from skopt.callbacks import TimerCallback from skopt.space.space import Categorical, Integer from atom.training import DirectClassifier, DirectRegressor from atom.utils import CUSTOM_SCORERS, PlotCallback from .utils import ( bin_test, bin_train, class_test, class_train, mnist, reg_test, reg_train, ) # Test _prepare_metric ============================================= >> def test_invalid_sequence_parameter(): """Assert that an error is raised for parameters with the wrong length.""" trainer = DirectClassifier( models="LR", metric=f1_score, needs_proba=[True, False], random_state=1, ) with pytest.raises(ValueError, match=r".*length should be equal.*"): trainer.run(bin_train, bin_test) def test_metric_is_sklearn_scorer(): """Assert that using a sklearn SCORER works.""" trainer = DirectClassifier("LR", metric="balanced_accuracy", random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == "balanced_accuracy" def test_metric_is_acronym(): """Assert that using the metric acronyms work.""" trainer = DirectClassifier("LR", metric="auc", random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == "roc_auc" @pytest.mark.parametrize("metric", CUSTOM_SCORERS) def test_metric_is_custom(metric): """Assert that using the metric acronyms work.""" trainer = DirectClassifier("LR", metric=metric, random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == CUSTOM_SCORERS[metric].__name__ def test_metric_is_invalid_scorer_name(): """Assert that an error is raised when scorer name is invalid.""" trainer = DirectClassifier("LR", metric="test", random_state=1) pytest.raises(ValueError, trainer.run, bin_train, bin_test) def test_metric_is_function(): """Assert that a function metric works.""" trainer = DirectClassifier("LR", metric=f1_score, random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == "f1_score" def test_metric_is_scorer(): """Assert that a scorer metric works.""" trainer = DirectClassifier("LR", metric=make_scorer(f1_score), random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == "f1" # Test _prepare_parameters =========================================== >> def test_all_classification_models(): """Assert that the default value selects all models.""" trainer = DirectClassifier(models=None, random_state=1) trainer.run(bin_train, bin_test) assert len(trainer.models) + len(trainer.errors) == 29 def test_all_regression_models(): """Assert that the default value selects all models.""" trainer = DirectRegressor(models=None, random_state=1) trainer.run(reg_train, reg_test) assert len(trainer.models) + len(trainer.errors) == 27 def test_multidim_predefined_model(): """Assert that an error is raised for multidim datasets with predefined models.""" trainer = DirectClassifier("OLS", random_state=1) with pytest.raises(ValueError, match=r".*Multidimensional datasets are.*"): trainer.run(*mnist) def test_model_is_predefined(): """Assert that predefined models are accepted.""" trainer = DirectClassifier("LR", random_state=1) trainer.run(bin_train, bin_test) assert trainer.models == "LR" @patch.dict("sys.modules", {"lightgbm": None}) def test_package_not_installed(): """Assert that an error is raised when the model's package is not installed.""" trainer = DirectClassifier("LGB", random_state=1) with pytest.raises(ModuleNotFoundError, match=r".*Unable to import.*"): trainer.run(bin_train, bin_test) def test_model_is_custom(): """Assert that custom models are accepted.""" trainer = DirectClassifier(RandomForestClassifier, random_state=1) trainer.run(bin_train, bin_test) assert trainer.models == "RFC" def test_models_get_right_name(): """Assert that the model names are transformed to the correct acronyms.""" trainer = DirectClassifier(["lR", "tReE"], random_state=1) trainer.run(bin_train, bin_test) assert trainer.models == ["LR", "Tree"] def test_invalid_model_name(): """Assert that an error is raised when the model is unknown.""" trainer = DirectClassifier(models="invalid", random_state=1) with pytest.raises(ValueError, match=r".*Unknown model.*"): trainer.run(bin_train, bin_test) def test_multiple_same_models(): """Assert that the same model can used with different names.""" trainer = DirectClassifier(["lr", "lr2", "lr_3"], random_state=1) trainer.run(bin_train, bin_test) assert trainer.models == ["LR", "LR2", "LR_3"] def test_only_task_models(): """Assert that an error is raised for models at invalid task.""" trainer = DirectClassifier("OLS", random_state=1) # Only regression with pytest.raises(ValueError, match=r".*can't perform classification.*"): trainer.run(bin_train, bin_test) trainer = DirectRegressor("LDA", random_state=1) # Only classification with pytest.raises(ValueError, match=r".*can't perform regression.*"): trainer.run(reg_train, reg_test) def test_reruns(): """Assert that rerunning a trainer works.""" trainer = DirectClassifier(["lr", "lda"], random_state=1) trainer.run(bin_train, bin_test) trainer.run(bin_train, bin_test) def test_duplicate_models(): """Assert that an error is raised with duplicate models.""" trainer = DirectClassifier(["lr", "LR", "lgb"], random_state=1) with pytest.raises(ValueError, match=r".*duplicate models.*"): trainer.run(bin_train, bin_test) def test_default_metric(): """Assert that a default metric is assigned depending on the task.""" trainer = DirectClassifier("LR", random_state=1) trainer.run(bin_train, bin_test) assert trainer.metric == "f1" trainer = DirectClassifier("LR", random_state=1) trainer.run(class_train, class_test) assert trainer.metric == "f1_weighted" trainer = DirectRegressor("LGB", random_state=1) trainer.run(reg_train, reg_test) assert trainer.metric == "r2" def test_sequence_parameters_invalid_length(): """Assert that an error is raised when the length is invalid.""" trainer = DirectClassifier("LR", n_calls=(2, 2), random_state=1) with pytest.raises(ValueError, match=r".*Length should be equal.*"): trainer.run(bin_train, bin_test) @pytest.mark.parametrize("n_calls", [-2, 1]) def test_n_calls_parameter_is_invalid(n_calls): """Assert that an error is raised when n_calls=1 or <0.""" trainer = DirectClassifier("LR", n_calls=n_calls, random_state=1) with pytest.raises(ValueError, match=r".*n_calls parameter.*"): trainer.run(bin_train, bin_test) def test_n_initial_points_parameter_is_zero(): """Assert that an error is raised when n_initial_points=0.""" trainer = DirectClassifier("LR", n_calls=2, n_initial_points=0, random_state=1) with pytest.raises(ValueError, match=r".*n_initial_points parameter.*"): trainer.run(bin_train, bin_test) def test_n_bootstrap_parameter_is_below_zero(): """Assert that an error is raised when n_bootstrap<0.""" trainer = DirectClassifier("LR", n_bootstrap=-1, random_state=1) with pytest.raises(ValueError, match=r".*n_bootstrap parameter.*"): trainer.run(bin_train, bin_test) def test_est_params_all_models(): """Assert that est_params passes the parameters to all models.""" trainer = DirectClassifier( models=["RF", "ET"], n_calls=2, n_initial_points=1, est_params={"n_estimators": 20, "all": {"bootstrap": False}}, random_state=1, ) trainer.run(bin_train, bin_test) assert trainer.et.estimator.get_params()["n_estimators"] == 20 assert trainer.rf.estimator.get_params()["bootstrap"] is False def test_est_params_per_model(): """Assert that est_params passes the parameters per model.""" trainer = DirectClassifier( models=["XGB", "LGB"], est_params={"xgb": {"n_estimators": 15}, "lgb": {"n_estimators": 20}}, random_state=1, ) trainer.run(bin_train, bin_test) assert trainer.xgb.estimator.get_params()["n_estimators"] == 15 assert trainer.lgb.estimator.get_params()["n_estimators"] == 20 def test_est_params_default_method(): """Assert that custom parameters overwrite the default ones.""" trainer = DirectClassifier("RF", est_params={"n_jobs": 3}, random_state=1) trainer.run(bin_train, bin_test) assert trainer.rf.estimator.get_params()["n_jobs"] == 3 assert trainer.rf.estimator.get_params()["random_state"] == 1 @pytest.mark.parametrize("model", ["XGB", "LGB", "CatB"]) def test_est_params_for_fit(model): """Assert that est_params is used for fit if ends in _fit.""" trainer = DirectClassifier( models=model, est_params={"early_stopping_rounds_fit": 2}, random_state=1, ) trainer.run(bin_train, bin_test) assert getattr(trainer, model)._stopped != ("---", "---") def test_est_params_unknown_param(): """Assert that unknown parameters in est_params are caught.""" trainer = DirectClassifier( models=["LR", "LGB"], n_calls=5, est_params={"test": 220}, random_state=1, ) trainer.run(bin_train, bin_test) assert list(trainer.errors.keys()) == ["LR"] # LGB passes since it accepts kwargs def test_est_params_unknown_param_fit(): """Assert that unknown parameters in est_params_fit are caught.""" trainer = DirectClassifier( models=["LR", "LGB"], est_params={"test_fit": 220}, random_state=1, ) with pytest.raises(RuntimeError): trainer.run(bin_train, bin_test) def test_base_estimator_default(): """Assert that GP is the default base estimator.""" trainer = DirectClassifier("LR", n_calls=5, random_state=1) trainer.run(bin_train, bin_test) assert trainer._bo["base_estimator"] == "GP" def test_base_estimator_invalid(): """Assert that an error is raised when the base estimator is invalid.""" trainer = DirectClassifier("LR", bo_params={"base_estimator": "u"}, random_state=1) with pytest.raises(ValueError, match=r".*base_estimator parameter.*"): trainer.run(bin_train, bin_test) @pytest.mark.parametrize("callback", [TimerCallback(), [TimerCallback()]]) def test_callback(callback): """Assert that custom callbacks are accepted.""" trainer = DirectClassifier( models="LR", n_calls=2, n_initial_points=2, bo_params={"callback": callback}, random_state=1, ) trainer.run(bin_train, bin_test) def test_all_callbacks(): """Assert that all predefined callbacks work as intended.""" trainer = DirectClassifier( models="LR", n_calls=2, n_initial_points=2, bo_params={"max_time": 50, "delta_x": 5, "delta_y": 5}, random_state=1, ) trainer.run(bin_train, bin_test) def test_invalid_max_time(): """Assert than an error is raised when max_time<=0.""" trainer = DirectClassifier("LR", bo_params={"max_time": 0}, random_state=1) with pytest.raises(ValueError, match=r".*max_time parameter.*"): trainer.run(bin_train, bin_test) def test_invalid_delta_x(): """Assert than an error is raised when delta_x<0.""" trainer = DirectClassifier("LR", bo_params={"delta_x": -2}, random_state=1) with pytest.raises(ValueError, match=r".*delta_x parameter.*"): trainer.run(bin_train, bin_test) def test_invalid_delta_y(): """Assert than an error is raised when delta_y<0.""" trainer = DirectClassifier("LR", bo_params={"delta_y": -2}, random_state=1) with pytest.raises(ValueError, match=r".*delta_y parameter.*"): trainer.run(bin_train, bin_test) def test_plot(): """Assert that plotting the BO runs without errors.""" trainer = DirectClassifier( models=["lSVM", "kSVM", "MLP"], n_calls=(17, 17, 40), n_initial_points=8, bo_params={"plot": True}, random_state=1, ) trainer.run(bin_train, bin_test) def test_invalid_cv(): """Assert than an error is raised when cv<=0.""" trainer = DirectClassifier("LR", bo_params={"cv": 0}, random_state=1) with pytest.raises(ValueError, match=r".*cv parameter.*"): trainer.run(bin_train, bin_test) def test_invalid_early_stopping(): """Assert than an error is raised when early_stopping<=0.""" trainer = DirectClassifier("LR", bo_params={"early_stopping": -1}, random_state=1) with pytest.raises(ValueError, match=r".*early_stopping parameter.*"): trainer.run(bin_train, bin_test) def test_custom_dimensions_is_list(): """Assert that the custom dimensions are for all models if list.""" trainer = DirectClassifier( models="LR", n_calls=2, n_initial_points=2, bo_params={"dimensions": [Integer(10, 20, name="max_iter")]}, random_state=1, ) trainer.run(bin_train, bin_test) assert list(trainer.lr.best_params) == ["max_iter"] def test_custom_dimensions_is_all(): """Assert that the custom dimensions can be set for all models.""" trainer = DirectClassifier( models=["LR1", "LR2"], n_calls=2, n_initial_points=2, bo_params={ "dimensions": { "all": [Integer(10, 20, name="max_iter")], "LR2": Categorical(["l1", "l2"], name="penalty"), }, }, random_state=1, ) trainer.run(bin_train, bin_test) assert list(trainer.lr1.best_params) == ["max_iter"] assert list(trainer.lr2.best_params) == ["max_iter", "penalty"] def test_custom_dimensions_per_model(): """Assert that the custom dimensions are distributed over the models.""" trainer = DirectClassifier( models=["LR1", "LR2"], n_calls=2, n_initial_points=2, bo_params={ "dimensions": { "lr1": [Integer(100, 200, name="max_iter")], "lr2": [Integer(300, 400, name="max_iter")], }, }, random_state=1, ) trainer.run(bin_train, bin_test) assert 100 <= trainer.lr1.best_params["max_iter"] <= 200 assert 300 <= trainer.lr2.best_params["max_iter"] <= 400 def test_optimizer_kwargs(): """Assert that the kwargs provided are passed to the optimizer.""" trainer = DirectClassifier( models="LR", n_calls=2, n_initial_points=2, bo_params={"acq_func": "EI"}, random_state=1, ) trainer.run(bin_train, bin_test) assert trainer._bo["kwargs"].get("acq_func") == "EI" # Test _core_iteration ============================================= >> def test_sequence_parameters(): """Assert that every model get his corresponding parameters.""" trainer = DirectClassifier( models=["LR", "Tree", "LGB"], n_calls=(2, 3, 4), n_initial_points=(1, 2, 3), n_bootstrap=[2, 5, 7], random_state=1, ) trainer.run(bin_train, bin_test) assert len(trainer.LR.bo) == 2 assert sum(trainer.tree.bo["call"].str.startswith("Initial")) == 2 assert len(trainer.lgb.metric_bootstrap) == 7 def test_custom_dimensions_for_bo(): """Assert that the BO runs when custom dimensions are provided.""" trainer = DirectRegressor( models="OLS", n_calls=5, bo_params={"dimensions": [Categorical([True, False], name="fit_intercept")]}, random_state=1, ) trainer.run(reg_train, reg_test) assert not trainer.ols.bo.empty def test_mlflow_run_is_started(): """Assert that a mlflow run starts with the run method.""" trainer = DirectRegressor(models="OLS", experiment="test", random_state=1) trainer.run(reg_train, reg_test) assert isinstance(trainer.ols._run, ActiveRun) def test_error_handling(): """Assert that models with errors are removed from the pipeline.""" trainer = DirectClassifier( models=["LR", "LDA"], n_calls=4, n_initial_points=[2, 5], random_state=1, ) trainer.run(bin_train, bin_test) assert trainer.errors.get("LDA") assert "LDA" not in
def visit_Lambda(self, node): # Like FunctionDef, but without the decorator_list or name. assert node._fields == ('args', 'body'), node._fields with self._NewScopeCtx(include_class_scopes=True): self.visit(node.args) old_in_FunctionDef = self._in_FunctionDef self._in_FunctionDef = True with self._NewScopeCtx(): self.visit(node.body) self._in_FunctionDef = old_in_FunctionDef def _visit_typecomment(self, typecomment): if typecomment is None: return node = ast.parse(typecomment) self.visit(node) def visit_arguments(self, node): if PY2: assert node._fields == ('args', 'vararg', 'kwarg', 'defaults'), node._fields elif sys.version_info >= (3, 8): assert node._fields == ('posonlyargs', 'args', 'vararg', 'kwonlyargs', 'kw_defaults', 'kwarg', 'defaults'), node._fields else: assert node._fields == ('args', 'vararg', 'kwonlyargs', 'kw_defaults', 'kwarg', 'defaults'), node._fields # Argument/parameter list. Note that the defaults should be # considered "Load"s from the upper scope, and the argument names are # "Store"s in the function scope. # E.g. consider: # def f(x=y, y=x): pass # Both x and y should be considered undefined (unless they were indeed # defined before the def). # We assume visit_arguments is always called from a _NewScopeCtx # context with self._UpScopeCtx(): self.visit(node.defaults) if PY3: for i in node.kw_defaults: if i: self.visit(i) # Store arg names. self.visit(node.args) if PY3: self.visit(node.kwonlyargs) if sys.version_info >= (3, 8): self.visit(node.posonlyargs) # Store vararg/kwarg names. self._visit_Store(node.vararg) self._visit_Store(node.kwarg) def visit_ExceptHandler(self, node): assert node._fields == ('type', 'name', 'body') if node.type: self.visit(node.type) if node.name: # ExceptHandler.name is a string in Python 3 and a Name with Store in # Python 2 if PY3: self._visit_Store(node.name) else: self.visit(node.name) self.visit(node.body) def visit_Dict(self, node): assert node._fields == ('keys', 'values') # In Python 3, keys can be None, indicating a ** expression for key in node.keys: if key: self.visit(key) self.visit(node.values) def visit_comprehension(self, node): # Visit a "comprehension" node, which is a component of list # comprehensions and generator expressions. self.visit(node.iter) def visit_target(target): if isinstance(target, ast.Name): self._visit_Store(target.id) elif isinstance(target, (ast.Tuple, ast.List)): for elt in target.elts: visit_target(elt) else: # Unusual stuff like: # [f(x) for x[0] in mylist] # [f(x) for x.foo in mylist] # [f(x) for x.foo[0].foo in mylist] self.visit(target) visit_target(node.target) self.visit(node.ifs) def visit_ListComp(self, node): # Visit a list comprehension node. # This is basically the same as the generic visit, except that we # visit the comprehension node(s) before the elt node. # (generic_visit() would visit the elt first, because that comes first # in ListComp._fields). # For Python2, we intentionally don't enter a new scope here, because # a list comprehensive _does_ leak variables out of its scope (unlike # generator expressions). # For Python3, we do need to enter a new scope here. if PY3: with self._NewScopeCtx(include_class_scopes=True): self.visit(node.generators) self.visit(node.elt) else: self.visit(node.generators) self.visit(node.elt) def visit_DictComp(self, node): # Visit a dict comprehension node. # This is similar to the generic visit, except: # - We visit the comprehension node(s) before the elt node. # - We create a new scope for the variables. # We do enter a new scope (for both py2 and py3). A dict comprehension # does _not_ leak variables out of its scope (unlike py2 list # comprehensions). with self._NewScopeCtx(include_class_scopes=True): self.visit(node.generators) self.visit(node.key) self.visit(node.value) def visit_SetComp(self, node): # Visit a set comprehension node. # We do enter a new scope (for both py2 and py3). A set comprehension # does _not_ leak variables out of its scope (unlike py2 list # comprehensions). with self._NewScopeCtx(include_class_scopes=True): self.visit(node.generators) self.visit(node.elt) def visit_GeneratorExp(self, node): # Visit a generator expression node. # We do enter a new scope (for both py2 and py3). A generator # expression does _not_ leak variables out of its scope (unlike py2 # list comprehensions). with self._NewScopeCtx(include_class_scopes=True): self.visit(node.generators) self.visit(node.elt) def visit_ImportFrom(self, node): modulename = "." * node.level + (node.module or "") logger.debug("visit_ImportFrom(%r, ...)", modulename) for alias_node in node.names: self.visit_alias(alias_node, modulename) def visit_alias(self, node, modulename=None): # Visit an import alias node. # TODO: Currently we treat 'import foo' the same as if the user did # 'foo = 123', i.e. we treat it as a black box (non-module). This is # to avoid actually importing it yet. But this means we won't know # whether foo.bar is available so we won't auto-import it. Maybe we # should give up on not importing it and just import it in a scratch # namespace, so we can check. self._visit_StoreImport(node, modulename) self.generic_visit(node) def visit_Name(self, node): logger.debug("visit_Name(%r)", node.id) self._visit_fullname(node.id, node.ctx) def visit_arg(self, node): assert not PY2 if sys.version_info >= (3, 8): assert node._fields == ('arg', 'annotation', 'type_comment'), node._fields else: assert node._fields == ('arg', 'annotation'), node._fields if node.annotation: self.visit(node.annotation) # Treat it like a Name node would from Python 2 self._visit_fullname(node.arg, ast.Param()) if sys.version_info >= (3, 8): self._visit_typecomment(node.type_comment) def visit_Attribute(self, node): name_revparts = [] n = node while isinstance(n, ast.Attribute): name_revparts.append(n.attr) n = n.value if not isinstance(n, ast.Name): # Attribute of a non-symbol, e.g. (a+b).c # We do nothing about "c", but we do recurse on (a+b) since those # may have symbols we care about. self.generic_visit(node) return name_revparts.append(n.id) name_parts = name_revparts[::-1] fullname = ".".join(name_parts) logger.debug("visit_Attribute(%r): fullname=%r, ctx=%r", node.attr, fullname, node.ctx) self._visit_fullname(fullname, node.ctx) def _visit_fullname(self, fullname, ctx): if isinstance(ctx, (ast.Store, ast.Param)): self._visit_Store(fullname) elif isinstance(ctx, ast.Load): self._visit_Load(fullname) def _visit_StoreImport(self, node, modulename): name = node.asname or node.name logger.debug("_visit_StoreImport(asname=%r,name=%r)", node.asname, node.name) is_star = node.name == '*' if is_star: logger.debug("Got star import: line %s: 'from %s import *'", self._lineno, modulename) if not node.asname and not is_star: # Handle leading prefixes so we don't think they're unused for prefix in DottedIdentifier(node.name).prefixes[:-1]: self._visit_Store(str(prefix), None) if self.unused_imports is None or is_star or modulename == "__future__": value = None else: imp = Import.from_split((modulename, node.name, name)) logger.debug("_visit_StoreImport(): imp = %r", imp) # Keep track of whether we've used this import. value = _UseChecker(name, imp, self._lineno) self._visit_Store(name, value) def _visit_Store(self, fullname, value=None): logger.debug("_visit_Store(%r)", fullname) if fullname is None: return scope = self.scopestack[-1] if PY3 and isinstance(fullname, ast.arg): fullname = fullname.arg if self.unused_imports is not None: if fullname != '*': # If we're storing "foo.bar.baz = 123", then "foo" and # "foo.bar" have now been used and the import should not be # removed. for ancestor in DottedIdentifier(fullname).prefixes[:-1]: if symbol_needs_import(ancestor, self.scopestack): m = (self._lineno, DottedIdentifier(fullname)) if m not in self.missing_imports: self.missing_imports.append(m) # If we're redefining something, and it has not been used, then # record it as unused. oldvalue = scope.get(fullname) if isinstance(oldvalue, _UseChecker) and not oldvalue.used: self.unused_imports.append((oldvalue.lineno, oldvalue.source)) scope[fullname] = value def visit_Delete(self, node): scope = self.scopestack[-1] for target in node.targets: if isinstance(target, ast.Name): # 'del foo' if target.id not in scope: # 'del x' without 'x' in current scope. Should we warn? continue del scope[target.id] elif isinstance(target, ast.Attribute): # 'del foo.bar.baz', 'del foo().bar', etc # We ignore the 'del ...bar' part and just visit the # left-hand-side of the delattr. We need to do this explicitly # instead of relying on a generic_visit on ``node`` itself. # Reason: We want visit_Attribute to process a getattr for # 'foo.bar'. self.visit(target.value) else: # 'del foo.bar[123]' (ast.Subscript), etc. # We can generically-visit the entire target node here. self.visit(target) # Don't call generic_visit(node) here. Reason: We already visit the # parts above, if relevant. def _visit_Load(self, fullname): logger.debug("_visit_Load(%r)", fullname) if self._in_FunctionDef: # We're in a FunctionDef. We need to defer checking whether this # references undefined names. The reason is that globals (or # stores in a parent function scope) may be stored later. # For example, bar() is defined later after the body of foo(), but # still available to foo() when it is called: # def foo(): # return bar() # def bar(): # return 42 # foo() # To support this, we clone the top of the scope stack and alias # the other scopes in the stack. Later stores in the same scope # shouldn't count, e.g. x should be considered undefined in the # following example: # def foo(): # print x # x = 1 # On the other hand, we intentionally alias the other scopes # rather than cloning them, because the point is to allow them to # be modified until we do the check at the end. if symbol_needs_import(fullname, self.scopestack): data
# regression test dla SAX 2.0 # $Id$ z xml.sax zaimportuj make_parser, ContentHandler, \ SAXException, SAXReaderNotAvailable, SAXParseException zaimportuj unittest spróbuj: make_parser() wyjąwszy SAXReaderNotAvailable: # don't try to test this module jeżeli we cannot create a parser podnieś unittest.SkipTest("no XML parsers available") z xml.sax.saxutils zaimportuj XMLGenerator, escape, unescape, quoteattr, \ XMLFilterBase, prepare_input_source z xml.sax.expatreader zaimportuj create_parser z xml.sax.handler zaimportuj feature_namespaces z xml.sax.xmlreader zaimportuj InputSource, AttributesImpl, AttributesNSImpl z io zaimportuj BytesIO, StringIO zaimportuj codecs zaimportuj gc zaimportuj os.path zaimportuj shutil z test zaimportuj support z test.support zaimportuj findfile, run_unittest, TESTFN TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata") TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata") spróbuj: TEST_XMLFILE.encode("utf-8") TEST_XMLFILE_OUT.encode("utf-8") wyjąwszy UnicodeEncodeError: podnieś unittest.SkipTest("filename jest nie encodable to utf8") supports_nonascii_filenames = Prawda jeżeli nie os.path.supports_unicode_filenames: spróbuj: support.TESTFN_UNICODE.encode(support.TESTFN_ENCODING) wyjąwszy (UnicodeError, TypeError): # Either the file system encoding jest Nic, albo the file name # cannot be encoded w the file system encoding. supports_nonascii_filenames = Nieprawda requires_nonascii_filenames = unittest.skipUnless( supports_nonascii_filenames, 'Requires non-ascii filenames support') ns_uri = "http://www.python.org/xml-ns/saxtest/" klasa XmlTestBase(unittest.TestCase): def verify_empty_attrs(self, attrs): self.assertRaises(KeyError, attrs.getValue, "attr") self.assertRaises(KeyError, attrs.getValueByQName, "attr") self.assertRaises(KeyError, attrs.getNameByQName, "attr") self.assertRaises(KeyError, attrs.getQNameByName, "attr") self.assertRaises(KeyError, attrs.__getitem__, "attr") self.assertEqual(attrs.getLength(), 0) self.assertEqual(attrs.getNames(), []) self.assertEqual(attrs.getQNames(), []) self.assertEqual(len(attrs), 0) self.assertNotIn("attr", attrs) self.assertEqual(list(attrs.keys()), []) self.assertEqual(attrs.get("attrs"), Nic) self.assertEqual(attrs.get("attrs", 25), 25) self.assertEqual(list(attrs.items()), []) self.assertEqual(list(attrs.values()), []) def verify_empty_nsattrs(self, attrs): self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr")) self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr") self.assertRaises(KeyError, attrs.getNameByQName, "ns:attr") self.assertRaises(KeyError, attrs.getQNameByName, (ns_uri, "attr")) self.assertRaises(KeyError, attrs.__getitem__, (ns_uri, "attr")) self.assertEqual(attrs.getLength(), 0) self.assertEqual(attrs.getNames(), []) self.assertEqual(attrs.getQNames(), []) self.assertEqual(len(attrs), 0) self.assertNotIn((ns_uri, "attr"), attrs) self.assertEqual(list(attrs.keys()), []) self.assertEqual(attrs.get((ns_uri, "attr")), Nic) self.assertEqual(attrs.get((ns_uri, "attr"), 25), 25) self.assertEqual(list(attrs.items()), []) self.assertEqual(list(attrs.values()), []) def verify_attrs_wattr(self, attrs): self.assertEqual(attrs.getLength(), 1) self.assertEqual(attrs.getNames(), ["attr"]) self.assertEqual(attrs.getQNames(), ["attr"]) self.assertEqual(len(attrs), 1) self.assertIn("attr", attrs) self.assertEqual(list(attrs.keys()), ["attr"]) self.assertEqual(attrs.get("attr"), "val") self.assertEqual(attrs.get("attr", 25), "val") self.assertEqual(list(attrs.items()), [("attr", "val")]) self.assertEqual(list(attrs.values()), ["val"]) self.assertEqual(attrs.getValue("attr"), "val") self.assertEqual(attrs.getValueByQName("attr"), "val") self.assertEqual(attrs.getNameByQName("attr"), "attr") self.assertEqual(attrs["attr"], "val") self.assertEqual(attrs.getQNameByName("attr"), "attr") def xml_str(doc, encoding=Nic): jeżeli encoding jest Nic: zwróć doc zwróć '<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc) def xml_bytes(doc, encoding, decl_encoding=...): jeżeli decl_encoding jest ...: decl_encoding = encoding zwróć xml_str(doc, decl_encoding).encode(encoding, 'xmlcharrefreplace') def make_xml_file(doc, encoding, decl_encoding=...): jeżeli decl_encoding jest ...: decl_encoding = encoding przy open(TESTFN, 'w', encoding=encoding, errors='xmlcharrefreplace') jako f: f.write(xml_str(doc, decl_encoding)) klasa ParseTest(unittest.TestCase): data = '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>' def tearDown(self): support.unlink(TESTFN) def check_parse(self, f): z xml.sax zaimportuj parse result = StringIO() parse(f, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) def test_parse_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') dla encoding w encodings: self.check_parse(StringIO(xml_str(self.data, encoding))) make_xml_file(self.data, encoding) przy open(TESTFN, 'r', encoding=encoding) jako f: self.check_parse(f) self.check_parse(StringIO(self.data)) make_xml_file(self.data, encoding, Nic) przy open(TESTFN, 'r', encoding=encoding) jako f: self.check_parse(f) def test_parse_bytes(self): # UTF-8 jest default encoding, US-ASCII jest compatible przy UTF-8, # UTF-16 jest autodetected encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') dla encoding w encodings: self.check_parse(BytesIO(xml_bytes(self.data, encoding))) make_xml_file(self.data, encoding) self.check_parse(TESTFN) przy open(TESTFN, 'rb') jako f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, encoding, Nic))) make_xml_file(self.data, encoding, Nic) self.check_parse(TESTFN) przy open(TESTFN, 'rb') jako f: self.check_parse(f) # accept UTF-8 przy BOM self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', 'utf-8'))) make_xml_file(self.data, 'utf-8-sig', 'utf-8') self.check_parse(TESTFN) przy open(TESTFN, 'rb') jako f: self.check_parse(f) self.check_parse(BytesIO(xml_bytes(self.data, 'utf-8-sig', Nic))) make_xml_file(self.data, 'utf-8-sig', Nic) self.check_parse(TESTFN) przy open(TESTFN, 'rb') jako f: self.check_parse(f) # accept data przy declared encoding self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1'))) make_xml_file(self.data, 'iso-8859-1') self.check_parse(TESTFN) przy open(TESTFN, 'rb') jako f: self.check_parse(f) # fail on non-UTF-8 incompatible data without declared encoding przy self.assertRaises(SAXException): self.check_parse(BytesIO(xml_bytes(self.data, 'iso-8859-1', Nic))) make_xml_file(self.data, 'iso-8859-1', Nic) przy support.check_warnings(('unclosed file', ResourceWarning)): # XXX Failed parser leaks an opened file. przy self.assertRaises(SAXException): self.check_parse(TESTFN) # Collect leaked file. gc.collect() przy open(TESTFN, 'rb') jako f: przy self.assertRaises(SAXException): self.check_parse(f) def test_parse_InputSource(self): # accept data without declared but przy explicitly specified encoding make_xml_file(self.data, 'iso-8859-1', Nic) przy open(TESTFN, 'rb') jako f: input = InputSource() input.setByteStream(f) input.setEncoding('iso-8859-1') self.check_parse(input) def check_parseString(self, s): z xml.sax zaimportuj parseString result = StringIO() parseString(s, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) def test_parseString_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') dla encoding w encodings: self.check_parseString(xml_str(self.data, encoding)) self.check_parseString(self.data) def test_parseString_bytes(self): # UTF-8 jest default encoding, US-ASCII jest compatible przy UTF-8, # UTF-16 jest autodetected encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') dla encoding w encodings: self.check_parseString(xml_bytes(self.data, encoding)) self.check_parseString(xml_bytes(self.data, encoding, Nic)) # accept UTF-8 przy BOM self.check_parseString(xml_bytes(self.data, 'utf-8-sig', 'utf-8')) self.check_parseString(xml_bytes(self.data, 'utf-8-sig', Nic)) # accept data przy declared encoding self.check_parseString(xml_bytes(self.data, 'iso-8859-1')) # fail on non-UTF-8 incompatible data without declared encoding przy self.assertRaises(SAXException): self.check_parseString(xml_bytes(self.data, 'iso-8859-1', Nic)) klasa MakeParserTest(unittest.TestCase): def test_make_parser2(self): # Creating parsers several times w a row should succeed. # Testing this because there have been failures of this kind # before. z xml.sax zaimportuj make_parser p = make_parser() z xml.sax zaimportuj make_parser p = make_parser() z xml.sax zaimportuj make_parser p = make_parser() z xml.sax zaimportuj make_parser p = make_parser() z xml.sax zaimportuj make_parser p = make_parser() z xml.sax zaimportuj make_parser p = make_parser() # =========================================================================== # # saxutils tests # # =========================================================================== klasa SaxutilsTest(unittest.TestCase): # ===== escape def test_escape_basic(self): self.assertEqual(escape("Donald Duck & Co"), "Donald Duck &amp; Co") def test_escape_all(self): self.assertEqual(escape("<Donald Duck & Co>"), "&lt;Donald Duck &amp; Co&gt;") def test_escape_extra(self): self.assertEqual(escape("Hei på deg", {"å" : "&aring;"}), "Hei p&aring; deg") # ===== unescape def test_unescape_basic(self): self.assertEqual(unescape("Donald Duck &amp; Co"), "Donald Duck & Co") def test_unescape_all(self): self.assertEqual(unescape("&lt;Donald Duck &amp; Co&gt;"), "<Donald Duck & Co>") def test_unescape_extra(self): self.assertEqual(unescape("Hei på deg", {"å" : "&aring;"}), "Hei p&aring; deg") def test_unescape_amp_extra(self): self.assertEqual(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;") # ===== quoteattr def test_quoteattr_basic(self): self.assertEqual(quoteattr("Donald Duck & Co"), '"Donald Duck &amp; Co"') def test_single_quoteattr(self): self.assertEqual(quoteattr('Includes "double" quotes'), '\'Includes "double" quotes\'') def test_double_quoteattr(self): self.assertEqual(quoteattr("Includes 'single' quotes"), "\"Includes 'single' quotes\"") def test_single_double_quoteattr(self): self.assertEqual(quoteattr("Includes 'single' oraz \"double\" quotes"), "\"Includes 'single' oraz &quot;double&quot; quotes\"") # ===== make_parser def test_make_parser(self): # Creating a parser should succeed - it should fall back # to the expatreader p = make_parser(['xml.parsers.no_such_parser']) klasa PrepareInputSourceTest(unittest.TestCase): def setUp(self): self.file = support.TESTFN przy open(self.file, "w") jako tmp: tmp.write("This was read z a file.") def tearDown(self): support.unlink(self.file) def make_byte_stream(self): zwróć BytesIO(b"This jest a byte stream.") def make_character_stream(self): zwróć StringIO("This jest a character stream.") def checkContent(self, stream, content): self.assertIsNotNic(stream) self.assertEqual(stream.read(), content) stream.close() def test_character_stream(self): # If the source jest an InputSource przy a character stream, use it. src = InputSource(self.file) src.setCharacterStream(self.make_character_stream()) prep = prepare_input_source(src) self.assertIsNic(prep.getByteStream()) self.checkContent(prep.getCharacterStream(), "This jest a character stream.") def test_byte_stream(self): # If the source jest an InputSource that does nie have a character # stream but does have a byte stream, use the byte stream. src = InputSource(self.file) src.setByteStream(self.make_byte_stream()) prep = prepare_input_source(src) self.assertIsNic(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This jest a byte stream.") def test_system_id(self): # If the source jest an InputSource that has neither a character # stream nor a byte stream, open the system ID. src = InputSource(self.file) prep = prepare_input_source(src) self.assertIsNic(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This was read z a file.") def test_string(self): # If the source jest a string, use it jako a system ID oraz open it. prep = prepare_input_source(self.file) self.assertIsNic(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This was read z a file.") def test_binary_file(self): # If the source jest a binary file-like object, use it jako a byte # stream. prep = prepare_input_source(self.make_byte_stream()) self.assertIsNic(prep.getCharacterStream()) self.checkContent(prep.getByteStream(), b"This jest a byte stream.") def test_text_file(self): # If the source jest a text file-like object, use it jako a character # stream. prep = prepare_input_source(self.make_character_stream()) self.assertIsNic(prep.getByteStream()) self.checkContent(prep.getCharacterStream(), "This jest a character stream.") # ===== XMLGenerator klasa XmlgenTest: def test_xmlgen_basic(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc></doc>")) def test_xmlgen_basic_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=Prawda) gen.startDocument() gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc/>")) def test_xmlgen_content(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.characters("huhei") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>huhei</doc>")) def test_xmlgen_content_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=Prawda) gen.startDocument() gen.startElement("doc", {}) gen.characters("huhei") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>huhei</doc>")) def test_xmlgen_pi(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.processingInstruction("test", "data") gen.startElement("doc", {}) gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<?test data?><doc></doc>")) def test_xmlgen_content_escape(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.characters("<huhei&") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml("<doc>&lt;huhei&amp;</doc>")) def test_xmlgen_attr_escape(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {"a": '"'}) gen.startElement("e", {"a": "'"}) gen.endElement("e") gen.startElement("e", {"a": "'\""}) gen.endElement("e") gen.startElement("e", {"a": "\n\r\t"}) gen.endElement("e") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml( "<doc a='\"'><e a=\"'\"></e>" "<e a=\"'&quot;\"></e>" "<e a=\"&#10;&#13;&#9;\"></e></doc>")) def test_xmlgen_encoding(self): encodings = ('iso-8859-15', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'utf-32', 'utf-32be', 'utf-32le') dla encoding w encodings: result = self.ioclass() gen = XMLGenerator(result, encoding=encoding) gen.startDocument() gen.startElement("doc", {"a": '\u20ac'}) gen.characters("\u20ac") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<doc a="\u20ac">\u20ac</doc>', encoding=encoding)) def test_xmlgen_unencodable(self): result = self.ioclass() gen = XMLGenerator(result, encoding='ascii') gen.startDocument() gen.startElement("doc", {"a": '\u20ac'}) gen.characters("\u20ac") gen.endElement("doc") gen.endDocument() self.assertEqual(result.getvalue(), self.xml('<doc a="&#8364;">&#8364;</doc>', encoding='ascii')) def test_xmlgen_ignorable(self): result = self.ioclass() gen = XMLGenerator(result) gen.startDocument() gen.startElement("doc", {}) gen.ignorableWhitespace(" ") gen.endElement("doc") gen.endDocument()
<gh_stars>1-10 # Generated from SQLParser.g4 by ANTLR 4.9.3 from antlr4 import * if __name__ is not None and "." in __name__: from .SQLParser import SQLParser else: from SQLParser import SQLParser """ Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ # mypy: ignore-errors from jasmine.sql.parser.sql_base import * # This class defines a complete listener for a parse tree produced by SQLParser. class SQLParserListener(ParseTreeListener): # Enter a parse tree produced by SQLParser#sqlProgram. def enterSqlProgram(self, ctx:SQLParser.SqlProgramContext): pass # Exit a parse tree produced by SQLParser#sqlProgram. def exitSqlProgram(self, ctx:SQLParser.SqlProgramContext): pass # Enter a parse tree produced by SQLParser#statement. def enterStatement(self, ctx:SQLParser.StatementContext): pass # Exit a parse tree produced by SQLParser#statement. def exitStatement(self, ctx:SQLParser.StatementContext): pass # Enter a parse tree produced by SQLParser#simpleStatement. def enterSimpleStatement(self, ctx:SQLParser.SimpleStatementContext): pass # Exit a parse tree produced by SQLParser#simpleStatement. def exitSimpleStatement(self, ctx:SQLParser.SimpleStatementContext): pass # Enter a parse tree produced by SQLParser#alterStatement. def enterAlterStatement(self, ctx:SQLParser.AlterStatementContext): pass # Exit a parse tree produced by SQLParser#alterStatement. def exitAlterStatement(self, ctx:SQLParser.AlterStatementContext): pass # Enter a parse tree produced by SQLParser#alterDatabase. def enterAlterDatabase(self, ctx:SQLParser.AlterDatabaseContext): pass # Exit a parse tree produced by SQLParser#alterDatabase. def exitAlterDatabase(self, ctx:SQLParser.AlterDatabaseContext): pass # Enter a parse tree produced by SQLParser#alterEvent. def enterAlterEvent(self, ctx:SQLParser.AlterEventContext): pass # Exit a parse tree produced by SQLParser#alterEvent. def exitAlterEvent(self, ctx:SQLParser.AlterEventContext): pass # Enter a parse tree produced by SQLParser#alterLogfileGroup. def enterAlterLogfileGroup(self, ctx:SQLParser.AlterLogfileGroupContext): pass # Exit a parse tree produced by SQLParser#alterLogfileGroup. def exitAlterLogfileGroup(self, ctx:SQLParser.AlterLogfileGroupContext): pass # Enter a parse tree produced by SQLParser#alterLogfileGroupOptions. def enterAlterLogfileGroupOptions(self, ctx:SQLParser.AlterLogfileGroupOptionsContext): pass # Exit a parse tree produced by SQLParser#alterLogfileGroupOptions. def exitAlterLogfileGroupOptions(self, ctx:SQLParser.AlterLogfileGroupOptionsContext): pass # Enter a parse tree produced by SQLParser#alterLogfileGroupOption. def enterAlterLogfileGroupOption(self, ctx:SQLParser.AlterLogfileGroupOptionContext): pass # Exit a parse tree produced by SQLParser#alterLogfileGroupOption. def exitAlterLogfileGroupOption(self, ctx:SQLParser.AlterLogfileGroupOptionContext): pass # Enter a parse tree produced by SQLParser#alterServer. def enterAlterServer(self, ctx:SQLParser.AlterServerContext): pass # Exit a parse tree produced by SQLParser#alterServer. def exitAlterServer(self, ctx:SQLParser.AlterServerContext): pass # Enter a parse tree produced by SQLParser#alterTable. def enterAlterTable(self, ctx:SQLParser.AlterTableContext): pass # Exit a parse tree produced by SQLParser#alterTable. def exitAlterTable(self, ctx:SQLParser.AlterTableContext): pass # Enter a parse tree produced by SQLParser#alterTableActions. def enterAlterTableActions(self, ctx:SQLParser.AlterTableActionsContext): pass # Exit a parse tree produced by SQLParser#alterTableActions. def exitAlterTableActions(self, ctx:SQLParser.AlterTableActionsContext): pass # Enter a parse tree produced by SQLParser#alterCommandList. def enterAlterCommandList(self, ctx:SQLParser.AlterCommandListContext): pass # Exit a parse tree produced by SQLParser#alterCommandList. def exitAlterCommandList(self, ctx:SQLParser.AlterCommandListContext): pass # Enter a parse tree produced by SQLParser#alterCommandsModifierList. def enterAlterCommandsModifierList(self, ctx:SQLParser.AlterCommandsModifierListContext): pass # Exit a parse tree produced by SQLParser#alterCommandsModifierList. def exitAlterCommandsModifierList(self, ctx:SQLParser.AlterCommandsModifierListContext): pass # Enter a parse tree produced by SQLParser#standaloneAlterCommands. def enterStandaloneAlterCommands(self, ctx:SQLParser.StandaloneAlterCommandsContext): pass # Exit a parse tree produced by SQLParser#standaloneAlterCommands. def exitStandaloneAlterCommands(self, ctx:SQLParser.StandaloneAlterCommandsContext): pass # Enter a parse tree produced by SQLParser#alterPartition. def enterAlterPartition(self, ctx:SQLParser.AlterPartitionContext): pass # Exit a parse tree produced by SQLParser#alterPartition. def exitAlterPartition(self, ctx:SQLParser.AlterPartitionContext): pass # Enter a parse tree produced by SQLParser#alterList. def enterAlterList(self, ctx:SQLParser.AlterListContext): pass # Exit a parse tree produced by SQLParser#alterList. def exitAlterList(self, ctx:SQLParser.AlterListContext): pass # Enter a parse tree produced by SQLParser#alterCommandsModifier. def enterAlterCommandsModifier(self, ctx:SQLParser.AlterCommandsModifierContext): pass # Exit a parse tree produced by SQLParser#alterCommandsModifier. def exitAlterCommandsModifier(self, ctx:SQLParser.AlterCommandsModifierContext): pass # Enter a parse tree produced by SQLParser#alterListItem. def enterAlterListItem(self, ctx:SQLParser.AlterListItemContext): pass # Exit a parse tree produced by SQLParser#alterListItem. def exitAlterListItem(self, ctx:SQLParser.AlterListItemContext): pass # Enter a parse tree produced by SQLParser#place. def enterPlace(self, ctx:SQLParser.PlaceContext): pass # Exit a parse tree produced by SQLParser#place. def exitPlace(self, ctx:SQLParser.PlaceContext): pass # Enter a parse tree produced by SQLParser#restrict. def enterRestrict(self, ctx:SQLParser.RestrictContext): pass # Exit a parse tree produced by SQLParser#restrict. def exitRestrict(self, ctx:SQLParser.RestrictContext): pass # Enter a parse tree produced by SQLParser#alterOrderList. def enterAlterOrderList(self, ctx:SQLParser.AlterOrderListContext): pass # Exit a parse tree produced by SQLParser#alterOrderList. def exitAlterOrderList(self, ctx:SQLParser.AlterOrderListContext): pass # Enter a parse tree produced by SQLParser#alterAlgorithmOption. def enterAlterAlgorithmOption(self, ctx:SQLParser.AlterAlgorithmOptionContext): pass # Exit a parse tree produced by SQLParser#alterAlgorithmOption. def exitAlterAlgorithmOption(self, ctx:SQLParser.AlterAlgorithmOptionContext): pass # Enter a parse tree produced by SQLParser#alterLockOption. def enterAlterLockOption(self, ctx:SQLParser.AlterLockOptionContext): pass # Exit a parse tree produced by SQLParser#alterLockOption. def exitAlterLockOption(self, ctx:SQLParser.AlterLockOptionContext): pass # Enter a parse tree produced by SQLParser#indexLockAndAlgorithm. def enterIndexLockAndAlgorithm(self, ctx:SQLParser.IndexLockAndAlgorithmContext): pass # Exit a parse tree produced by SQLParser#indexLockAndAlgorithm. def exitIndexLockAndAlgorithm(self, ctx:SQLParser.IndexLockAndAlgorithmContext): pass # Enter a parse tree produced by SQLParser#withValidation. def enterWithValidation(self, ctx:SQLParser.WithValidationContext): pass # Exit a parse tree produced by SQLParser#withValidation. def exitWithValidation(self, ctx:SQLParser.WithValidationContext): pass # Enter a parse tree produced by SQLParser#removePartitioning. def enterRemovePartitioning(self, ctx:SQLParser.RemovePartitioningContext): pass # Exit a parse tree produced by SQLParser#removePartitioning. def exitRemovePartitioning(self, ctx:SQLParser.RemovePartitioningContext): pass # Enter a parse tree produced by SQLParser#allOrPartitionNameList. def enterAllOrPartitionNameList(self, ctx:SQLParser.AllOrPartitionNameListContext): pass # Exit a parse tree produced by SQLParser#allOrPartitionNameList. def exitAllOrPartitionNameList(self, ctx:SQLParser.AllOrPartitionNameListContext): pass # Enter a parse tree produced by SQLParser#alterTablespace. def enterAlterTablespace(self, ctx:SQLParser.AlterTablespaceContext): pass # Exit a parse tree produced by SQLParser#alterTablespace. def exitAlterTablespace(self, ctx:SQLParser.AlterTablespaceContext): pass # Enter a parse tree produced by SQLParser#alterUndoTablespace. def enterAlterUndoTablespace(self, ctx:SQLParser.AlterUndoTablespaceContext): pass # Exit a parse tree produced by SQLParser#alterUndoTablespace. def exitAlterUndoTablespace(self, ctx:SQLParser.AlterUndoTablespaceContext): pass # Enter a parse tree produced by SQLParser#undoTableSpaceOptions. def enterUndoTableSpaceOptions(self, ctx:SQLParser.UndoTableSpaceOptionsContext): pass # Exit a parse tree produced by SQLParser#undoTableSpaceOptions. def exitUndoTableSpaceOptions(self, ctx:SQLParser.UndoTableSpaceOptionsContext): pass # Enter a parse tree produced by SQLParser#undoTableSpaceOption. def enterUndoTableSpaceOption(self, ctx:SQLParser.UndoTableSpaceOptionContext): pass # Exit a parse tree produced by SQLParser#undoTableSpaceOption. def exitUndoTableSpaceOption(self, ctx:SQLParser.UndoTableSpaceOptionContext): pass # Enter a parse tree produced by SQLParser#alterTablespaceOptions. def enterAlterTablespaceOptions(self, ctx:SQLParser.AlterTablespaceOptionsContext): pass # Exit a parse tree produced by SQLParser#alterTablespaceOptions. def exitAlterTablespaceOptions(self, ctx:SQLParser.AlterTablespaceOptionsContext): pass # Enter a parse tree produced by SQLParser#alterTablespaceOption. def enterAlterTablespaceOption(self, ctx:SQLParser.AlterTablespaceOptionContext): pass # Exit a parse tree produced by SQLParser#alterTablespaceOption. def exitAlterTablespaceOption(self, ctx:SQLParser.AlterTablespaceOptionContext): pass # Enter a parse tree produced by SQLParser#changeTablespaceOption. def enterChangeTablespaceOption(self, ctx:SQLParser.ChangeTablespaceOptionContext): pass # Exit a parse tree produced by SQLParser#changeTablespaceOption. def exitChangeTablespaceOption(self, ctx:SQLParser.ChangeTablespaceOptionContext): pass # Enter a parse tree produced by SQLParser#alterView. def enterAlterView(self, ctx:SQLParser.AlterViewContext): pass # Exit a parse tree produced by SQLParser#alterView. def exitAlterView(self, ctx:SQLParser.AlterViewContext): pass # Enter a parse tree produced by SQLParser#viewTail. def enterViewTail(self, ctx:SQLParser.ViewTailContext): pass # Exit a parse tree produced by SQLParser#viewTail. def exitViewTail(self, ctx:SQLParser.ViewTailContext): pass # Enter a parse tree produced by SQLParser#viewSelect. def enterViewSelect(self, ctx:SQLParser.ViewSelectContext): pass # Exit a parse tree produced by SQLParser#viewSelect. def exitViewSelect(self, ctx:SQLParser.ViewSelectContext): pass # Enter a parse tree produced by SQLParser#viewCheckOption. def enterViewCheckOption(self, ctx:SQLParser.ViewCheckOptionContext): pass # Exit a parse tree produced by SQLParser#viewCheckOption. def exitViewCheckOption(self, ctx:SQLParser.ViewCheckOptionContext): pass # Enter a parse tree produced by SQLParser#createStatement. def enterCreateStatement(self, ctx:SQLParser.CreateStatementContext): pass # Exit a parse tree produced by SQLParser#createStatement. def exitCreateStatement(self, ctx:SQLParser.CreateStatementContext): pass # Enter a parse tree produced by SQLParser#createDatabase. def enterCreateDatabase(self, ctx:SQLParser.CreateDatabaseContext): pass # Exit a parse tree produced by SQLParser#createDatabase. def exitCreateDatabase(self, ctx:SQLParser.CreateDatabaseContext): pass # Enter a parse tree produced by SQLParser#createDatabaseOption. def enterCreateDatabaseOption(self, ctx:SQLParser.CreateDatabaseOptionContext): pass # Exit a parse tree produced by SQLParser#createDatabaseOption. def exitCreateDatabaseOption(self, ctx:SQLParser.CreateDatabaseOptionContext): pass # Enter a parse tree produced by SQLParser#createTable. def enterCreateTable(self, ctx:SQLParser.CreateTableContext): pass # Exit a parse tree produced by SQLParser#createTable. def exitCreateTable(self, ctx:SQLParser.CreateTableContext): pass # Enter a parse tree produced by SQLParser#tableElementList. def enterTableElementList(self, ctx:SQLParser.TableElementListContext): pass # Exit a parse tree produced by SQLParser#tableElementList. def exitTableElementList(self, ctx:SQLParser.TableElementListContext): pass # Enter a parse tree produced by SQLParser#tableElement. def enterTableElement(self, ctx:SQLParser.TableElementContext): pass # Exit a parse tree produced by
# based on DeepLTL: https://github.com/reactive-systems/deepltl # pylint: disable=line-too-long """Parser for LTL formulas in different notations""" from enum import Enum import re import random from functools import reduce, total_ordering import operator import sympy as sy import sympy.logic as syl # Regular expression for allowed APs. Can disallow 't' and 'f', but all lowercase characters should be fine ap_alphabetic_re = r'[a-z]' # ap_alphabetic_re = '[a-eg-su-z]' ap_p_numeric_re = r'p\d+' def ltl_formula(formula_string: str, format: str = 'spot') -> 'LTLFormula': """Parse a LTL formula in the specified format (spot, lbt, network-infix, network-polish)""" token_list = tokenize_formula(formula_string, format.split('-')[0]) if format == 'spot' or format == 'network-infix': tree, remainder = parse_infix_formula(token_list) elif format == 'lbt' or format == 'network-polish': tree, remainder = parse_polish_formula(token_list) else: raise ValueError("'format' must be one of: spot, lbt, network-infix, network-polish") if remainder: raise ParseError("Could not fully parse formula, remainder: '" + str(remainder) + "'") return tree class LTLFormula(): """Represents a parsed LTL formula, use to_str() to get a representation in the desired format (spot, lbt, network-infix, network-polish)""" def __str__(self): return self.to_str(format='spot') def to_str(self, format='spot', spacing=None, full_parens=False) -> str: # spacing: 'none' (a&X!b), 'binary ops' (a & X!b), 'all ops' (a & X ! a) if format == 'spot': return self._to_str('infix', 'spot', spacing=spacing if spacing is not None else 'binary ops', full_parens=full_parens) elif format == 'lbt': return self._to_str('polish', 'lbt', spacing=spacing if spacing is not None else 'all ops', full_parens=full_parens) elif format == 'network-infix': if spacing is None: spacing = 'none' return self._to_str('infix', 'network', spacing=spacing, full_parens=full_parens) elif format == 'network-polish': if spacing is None: spacing = 'none' return self._to_str('polish', 'network', spacing=spacing, full_parens=full_parens) else: raise ValueError("Unrecognized format") def _to_str(self, notation, format_, spacing, full_parens): raise NotImplementedError() def equal_to(self, other: 'LTLFormula', extended_eq=False): raise NotImplementedError() def size(self): raise NotImplementedError() def contained_aps(self): raise NotImplementedError() def rewrite(self, token): raise NotImplementedError() def __add__(self, other): if other is None: return self if not isinstance(other, LTLFormula): raise ValueError('and operand is no formula') return LTLFormulaBinaryOp(Token.AND, self, other) def __radd__(self, other): return self.__add__(other) def to_sympy(self): raise NotImplementedError() def negation_normal_form(self, negate=False): raise NotImplementedError() def relax_to_prop(self): raise NotImplementedError() @total_ordering class Literal: def __init__(self, name, negated=False): self.name = name self.negated = negated def to_str(self, **kwargs): return ('!' if self.negated else '') + self.name def contained_aps(self): if self.name == '1': return set() else: return {self.name} def __hash__(self): return hash((self.name, self.negated)) def __eq__(self, other: 'Literal'): return self.negated == other.negated and self.name == other.name def __lt__(self, other: 'Literal'): return self.name < other.name def to_formula(self, boolean=True): if boolean: f = F_AP(self.name) return F_NOT(f) if self.negated else f else: raise ValueError class LiteralSet: def __init__(self, literals): self.literals = set(literals) @classmethod def from_str(cls, s, **kwargs): s = s.split(',') literals = [] for lit in s: if lit[0] == '!': literals.append(Literal(lit[1:], True)) else: literals.append(Literal(lit, False)) return cls(literals) def to_str(self, *args, **kwargs): return ','.join([q.to_str() for q in self.literals]) def equal_to(self, other: 'LiteralSet', **kwargs): return len(self.literals) == len(other.literals) and all([a == b for a, b in zip(sorted(self.literals), sorted(other.literals))]) def contained_aps(self): return reduce(operator.or_, [q.contained_aps() for q in self.literals]) def to_formula(self, boolean=True): return reduce(F_AND, (q.to_formula(boolean=boolean) for q in self.literals)) def dec_helper(node): if node.type_ == Token.OR: return dec_helper(node.lchild) + dec_helper(node.rchild) else: return [node] class ParseError(Exception): pass Token = Enum('Node', 'NOT AND OR IMPLIES EQUIV XOR NEXT UNTIL WEAKUNTIL RELEASE STRONGRELEASE GLOBALLY FINALLY TRUE FALSE AP LPAR RPAR STEP PAD EOS START UNK') token_dict_spot = {'!':(1, Token.NOT), '&':(2, Token.AND), '|':(2, Token.OR), '->':(2, Token.IMPLIES), '<->':(2, Token.EQUIV), 'X':(1, Token.NEXT), 'U':(2, Token.UNTIL), 'W':(2, Token.WEAKUNTIL), 'R':(2, Token.RELEASE), 'M':(2, Token.STRONGRELEASE), 'G':(1, Token.GLOBALLY), 'F':(1, Token.FINALLY), '1':(0, Token.TRUE), '0':(0, Token.FALSE), '(':(-1, Token.LPAR), ')':(-1, Token.RPAR)} token_reverse_dict_spot = {token: ch for ch, (num_children, token) in token_dict_spot.items()} token_dict_network = token_dict_spot.copy() del token_dict_network['->'] token_dict_network['>'] = (2,Token.IMPLIES) del token_dict_network['<->'] token_dict_network['='] = (2,Token.EQUIV) token_reverse_dict_network = token_reverse_dict_spot.copy() token_reverse_dict_network[Token.IMPLIES] = '>' token_reverse_dict_network[Token.EQUIV] = '=' token_dict_lbt = {'!':(1, Token.NOT), '&':(2, Token.AND), '|':(2, Token.OR), 'i':(2, Token.IMPLIES), 'e':(2, Token.EQUIV), '^':(2, Token.XOR), 'X':(1, Token.NEXT), 'U':(2, Token.UNTIL), 'W':(2, Token.WEAKUNTIL), 'R':(2, Token.RELEASE), 'M':(2, Token.STRONGRELEASE), 'G':(1, Token.GLOBALLY), 'F':(1, Token.FINALLY), 't':(0, Token.TRUE), 'f':(0, Token.FALSE)} token_reverse_dict_lbt = {token: ch for ch, (num_children, token) in token_dict_lbt.items()} precedence = {Token.NOT : 1, Token.AND : 3, Token.OR : 4, Token.IMPLIES : 5, Token.EQUIV : 6, Token.XOR : 6, Token.NEXT : 1, Token.UNTIL : 2, Token.WEAKUNTIL : 2, Token.RELEASE : 2, Token.STRONGRELEASE : 2, Token.GLOBALLY : 1, Token.FINALLY : 1, Token.TRUE : 0, Token.FALSE : 0, Token.AP : 0} # higher number = weaker left_associative = {Token.AND : True, Token.OR: True, Token.IMPLIES : False, Token.EQUIV : None, Token.XOR : None, Token.UNTIL : False, Token.WEAKUNTIL : False, Token.RELEASE : False, Token.STRONGRELEASE : False} sympy_tokens = {Token.NOT : syl.Not, Token.AND : syl.And, Token.OR : syl.Or, Token.IMPLIES : syl.Implies, Token.EQUIV : syl.Equivalent, Token.XOR : syl.Xor, Token.TRUE : syl.true, Token.FALSE : syl.false} binary_ops = {Token.AND, Token.OR, Token.IMPLIES, Token.EQUIV, Token.UNTIL, Token.WEAKUNTIL} #, Token.RELEASE} # todo: clean handling of release unary_ops = {Token.NOT, Token.NEXT, Token.GLOBALLY, Token.FINALLY} boolean_tokens = {Token.NOT, Token.AND, Token.OR, Token.IMPLIES, Token.EQUIV, Token.TRUE, Token.FALSE, Token.AP} ltl_tokens = {Token.NEXT, Token.UNTIL, Token.WEAKUNTIL, Token.RELEASE, Token.GLOBALLY, Token.FINALLY} class LTLFormulaBinaryOp(LTLFormula): def __init__(self, type_, lchild, rchild): self.type_ = type_ self.lchild = lchild self.rchild = rchild self.precedence = precedence[type_] self.left_associative = left_associative[type_] def _to_str(self, notation, format_, spacing, full_parens): space = '' if spacing == 'none' else ' ' if notation == 'polish': return globals()['token_reverse_dict_' + format_][self.type_] + space + self.lchild._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) + space + self.rchild._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) elif notation == 'infix': if full_parens or self.lchild.precedence > self.precedence: par_left = True elif self.lchild.precedence == self.precedence: par_left = self.left_associative is None or not self.left_associative else: par_left = False if full_parens or self.rchild.precedence > self.precedence: par_right = True elif self.rchild.precedence == self.precedence: par_right = self.left_associative is None or self.left_associative else: par_right = False return ('(' if par_left else '') + self.lchild._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) + (')' if par_left else '') + space + globals()['token_reverse_dict_' + format_][self.type_] + space + ('(' if par_right else '') + self.rchild._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) + (')' if par_right else '') else: raise ValueError("Unrecognized notation") def equal_to(self, other: LTLFormula, extended_eq=False): if not isinstance(other, LTLFormulaBinaryOp) or not self.type_ == other.type_: return False children_equal = self.lchild.equal_to(other.lchild, extended_eq=extended_eq) and self.rchild.equal_to(other.rchild, extended_eq=extended_eq) if extended_eq and self.type_ in [Token.AND, Token.OR]: children_equal = children_equal or (self.lchild.equal_to(other.rchild, extended_eq=extended_eq) and self.rchild.equal_to(other.lchild, extended_eq=extended_eq)) return children_equal def size(self): return 1 + self.lchild.size() + self.rchild.size() def contained_aps(self): return self.lchild.contained_aps() | self.rchild.contained_aps() def rewrite(self, token): lchild_r = self.lchild.rewrite(token) rchild_r = self.rchild.rewrite(token) if self.type_ == token: if token == Token.OR: return F_NOT(F_AND(F_NOT(lchild_r), F_NOT(rchild_r))) elif token == Token.WEAKUNTIL: return F_RELEASE(rchild_r, F_OR(lchild_r, rchild_r)) else: raise ValueError("Don't know how to rewrite " + str(token)) else: return LTLFormulaBinaryOp(self.type_, lchild_r, rchild_r) def to_sympy(self): return sympy_tokens[self.type_](self.lchild.to_sympy(), self.rchild.to_sympy()) def __iter__(self): return IterHelper(self) def negation_normal_form(self, negate=False): if negate: if self.type_ == Token.AND: return F_OR(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True)) if self.type_ == Token.OR: return F_AND(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True)) if self.type_ == Token.IMPLIES: return F_AND(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(True)) if self.type_ == Token.EQUIV: return F_AND(F_OR(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False)), F_OR(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True))) if self.type_ == Token.XOR: return F_OR(F_AND(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False)), F_AND(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True))) if self.type_ == Token.UNTIL: return LTLFormulaBinaryOp(Token.RELEASE, self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True)) if self.type_ == Token.WEAKUNTIL: return LTLFormulaBinaryOp(Token.UNTIL, self.rchild.negation_normal_form(True), F_AND(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True))) if self.type_ == Token.RELEASE: return LTLFormulaBinaryOp(Token.UNTIL, self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True)) raise NotImplementedError() else: if self.type_ == Token.IMPLIES: return F_OR(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(False)) if self.type_ == Token.EQUIV: return F_OR(F_AND(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False)), F_AND(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True))) if self.type_ == Token.XOR: return F_AND(F_OR(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False)), F_OR(self.lchild.negation_normal_form(True), self.rchild.negation_normal_form(True))) if self.type_ == Token.WEAKUNTIL: return LTLFormulaBinaryOp(Token.RELEASE, self.rchild.negation_normal_form(False), F_OR(self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False))) if self.type_ in [Token.AND, Token.OR, Token.UNTIL, Token.RELEASE]: return LTLFormulaBinaryOp(self.type_, self.lchild.negation_normal_form(False), self.rchild.negation_normal_form(False)) raise NotImplementedError() def relax_to_prop(self): lchild, rchild, = self.lchild.relax_to_prop(), self.rchild.relax_to_prop() if self.type_ == Token.UNTIL: return F_OR(lchild, rchild) if self.type_ == Token.RELEASE: return F_OR(rchild, F_AND(lchild, rchild)) if self.type_ in [Token.AND, Token.OR]: return LTLFormulaBinaryOp(self.type_, lchild, rchild) raise ValueError('Require negation normal form') class LTLFormulaUnaryOp(LTLFormula): def __init__(self, type_, child): self.type_ = type_ self.child = child self.precedence = precedence[type_] def _to_str(self, notation, format_, spacing, full_parens): space = '' if spacing in ['none', 'binary ops'] else ' ' if notation == 'polish': return globals()['token_reverse_dict_' + format_][self.type_] + space + self.child._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) elif notation == 'infix': par = (self.child.precedence > self.precedence) or full_parens return globals()['token_reverse_dict_' + format_][self.type_] + space + ('(' if par else '') + self.child._to_str(notation=notation, format_=format_, spacing=spacing, full_parens=full_parens) + (')' if par else '') else: raise ValueError("Unrecognized notation") def equal_to(self, other: LTLFormula, extended_eq=False): return isinstance(other, LTLFormulaUnaryOp) and self.type_ == other.type_ and self.child.equal_to(other.child, extended_eq=extended_eq) def size(self): return 1 + self.child.size() def contained_aps(self): return self.child.contained_aps()
to s3 and return the location. Returns: s3 uri """ local_mode = self.output_path.startswith("file://") if self.code_location is None and local_mode: code_bucket = self.sagemaker_session.default_bucket() code_s3_prefix = "{}/{}".format(self._current_job_name, "source") kms_key = None elif self.code_location is None: code_bucket, _ = parse_s3_url(self.output_path) code_s3_prefix = "{}/{}".format(self._current_job_name, "source") kms_key = self.output_kms_key elif local_mode: code_bucket, key_prefix = parse_s3_url(self.code_location) code_s3_prefix = "/".join(filter(None, [key_prefix, self._current_job_name, "source"])) kms_key = None else: code_bucket, key_prefix = parse_s3_url(self.code_location) code_s3_prefix = "/".join(filter(None, [key_prefix, self._current_job_name, "source"])) output_bucket, _ = parse_s3_url(self.output_path) kms_key = self.output_kms_key if code_bucket == output_bucket else None return tar_and_upload_dir( session=self.sagemaker_session.boto_session, bucket=code_bucket, s3_key_prefix=code_s3_prefix, script=self.entry_point, directory=self.source_dir, dependencies=self.dependencies, kms_key=kms_key, s3_resource=self.sagemaker_session.s3_resource, ) def _model_source_dir(self): """Get the appropriate value to pass as ``source_dir`` to a model constructor. Returns: str: Either a local or an S3 path pointing to the ``source_dir`` to be used for code by the model to be deployed """ return ( self.source_dir if self.sagemaker_session.local_mode else self.uploaded_code.s3_prefix ) def _model_entry_point(self): """Get the appropriate value to pass as ``entry_point`` to a model constructor. Returns: str: The path to the entry point script. This can be either an absolute path or a path relative to ``self._model_source_dir()``. """ if self.sagemaker_session.local_mode or (self._model_source_dir() is None): return self.entry_point return self.uploaded_code.script_name def hyperparameters(self): """Return the hyperparameters as a dictionary to use for training. The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which trains the model, calls this method to find the hyperparameters. Returns: dict[str, str]: The hyperparameters. """ return self._json_encode_hyperparameters(self._hyperparameters) @classmethod def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): """Convert the job description to init params that can be handled by the class constructor. Args: job_details: the returned job details from a describe_training_job API call. model_channel_name (str): Name of the channel where pre-trained model data will be downloaded Returns: dictionary: The transformed init_params """ init_params = super(Framework, cls)._prepare_init_params_from_job_description( job_details, model_channel_name ) init_params["entry_point"] = json.loads( init_params["hyperparameters"].get(SCRIPT_PARAM_NAME) ) init_params["source_dir"] = json.loads(init_params["hyperparameters"].get(DIR_PARAM_NAME)) init_params["container_log_level"] = json.loads( init_params["hyperparameters"].get(CONTAINER_LOG_LEVEL_PARAM_NAME) ) hyperparameters = {} for k, v in init_params["hyperparameters"].items(): # Tuning jobs add this special hyperparameter which is not JSON serialized if k == "_tuning_objective_metric": if v.startswith('"') and v.endswith('"'): v = v.strip('"') hyperparameters[k] = v else: hyperparameters[k] = json.loads(v) init_params["hyperparameters"] = hyperparameters return init_params def training_image_uri(self): """Return the Docker image to use for training. The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which does the model training, calls this method to find the image to use for model training. Returns: str: The URI of the Docker image. """ if self.image_uri: return self.image_uri if hasattr(self, "distribution"): distribution = self.distribution # pylint: disable=no-member else: distribution = None if hasattr(self, "tensorflow_version") or hasattr(self, "pytorch_version"): processor = image_uris._processor(self.instance_type, ["cpu", "gpu"]) container_version = "cu110-ubuntu18.04" if processor == "gpu" else None if self.tensorflow_version is not None: # pylint: disable=no-member base_framework_version = ( f"tensorflow{self.tensorflow_version}" # pylint: disable=no-member ) else: base_framework_version = ( f"pytorch{self.pytorch_version}" # pylint: disable=no-member ) else: container_version = None base_framework_version = None return image_uris.retrieve( self._framework_name, self.sagemaker_session.boto_region_name, instance_type=self.instance_type, version=self.framework_version, # pylint: disable=no-member py_version=self.py_version, # pylint: disable=no-member image_scope="training", distribution=distribution, base_framework_version=base_framework_version, container_version=container_version, ) @classmethod def attach(cls, training_job_name, sagemaker_session=None, model_channel_name="model"): """Attach to an existing training job. Create an Estimator bound to an existing training job, each subclass is responsible to implement ``_prepare_init_params_from_job_description()`` as this method delegates the actual conversion of a training job description to the arguments that the class constructor expects. After attaching, if the training job has a Complete status, it can be ``deploy()`` ed to create a SageMaker Endpoint and return a ``Predictor``. If the training job is in progress, attach will block until the training job completes, but logs of the training job will not display. To see the logs content, please call ``logs()`` Examples: >>> my_estimator.fit(wait=False) >>> training_job_name = my_estimator.latest_training_job.name Later on: >>> attached_estimator = Estimator.attach(training_job_name) >>> attached_estimator.logs() >>> attached_estimator.deploy() Args: training_job_name (str): The name of the training job to attach to. sagemaker_session (sagemaker.session.Session): Session object which manages interactions with Amazon SageMaker APIs and any other AWS services needed. If not specified, the estimator creates one using the default AWS configuration chain. model_channel_name (str): Name of the channel where pre-trained model data will be downloaded (default: 'model'). If no channel with the same name exists in the training job, this option will be ignored. Returns: Instance of the calling ``Estimator`` Class with the attached training job. """ estimator = super(Framework, cls).attach( training_job_name, sagemaker_session, model_channel_name ) # pylint gets confused thinking that estimator is an EstimatorBase instance, but it actually # is a Framework or any of its derived classes. We can safely ignore the no-member errors. estimator.uploaded_code = UploadedCode( estimator.source_dir, estimator.entry_point # pylint: disable=no-member ) return estimator @staticmethod def _json_encode_hyperparameters(hyperparameters): """Placeholder docstring""" current_hyperparameters = hyperparameters if current_hyperparameters is not None: hyperparameters = { str(k): (v if isinstance(v, (Parameter, Expression, Properties)) else json.dumps(v)) for (k, v) in current_hyperparameters.items() } return hyperparameters @classmethod def _update_init_params(cls, hp, tf_arguments): """Placeholder docstring""" updated_params = {} for argument in tf_arguments: value = hp.pop(argument, None) if value is not None: value = json.loads(value) updated_params[argument] = value return updated_params def transformer( self, instance_count, instance_type, strategy=None, assemble_with=None, output_path=None, output_kms_key=None, accept=None, env=None, max_concurrent_transforms=None, max_payload=None, tags=None, role=None, model_server_workers=None, volume_kms_key=None, entry_point=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT, enable_network_isolation=None, model_name=None, ): """Return a ``Transformer`` that uses a SageMaker Model based on the training job. It reuses the SageMaker Session and base job name used by the Estimator. Args: instance_count (int): Number of EC2 instances to use. instance_type (str): Type of EC2 instance to use, for example, 'ml.c4.xlarge'. strategy (str): The strategy used to decide how to batch records in a single request (default: None). Valid values: 'MultiRecord' and 'SingleRecord'. assemble_with (str): How the output is assembled (default: None). Valid values: 'Line' or 'None'. output_path (str): S3 location for saving the transform result. If not specified, results are stored to a default bucket. output_kms_key (str): Optional. KMS key ID for encrypting the transform output (default: None). accept (str): The accept header passed by the client to the inference endpoint. If it is supported by the endpoint, it will be the format of the batch transform output. env (dict): Environment variables to be set for use during the transform job (default: None). max_concurrent_transforms (int): The maximum number of HTTP requests to be made to each individual transform container at one time. max_payload (int): Maximum size of the payload in a single HTTP request to the container in MB. tags (list[dict]): List of tags for labeling a transform job. If none specified, then the tags used for the training job are used for the transform job. role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during transform jobs. If not specified, the role from the Estimator will be used. model_server_workers (int): Optional. The number of worker processes used by the inference server. If None, server will use one worker per vCPU. volume_kms_key (str): Optional. KMS key ID for encrypting the volume attached to the ML compute instance (default: None). entry_point (str): Path (absolute or relative) to the local Python source file which should be executed as the entry point to training. If ``source_dir`` is specified, then ``entry_point`` must point to a file located at the root of ``source_dir``. If not specified, the training entry point is used. vpc_config_override (dict[str, list[str]]): Optional override for the VpcConfig set on the model. Default: use subnets and security groups from this Estimator. * 'Subnets' (list[str]): List of subnet ids. * 'SecurityGroupIds' (list[str]): List of security group ids. enable_network_isolation (bool): Specifies whether container will run in network isolation mode. Network isolation mode restricts the container access to outside networks (such as the internet). The container does not make any inbound or outbound network calls. If True, a channel named "code" will be created for any user entry script for inference. Also known as Internet-free mode. If not specified, this setting is taken from the estimator's current configuration. model_name (str): Name to use for creating an Amazon SageMaker model. If not specified, the estimator generates a default job name based on the training image name and current timestamp. Returns: sagemaker.transformer.Transformer:
import pytest import numpy as np from numpy.testing import assert_array_almost_equal, assert_equal from SciDataTool import DataLinspace, DataTime, Norm_ref, Data1D, DataPattern @pytest.mark.validation def test_get_data_along(): f = 50 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=10, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=2 * np.pi, number=20, include_endpoint=False, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values()) field = 5 * np.cos(2 * np.pi * f * ta + 3 * at) Field = DataTime( name="Example field", symbol="X", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Angle, Time], values=field, ) # Check slicing "time=sum" Field_extract = Field.get_data_along("angle", "time=sum") # Check transfer of normalizations assert Field.normalizations == Field_extract.normalizations assert isinstance(Field_extract.axes[0], DataLinspace) assert_array_almost_equal( Field_extract.axes[0].get_values(), Field.axes[0].get_values() ) @pytest.mark.validation def test_get_data_along_symmetry(): f = 50 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=10, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=np.pi, number=20, include_endpoint=False, symmetries={"period": 2}, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values(is_smallestperiod=True)) field = 5 * np.cos(2 * np.pi * f * ta + 3 * at) Field = DataTime( name="Example field", symbol="X", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Angle, Time], values=field, ) # Check slicing "time=sum" Field_extract = Field.get_data_along("angle", "time=sum") # Check transfer of symmetries assert Field_extract.axes[0].symmetries == dict() Field_extract = Field.get_data_along("angle[smallestperiod]", "time=sum") # Check transfer of symmetries assert Field_extract.axes[0].symmetries == {"period": 2} @pytest.mark.validation def test_get_data_along_single(): f = 50 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=1, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=np.pi, number=20, include_endpoint=False, symmetries={"period": 2}, ) Slice = DataLinspace( name="z", unit="m", initial=0, final=10, number=30, include_endpoint=False, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values(is_smallestperiod=True)) field = 5 * np.cos(2 * np.pi * f * ta + 3 * at) field_tot = np.zeros((1, 20, 30)) for i in range(30): field_tot[:, :, i] = field.T + i Field = DataTime( name="Example field", symbol="X", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time, Angle, Slice], values=field_tot, ) # Check slicing "z=sum" Field_extract = Field.get_data_along("time", "angle[smallestperiod]", "z=sum") # Check shape assert Field_extract.values.shape == (1, 20) # Check time axis assert Field_extract.axes[0].name == "time" @pytest.mark.validation def test_get_data_along_integrate(): # Test integrate / sum / mean / rms with and without anti-periodicity f = 50 A = 5 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=10, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=2 * np.pi, number=20, include_endpoint=False, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values()) field = A * np.cos(2 * np.pi * f * ta + 3 * at) Field = DataTime( name="Example field", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time, Angle], values=field.T, ) Field_int = Field.get_data_along("time=integrate", "angle") assert_array_almost_equal(Field_int.values, 0, decimal=16) assert Field_int.unit == "ms" Field_mean = Field.get_data_along("time=mean", "angle") assert_array_almost_equal(Field_mean.values, 0, decimal=15) assert Field_mean.unit == "m" Field_sum = Field.get_data_along("time=sum", "angle") assert_array_almost_equal(Field_sum.values, 0, decimal=14) assert Field_sum.unit == "m" Field_rms = Field.get_data_along("time=rms", "angle") assert_array_almost_equal(Field_rms.values, A / np.sqrt(2), decimal=15) assert Field_rms.unit == "m" Field_int_loc = Field.get_data_along("time=integrate_local", "angle") assert_array_almost_equal(np.sum(Field_int_loc.values), 0, decimal=16) assert Field_int_loc.unit == "ms" Field.unit = "N/m^2" Time.unit = "m" Field_int = Field.get_data_along("time=integrate", "angle=integrate") assert Field_int.unit == "N" Time.unit = "s" Field.unit = "m" # Anti-periodic signal Time0 = Time.get_axis_periodic(Nper=1, is_aper=True) ta0, at0 = np.meshgrid(Time0.get_values(is_smallestperiod=True), Angle.get_values()) field0 = A * np.cos(2 * np.pi * f * ta0 + 3 * at0) Field0 = DataTime( name="Example field", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time0, Angle], values=field0.T, ) Field_int0 = Field0.get_data_along("time=integrate", "angle") assert_array_almost_equal(Field_int0.values, 0, decimal=16) Field_mean0 = Field0.get_data_along("time=mean", "angle") assert_array_almost_equal(Field_mean0.values, 0, decimal=15) Field_sum0 = Field0.get_data_along("time=sum", "angle") assert_array_almost_equal(Field_sum0.values, 0, decimal=14) Field_rms0 = Field0.get_data_along("time=rms", "angle") assert_array_almost_equal(Field_rms0.values, A / np.sqrt(2), decimal=15) Field_int_loc0 = Field0.get_data_along("time=integrate_local", "angle") assert_array_almost_equal(np.sum(Field_int_loc0.values), 0, decimal=16) # Test integrate / sum / mean / rms with and without periodicity f = 32.1258 A = 12.478 Time1 = DataLinspace( name="time", unit="s", initial=0, final=0.5 / f, number=10, include_endpoint=False, symmetries={"period": 2}, ) ta1, at1 = np.meshgrid(Time1.get_values(is_smallestperiod=True), Angle.get_values()) field1 = A * np.cos(2 * np.pi * f * ta1 + 3 * at1) ** 2 Field1 = DataTime( name="Example field", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time1, Angle], values=field1.T, ) Time2 = Time1.get_axis_periodic(Nper=1, is_aper=False) ta2, at2 = np.meshgrid(Time2.get_values(), Angle.get_values()) field2 = A * np.cos(2 * np.pi * f * ta2 + 3 * at2) ** 2 Field2 = DataTime( name="Example field", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time2, Angle], values=field2.T, ) assert_array_almost_equal(Time1.get_values(), Time2.get_values(), decimal=16) Field_int1 = Field1.get_data_along("time=integrate", "angle") Field_int2 = Field2.get_data_along("time=integrate", "angle") assert_array_almost_equal(Field_int1.values, 0.5 * A / f, decimal=15) assert_array_almost_equal(Field_int2.values, 0.5 * A / f, decimal=15) Field_mean1 = Field1.get_data_along("time=mean", "angle") Field_mean2 = Field2.get_data_along("time=mean", "angle") assert_array_almost_equal(Field_mean1.values, 0.5 * A, decimal=14) assert_array_almost_equal(Field_mean2.values, 0.5 * A, decimal=14) Field_rms1 = Field1.get_data_along("time=rms", "angle") Field_rms2 = Field2.get_data_along("time=rms", "angle") assert_array_almost_equal(Field_rms1.values, np.sqrt(3 * A ** 2 / 8), decimal=14) assert_array_almost_equal(Field_rms2.values, np.sqrt(3 * A ** 2 / 8), decimal=14) # Test unit change Field.unit = "ms" Field_int = Field.get_data_along("time=integrate") assert Field_int.unit == "ms2" Field.unit = "m/s" Field_int = Field.get_data_along("time=integrate") assert Field_int.unit == "m" Field.unit = "m/s2" Field_int = Field.get_data_along("time=integrate") assert Field_int.unit == "m/s" Field.unit = "m/s3" Field_int = Field.get_data_along("time=integrate") assert Field_int.unit == "m/s2" Field.unit = "ms" Field_int = Field.get_data_along("time=integrate") assert Field_int.unit == "ms2" @pytest.mark.validation def test_get_data_along_antiderivate(): f = 50 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=100, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=2 * np.pi, number=200, include_endpoint=False, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values()) field = 5 * np.cos(2 * np.pi * f * ta + 3 * at) Field = DataTime( name="<NAME>", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time, Angle], values=field.T, ) # Time derivation Field_anti_t = Field.get_data_along("time=antiderivate", "angle") assert Field_anti_t.unit == "ms", "wrong unit: " + Field_anti_t.unit field_anti_t_check = Field_anti_t.values field_anti_t_ref = 5 / (2 * np.pi * f) * np.sin(2 * np.pi * f * ta.T + 3 * at.T) assert_array_almost_equal(field_anti_t_check, field_anti_t_ref, decimal=5) # Angle derivation Field_anti_a = Field.get_data_along("time", "angle=antiderivate") assert Field_anti_a.unit == "m2", "wrong unit: " + Field_anti_a.unit field_anti_a_check = Field_anti_a.values field_anti_a_ref = 5 / 3 * np.sin(2 * np.pi * f * ta.T + 3 * at.T) assert_array_almost_equal(field_anti_a_check, field_anti_a_ref, decimal=3) Field_int = Field.get_data_along("time=antiderivate", "angle") assert Field_int.unit == "ms" Field.unit = "ms" Field_int = Field.get_data_along("time=antiderivate") assert Field_int.unit == "ms2" Field.unit = "m/s" Field_int = Field.get_data_along("time=antiderivate") assert Field_int.unit == "m" Field.unit = "m/s2" Field_int = Field.get_data_along("time=antiderivate") assert Field_int.unit == "m/s" Field.unit = "m/s3" Field_int = Field.get_data_along("time=antiderivate") assert Field_int.unit == "m/s2" Field.unit = "ms" Field_int = Field.get_data_along("time=antiderivate") assert Field_int.unit == "ms2" @pytest.mark.validation def test_get_data_along_derivate(): f = 50 Time = DataLinspace( name="time", unit="s", initial=0, final=1 / f, number=100, include_endpoint=False, ) Angle = DataLinspace( name="angle", unit="rad", initial=0, final=2 * np.pi, number=200, include_endpoint=False, ) ta, at = np.meshgrid(Time.get_values(), Angle.get_values()) field = 5 * np.cos(2 * np.pi * f * ta + 3 * at) Field = DataTime( name="Example field", symbol="X", unit="m", normalizations={"ref": Norm_ref(ref=2e-5)}, axes=[Time, Angle], values=field.T, ) # Time derivation Field_diff_t = Field.get_data_along("time=derivate", "angle") assert Field_diff_t.unit == "m/s" field_diff_t_check = Field_diff_t.values field_diff_t_ref = -5 * 2 * np.pi * f * np.sin(2 * np.pi * f * ta.T + 3 * at.T) assert_array_almost_equal(field_diff_t_check, field_diff_t_ref, decimal=0) # TODO: check and understand discrepancy in field_diff_t_ref/field_diff_t_check # Angle derivation Field_diff_a = Field.get_data_along("time", "angle=derivate") assert Field_diff_a.unit == "" field_diff_a_check = Field_diff_a.values field_diff_a_ref = -5 * 3 * np.sin(2 * np.pi * f * ta.T + 3 * at.T) assert_array_almost_equal(field_diff_a_check, field_diff_a_ref, decimal=1) # TODO: check and understand discrepancy in field_diff_a_ref/field_diff_a_check # Freqs derivation Field_ft = Field.time_to_freq() Field_der = Field_ft.get_data_along("freqs=derivate", "angle[0]") assert Field_der.unit == "m/s" result_ft = Field_ft.get_along("freqs", "angle[0]") freqs = result_ft["freqs"] field_ft = result_ft["X"] assert_array_almost_equal( np.squeeze(Field_der.values), field_ft * 2 * 1j * np.pi * freqs ) Field_ft.unit = "m/s" Field_der = Field_ft.get_data_along("freqs=derivate", "wavenumber") assert Field_der.unit == "m/s2" Field_ft.unit = "ms" Field_der = Field_ft.get_data_along("freqs=derivate", "wavenumber") assert Field_der.unit == "m" Field_ft.unit = "ms2" Field_der = Field_ft.get_data_along("freqs=derivate", "wavenumber") assert Field_der.unit == "ms" Field_ft.unit = "ms3" Field_der = Field_ft.get_data_along("freqs=derivate", "wavenumber") assert Field_der.unit == "ms2" @pytest.mark.validation def test_get_data_along_to_linspace(): """Test to_linspace method that is called in get_data_along""" Time = Data1D(name="time", unit="s", values=np.linspace(0, 1, 100)) Angle = Data1D(name="angle", unit="rad", values=np.array([0])) Phase = Data1D( name="phase", unit="", values=["A", "B", "C"], is_components=True, ) Time_lin = Time.to_linspace() Angle_lin = Angle.to_linspace() Phase_lin = Phase.to_linspace() # Check transfer of normalizations assert isinstance(Time_lin, DataLinspace), "Time axis not a linspace" assert isinstance(Angle_lin, Data1D), "Angle axis not a Data1D" assert isinstance(Phase_lin, Data1D), "Phase axis not a Data1D" assert_array_almost_equal(Time.get_values(), Time_lin.get_values()) @pytest.mark.validation @pytest.mark.skip(reason="still under development") def test_get_data_along_integrate_local(): # Test integrate / sum / mean / rms with and without anti-periodicity
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import unittest from typing import Dict from silk.tests.silk_replay import SilkReplayer from silk.tools.otns_manager import RoleType, OtnsNode from silk.unit_tests.testcase import SilkMockingTestCase class OTNSLogReplayTest(SilkMockingTestCase): """Silk unit test case for log replayer. In the test methods in this class, we pause at certain stages of the log parsing process to verify the status of OTNS manager to confirm the replayer correctly parses the log. The stop_regex is usually the end of current test phase or the start of next test phase. """ def setUp(self): """Test method set up. """ super().setUp() hwconfig_path = Path(__file__).parent / "fixture/hwconfig.ini" self.args = ["tests/silk_replay.py", "-v2", "-c", str(hwconfig_path), "-s", "localhost", "-p", "100"] def create_replayer(self, log_filename: str) -> SilkReplayer: """Prepare a replayer for a test. Args: log_filename (str): log file basename. Returns: SilkReplayer: a SilkReplayer prepared for a test. """ log_path = str(Path(__file__).parent / f"fixture/{log_filename}") replayer = SilkReplayer(argv=self.args + [log_path], run_now=False) replayer.otns_manager = self.manager return replayer def verify_nodes_added(self, node_number: int) -> Dict[int, OtnsNode]: """Verify that a set number of nodes are created in the OTNS manager. Returns: Dict[int, OtnsNode]: a dictionary mapping from node ID to the OTNS nodes. """ otns_nodes = {} self.assertEqual(node_number, len(self.manager.otns_node_map)) for node in self.manager.otns_node_map.values(): otns_nodes[node.node_id] = node self.assertNotEqual(node.node_id, node.extaddr) self.assertEqual(RoleType.DISABLED, node.role) self.assertFalse(node.children) self.assertFalse(node.neighbors) return otns_nodes def testReplayFormNetwork(self): """Test replaying the form network test case log. The log file runs with 7 nodes to form a Thread network, with 1 leader, 4 routers, and 2 SEDs. Nodes are numbered 2 to 8. Node 2 becomes the leader and nodes 3-6 become routers. 7-8 become SEDs and children of node 2. """ def assert_network_topology(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) children = [nodes[child_id].extaddr for child_id in range(7, 9)] for child_extaddr in children: self.assertIn(child_extaddr, nodes[2].children) for node_id in range(3, 7): self.assertEqual(RoleType.ROUTER, nodes[node_id].role) for node_id in range(7, 9): self.assertEqual(RoleType.CHILD, nodes[node_id].role) # fully meshed network, each of the 5 routers have 4 neighbors for node_id in range(2, 7): self.assertEqual(4, len(nodes[node_id].neighbors)) neighbors = [nodes[neighbor_id].extaddr for neighbor_id in range(2, 7) if neighbor_id != node_id] for neighbor_extaddr in neighbors: self.assertIn(neighbor_extaddr, nodes[node_id].neighbors) test_class = "TestFormNetwork" test_phases = [ "test01_Pairing", "test02_GetWpanStatus", "test03_PingRouterLLA", "test04_PingRouterMLA", "test05_PingRouterULA" ] replayer = self.create_replayer("form_network_log.txt") # setting up: nodes added line_number = replayer.run(stop_regex=fr"SET UP {test_class}.{test_phases[0]}") otns_nodes = self.verify_nodes_added(7) # pairing: node modes change; title changes udp_expect_thread = self.expect_udp_messages([("mode=sn", 7), ("mode=sn", 8)]) grpc_expect_thread = self.expect_grpc_commands([f"title \"{test_class}.{test_phases[0]}\" x 0 y 20 fs 20"]) line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[0]}") self.wait_for_expect(udp_expect_thread) self.wait_for_expect(grpc_expect_thread) self.assertEqual( 7, len(self.manager.otns_node_map), ) for phase in range(1, 5): line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[phase]}") assert_network_topology(otns_nodes) # tearing down: nodes removed expect_thread = self.expect_grpc_commands([f"del {i}" for i in range(2, 9)]) replayer.run(start_line=line_number) self.wait_for_expect(expect_thread) self.assertFalse(self.manager.otns_node_map) def testReplayRouterTable(self): """Test replaying the router table test case log. The log file runs with 5 nodes to form a Thread network, with 1 leader, 3 routers and 1 SED. Nodes are numbered 2 to 8. Node 2 becomes leader, 3-5 become routers. Node 6 becomes a child of node 5. Nodes 2-4 forms full mesh, and node 5 becomes neighbor of node 4. """ def assert_network_topology(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) for node_id in range(3, 6): self.assertEqual(RoleType.ROUTER, nodes[node_id].role) self.assertEqual(RoleType.CHILD, nodes[6].role) self.assertIn(nodes[6].extaddr, nodes[5].children) # nodes 2 and 3 has two neighbors for node_id in range(2, 4): self.assertEqual(2, len(nodes[node_id].neighbors)) test_class = "TestRouterTable" test_phases = [ "test01_Form_Network", "test02_Verify_Node_Type", "test03_Verify_r1_Router_Table", "test04_Verify_r3_Router_Table", "test05_Verify_r4_Router_Table" ] replayer = self.create_replayer("router_table_log.txt") # setting up: nodes added line_number = replayer.run(stop_regex=fr"SET UP {test_class}.{test_phases[0]}") otns_nodes = self.verify_nodes_added(5) # form network: node modes change; title changes udp_expect_thread = self.expect_udp_messages([("mode=sn", 6)]) grpc_expect_thread = self.expect_grpc_commands([f"title \"{test_class}.{test_phases[0]}\" x 0 y 20 fs 20"]) line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[0]}") self.wait_for_expect(udp_expect_thread) self.wait_for_expect(grpc_expect_thread) self.assertEqual(5, len(self.manager.otns_node_map)) for phase in range(1, 5): line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[phase]}") assert_network_topology(otns_nodes) # tearing down: nodes removed expect_thread = self.expect_grpc_commands([f"del {i}" for i in range(2, 7)]) replayer.run(start_line=line_number) self.wait_for_expect(expect_thread) self.assertFalse(self.manager.otns_node_map) def testReplayChildTable(self): """Test replaying the child table test case log. The log file runs with 7 nodes to form a Thread network, with 1 leader and 6 FEDs. Nodes are numbered 2 to 8. Node 2 becomes leader, 3-8 become children of node 2. """ def assert_network_topology(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) for node_id in range(3, 9): self.assertEqual(RoleType.CHILD, nodes[node_id].role) self.assertEqual(6, len(nodes[2].children)) # nodes 2 and 3 has two neighbors for node_id in range(3, 9): self.assertIn(nodes[node_id].extaddr, nodes[2].children) test_class = "TestChildTable" test_phases = [ "test01_Pairing", "test02_Verify_ChildTable", "test03_Verify_ChildTableAddress", "test04_Verify_ChildTable_AsValMap" ] replayer = self.create_replayer("child_table_log.txt") # setting up: nodes added line_number = replayer.run(stop_regex=fr"SET UP {test_class}.{test_phases[0]}") otns_nodes = self.verify_nodes_added(7) # pairing line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[0]}") self.assertEqual(7, len(self.manager.otns_node_map)) for phase in range(1, 4): line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[phase]}") assert_network_topology(otns_nodes) # tearing down: nodes removed expect_thread = self.expect_grpc_commands([f"del {i}" for i in range(2, 9)]) replayer.run(start_line=line_number) self.wait_for_expect(expect_thread) self.assertFalse(self.manager.otns_node_map) def testReplayNeighborTable(self): """Test replaying the neighbor table test case log. The log file runs with 4 nodes to form a Thread network, with 1 leader, 1 router, 1 FED, and 1 SED. Nodes are numbered 2 to 5. Node 2 becomes leader, 3 becomes router, 4 becomes SED, and 5 becomes FED. Nodes 2 and 3 are neighbors, and 4 becomes a child of 2, while 5 becomes a child of 3. """ def assert_network_topology(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) self.assertEqual(RoleType.ROUTER, nodes[3].role) for node_id in range(4, 6): self.assertEqual(RoleType.CHILD, nodes[node_id].role) self.assertEqual(1, len(nodes[2].neighbors)) self.assertEqual(1, len(nodes[3].neighbors)) self.assertEqual(1, len(nodes[2].children)) self.assertEqual(1, len(nodes[3].children)) self.assertIn(nodes[2].extaddr, nodes[3].neighbors) self.assertIn(nodes[3].extaddr, nodes[2].neighbors) self.assertIn(nodes[4].extaddr, nodes[2].children) self.assertIn(nodes[5].extaddr, nodes[3].children) test_class = "TestNeighborTable" test_phases = [ "test01_Form_Network", "test02_Verify_Router_Type", "test03_Verify_Children", "test04_Verify_Router", "test05_Verify_NeighborTable_AsValMap" ] replayer = self.create_replayer("neighbor_table_log.txt") # setting up: nodes added line_number = replayer.run(stop_regex=fr"SET UP {test_class}.{test_phases[0]}") otns_nodes = self.verify_nodes_added(4) # form network: node modes change; title changes expect_thread = self.expect_udp_messages([("mode=sn", 4)]) line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[0]}") self.wait_for_expect(expect_thread) self.assertEqual(4, len(self.manager.otns_node_map)) for phase in range(1, 5): line_number = replayer.run(start_line=line_number, stop_regex=fr"TEAR DOWN {test_class}.{test_phases[phase]}") assert_network_topology(otns_nodes) # tearing down: nodes removed expect_thread = self.expect_grpc_commands([f"del {i}" for i in range(2, 6)]) replayer.run(start_line=line_number) self.wait_for_expect(expect_thread) self.assertFalse(self.manager.otns_node_map) def testReplayPartitionMerge(self): """Test replaying the partition merge test case log. The log file runs with 4 nodes to form a Thread network, with 1 leader, 1 router, and 2 FEDs. Nodes are numbered 2 to 5. Initially node 2 becomes leader, 3 becomes router, 4-5 become FED. Nodes 2 and 3 are neighbors, and 4 becomes a child of 2, while 5 becomes a child of 3. The test separates the two so that 3 becomes a leader on its own, then merge the partitions again. """ def assert_network_topology_one_partition(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) self.assertEqual(RoleType.ROUTER, nodes[3].role) for node_id in range(4, 6): self.assertEqual(RoleType.CHILD, nodes[node_id].role) self.assertEqual(1, len(nodes[2].neighbors)) self.assertEqual(1, len(nodes[3].neighbors)) self.assertEqual(1, len(nodes[2].children)) self.assertEqual(1, len(nodes[3].children)) self.assertIn(nodes[2].extaddr, nodes[3].neighbors) self.assertIn(nodes[3].extaddr, nodes[2].neighbors) self.assertIn(nodes[4].extaddr, nodes[2].children) self.assertIn(nodes[5].extaddr, nodes[3].children) def assert_network_topology_two_partitions(nodes: Dict[int, OtnsNode]): """Assert that the network topology is as described above. Args: nodes (Dict[int, OtnsNode]) nodes from the OTNS manager. """ self.assertEqual(RoleType.LEADER, nodes[2].role) self.assertEqual(RoleType.LEADER, nodes[3].role) for node_id in range(4, 6): self.assertEqual(RoleType.CHILD, nodes[node_id].role) self.assertFalse(nodes[2].neighbors) self.assertFalse(nodes[3].neighbors) self.assertEqual(1, len(nodes[2].children)) self.assertEqual(1, len(nodes[3].children)) self.assertNotIn(nodes[2].extaddr, nodes[3].neighbors) self.assertNotIn(nodes[3].extaddr, nodes[2].neighbors) self.assertIn(nodes[4].extaddr, nodes[2].children) self.assertIn(nodes[5].extaddr, nodes[3].children) test_class = "TestPartitionMerge" test_phases = [ "test01_pairing", "test02_unallowlist_r1_r2", "test03_allowlist_r1_r2", "test04_verify_role_prefix_childTable" ] replayer = self.create_replayer("partition_merge_log.txt")
has changed, or None if the file hasn't changed at all. """ file_contents = _ReadWriteableFile(iwyu_record.filename, flags.dry_run or flags.checkout_command) if not file_contents: print('(skipping %s: not a writable file)' % iwyu_record.filename) return None print(">>> Fixing #includes in '%s'" % iwyu_record.filename) file_lines = ParseOneFile(file_contents, iwyu_record) old_lines = [fl.line for fl in file_lines if fl is not None and fl.line is not None] fixed_lines = FixFileLines(iwyu_record, file_lines, flags) fixed_lines = [line for line in fixed_lines if line is not None] if old_lines == fixed_lines: print("No changes in file ", iwyu_record.filename) return None if flags.dry_run: PrintFileDiff(old_lines, fixed_lines) return fixed_lines def CreateCLForCheckoutCommand(checkout_command, invoking_command): """Create a CL using a command inferred from the checkout_command. Arguments: checkout_commmand: The command specified with --checkout_command invoking_command: If not None, the command line passed to iwyu.py Returns: A CL number on success, else None. If the checkout_command is 'p4|g4|v4 edit' then attempt to create a CL with an appropriate description. On success, return the CL number. Otherwise return None. """ if checkout_command in ('p4 edit', 'g4 edit', 'v4 edit'): what4 = checkout_command.split(' ')[0] else: # We don't know how to create a CL. Punt. return None description_lines = ['\tInclude what you use.\n'] if invoking_command: description_lines.append( '\tThe following command was run to modify the files:\n') description_lines.append('\t' + invoking_command + '\n') # The change description must be of a certain form. First invoke # '<what4> client -o' to create a template, then replace # '<enter description here>' with the desired description. # The lines after that are File lines, which we will discard # here, because we will add the files via '<what4> edit -c <CL#>'. input_lines = [] description_added = False output_lines = [] for line in _GetCommandOutputLines(what4, ['change', '-o']): output_lines.append(line) if line == '\t<enter description here>\n': input_lines.extend(description_lines) description_added = True break else: input_lines.append(line) if not description_added: print('ERROR: Didn\'t find "\t<enter description here>" in' ' "%s change -o" output' % what4) for line in output_lines: print(line, end=None) return None input_text = ''.join(input_lines) output = _GetCommandOutputWithInput('%s change -i' % what4, input_text) # Parse output for "Changelist XXX created." m = re.match(r'Change (\d+) created.', output) if not m: print('ERROR: Unexpected change creation output "%s"' % output) return None return m.group(1) def FixManyFiles(iwyu_records, flags): """Given a list of iwyu_records, fix each file listed in the record. For each iwyu record in the input, which lists the #includes and forward-declares to add, remove, and re-sort, loads the file, makes the fixes, and writes the fixed file to disk. The flags affect the details of the fixing. Arguments: iwyu_records: a collection of IWYUOutputRecord objects holding the parsed output of the include-what-you-use script (run at verbose level 1 or higher) pertaining to a single source file. iwyu_record.filename indicates what file to edit. flags: commandline flags, as parsed by optparse. We use flags.dry_run and flags.checkout_command, which determine how we read and write files, and other flags indirectly. Returns: The number of files fixed (as opposed to ones that needed no fixing). """ file_and_fix_pairs = [] files_to_checkout = [] for iwyu_record in iwyu_records: try: fixed_lines = GetFixedFile(iwyu_record, flags) if fixed_lines is not None: file_and_fix_pairs.append((iwyu_record.filename, fixed_lines)) if flags.checkout_command and \ not flags.dry_run and \ not os.access(iwyu_record.filename, os.W_OK): files_to_checkout.append(iwyu_record.filename) except FixIncludesError as why: print('ERROR: %s - skipping file %s' % (why, iwyu_record.filename)) # It's much faster to check out all the files at once. if flags.checkout_command and files_to_checkout: checkout_command = flags.checkout_command # If --create_cl_if_possible was specified, AND if all files that # need fixing are not writable (not opened for edit in this # client), try to create a CL to contain those edits. This is to # avoid inadvertently creating multiple CLs. if (flags.create_cl_if_possible and len(files_to_checkout) == len(file_and_fix_pairs)): cl = CreateCLForCheckoutCommand(flags.checkout_command, flags.invoking_command_line) if cl: # Assumption: the checkout command supports the '-c <CL#>' syntax. checkout_command += (' -c ' + cl) # Else if --append_to_cl was specified, add the files that need # editing to the specified (existing) CL. # NOTE: If one or more of these files is already open, this will # presumably fail. elif flags.append_to_cl: checkout_command += (' -c %d' % flags.append_to_cl) _RunCommand(checkout_command, files_to_checkout) if not flags.dry_run: for filename, fixed_lines in file_and_fix_pairs: _WriteFileContents(filename, fixed_lines) files_fixed = [filename for filename, _ in file_and_fix_pairs] print('IWYU edited %d files on your behalf.\n' % len(files_fixed)) return len(files_fixed) def ProcessIWYUOutput(f, files_to_process, flags): """Fix the #include and forward-declare lines as directed by f. Given a file object that has the output of the include_what_you_use script, see every file to be edited and edit it, if appropriate. Arguments: f: an iterable object that is the output of include_what_you_use. files_to_process: A set of filenames, or None. If not None, we ignore files mentioned in f that are not in files_to_process. flags: commandline flags, as parsed by optparse. The only flag we use directly is flags.ignore_re, to indicate files not to process; we also pass the flags to other routines. Returns: The number of files that had to be modified (because they weren't already all correct). In dry_run mode, returns the number of files that would have been modified. """ # First collect all the iwyu data from stdin. # Maintain sort order by using OrderedDict instead of dict iwyu_output_records = OrderedDict() # IWYUOutputRecords keyed by filename while True: iwyu_output_parser = IWYUOutputParser() try: iwyu_record = iwyu_output_parser.ParseOneRecord(f, flags) if not iwyu_record: break except FixIncludesError as why: print('ERROR: %s' % why) continue filename = iwyu_record.filename if files_to_process is not None and filename not in files_to_process: print('(skipping %s: not listed on commandline)' % filename) continue if flags.ignore_re and re.search(flags.ignore_re, filename): print('(skipping %s: it matches --ignore_re, which is %s)' % ( filename, flags.ignore_re)) continue if filename in iwyu_output_records: iwyu_output_records[filename].Merge(iwyu_record) else: iwyu_output_records[filename] = iwyu_record # Now ignore all the files that never had any contentful changes # seen for them. (We have to wait until we're all done, since a .h # file may have a contentful change when #included from one .cc # file, but not another, and we need to have merged them above.) for filename in iwyu_output_records: if not iwyu_output_records[filename].HasContentfulChanges(): print('(skipping %s: iwyu reports no contentful changes)' % filename) # Mark that we're skipping this file by setting the record to None iwyu_output_records[filename] = None # Now do all the fixing, and return the number of files modified contentful_records = [ior for ior in iwyu_output_records.values() if ior] return FixManyFiles(contentful_records, flags) def SortIncludesInFiles(files_to_process, flags): """For each file in files_to_process, sort its #includes. This reads each input file, sorts the #include lines, and replaces the input file with the result. Like ProcessIWYUOutput, this requires that the file be writable, or that flags.checkout_command be set. SortIncludesInFiles does not add or remove any #includes. It also ignores forward-declares. Arguments: files_to_process: a list (or set) of filenames. flags: commandline flags, as parsed by optparse. We do not use any flags directly, but pass them to other routines. Returns: The number of files that had to be modified (because they weren't already all correct, that is, already in sorted order). """ num_fixes_made = 0 sort_only_iwyu_records = [] for filename in files_to_process: # An empty iwyu record has no adds or deletes, so its only effect # is to cause us to sort the #include lines. (Since fix_includes # gets all its knowledge of where forward-declare lines are from # the iwyu input, with an empty iwyu record it just ignores all # the forward-declare lines entirely.) sort_only_iwyu_records.append(IWYUOutputRecord(filename)) return FixManyFiles(sort_only_iwyu_records, flags) def main(argv): # Parse the command line. parser = optparse.OptionParser(usage=_USAGE) parser.add_option('-b', '--blank_lines', action='store_true', default=True, help=('Put a blank line between primary header file and' ' C/C++ system #includes, and another blank line' ' between system #includes and google #includes' ' [default]')) parser.add_option('--noblank_lines', action='store_false', dest='blank_lines') parser.add_option('--comments', action='store_true', default=False, help='Put comments after the #include lines') parser.add_option('--nocomments', action='store_false', dest='comments') parser.add_option('--safe_headers', action='store_true', default=True, help=('Do not remove unused #includes/fwd-declares from' ' header files; just add new ones [default]')) parser.add_option('--nosafe_headers', action='store_false', dest='safe_headers') parser.add_option('-s', '--sort_only', action='store_true', help=('Just sort #includes
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_mongo_db_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}'} # type: ignore def begin_delete_mongo_db_database( self, resource_group_name, # type: str account_name, # type: str database_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes an existing Azure Cosmos DB MongoDB database. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param database_name: Cosmos DB database name. :type database_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_mongo_db_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_mongo_db_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}'} # type: ignore def get_mongo_db_database_throughput( self, resource_group_name, # type: str account_name, # type: str database_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.ThroughputSettingsGetResults" """Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database account with the provided name. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param database_name: Cosmos DB database name. :type database_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ThroughputSettingsGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ThroughputSettingsGetResults"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-15" accept = "application/json" # Construct URL url = self.get_mongo_db_database_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_mongo_db_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_mongo_db_database_throughput_initial( self, resource_group_name, # type: str account_name, # type: str database_name, # type: str update_throughput_parameters, # type: "_models.ThroughputSettingsUpdateParameters" **kwargs # type: Any ): # type: (...) -> Optional["_models.ThroughputSettingsGetResults"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ThroughputSettingsGetResults"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-15" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._update_mongo_db_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(_models.ErrorResponseUpdatedFormat, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_mongo_db_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_mongo_db_database_throughput( self, resource_group_name, # type: str account_name, # type: str database_name, # type: str update_throughput_parameters, # type: "_models.ThroughputSettingsUpdateParameters" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.ThroughputSettingsGetResults"] """Update RUs per second of the an Azure Cosmos DB MongoDB database. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param database_name: Cosmos DB database name. :type database_name: str :param update_throughput_parameters: The RUs per second of the parameters to provide for the current MongoDB database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either ThroughputSettingsGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ThroughputSettingsGetResults"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._update_mongo_db_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_mongo_db_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_mongo_db_database_to_autoscale_initial( self, resource_group_name, # type: str account_name, # type: str database_name, # type: str **kwargs # type: Any ): # type: (...) -> Optional["_models.ThroughputSettingsGetResults"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ThroughputSettingsGetResults"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-15" accept = "application/json" # Construct URL url = self._migrate_mongo_db_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(_models.ErrorResponseUpdatedFormat, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200:
# PlacesCNN for scene classification # # by <NAME> # last modified by <NAME>, Dec.27, 2017 with latest pytorch and torchvision (upgrade your torchvision please if there is trn.Resize error) import torch import datetime from torch.autograd import Variable as V import torchvision.models as models from torchvision import transforms as trn from torch.nn import functional as F import os import xlsxwriter from PIL import Image from anytree import Node, RenderTree from collections import defaultdict import json # importing csv module import csv # th architecture to use arch = 'resnet18' # load the pre-trained weights model_file = '%s_places365.pth.tar' % arch if not os.access(model_file, os.W_OK): weight_url = 'http://places2.csail.mit.edu/models_places365/' + model_file os.system('wget ' + weight_url) model = models.__dict__[arch](num_classes=365) checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage) state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} model.load_state_dict(state_dict) model.eval() # load the image transformer centre_crop = trn.Compose([ trn.Resize((256,256)), trn.CenterCrop(224), trn.ToTensor(), trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # load the class label file_name = 'categories_places365.txt' if not os.access(file_name, os.W_OK): synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/categories_places365.txt' os.system('wget ' + synset_url) classes = list() with open(file_name) as class_file: for line in class_file: classes.append(line.strip().split(' ')[0][3:]) classes = tuple(classes) from os import listdir from os.path import isfile, join mypath = 'C:\\Users\\marti\\Documents\\Kuleuven\\Masterjaar\\Masterproef\\fotos-pieter\\fotos\\BENLFR' onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] hour = datetime.datetime.now().hour minute = datetime.datetime.now().minute second = datetime.datetime.now().second date = datetime.datetime.now().date() workbook = xlsxwriter.Workbook('C:\\Users\\marti\\Desktop\\ResultatenRouteYou\\stat' + str(date) +'_' + str(hour)+str(minute)+str(second)+'.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1','Type') worksheet.write('B1','#') worksheet.write('C1','Juist') worksheet.write('D1','Fout') worksheet.write('E1','False neg') worksheet.write('F1','False pos') juist = 0 nietGevonden = 0 falseNegTeller = 0 falsePosTeller = 0 class Resultaat: def __init__(self,type): self.type = type; self.aantal = 0 self.juist = 0 self.fout = 0 self.falseNeg = 0 self.falsePos = 0 GeneralTypeID_dict = {} POITypes = dict() Childs = dict() Parent = dict() RelatedWord = dict() church = ["synagoge", "mausoleum","tower"] castle = ["moat","canal","pond","palace","ruin","formal_garden"] palace = ["moat","canal","pond","castle","ruin","formal_garden"] bridge = ["canal","river","viaduct","aqueduct", "lock_chamber", "rope_bridge","moat","industrial_area"] street = ["crosswalk","plaza","alley"] crosswalk = ["street","plaza","alley"] park = ["forest_road","picnic_area","forest_pad","field/wild", "japanese_garden","botanical","garden/yard","rainforest","path/forest_path","vegetable_garden"] lawn = ["formal_garden","topiary_garden","botanical_garden","yard"] building = ["crosswalk","parking_garage","synagoge","hangar","farm","manufactured_home","burrough","patio","porch","museum"] house = ["oast_house"] square = ["fountain"] hotel_room = ["bedchamber","bedroom","youth_hostel"] bedchamber = ["hotel_room","bedroom","youth_hostel"] bedroom = ["bedchamber","hotel_room","youth_hostel"] youth_hostel = ["bedchamber","bedroom","hotel_room"] quest_room = ["bedchamber","bedroom","hotel_room","quest_room"] restaurant = ["dining_room","dining_hall","banquet_hall","sushi_bar","pizzeria"] orchard = ["field","path","garden"] RelatedWord["castle"] = castle RelatedWord["bridge"] = bridge RelatedWord["street"] = street RelatedWord["crosswalk"] = crosswalk RelatedWord["park"] = park RelatedWord["lawn"] = lawn RelatedWord["building"] = building RelatedWord["house"] = house RelatedWord["square"] = square RelatedWord["church"] = church RelatedWord["hotel_room"] = hotel_room RelatedWord["bedchamber"] = bedchamber RelatedWord["bedroom"] = bedroom RelatedWord["youth_hostel"] = youth_hostel RelatedWord["quest room"] = youth_hostel RelatedWord["restaurant"] = restaurant RelatedWord["orchard"] = orchard RelatedWord["palace"] = palace class resPlaces(object): def __init__(self, data,percentage): self.data = data self.percentage = percentage class Node(object): def __init__(self, data): self.data = data self.children = [] self.parent = [] def add_child(self, obj): self.children.append(obj) def add_parent(self, obj): self.parent = obj def addType(id, value): if id in POITypes: print('error') else: POITypes[id] = value def addChilds(id, value): if id in Childs: print('error') else: Childs[id] = value def addParent(id, value): Parent[id] = value def GenerateTreePOI(): f = open('poi_types.csv', encoding='UTF-8') data = [] line_count = 0 for line in f: data_line = line.rstrip().split(';') if line_count == 0: line_count += 1 else: res = data_line[1] res = res.replace("\"\"", "\"") res = res[:-1] res = res[1:] jsonObject = json.loads(res) englishTranslation = "" for i in jsonObject: if i.get('en'): englishTranslation = i.get('en') addType(data_line[0],Node(englishTranslation.lower())) addChilds(data_line[0],data_line[2].lower()) GeneralTypeID_dict[str(englishTranslation).lower()] = data_line[0] line_count += 1 for childId in Childs: if(Childs.get(childId) != ""): test = json.loads(Childs.get(childId)) for integ in test: POITypes.get(str(childId)).add_child(POITypes.get(str(integ))) POITypes.get(str(integ)).add_parent(POITypes.get(str(childId))) print("Tree build") return def evaluate(resultPlaces): for i in range(0, 5): if(resultPlaces[i].percentage > 0.35): if (resultPlaces[i].data != None): return resultPlaces[i] perc = resultPlaces[0].percentage indexObjectNul = 0 objectNul = resultPlaces[indexObjectNul].data #if(objectNul != None): while(perc < 0.35): if (objectNul != None): if(objectNul.data != "poi"): perc = resultPlaces[indexObjectNul].percentage for i in range(indexObjectNul+1, 5): if(resultPlaces[i].data != None): object = resultPlaces[i].data while(object.data != "poi"): if(objectNul == object): perc = perc + resultPlaces[i].percentage break else : object = object.parent if(perc < 0.35): objectNul = objectNul.parent else: while True: indexObjectNul = indexObjectNul + 1 objectNul = resultPlaces[indexObjectNul].data perc = resultPlaces[indexObjectNul].percentage if(indexObjectNul == 4): return -1 break else: while True: indexObjectNul = indexObjectNul + 1 objectNul = resultPlaces[indexObjectNul].data perc = resultPlaces[indexObjectNul].percentage if (indexObjectNul == 4): return -1 break # else: # return -1 return resPlaces(objectNul,perc) resultaatList = [] GenerateTreePOI() for file in onlyfiles: print('fileName -> {}', file) # load the test image # if not os.access(img_name, os.W_OK): # img_url = 'http://places.csail.mit.edu/demo/' + img_name # os.system('wget ' + img_url) if(file.find(".jpeg") != -1 or file.find(".jpg") != -1 or file.find(".png") != -1): try: img = Image.open(mypath + "\\" + file) input_img = V(centre_crop(img).unsqueeze(0)) # forward pass logit = model.forward(input_img) h_x = F.softmax(logit, 1).data.squeeze() probs, idx = h_x.sort(0, True) print('{} prediction on {}'.format(arch, file)) resultPlaces = [] check = 0 juistCheck = 0 nietGevondenCheck = 0 falseNegCheck = 0 falsePosCheck = 0 checkResult = 0 klasse = [] falseNeg = [] falsePos = [] result = "" # output the prediction for i in range(0, 5): print('{:.3f} -> {}'.format(probs[i], classes[idx[i]])) for i in range(0, 5): result = result + "_" + classes[idx[i]] #todo #Sommige classes uit de categorie_places365.txt bevatten categorien zoals church/outside #voorlopig neem ik gewoon het eerste deel daarvan/ in de toekomst nog wijzigen classes_split = classes[idx[i]].split("/") percentage = float('{:.3f}'.format(probs[i])) if(RelatedWord.get(classes_split[0]) != None): for related in RelatedWord.get(classes_split[0]): for index in range(0, 5): if(i != index): classes_split_intern = classes[idx[index]].split("/") if(classes_split_intern[0] == related): percentage = percentage + float('{:.3f}'.format(probs[index])) # speciale gevallen if(classes_split[0] == "bedroom" or classes_split[0] == "hotel_room" or classes_split[0] == "youth_hostel" ): classes_split[0] = "quest room" ############################################# #slecht geprogrammeerd omdat guest room hier harcoded staat maar lukt gelijk niet anders :( if (str('quest room') == classes_split[0]): resultPlaces.append(resPlaces(POITypes.get(GeneralTypeID_dict.get("guest room")),percentage)) else: resultPlaces.append(resPlaces(POITypes.get(GeneralTypeID_dict.get(classes_split[0])),percentage)) resEvaluate = evaluate(resultPlaces) check = 0 juistCheck = 0 nietGevondenCheck = 0 falseNegCheck = 0 falsePosCheck = 0 checkResult = 0 klasse = [] falseNeg = [] falsePos = [] if(resEvaluate == -1): #geen goede match gevonden print('geen goed match gevonden') else: #goede match gevonden :) if(resEvaluate.data != None): if ((resEvaluate.data.data.find("cathedral") != -1)): klasse.append("Kerk") klasse.append("Kathedraal") klasse.append("Kapel") klasse.append("POI") klasse.append("Erfgoed") klasse.append("Foto-stopplaats") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") falsePos.append("Kasteel") falsePos.append("Abdij") falsePos.append("Belfort") falsePos.append("Burcht") check = 1 elif ((resEvaluate.data.data.find("church") != -1)): klasse.append("Kerk") klasse.append("Kathedraal") klasse.append("Kapel") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") falsePos.append("Burcht") falsePos.append("Kasteel") falsePos.append("Abdij") falsePos.append("Belfort") check = 1 elif ((resEvaluate.data.data.find("synagoge") != -1)): klasse.append("Kerk") klasse.append("Kathedraal") klasse.append("Kapel") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") falsePos.append("Burcht") falsePos.append("Kasteel") check = 1 elif (resEvaluate.data.data.find("bridge") != -1): klasse.append("Brug") klasse.append("POI") klasse.append("Foto-stopplaats") check = 1 elif (resEvaluate.data.data.find("building") != -1): klasse.append("Huis") klasse.append("Gebouw") klasse.append("Herenhuis") klasse.append("Herenwoonst") klasse.append("Stadhuis") klasse.append("Kantoorgebouw") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Boerderij") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falseNeg.append("Kerk") falseNeg.append("Kathedraal") falseNeg.append("Kapel") falseNeg.append("Abdij") falseNeg.append("Burcht") falseNeg.append("B&B") falseNeg.append("Boekenwinkel") falseNeg.append("Cafe") falseNeg.append("Architecturale plaats") falseNeg.append("Begijnhof") falseNeg.append("Museum") falseNeg.append("School") falseNeg.append("Voetbalstadion") falseNeg.append("Hotel") falseNeg.append("Hostel") falseNeg.append("Kasteel") falseNeg.append("Brouwerij") falseNeg.append("Hoeve") falseNeg.append("Landgoed") falseNeg.append("Klooster") falseNeg.append("Belfort") falseNeg.append("Hotel") falsePos.append("Plein") elif (resEvaluate.data.data.find("house") != -1): klasse.append("Huis") klasse.append("Gebouw") klasse.append("Herenhuis") klasse.append("Herenwoonst") klasse.append("Stadhuis") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") klasse.append("Hoeve") falseNeg.append("Kerk") falseNeg.append("Kathedraal") falseNeg.append("Kapel") falseNeg.append("Abdij") falseNeg.append("Burcht") falseNeg.append("B&B") falseNeg.append("Boekenwinkel") falseNeg.append("Cafe") falseNeg.append("Architecturale plaats") falseNeg.append("Begijnhof") falseNeg.append("Museum") falseNeg.append("Hotel") falseNeg.append("Hostel") falseNeg.append("Brouwerij") falseNeg.append("Hotel") falsePos.append("Kasteel") elif (resEvaluate.data.data.find("stadium") != -1): klasse.append("Voetbalstadion") klasse.append("POI") klasse.append("Foto-stopplaats") check = 1 elif (resEvaluate.data.data.find("windmill") != -1): klasse.append("Windmolen") klasse.append("POI") klasse.append("Foto-stopplaats") falsePos.append("Belfort") check = 1 elif (resEvaluate.data.data.find("castle") != -1): klasse.append("Kasteel") klasse.append("Burcht") klasse.append("Vesting") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") klasse.append("Landgoed") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") falsePos.append("Historisch gebouw") check = 1 elif (resEvaluate.data.data.find("palace")!= -1): klasse.append("Kasteel") klasse.append("Burcht") klasse.append("Vesting") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") klasse.append("Landgoed") falsePos.append("Abdij") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") check = 1 elif (resEvaluate.data.data.find("tower")!= -1): klasse.append("Belfort") klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falsePos.append("Huis") falsePos.append("Gebouw") falsePos.append("Herenhuis") falseNeg.append("Kathedraal") falseNeg.append("Kerk") check = 1 elif (resEvaluate.data.data.find("canal")!= -1): klasse.append("Kanaal") klasse.append("Kolk") klasse.append("Water") klasse.append("POI") klasse.append("Foto-stopplaats") falseNeg.append("Brug") check = 1 elif (resEvaluate.data.data.find("moat/water") != -1): klasse.append("Kanaal") klasse.append("Kolk") klasse.append("POI") klasse.append("Foto-stopplaats") falseNeg.append("Brug") falseNeg.append("Burcht") check = 1 elif (resEvaluate.data.data.find("cemetery") != -1): klasse.append("Begraafplaats") klasse.append("Militaire begraafplaats") klasse.append("POI") klasse.append("Erfgoed") falsePos.append("Park") check = 1 elif (resEvaluate.data.data.find("park") != -1): klasse.append("Park") klasse.append("POI") falseNeg.append("Bos") falseNeg.append("Begraafplaats") falseNeg.append("Militaire begraafplaats") check = 1 elif (resEvaluate.data.data.find("guest room") != -1): klasse.append("Hotel") klasse.append("Hostel") klasse.append("POI") check = 1 elif (resEvaluate.data.data.find("restaurant") != -1): klasse.append("POI") falseNeg.append("Hotel") check = 1 elif (resEvaluate.data.data.find("structure") != -1): klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") falseNeg.append("Brug") falseNeg.append("Burcht") falseNeg.append("Huis") falseNeg.append("Gebouw") falseNeg.append("Herenhuis") falseNeg.append("Historisch gebouw") falseNeg.append("Kasteel") falseNeg.append("Vesting") falseNeg.append("Kerk") falseNeg.append("Kathedraal") falseNeg.append("Kasteel") falseNeg.append("Brouwerij") falseNeg.append("Windmolen") falseNeg.append("Klooster") falseNeg.append("Hotel") falseNeg.append("Kapel") falseNeg.append("Abdij") falseNeg.append("Burcht") falseNeg.append("B&B") falseNeg.append("Boekenwinkel") falseNeg.append("Cafe") falseNeg.append("Architecturale plaats") falseNeg.append("Belfort") falseNeg.append("Militaire begraafplaats") falseNeg.append("Boerderij") falseNeg.append("Hotel") falseNeg.append("Landgoed") check = 1 elif (resEvaluate.data.data.find("courtyard") != -1): klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Plein") klasse.append("Historisch gebouw") klasse.append("Historische plaats") klasse.append("Historische dorp") klasse.append("Historische stad") klasse.append("Historische gebeurtenis") elif (resEvaluate.data.data.find("square") != -1): klasse.append("POI") klasse.append("Foto-stopplaats") klasse.append("Erfgoed") klasse.append("Plein") klasse.append("Historisch gebouw") klasse.append("Historische
raise NotImplementedError else: raise NotImplementedError @torch.jit.unused def _set_aux_loss(self, outputs_class, outputs_coord): # this is a workaround to make torchscript happy, as torchscript # doesn't support dictionary with non-homogeneous values, such # as a dict having both a Tensor and a list. return [{'pred_logits': a, 'pred_boxes': b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])] def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2): """ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples. Default = -1 (no weighting). gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor """ prob = inputs.sigmoid() ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") p_t = prob * targets + (1 - prob) * (1 - targets) loss = ce_loss * ((1 - p_t) ** gamma) if alpha >= 0: alpha_t = alpha * targets + (1 - alpha) * (1 - targets) loss = alpha_t * loss return loss.mean(1).sum() / num_boxes class SetCriterion(nn.Module): """ This class computes the loss for Meta-DETR. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box) """ def __init__(self, args, num_classes, matcher, weight_dict, losses, focal_alpha=0.25): """ Create the criterion. Parameters: num_classes: number of object categories, omitting the special no-object category matcher: module able to compute a matching between targets and proposals weight_dict: dict containing as key the names of the losses and as values their relative weight. losses: list of all the losses to be applied. See get_loss for list of available losses. focal_alpha: alpha in Focal Loss """ super().__init__() self.args = args self.num_classes = num_classes self.matcher = matcher self.weight_dict = weight_dict self.losses = losses self.focal_alpha = focal_alpha def loss_labels(self, outputs, targets, indices, num_boxes, log=True): """Classification loss (NLL) targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes] """ assert 'pred_logits' in outputs src_logits = outputs['pred_logits'] idx = self._get_src_permutation_idx(indices) target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]) target_classes = torch.full(src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device) target_classes[idx] = target_classes_o target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1], dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device) target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1) target_classes_onehot = target_classes_onehot[:, :, :-1] # ################### Only Produce Loss for Activated Categories ################### activated_class_ids = outputs['activated_class_ids'] # (bs, num_support) activated_class_ids = activated_class_ids.unsqueeze(1).repeat(1, target_classes_onehot.shape[1], 1) loss_ce = sigmoid_focal_loss(src_logits.gather(2, activated_class_ids), target_classes_onehot.gather(2, activated_class_ids), num_boxes, alpha=self.focal_alpha, gamma=2) loss_ce = loss_ce * src_logits.shape[1] losses = {'loss_ce': loss_ce} if log: losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0] return losses @torch.no_grad() def loss_cardinality(self, outputs, targets, indices, num_boxes): """ Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients """ pred_logits = outputs['pred_logits'] device = pred_logits.device tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device) # Count the number of predictions that are NOT "no-object" (which is the last class) card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1) card_err = F.l1_loss(card_pred.float(), tgt_lengths.float()) losses = {'cardinality_error': card_err} return losses def loss_boxes(self, outputs, targets, indices, num_boxes): """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size. """ assert 'pred_boxes' in outputs idx = self._get_src_permutation_idx(indices) src_boxes = outputs['pred_boxes'][idx] target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0) loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none') losses = dict() losses['loss_bbox'] = loss_bbox.sum() / num_boxes loss_giou = 1 - torch.diag( box_ops.generalized_box_iou( box_ops.box_cxcywh_to_xyxy(src_boxes), box_ops.box_cxcywh_to_xyxy(target_boxes) ) ) losses['loss_giou'] = loss_giou.sum() / num_boxes return losses def loss_category_codes_cls(self, outputs, targets, indices, num_boxes): logits = outputs['category_codes_cls_logits'] targets = outputs['category_codes_cls_targets'] losses = { "loss_category_codes_cls": F.cross_entropy(logits, targets) } return losses def _get_src_permutation_idx(self, indices): # permute predictions following indices batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) src_idx = torch.cat([src for (src, _) in indices]) return batch_idx, src_idx def _get_tgt_permutation_idx(self, indices): # permute targets following indices batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) tgt_idx = torch.cat([tgt for (_, tgt) in indices]) return batch_idx, tgt_idx def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs): loss_map = { 'labels': self.loss_labels, 'cardinality': self.loss_cardinality, 'boxes': self.loss_boxes, 'category_codes_cls': self.loss_category_codes_cls, } assert loss in loss_map, f'do you really want to compute {loss} loss?' return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs) def forward(self, outputs): """ This performs the loss computation. Parameters: outputs: dict of tensors, see the output specification of the model for the format """ # Since we are doing meta-learning over our constructed meta-tasks, the targets for these meta-tasks are # stored in outputs['meta_targets']. We dont use original targets. targets = outputs['meta_targets'] outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs' and k != 'enc_outputs'} # Retrieve the matching between the outputs of the last layer and the targets indices = self.matcher(outputs_without_aux, targets) # Compute the average number of target boxes accross all nodes, for normalization purposes num_boxes = sum(len(t["labels"]) for t in targets) num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) if is_dist_avail_and_initialized(): torch.distributed.all_reduce(num_boxes) num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item() # Compute all the requested losses losses = {} for loss in self.losses: kwargs = {} losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes, **kwargs)) # In case of auxiliary losses, we repeat this process with the output of each intermediate layer. if 'aux_outputs' in outputs: for i, aux_outputs in enumerate(outputs['aux_outputs']): indices = self.matcher(aux_outputs, targets) for loss in self.losses: if loss == 'category_codes_cls': # meta-attention cls loss not for aux_outputs continue kwargs = {} if loss == 'labels': # Logging is enabled only for the last layer kwargs['log'] = False l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs) l_dict = {k + f'_{i}': v for k, v in l_dict.items()} losses.update(l_dict) return losses class PostProcess(nn.Module): """ This module converts the model's output into the format expected by the coco api""" @torch.no_grad() def forward(self, outputs, target_sizes): """ Perform the computation Parameters: outputs: raw outputs of the model target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch For evaluation, this must be the original image size (before any data augmentation) For visualization, this should be the image size after data augment, but before padding """ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes'] batchsize = outputs['batchsize'] num_episode = outputs['num_episode'] num_queries = outputs['num_queries'] num_classes = outputs['num_classes'] out_logits = out_logits.view(batchsize, num_episode * num_queries, num_classes) out_bbox = out_bbox.view(batchsize, num_episode * num_queries, 4) assert len(out_logits) == len(target_sizes) assert target_sizes.shape[1] == 2 prob = out_logits.sigmoid() topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1) scores = topk_values topk_boxes = topk_indexes // out_logits.shape[2] labels = topk_indexes % out_logits.shape[2] boxes = box_ops.box_cxcywh_to_xyxy(out_bbox) boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4)) # and from relative [0, 1] to absolute [0, height] coordinates img_h, img_w = target_sizes.unbind(1) scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) boxes = boxes * scale_fct[:, None, :] results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)] return results class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x def build(args): if args.dataset_file in ['coco', 'coco_base']: num_classes = 91 elif args.dataset_file in ['voc', 'voc_base1', 'voc_base2', 'voc_base3']: num_classes = 21 else: raise
= assignments if device_states is not None: body['device_states'] = device_states if install_summary is not None: body['install_summary'] = install_summary if user_state_summary is not None: body['user_state_summary'] = user_state_summary return client.update_managed_e_books(managed_e_book_id=managed_e_book_id, body=body) def devicescorpmgt_deviceappmanagement_update_mdm_window_information_protection_policy(client, mdm_windows_information_protection_policy_id, id_=None, created_date_time=None, description=None, display_name=None, last_modified_date_time=None, version=None, azure_rights_management_services_allowed=None, data_recovery_certificate=None, enforcement_level=None, enterprise_domain=None, enterprise_internal_proxy_servers=None, enterprise_ip_ranges=None, enterprise_ip_ranges_are_authoritative=None, enterprise_network_domain_names=None, enterprise_protected_domain_names=None, enterprise_proxied_domains=None, enterprise_proxy_servers=None, enterprise_proxy_servers_are_authoritative=None, exempt_apps=None, icons_visible=None, indexing_encrypted_stores_or_items_blocked=None, is_assigned=None, neutral_domain_resources=None, protected_apps=None, protection_under_lock_config_required=None, revoke_on_unenroll_disabled=None, rights_management_services_template_id=None, smb_auto_encrypted_file_extensions=None, assignments=None, exempt_app_locker_files=None, protected_app_locker_files=None): body = {} if id_ is not None: body['id'] = id_ if created_date_time is not None: body['created_date_time'] = created_date_time if description is not None: body['description'] = description if display_name is not None: body['display_name'] = display_name if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if version is not None: body['version'] = version if azure_rights_management_services_allowed is not None: body['azure_rights_management_services_allowed'] = azure_rights_management_services_allowed if data_recovery_certificate is not None: body['data_recovery_certificate'] = data_recovery_certificate if enforcement_level is not None: body['enforcement_level'] = enforcement_level if enterprise_domain is not None: body['enterprise_domain'] = enterprise_domain if enterprise_internal_proxy_servers is not None: body['enterprise_internal_proxy_servers'] = enterprise_internal_proxy_servers if enterprise_ip_ranges is not None: body['enterprise_ip_ranges'] = enterprise_ip_ranges if enterprise_ip_ranges_are_authoritative is not None: body['enterprise_ip_ranges_are_authoritative'] = enterprise_ip_ranges_are_authoritative if enterprise_network_domain_names is not None: body['enterprise_network_domain_names'] = enterprise_network_domain_names if enterprise_protected_domain_names is not None: body['enterprise_protected_domain_names'] = enterprise_protected_domain_names if enterprise_proxied_domains is not None: body['enterprise_proxied_domains'] = enterprise_proxied_domains if enterprise_proxy_servers is not None: body['enterprise_proxy_servers'] = enterprise_proxy_servers if enterprise_proxy_servers_are_authoritative is not None: body['enterprise_proxy_servers_are_authoritative'] = enterprise_proxy_servers_are_authoritative if exempt_apps is not None: body['exempt_apps'] = exempt_apps if icons_visible is not None: body['icons_visible'] = icons_visible if indexing_encrypted_stores_or_items_blocked is not None: body['indexing_encrypted_stores_or_items_blocked'] = indexing_encrypted_stores_or_items_blocked if is_assigned is not None: body['is_assigned'] = is_assigned if neutral_domain_resources is not None: body['neutral_domain_resources'] = neutral_domain_resources if protected_apps is not None: body['protected_apps'] = protected_apps if protection_under_lock_config_required is not None: body['protection_under_lock_config_required'] = protection_under_lock_config_required if revoke_on_unenroll_disabled is not None: body['revoke_on_unenroll_disabled'] = revoke_on_unenroll_disabled if rights_management_services_template_id is not None: body['rights_management_services_template_id'] = rights_management_services_template_id if smb_auto_encrypted_file_extensions is not None: body['smb_auto_encrypted_file_extensions'] = smb_auto_encrypted_file_extensions if assignments is not None: body['assignments'] = assignments if exempt_app_locker_files is not None: body['exempt_app_locker_files'] = exempt_app_locker_files if protected_app_locker_files is not None: body['protected_app_locker_files'] = protected_app_locker_files return client.update_mdm_windows_information_protection_policies(mdm_windows_information_protection_policy_id=mdm_windows_information_protection_policy_id, body=body) def devicescorpmgt_deviceappmanagement_update_mobile_app(client, mobile_app_id, id_=None, created_date_time=None, description=None, developer=None, display_name=None, information_url=None, is_featured=None, large_icon=None, last_modified_date_time=None, notes=None, owner=None, privacy_information_url=None, publisher=None, publishing_state=None, assignments=None, categories=None): body = {} if id_ is not None: body['id'] = id_ if created_date_time is not None: body['created_date_time'] = created_date_time if description is not None: body['description'] = description if developer is not None: body['developer'] = developer if display_name is not None: body['display_name'] = display_name if information_url is not None: body['information_url'] = information_url if is_featured is not None: body['is_featured'] = is_featured if large_icon is not None: body['large_icon'] = large_icon if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if notes is not None: body['notes'] = notes if owner is not None: body['owner'] = owner if privacy_information_url is not None: body['privacy_information_url'] = privacy_information_url if publisher is not None: body['publisher'] = publisher if publishing_state is not None: body['publishing_state'] = publishing_state if assignments is not None: body['assignments'] = assignments if categories is not None: body['categories'] = categories return client.update_mobile_apps(mobile_app_id=mobile_app_id, body=body) def devicescorpmgt_deviceappmanagement_update_mobile_app_category(client, mobile_app_category_id, id_=None, display_name=None, last_modified_date_time=None): body = {} if id_ is not None: body['id'] = id_ if display_name is not None: body['display_name'] = display_name if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time return client.update_mobile_app_categories(mobile_app_category_id=mobile_app_category_id, body=body) def devicescorpmgt_deviceappmanagement_update_mobile_app_configuration(client, managed_device_mobile_app_configuration_id, id_=None, created_date_time=None, description=None, display_name=None, last_modified_date_time=None, targeted_mobile_apps=None, version=None, assignments=None, device_statuses=None, device_status_summary=None, user_statuses=None, user_status_summary=None): body = {} if id_ is not None: body['id'] = id_ if created_date_time is not None: body['created_date_time'] = created_date_time if description is not None: body['description'] = description if display_name is not None: body['display_name'] = display_name if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if targeted_mobile_apps is not None: body['targeted_mobile_apps'] = targeted_mobile_apps if version is not None: body['version'] = version if assignments is not None: body['assignments'] = assignments if device_statuses is not None: body['device_statuses'] = device_statuses if device_status_summary is not None: body['device_status_summary'] = device_status_summary if user_statuses is not None: body['user_statuses'] = user_statuses if user_status_summary is not None: body['user_status_summary'] = user_status_summary return client.update_mobile_app_configurations(managed_device_mobile_app_configuration_id=managed_device_mobile_app_configuration_id, body=body) def devicescorpmgt_deviceappmanagement_update_targeted_managed_app_configuration(client, targeted_managed_app_configuration_id, id_=None, created_date_time=None, description=None, display_name=None, last_modified_date_time=None, version=None, custom_settings=None, deployed_app_count=None, is_assigned=None, apps=None, assignments=None, microsoft_graph_entity_id=None, configuration_deployed_user_count=None, configuration_deployment_summary_per_app=None, microsoft_graph_managed_app_policy_deployment_summary_display_name=None, last_refresh_time=None, microsoft_graph_managed_app_policy_deployment_summary_version=None): body = {} if id_ is not None: body['id'] = id_ if created_date_time is not None: body['created_date_time'] = created_date_time if description is not None: body['description'] = description if display_name is not None: body['display_name'] = display_name if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if version is not None: body['version'] = version if custom_settings is not None: body['custom_settings'] = custom_settings if deployed_app_count is not None: body['deployed_app_count'] = deployed_app_count if is_assigned is not None: body['is_assigned'] = is_assigned if apps is not None: body['apps'] = apps if assignments is not None: body['assignments'] = assignments body['deployment_summary'] = {} if microsoft_graph_entity_id is not None: body['deployment_summary']['id'] = microsoft_graph_entity_id if configuration_deployed_user_count is not None: body['deployment_summary']['configuration_deployed_user_count'] = configuration_deployed_user_count if configuration_deployment_summary_per_app is not None: body['deployment_summary']['configuration_deployment_summary_per_app'] = configuration_deployment_summary_per_app if microsoft_graph_managed_app_policy_deployment_summary_display_name is not None: body['deployment_summary']['display_name'] = microsoft_graph_managed_app_policy_deployment_summary_display_name if last_refresh_time is not None: body['deployment_summary']['last_refresh_time'] = last_refresh_time if microsoft_graph_managed_app_policy_deployment_summary_version is not None: body['deployment_summary']['version'] = microsoft_graph_managed_app_policy_deployment_summary_version if len(body['deployment_summary']) == 0: del body['deployment_summary'] return client.update_targeted_managed_app_configurations(targeted_managed_app_configuration_id=targeted_managed_app_configuration_id, body=body) def devicescorpmgt_deviceappmanagement_update_vpp_token(client, vpp_token_id, id_=None, apple_id=None, automatically_update_apps=None, country_or_region=None, expiration_date_time=None, last_modified_date_time=None, last_sync_date_time=None, last_sync_status=None, organization_name=None, state=None, token=None, vpp_token_account_type=None): body = {} if id_ is not None: body['id'] = id_ if apple_id is not None: body['apple_id'] = apple_id if automatically_update_apps is not None: body['automatically_update_apps'] = automatically_update_apps if country_or_region is not None: body['country_or_region'] = country_or_region if expiration_date_time is not None: body['expiration_date_time'] = expiration_date_time if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if last_sync_date_time is not None: body['last_sync_date_time'] = last_sync_date_time if last_sync_status is not None: body['last_sync_status'] = last_sync_status if organization_name is not None: body['organization_name'] = organization_name if state is not None: body['state'] = state if token is not None: body['token'] = token if vpp_token_account_type is not None: body['vpp_token_account_type'] = vpp_token_account_type return client.update_vpp_tokens(vpp_token_id=vpp_token_id, body=body) def devicescorpmgt_deviceappmanagement_update_window_information_protection_policy(client, windows_information_protection_policy_id, id_=None, created_date_time=None, description=None, display_name=None, last_modified_date_time=None, version=None, azure_rights_management_services_allowed=None, data_recovery_certificate=None, enforcement_level=None, enterprise_domain=None, enterprise_internal_proxy_servers=None, enterprise_ip_ranges=None, enterprise_ip_ranges_are_authoritative=None, enterprise_network_domain_names=None, enterprise_protected_domain_names=None, enterprise_proxied_domains=None, enterprise_proxy_servers=None, enterprise_proxy_servers_are_authoritative=None, exempt_apps=None, icons_visible=None, indexing_encrypted_stores_or_items_blocked=None, is_assigned=None, neutral_domain_resources=None, protected_apps=None, protection_under_lock_config_required=None, revoke_on_unenroll_disabled=None, rights_management_services_template_id=None, smb_auto_encrypted_file_extensions=None, assignments=None, exempt_app_locker_files=None, protected_app_locker_files=None, days_without_contact_before_unenroll=None, mdm_enrollment_url=None, minutes_of_inactivity_before_device_lock=None, number_of_past_pins_remembered=None, password_maximum_attempt_count=None, pin_expiration_days=None, pin_lowercase_letters=None, pin_minimum_length=None, pin_special_characters=None, pin_uppercase_letters=None, revoke_on_mdm_handoff_disabled=None, windows_hello_for_business_blocked=None): body = {} if id_ is not None: body['id'] = id_ if created_date_time is not None: body['created_date_time'] = created_date_time if description is not None: body['description'] = description if display_name is not None: body['display_name'] = display_name if last_modified_date_time is not None: body['last_modified_date_time'] = last_modified_date_time if version is not None: body['version'] = version if azure_rights_management_services_allowed is not None: body['azure_rights_management_services_allowed'] = azure_rights_management_services_allowed if data_recovery_certificate is not None: body['data_recovery_certificate'] = data_recovery_certificate if enforcement_level is not None: body['enforcement_level'] = enforcement_level if enterprise_domain is not None: body['enterprise_domain'] = enterprise_domain if enterprise_internal_proxy_servers is not None: body['enterprise_internal_proxy_servers'] = enterprise_internal_proxy_servers if enterprise_ip_ranges is not None: body['enterprise_ip_ranges'] = enterprise_ip_ranges if enterprise_ip_ranges_are_authoritative is not None: body['enterprise_ip_ranges_are_authoritative'] = enterprise_ip_ranges_are_authoritative if enterprise_network_domain_names is not None: body['enterprise_network_domain_names'] = enterprise_network_domain_names if enterprise_protected_domain_names is not None: body['enterprise_protected_domain_names'] = enterprise_protected_domain_names if enterprise_proxied_domains is not None: body['enterprise_proxied_domains'] = enterprise_proxied_domains if enterprise_proxy_servers is not None: body['enterprise_proxy_servers'] = enterprise_proxy_servers if enterprise_proxy_servers_are_authoritative is not None: body['enterprise_proxy_servers_are_authoritative'] = enterprise_proxy_servers_are_authoritative if exempt_apps is not None: body['exempt_apps'] = exempt_apps if icons_visible is not None: body['icons_visible'] = icons_visible if indexing_encrypted_stores_or_items_blocked is not None: body['indexing_encrypted_stores_or_items_blocked'] = indexing_encrypted_stores_or_items_blocked if is_assigned is not None: body['is_assigned'] = is_assigned if neutral_domain_resources is not None: body['neutral_domain_resources'] = neutral_domain_resources if protected_apps is not None: body['protected_apps'] = protected_apps if protection_under_lock_config_required is not None: body['protection_under_lock_config_required'] = protection_under_lock_config_required if revoke_on_unenroll_disabled is not None: body['revoke_on_unenroll_disabled'] = revoke_on_unenroll_disabled if rights_management_services_template_id is not None: body['rights_management_services_template_id'] = rights_management_services_template_id if smb_auto_encrypted_file_extensions is not None: body['smb_auto_encrypted_file_extensions'] = smb_auto_encrypted_file_extensions if assignments is not None: body['assignments'] = assignments if exempt_app_locker_files is not None: body['exempt_app_locker_files'] = exempt_app_locker_files if protected_app_locker_files is not None: body['protected_app_locker_files'] = protected_app_locker_files if days_without_contact_before_unenroll is not None: body['days_without_contact_before_unenroll'] = days_without_contact_before_unenroll if mdm_enrollment_url is not None: body['mdm_enrollment_url'] = mdm_enrollment_url if minutes_of_inactivity_before_device_lock is not None: body['minutes_of_inactivity_before_device_lock'] = minutes_of_inactivity_before_device_lock if number_of_past_pins_remembered is not None: body['number_of_past_pins_remembered'] = number_of_past_pins_remembered if password_maximum_attempt_count is not None: body['password_maximum_attempt_count'] = password_maximum_attempt_count if pin_expiration_days is not None: body['pin_expiration_days'] = pin_expiration_days if pin_lowercase_letters is not None: body['pin_lowercase_letters'] = pin_lowercase_letters if pin_minimum_length is not None: body['pin_minimum_length'] = pin_minimum_length if pin_special_characters is not None: body['pin_special_characters'] = pin_special_characters if pin_uppercase_letters is not None: body['pin_uppercase_letters'] =
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * """" IMPORTS """ import json import requests from datetime import datetime, timedelta # Disable insecure warnings requests.packages.urllib3.disable_warnings() ''' GLOBAL VARS ''' # PagerDuty API works only with secured communication. USE_SSL = not demisto.params().get('insecure', False) USE_PROXY = demisto.params().get('proxy', True) API_KEY = demisto.params()['APIKey'] SERVICE_KEY = demisto.params()['ServiceKey'] FETCH_INTERVAL = demisto.params()['FetchInterval'] SERVER_URL = 'https://api.pagerduty.com/' CREATE_EVENT_URL = 'https://events.pagerduty.com/v2/enqueue' DEFAULT_HEADERS = { 'Authorization': 'Token token=' + API_KEY, 'Accept': 'application/vnd.pagerduty+json;version=2' } '''HANDLE PROXY''' if not USE_PROXY: del os.environ['HTTP_PROXY'] del os.environ['HTTPS_PROXY'] del os.environ['http_proxy'] del os.environ['https_proxy'] '''PARAMS''' UTC_PARAM = '&time_zone=UTC' STATUSES = 'statuses%5B%5D' INCLUDED_FIELDS = '&include%5B%5D=first_trigger_log_entries&include%5B%5D=assignments' '''SUFFIX ENDPOINTS''' GET_SCHEDULES_SUFFIX = 'schedules' CREATE_INCIDENT_SUFFIX = 'incidents' GET_INCIDENT_SUFFIX = 'incidents/' GET_SERVICES_SUFFIX = 'services' ON_CALL_BY_SCHEDULE_SUFFIX = 'schedules/{0}/users' ON_CALLS_USERS_SUFFIX = 'oncalls?include%5B%5D=users' USERS_NOTIFICATION_RULE = 'users/{0}/notification_rules' GET_INCIDENTS_SUFFIX = 'incidents?include%5B%5D=assignees' USERS_CONTACT_METHODS_SUFFIX = 'users/{0}/contact_methods' '''CONTACT_METHOD_TYPES''' SMS_CONTACT_TYPE = 'sms_contact_method' EMAIL_CONTACT_TYPE = 'email_contact_method' PHONE_CONTACT_TYPE = 'phone_contact_method' PUSH_CONTACT_TYPE = 'push_notification_contact_method' CONTACT_METHODS_TO_HUMAN_READABLE = { '': 'Unknown', SMS_CONTACT_TYPE: 'SMS', PUSH_CONTACT_TYPE: 'Push', EMAIL_CONTACT_TYPE: 'Email', PHONE_CONTACT_TYPE: 'Phone' } '''TABLE NAMES''' SERVICES = 'Service List' SCHEDULES = 'All Schedules' TRIGGER_EVENT = 'Trigger Event' RESOLVE_EVENT = 'Resolve Event' ACKNOLWEDGE_EVENT = 'Acknowledge Event' USERS_ON_CALL = 'Users On Call' INCIDETS_LIST = 'PagerDuty Incidents' INCIDENT = 'PagerDuty Incident' CONTACT_METHODS = 'Contact Methods' USERS_ON_CALL_NOW = 'Users On Call Now' NOTIFICATION_RULES = 'User notification rules' '''TABLE HEADERS''' CONTACT_METHODS_HEADERS = ['ID', 'Type', 'Details'] SERVICES_HEADERS = ['ID', 'Name', 'Status', 'Created At', 'Integration'] NOTIFICATION_RULES_HEADERS = ['ID', 'Type', 'Urgency', 'Notification timeout(minutes)'] SCHEDULES_HEADERS = ['ID', 'Name', 'Today', 'Time Zone', 'Escalation Policy', 'Escalation Policy ID'] USERS_ON_CALL_NOW_HEADERS = ['ID', 'Email', 'Name', 'Role', 'User Url', 'Time Zone'] INCIDENTS_HEADERS = ['ID', 'Title', 'Description', 'Status', 'Created On', 'Urgency', 'Html Url', 'Assigned To User', 'Service ID', 'Service Name', 'Escalation Policy', 'Last Status Change On', 'Last Status Change By', 'Number Of Escalations', 'Resolved By User', 'Resolve Reason'] ''' HELPER FUNCTIONS ''' def http_request(method, url, params_dict=None, data=None): LOG('running %s request with url=%s\nparams=%s' % (method, url, json.dumps(params_dict))) try: res = requests.request(method, url, verify=USE_SSL, params=params_dict, headers=DEFAULT_HEADERS, data=data ) res.raise_for_status() return res.json() except Exception as e: LOG(e) raise(e) def translate_severity(sev): if sev == 'high': return 3 elif sev == 'Low': return 1 return 0 def test_module(): try: get_on_call_now_users_command() except Exception as e: raise Exception(e.message) demisto.results('ok') def extract_on_call_user_data(users): """Extact data about user from a given schedule.""" outputs = [] contexts = [] for user in users: output = {} context = {} output['ID'] = user.get('id') output['Name'] = user.get('name') output['Role'] = user.get('role') output['Email'] = user.get('email') output['Time Zone'] = user.get('time_zone') output['User Url'] = user.get('html_url') context['ID'] = output['ID'] context['Role'] = output['Role'] context['Email'] = output['Email'] context['Username'] = output['Name'] context['DisplayName'] = output['Name'] context['TimeZone'] = output['Time Zone'] outputs.append(output) contexts.append(context) return { 'Type': entryTypes['note'], 'Contents': users, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(USERS_ON_CALL, outputs, USERS_ON_CALL_NOW_HEADERS), 'EntryContext': { 'PagerDutyUser(val.ID==obj.ID)': contexts } } def extract_on_call_now_user_data(users_on_call_now): """Extract the user data from the oncalls json.""" outputs = [] # type: List[Dict] contexts = [] # type: List[Dict] oncalls = users_on_call_now.get('oncalls', {}) for i in xrange(len(oncalls)): output = {} context = {} data = oncalls[i] user = data.get('user') output['ID'] = user.get('id') output['Name'] = user.get('name') output['Role'] = user.get('role') output['Email'] = user.get('email') output['User Url'] = user.get('html_url') output['Time Zone'] = user.get('time_zone') context['ID'] = output['ID'] context['Role'] = output['Role'] context['Email'] = output['Email'] context['Username'] = output['Name'] context['DisplayName'] = output['Name'] context['TimeZone'] = output['Time Zone'] escal_level = data.get('escalation_level', 1) outputs.insert(escal_level - 1, output) contexts.insert(escal_level - 1, context) return { 'Type': entryTypes['note'], 'Contents': users_on_call_now, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(USERS_ON_CALL_NOW, outputs, USERS_ON_CALL_NOW_HEADERS), 'EntryContext': { 'PagerDutyUser(val.ID===obj.ID)': contexts } } def parse_incident_data(incidents): """Parse incident data to output,context format""" outputs = [] contexts = [] raw_response = [] for i, incident in enumerate(incidents): output = {} context = {} context['ID'] = output['ID'] = incident.get('id') context['Title'] = output['Title'] = incident.get('summary') output['Description'] = incident.get('first_trigger_log_entry', {}).get('channel', {}).get('details', '') context['Description'] = output['Description'] context['Status'] = output['Status'] = incident.get('status') context['created_at'] = output['Created On'] = incident.get('created_at') context['urgency'] = output['Urgency'] = incident.get('urgency', '') output['Html Url'] = incident.get('html_url') if len(incident.get('assignments', [])) > 0: output['Assigned To User'] = incident['assignments'][0].get('assignee', {}).get('name') else: output['Assigned To User'] = '-' context['assignee'] = output['Assigned To User'] context['service_id'] = output['Service ID'] = incident.get('service', {}).get('id') context['service_name'] = output['Service Name'] = incident.get('service', {}).get('summary') output['Escalation Policy'] = incident.get('escalation_policy', {}).get('summary') context['escalation_policy'] = output['Escalation Policy'] context['last_status_change_at'] = output['Last Status Change On'] = incident.get('last_status_change_at') output['Last Status Change By'] = incident.get('last_status_change_by', {}).get('summary') context['last_status_change_by'] = output['Last Status Change By'] context['number_of_escalations'] = output['Number Of Escalations'] = incident.get('number_of_escalations') if output['Status'] == 'resolved': output['Resolved By User'] = output['Last Status Change By'] else: output['Resolved By User'] = '-' context['resolved_by'] = output['Assigned To User'] context['resolve_reason'] = output['Resolve reason'] = incident.get('resolve_reason', '') context['teams'] = [] for team in incident.get('teams', []): team_id = team.get('id', '') team_name = team.get('summary', '') team_data = { "ID": team_id, "Name": team_name } context['teams'].append(team_data) assignment = incident.get('assignments', [{}, ]) if len(assignment) > 0: context['assignment'] = { "time": assignment[0].get('at', ''), "assignee": assignment[0].get('assignee', {}).get('summary', ''), } else: context['assignment'] = {} acknowledgements = incident.get('acknowledgements', [{}, ]) if len(acknowledgements) > 0: context['acknowledgement'] = { "time": assignment[0].get('at', ''), "acknowledger": assignment[0].get('acknowledger', {}).get('summary', ''), } else: context['acknowledgement'] = {} outputs.append(output) contexts.append(context) raw_response.append(incident) return outputs, contexts, raw_response def extract_incidents_data(incidents, table_name): """Extact data about incidents.""" outputs, contexts, _ = parse_incident_data(incidents) return { 'Type': entryTypes['note'], 'Contents': incidents, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(table_name, outputs, INCIDENTS_HEADERS, removeNull=True), 'EntryContext': { 'PagerDuty.Incidents(val.ID==obj.ID)': contexts } } def extract_all_schedules_data(schedules): """Extract the data about all the schedules.""" outputs = [] contexts = [] for i in range(len(schedules)): output = {} context = {} # type: Dict data = schedules[i] output['ID'] = data.get('id') output['Name'] = data.get('name') output['Time Zone'] = data.get('time_zone') output['Today'] = datetime.today().strftime('%Y-%m-%d') escalation_policies = data.get('escalation_policies', []) if len(escalation_policies) > 0: output['Escalation Policy ID'] = escalation_policies[0].get('id') output['Escalation Policy'] = escalation_policies[0].get('summary') context['escalation_policies'] = [{}, ] context['escalation_policies'][0]['name'] = output['Escalation Policy'] context['escalation_policies'][0]['id'] = output['Escalation Policy ID'] else: output['Escalation Policy'] = '-' output['Escalation Policy ID'] = '-' context['id'] = output['ID'] context['name'] = output['Name'] context['today'] = output['Today'] context['time_zone'] = output['Time Zone'] outputs.append(output) contexts.append(context) return { 'Type': entryTypes['note'], 'Contents': schedules, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(SCHEDULES, outputs, SCHEDULES_HEADERS), 'EntryContext': { 'PagerDuty.Schedules(val.id==obj.id)': contexts, } } def create_new_incident(source, summary, severity, action, description='No description', group='', event_class='', component='', incident_key=None, service_key=SERVICE_KEY): """Create a new incident in the PagerDuty instance.""" payload = { 'routing_key': service_key, 'event_action': action, 'dedup_key': incident_key, 'images': [], 'links': [], 'payload': { 'summary': summary, 'source': source, 'severity': severity, 'group': group, 'class': event_class, 'component': component, 'custom_details': { 'description': description } } } return http_request('POST', CREATE_EVENT_URL, data=json.dumps(payload)) def resolve_or_ack_incident(action, incident_key, service_key=SERVICE_KEY): """Resolve or Acknowledge an incident in the PagerDuty instance.""" payload = { 'routing_key': service_key, 'event_action': action, 'dedup_key': incident_key } return http_request('POST', CREATE_EVENT_URL, data=json.dumps(payload)) def extract_new_event_data(table_name, response): """Extract the data from the response of creating a new command.""" output = {} context = {} output['Status'] = response.get('status', '') output['Message'] = response.get('message', '') output['Incident key'] = response.get('dedup_key', '') context['Status'] = output['Status'] context['Message'] = output['Message'] context['incident_key'] = output['Incident key'] return { 'Type': entryTypes['note'], 'Contents': response, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(table_name, output), 'EntryContext': { 'PagerDuty.Event(val.incident_key==obj.dedup_key)': context, 'Event.ID(val.ID==obj.dedup_key)': context['incident_key'] } } def extract_users_contact_methods(user_contact_methods): """Extract all the contact methods of a given user.""" outputs = [] contexts = [] contact_methods = user_contact_methods.get('contact_methods') for contact_method in contact_methods: output = {} output['ID'] = contact_method.get('id') output['Type'] = CONTACT_METHODS_TO_HUMAN_READABLE[contact_method.get('type', '')] country_code = str(contact_method.get('country_code', '')) address = contact_method.get('address', '') output['Details'] = country_code + address outputs.append(output) del contact_method['address'] if output['Type'] == 'SMS' or output['Type'] == 'Phone': del contact_method['country_code'] contact_method['phone'] = output['Details'] else: contact_method['email'] = output['Details'] contexts.append(contact_method) return { 'Type': entryTypes['note'], 'Contents': user_contact_methods, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(CONTACT_METHODS, outputs, CONTACT_METHODS_HEADERS), 'EntryContext': { 'PagerDuty.Contact_methods(val.id==obj.id)': contexts, } } def extract_users_notification_role(user_notication_role): """Extract the notification role of a given user.""" outputs = [] notification_rules = user_notication_role.get('notification_rules') for notification_rule in notification_rules: output = {} output['ID'] = notification_rule.get('id') output['Type'] = notification_rule.get('type', '') output['Urgency'] = notification_rule.get('urgency') output['Notification timeout(minutes)'] = notification_rule.get('start_delay_in_minutes') outputs.append(output) return { 'Type': entryTypes['note'], 'Contents': user_notication_role, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(NOTIFICATION_RULES, outputs, NOTIFICATION_RULES_HEADERS), 'EntryContext': { 'PagerDuty.Notification_rules(val.id==obj.id)': notification_rules, } } '''COMMANDS''' def fetch_incidents(): param_dict = {} now_time = datetime.utcnow() now = datetime.isoformat(now_time) lastRunObject = demisto.getLastRun() if lastRunObject: param_dict['since'] = lastRunObject['time'] else: param_dict['since'] = datetime.isoformat(now_time - timedelta(minutes=int(FETCH_INTERVAL))) param_dict['until'] = now url = SERVER_URL + GET_INCIDENTS_SUFFIX + configure_status() res = http_request('GET', url, param_dict) _, parsed_incidents, raw_responses = parse_incident_data(res.get('incidents', [])) incidents = [] for incident, raw_response in zip(parsed_incidents, raw_responses): incidents.append({ 'name': incident['ID'] + ' - ' + incident['Title'], 'occurred': incident['created_at'], 'severity': translate_severity(incident['urgency']), 'rawJSON': json.dumps(raw_response) }) demisto.incidents(incidents) demisto.setLastRun({'time': now}) def configure_status(status='triggered,acknowledged'): statuses = status.split(',') statuses_string = "&" + STATUSES + '=' statuses = statuses_string.join(statuses) status_request = '&' + STATUSES + '=' + statuses status_request = status_request + INCLUDED_FIELDS + UTC_PARAM return status_request def get_incidents_command(since=None, until=None, status='triggered,acknowledged',
Reservation) def terminate_instances(self, instance_ids=None): """ Terminate the instances specified @type instance_ids: list @param instance_ids: A list of strings of the Instance IDs to terminate @rtype: list @return: A list of the instances terminated """ params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceId') return self.get_list('TerminateInstances', params, [('item', Instance)]) def get_console_output(self, instance_id): """ Retrieves the console output for the specified instance. See http://docs.amazonwebservices.com/AWSEC2/2008-02-01/DeveloperGuide/ApiReference-Query-GetConsoleOutput.html @type instance_id: string @param instance_id: The instance ID of a running instance on the cloud. @rtype: L{boto.ec2.instance.ConsoleOutput} @return: The console output as a ConsoleOutput object """ params = {} self.build_list_params(params, [instance_id], 'InstanceId') return self.get_object('GetConsoleOutput', params, ConsoleOutput) def reboot_instances(self, instance_ids=None): """ Reboot the specified instances. @type instance_ids: list @param instance_ids: The instances to terminate and reboot """ params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceId') return self.get_status('RebootInstances', params) def confirm_product_instance(self, product_code, instance_id): params = {'ProductCode' : product_code, 'InstanceId' : instance_id} rs = self.get_object('ConfirmProductInstance', params, ResultSet) return (rs.status, rs.ownerId) # Zone methods def get_all_zones(self, zones=None): """ Get all Availability Zones associated with the current region. @type zones: list @param zones: Optional list of zones. If this list is present, only the Zones associated with these zone names will be returned. @rtype: list of L{boto.ec2.zone.Zone} @return: The requested Zone objects """ params = {} if zones: self.build_list_params(params, zones, 'ZoneName') return self.get_list('DescribeAvailabilityZones', params, [('item', Zone)]) # Address methods def get_all_addresses(self, addresses=None): """ Get all EIP's associated with the current credentials. @type addresses: list @param addresses: Optional list of addresses. If this list is present, only the Addresses associated with these addresses will be returned. @rtype: list of L{boto.ec2.address.Address} @return: The requested Address objects """ params = {} if addresses: self.build_list_params(params, addresses, 'PublicIp') return self.get_list('DescribeAddresses', params, [('item', Address)]) def allocate_address(self): """ Allocate a new Elastic IP address and associate it with your account. @rtype: L{boto.ec2.address.Address} @return: The newly allocated Address """ return self.get_object('AllocateAddress', None, Address) def associate_address(self, instance_id, public_ip): """ Associate an Elastic IP address with a currently running instance. @type instance_id: string @param instance_id: The ID of the instance @type public_ip: string @param public_ip: The public IP address @rtype: bool @return: True if successful """ params = {'InstanceId' : instance_id, 'PublicIp' : public_ip} return self.get_status('AssociateAddress', params) def disassociate_address(self, public_ip): """ Disassociate an Elastic IP address from a currently running instance. @type public_ip: string @param public_ip: The public IP address @rtype: bool @return: True if successful """ params = {'PublicIp' : public_ip} return self.get_status('DisassociateAddress', params) def release_address(self, public_ip): """ Free up an Elastic IP address @type public_ip: string @param public_ip: The public IP address @rtype: bool @return: True if successful """ params = {'PublicIp' : public_ip} return self.get_status('ReleaseAddress', params) # Volume methods def get_all_volumes(self, volume_ids=None): """ Get all Volumes associated with the current credentials. @type volume_ids: list @param volume_ids: Optional list of volume ids. If this list is present, only the volumes associated with these volume ids will be returned. @rtype: list of L{boto.ec2.volume.Volume} @return: The requested Volume objects """ params = {} if volume_ids: self.build_list_params(params, volume_ids, 'VolumeId') return self.get_list('DescribeVolumes', params, [('item', Volume)]) def create_volume(self, size, zone, snapshot=None): """ Create a new EBS Volume. @type size: int @param size: The size of the new volume, in GiB @type zone: string or L{boto.ec2.zone.Zone} @param zone: The availability zone in which the Volume will be created. @type snapshot: string or L{boto.ec2.snapshot.Snapshot} @param snapshot: The snapshot from which the new Volume will be created. """ if isinstance(zone, Zone): zone = zone.name params = {'Size': size, 'AvailabilityZone' : zone} if snapshot: if isinstance(snapshot, Snapshot): snapshot = snapshot.id params['SnapshotId'] = snapshot return self.get_object('CreateVolume', params, Volume) def delete_volume(self, volume_id): params = {'VolumeId': volume_id} return self.get_status('DeleteVolume', params) def attach_volume(self, volume_id, instance_id, device): params = {'InstanceId' : instance_id, 'VolumeId' : volume_id, 'Device' : device} return self.get_status('AttachVolume', params) def detach_volume(self, volume_id, instance_id, device='', force=False): params = {'InstanceId' : instance_id, 'VolumeId' : volume_id, 'Device' : device} if force: params['Force'] = 'true' return self.get_status('DetachVolume', params) # Snapshot methods def get_all_snapshots(self, snapshot_ids=None): """ Get all EBS Snapshots associated with the current credentials. @type snapshot_ids: list @param snapshot_ids: Optional list of snapshot ids. If this list is present, only the Snapshots associated with these snapshot ids will be returned. @rtype: list of L{boto.ec2.snapshot.Snapshot} @return: The requested Snapshot objects """ params = {} if snapshot_ids: self.build_list_params(params, snapshot_ids, 'SnapshotId') return self.get_list('DescribeSnapshots', params, [('item', Snapshot)]) def create_snapshot(self, volume_id): params = {'VolumeId' : volume_id} return self.get_object('CreateSnapshot', params, Snapshot) def delete_snapshot(self, snapshot_id): params = {'SnapshotId': snapshot_id} return self.get_status('DeleteSnapshot', params) # Keypair methods def get_all_key_pairs(self, keynames=None): """ Get all key pairs associated with your account. @type keynames: list @param keynames: A list of the names of keypairs to retrieve. If not provided, all key pairs will be returned. @rtype: list @return: A list of L{KeyPairs<boto.ec2.keypair.KeyPair>} """ params = {} if keynames: self.build_list_params(params, keynames, 'KeyName') return self.get_list('DescribeKeyPairs', params, [('item', KeyPair)]) def get_key_pair(self, keyname): """ Convenience method to retrieve a specific keypair (KeyPair). @type image_id: string @param image_id: the ID of the Image to retrieve @rtype: L{KeyPair<boto.ec2.keypair.KeyPair>} @return: The KeyPair specified or None if it is not found """ try: return self.get_all_key_pairs(keynames=[keyname])[0] except IndexError: # None of those key pairs available return None def create_key_pair(self, key_name): """ Create a new key pair for your account. This will create the key pair within the region you are currently connected to. @type key_name: string @param key_name: The name of the new keypair @rtype: L{KeyPair<boto.ec2.keypair.KeyPair>} @return: The newly created L{KeyPair<boto.ec2.keypair.KeyPair>}. The material attribute of the new KeyPair object will contain the the unencrypted PEM encoded RSA private key. """ params = {'KeyName':key_name} return self.get_object('CreateKeyPair', params, KeyPair) def delete_key_pair(self, key_name): """ Delete a key pair from your account. @type key_name: string @param key_name: The name of the keypair to delete """ params = {'KeyName':key_name} return self.get_status('DeleteKeyPair', params) # SecurityGroup methods def get_all_security_groups(self, groupnames=None): """ Get all security groups associated with your account in a region. @type groupnames: list @param groupnames: A list of the names of security groups to retrieve. If not provided, all security groups will be returned. @rtype: list @return: A list of L{SecurityGroups<boto.ec2.securitygroup.SecurityGroup>} """ params = {} if groupnames: self.build_list_params(params, groupnames, 'GroupName') return self.get_list('DescribeSecurityGroups', params, [('item', SecurityGroup)]) def create_security_group(self, name, description): """ Create a new security group for your account. This will create the security group within the region you are currently connected to. @type name: string @param name: The name of the new security group @type description: string @param description: The description of the new security group @rtype: L{SecurityGroup<boto.ec2.securitygroup.SecurityGroup>} @return: The newly created L{KeyPair<boto.ec2.keypair.KeyPair>}. """ params = {'GroupName':name, 'GroupDescription':description} group = self.get_object('CreateSecurityGroup', params, SecurityGroup) group.name = name group.description = description return group def delete_security_group(self, name): """ Delete a security group from your account. @type key_name: string @param key_name: The name of the keypair to delete """ params = {'GroupName':name} return self.get_status('DeleteSecurityGroup', params) def authorize_security_group(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None): """ Add a new rule to an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are authorizing another group or you are authorizing some ip-based rule. @type group_name: string @param group_name: The name of the security group you are adding the rule to. @type src_security_group_name: string @param src_security_group_name: The name of the security group you are granting access to. @type src_security_group_owner_id: string @param src_security_group_owner_id: The ID of the owner of the security group you are granting access to. @type ip_protocol: string @param ip_protocol: Either tcp | udp | icmp @type from_port: int @param from_port: The beginning port number you are enabling @type to_port: int @param to_port: The ending port number you are enabling @type to_port: string @param to_port: The CIDR block you are providing access
<filename>report/oraclerpt.py<gh_stars>0 # -*- coding:utf-8 -*- ''' @project: '__dbreport__.py' @modules: report.oraclerpt @description: @author: abelit @email: <EMAIL> @created:Mar 5, 2018 @licence: GPL ''' __version__ = '''$Id$''' # from reportlab.lib.testutils import outputfile,setOutDir # setOutDir(__name__) from reportlab.pdfgen import canvas from reportlab.lib.units import inch, cm from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus.frames import Frame from reportlab.platypus.paragraph import Paragraph from reportlab.platypus.flowables import Spacer, Preformatted from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate, NextPageTemplate from reportlab.platypus import tableofcontents, PageBreak from reportlab.lib.enums import TA_CENTER, TA_LEFT from reportlab.platypus import Table, TableStyle from reportlab.lib import colors from reportlab.graphics import shapes from reportlab.graphics.widgets import signsandsymbols # 导入生产条形码的工具包 from reportlab.graphics.barcode import eanbc, qr from reportlab.graphics.shapes import Drawing, Image, Rect from reportlab.graphics import renderPDF # 导入注册字体的模块 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.platypus import Image as platImage from math import sqrt import datetime, calendar, time import random import io # 导入画图模块 import matplotlib.pyplot as plt # import matplotlib.dates as mdates # 导入自定义模块 # 导入数据库信息提取模块 from report.database import Oracle # 导入系统获取操作系统信息模块 from report.host import HostMetric from config import settings # 注册字体 pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) pdfmetrics.registerFont(TTFont('msyh', settings.path_settings['font'] + 'msyh.ttf')) myFontName = 'msyh' class BarCodes: barcode_value = '' for i in range(10): barcode_value = barcode_value + str(random.randint(0, 9)) def genEan13Barcode(self, canvas, x, y, width=50, height=10, barcode_value=barcode_value): # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) d = Drawing(width=width, height=height) d.add(barcode_eanbc13) renderPDF.draw(d, canvas, x, y) def genEan8Barcode(self, canvas, x, y, width, height, barcode_value="1234567890"): # draw the eanbc8 code barcode_eanbc8 = eanbc.Ean8BarcodeWidget(self.barcode_value) d = Drawing(width=width, height=height) d.add(barcode_eanbc8) renderPDF.draw(d, canvas, x, y) def genQrCode(self, canvas, x, y, width, height, qr_value='http://www.dataforum.org'): # draw a QR code qr_code = qr.QrCodeWidget(qr_value) bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(width, height, transform=[45. / width, 0, 0, 45. / height, 0, 0]) d.add(qr_code) renderPDF.draw(d, canvas, x, y) class DrawShape: def drawArrow(self, xdraw, ydraw, size, rotate, x, y, color): # drawArrow(10,20,20,90,0,-15,colors.green) # drawArrow(10,20,20,-90,-20,-5,colors.red) # 画绿色向上箭头 d = shapes.Drawing(xdraw, ydraw) ao = signsandsymbols.ArrowOne() ao.fillColor = color ao.size = size d.rotate(rotate) ao.x, ao.y = x, y d.add(ao) return d def drawAlert(self, xdraw, ydraw, size, x, y, strokewidth, color): # drawAlert(20,20,20,0,0,4,colors.red) # drawAlert(20,20,20,0,0,0,colors.green) # 画告警图 d = Drawing(xdraw, ydraw) ds = signsandsymbols.DangerSign() ds.x, ds.y = x, y ds.size = size ds.strokeWidth = strokewidth ds.fillColor = color d.add(ds) return d def drawSmile(self, xdraw, ydraw, size, x, y): # drawSmile(20,20,20,0,0) d = Drawing(xdraw, ydraw) ds = signsandsymbols.SmileyFace() ds.x, ds.y = x, y ds.size = size d.add(ds) return d def drawCrossbox(self, xdraw, ydraw, size, x, y, crosscolor, fillcolor): # drawCrossbox(20,20,20,0,0,colors.red,colors.white) # drawCrossbox(20,20,20,0,0,colors.green,colors.green) # 画Xbox信息 d = Drawing(xdraw, ydraw) ds = signsandsymbols.Crossbox() ds.x, ds.y = x, y ds.size = size ds.crosswidth = 3 ds.crossColor = crosscolor ds.fillColor = fillcolor d.add(ds) return d def drawBattery(self, xdraw, ydraw, pct, pctcolor): # drawBattery(25,20,5,colors.green) # 画使用率图 d = Drawing(xdraw, ydraw) r = Rect(0, 0, 25 * pct, ydraw) r.fillColor = pctcolor r.strokeColor = colors.green r.strokeWidth = 0 s = Rect(0, 0, xdraw, ydraw) s.fillColor = colors.white s.strokeColor = colors.green d.add(s) d.add(r) return d def plot_curve(x, y, title, xlabel, ylabel): plt.figure(figsize=(20, 5)) # xs = [datetime.datetime.strptime(d, '%Y-%m-%d').date() for d in x] # plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d')) # plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.title(title) plt.plot(x, y, 'o-') plt.gcf().autofmt_xdate() # 自动旋转日期标记 plt.ylabel(ylabel) plt.xlabel(xlabel) # plt.show() imgdata = io.BytesIO() plt.savefig(imgdata, format='png') imgdata.seek(0) # rewind the data img = platImage(imgdata, 600, 180) return img # def makeHeaderStyle(level, fontName=myFontName): "Make a header style for different levels." assert level >= 0, "Level must be >= 0." PS = ParagraphStyle size = 24.0 / sqrt(1 + level) style = PS(name='Heading' + str(level), fontName=fontName, fontSize=size, leading=size * 1.2, spaceBefore=size / 4.0, spaceAfter=size / 8.0) return style def makeBodyStyle(fontName=myFontName, firstLineIndent=20): "Body text style - the default will do" # return ParagraphStyle('body') styleSheet = getSampleStyleSheet() myBodyStyle = styleSheet['BodyText'] myBodyStyle.fontName = fontName myBodyStyle.leading = 14 myBodyStyle.firstLineIndent = firstLineIndent myBodyStyle.wordWrap = 'CJK' return myBodyStyle def makeTitleStyle(fontSize=18, fontName=myFontName): "Title text style - the default will do" # return ParagraphStyle('body') styleSheet = getSampleStyleSheet() myTitleStyle = styleSheet['Title'] myTitleStyle.fontName = fontName myTitleStyle.fontSize = fontSize return myTitleStyle def makeListTitleStyle(fontSize=18, fontName=myFontName): "Title text style - the default will do" styleSheet = getSampleStyleSheet() myTitleStyle = styleSheet['Title'] myTitleStyle.alignment = TA_LEFT myTitleStyle.fontName = fontName myTitleStyle.fontSize = fontSize return myTitleStyle def makeTocHeaderStyle(level, delta, epsilon, fontName=myFontName): "Make a header style for different levels." assert level >= 0, "Level must be >= 0." PS = ParagraphStyle size = 12 style = PS(name='Heading' + str(level), fontName=fontName, fontSize=size, leading=size * 1.2, spaceBefore=size / 4.0, spaceAfter=size / 8.0, firstLineIndent=-epsilon, leftIndent=level * delta + epsilon) return style def makeTableTitleStyle(fontSize=12, fontName=myFontName): styleSheet = getSampleStyleSheet() myTitleStyle = styleSheet['BodyText'] myTitleStyle.alignment = TA_CENTER myTitleStyle.leading = 18 myTitleStyle.fontName = fontName myTitleStyle.fontSize = fontSize return myTitleStyle def makeTable(data, title=None, note=None, colwidth=None): lst = [] # if colwidth is not None: # cw = list(colwidth) # for i in range(len(cw)-1): # cw[i] = cw[i] * tablewidth # colwidth = tuple(cw) t = Table(data, colWidths=colwidth) ts = TableStyle( [('LINEABOVE', (0, 0), (-1, 0), 2, colors.green), ('LINEABOVE', (0, 1), (-1, -1), 0.25, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 3, colors.green, 'butt'), ('LINEBELOW', (0, -1), (-1, -1), 1, colors.white, 'butt'), ('FONT', (0, 0), (-1, 0), 'msyh'), ('FONT', (0, 0), (-1, -1), 'msyh'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN', (2, 1), (-1, -1), 'LEFT'), ('TEXTCOLOR', (0, 1), (0, -1), colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(0, 0.7, 0.7))] ) t.setStyle(ts) if title is not None: lst.append(Paragraph(title, makeTableTitleStyle())) lst.append(t) if note is not None: lst.append(Paragraph(note, makeBodyStyle())) lst.append(Spacer(0, 0.5 * cm)) return lst def wrapTable(data, cols=None, style=makeBodyStyle(firstLineIndent=0)): ''' To auto wrap text in the cells of the table. usage: data = wrapTable(data, cols=[1,2]) ''' formated_data = [] collist = [] if isinstance(cols, int): collist.append(cols) cols = tuple(collist) for dvalue in data: nvalue = list(dvalue) if cols is not None: for i in cols: nvalue[i] = Paragraph(nvalue[i], style) formated_data.append(nvalue) return formated_data class MyDocTemplate(BaseDocTemplate): "The document template used for all PDF documents." _invalidInitArgs = ('pageTemplates',) def __init__(self, conf, filename, **kw): frame_first_page = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='first') frame_remaining_pages = Frame(2.5 * cm, 2.5 * cm, 16 * cm, 25 * cm, id='remaining') frame_last_page = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='last') self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) firstpage_template = PageTemplate(id='first_page', frames=frame_first_page, onPage=self.on_first_page) mainpage_template = PageTemplate(id='remaining_pages', frames=frame_remaining_pages, onPage=self.on_remaining_pages) lastpage_template = PageTemplate(id='last_page', frames=frame_last_page, onPage=self.on_last_page) self.addPageTemplates([firstpage_template, mainpage_template, lastpage_template]) self.rptsettings = conf.getReportSetting() #print(self.rptsettings) def afterFlowable(self, flowable): "Registers TOC entries." if flowable.__class__.__name__ == 'Paragraph': styleName = flowable.style.name if styleName[:7] == 'Heading': key = str(hash(flowable)) self.canv.bookmarkPage(key) # Register TOC entries. level = int(styleName[7:]) text = flowable.getPlainText() pageNum = self.page - 1 # Try calling this with and without a key to test both # Entries of every second level will have links, others won't if level % 2 == 1: self.notify('TOCEntry', (level, text, pageNum, key)) else: self.notify('TOCEntry', (level, text, pageNum)) key = str(hash(flowable)) canvas = self.canv canvas.setFont(myFontName, 12) # 在页眉生成格式为标题1的标题内容 global gtext if text and level == 0: gtext = text canvas.drawString(1.1 * inch, 11.10 * inch, gtext) # 生成标签 canvas.bookmarkPage(key) canvas.addOutlineEntry(text, key, level=level, closed=0) def on_first_page(self, canvas, doc): canvas.saveState() # 封面字体及字体大小 canvas.setFont(myFontName, 19) # 封面背景 canvas.setFillColorRGB(0.9, 0.9, 0.9) canvas.setStrokeColorRGB(0.6, 0.6, 0.6) canvas.rect(0 * cm, 0.5 * cm, 25 * cm, 30 * cm, fill=1) # 封面上下彩线 count = 0 for i in range(0, 12): if count % 2 == 0: canvas.setStrokeColorRGB(0.6, 0.6, 0.6) # 设置线的粗细 canvas.setLineWidth(1) else: canvas.setStrokeColorRGB(0.0, 0.3, 0.6) canvas.setLineWidth(3) # 绘制顶部线 canvas.line(0 * inch, (0.0 + i * 0.025) * inch, 8.5 * inch, (0 + i * 0.025) * inch) # 绘制底部线 canvas.line(0 * inch, (11.4 + i * 0.025) * inch, 8.5 * inch, (11.4 + i * 0.025) * inch) count = count + 1 # 封面标题 date_range = calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month) year = str(datetime.datetime.now().year) month = str(datetime.datetime.now().month) start_date = str(1) end_date = str(date_range[1]) title = self.rptsettings['report_title'] title1 = self.rptsettings['report_title1'] if self.rptsettings['report_title2'] and self.rptsettings['report_title2'] != '': title2 = self.rptsettings['report_title2'] else: title2 = '(' + year + '/' + month + '/' + start_date + '-' + year + '/' + month + '/' + end_date + ')' #print((8.3-(8.3/21.5)*title.__len__())/2) canvas.setFillColorRGB(0, 0.3, 0.6) canvas.setFont(myFontName, 28) # width = 8.3*inch canvas.drawString(((8.3-(8.3/21.5)*title.__len__())/2)*inch, 10 * inch, title) canvas.drawString(((8.3-(8.3/21.5)*title1.__len__())/2) * inch, 9.5 * inch, title1) canvas.setFillColorRGB(0, 0, 0) canvas.setFont(myFontName, 16) canvas.drawString(2.8 * inch, 9 * inch, title2) # 封面中间部分,图片和部分文字 canvas.setFillColorRGB(0.0, 0.3, 0.6) canvas.setStrokeColorRGB(0.0, 0.3, 0.6) canvas.drawImage(self.rptsettings['cover_logo'], 0 * inch, 3.5 * inch, 600, 330)
import json import unittest from flask_caching import Cache from app import app, db from apps.shop.models import ( ShopItems, ShopCategories, ShopItemsCategoriesMapping, ShopItemLogos, ShopItemsURLMapping ) from apps.users.models import Users, UsersAccessTokens, UsersAccessLevels, UsersAccessMapping from apps.utils.time import get_datetime, get_datetime_one_hour_ahead class TestShopViews(unittest.TestCase): def setUp(self): # Clear redis cache completely cache = Cache() cache.init_app(app, config={"CACHE_TYPE": "RedisCache"}) with app.app_context(): cache.clear() self.app = app.test_client() # Add some categories cat1 = ShopCategories( Category="Units", SubCategory="Tests" ) cat2 = ShopCategories( Category="UnitTests", SubCategory="TestsUnits" ) db.session.add(cat1) db.session.add(cat2) db.session.commit() self.valid_cats = [cat1.ShopCategoryID, cat2.ShopCategoryID] # And some 3rd party logos logo1 = ShopItemLogos( Image="unittest-spotify.jpg", Created=get_datetime() ) logo2 = ShopItemLogos( Image="unittest-bandcamp.jpg", Created=get_datetime() ) logo3 = ShopItemLogos( Image="unittest-amazon.jpg", Created=get_datetime() ) logo4 = ShopItemLogos( Image="unittest-deezer.jpg", Created=get_datetime() ) db.session.add(logo1) db.session.add(logo2) db.session.add(logo3) db.session.add(logo4) db.session.commit() self.valid_logo_ids = [ logo1.ShopItemLogoID, logo2.ShopItemLogoID, logo3.ShopItemLogoID, logo4.ShopItemLogoID, ] # Add three shop items and related data item1 = ShopItems( Title="UnitTest ShopItem 1", Description="UnitTest This is item 1", Price=15.99, Currency="EUR", Image="unittest-shopitem1.jpg", Created=get_datetime() ) db.session.add(item1) db.session.commit() self.valid_items = [item1.ShopItemID] item1_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[0] ) item1_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[1] ) db.session.add(item1_cat1) db.session.add(item1_cat2) db.session.commit() item1_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item1_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item1_url1) db.session.add(item1_url2) db.session.commit() # Item 2 item2 = ShopItems( Title="UnitTest ShopItem 2", Description="UnitTest This is item 2", Price=8.49, Currency="EUR", Image="unittest-shopitem2.jpg", Created=get_datetime() ) db.session.add(item2) db.session.commit() self.valid_items.append(item2.ShopItemID) item2_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[1], ShopCategoryID=self.valid_cats[0] ) db.session.add(item2_cat1) db.session.commit() item2_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item2_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item2_url1) db.session.add(item2_url2) db.session.commit() # Item 3 item3 = ShopItems( Title="UnitTest ShopItem 3", Description="UnitTest This is item 3", Price=12, Currency="EUR", Image="unittest-shopitem3.jpg", Created=get_datetime() ) db.session.add(item3) db.session.commit() self.valid_items.append(item3.ShopItemID) item3_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[0] ) item3_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[1] ) db.session.add(item3_cat1) db.session.add(item3_cat2) db.session.commit() item3_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item3_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item3_url1) db.session.add(item3_url2) db.session.commit() # We also need a valid admin user for the add release endpoint test. user = Users( Name="UnitTest Admin", Username="unittest", Password="password" ) db.session.add(user) db.session.commit() # This is non-standard, but is fine for testing. self.access_token = "<PASSWORD>-access-token" user_token = UsersAccessTokens( UserID=user.UserID, AccessToken=self.access_token, ExpirationDate=get_datetime_one_hour_ahead() ) db.session.add(user_token) db.session.commit() # Define level for admin if not UsersAccessLevels.query.filter_by(LevelName="Admin").first(): access_level = UsersAccessLevels( UsersAccessLevelID=4, LevelName="Admin" ) db.session.add(access_level) db.session.commit() grant_admin = UsersAccessMapping( UserID=user.UserID, UsersAccessLevelID=4 ) db.session.add(grant_admin) db.session.commit() self.user_id = user.UserID def tearDown(self): for cat in ShopCategories.query.filter(ShopCategories.Category.like("Unit%")).all(): db.session.delete(cat) for logo in ShopItemLogos.query.filter(ShopItemLogos.Image.like("unittest%")).all(): db.session.delete(logo) for item in ShopItems.query.filter(ShopItems.Title.like("UnitTest%")).all(): db.session.delete(item) db.session.commit() user = Users.query.filter_by(UserID=self.user_id).first() db.session.delete(user) db.session.commit() def test_getting_all_shopitems(self): """This should return all the shopitems along with their associated data, in ascending order, ID=1 first.""" response = self.app.get("/api/1.0/shopitems/") data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(3, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 1", data["shopItems"][0]["description"]) self.assertEqual(15.99, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem1.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) def test_getting_specific_shopitem(self): """Should return the data of the specified shopitem.""" response = self.app.get("/api/1.0/shopitems/{}".format(self.valid_items[2])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(1, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 3", data["shopItems"][0]["description"]) self.assertEqual(12, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem3.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) self.assertEqual("BandCamp", data["shopItems"][0]["urls"][1]["urlTitle"]) self.assertEqual( "http://www.example.com/bandcamp", data["shopItems"][0]["urls"][1]["url"] ) self.assertEqual(self.valid_logo_ids[1], data["shopItems"][0]["urls"][1]["logoID"]) def test_getting_shopitems_by_category(self): """Should return all items that match the subcategory.""" response = self.app.get("/api/1.0/shopitems/category/{}/".format(self.valid_cats[1])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertNotEqual(None, data) self.assertEqual(2, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][1]["title"]) def test_adding_shopitem(self): """Should add the new item and its related data (categories and urls). For URLs, there is no valid case to reference any existing URLs in the database, so they will be added every time. However, we can reuse a logo (eg. Spotify), so basically you can pick a logo in the UI and then the POST data will have an ID.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[ self.valid_cats[0], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon", "url": "http://www.example.com/amazon/123", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=item.ShopItemID).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Post", item.Title) self.assertEqual("UnitTest Description", item.Description) self.assertEqual(14.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-post.jpg", item.Image) self.assertEqual(2, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(2, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/1", urls[0].URL) self.assertEqual("Amazon", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/123", urls[1].URL) def test_updating_shop_item(self): """Should replace all existing values with the new updated values.""" response = self.app.put( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( dict( title="UnitTest Updated Title", description="UnitTest Updated Description", price=11.95, currency="EUR", image="unittest-update.jpg", categories=[ self.valid_cats[0], self.valid_cats[1], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/2", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon MP3", "url": "http://www.example.com/amazon/124", "logoID": self.valid_logo_ids[2] }, { "title": "BandCamp", "url": "http://www.example.com/bandcamp/987", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(200, response.status_code) self.assertEqual("", response.data.decode()) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Updated Title", item.Title) self.assertEqual("UnitTest Updated Description", item.Description) self.assertEqual(11.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-update.jpg", item.Image) self.assertNotEqual("", item.Updated) self.assertEqual(3, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(3, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/2", urls[0].URL) self.assertEqual("Amazon MP3", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/124", urls[1].URL) self.assertEqual("BandCamp", urls[2].URLTitle) self.assertEqual("http://www.example.com/bandcamp/987", urls[2].URL) def test_patching_shopitem_add(self): """Patch a ShopItems entry with "add" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "add", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "add", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "add", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest Patched Title", item.Title) self.assertEqual(2, len(cats)) self.assertEqual(3, len(urls)) self.assertEqual("Deezer", urls[2].URLTitle) self.assertEqual("deezer.com", urls[2].URL) def test_patching_shopitem_copy(self): """Patch a ShopItems entry with "copy" operation. There is no possible copy operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/title", "path": "/description" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest ShopItem 2", item.Description) def test_patching_shopitem_move(self): """Patch a ShopItems entry with "move" operation. Move will by definition empty the source resource and populate the target resource with the value from source. However, this does not currently work yet due to SQLAlchemy and JSONPatch incompatibility. Just the value is replaced. The correct behaviour will be implemented later on.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "move", "from": "/description", "path": "/image" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest This is item 2", item.Image) def test_patching_shopitem_remove(self): """Patch a ShopItems entry with "remove" operation. This does not work for the base object due to SQLAlchemy JSONPatch incompatibility. But it does work for the joined tables URLs and categories.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "remove", "path": "/title" }), dict({ "op": "remove", "path": "/categories" }), dict({ "op": "remove", "path": "/urls" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual([], cats) self.assertEqual([], urls) def test_patching_shopitem_replace(self): """Patch a ShopItems entry with "replace" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "replace", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "replace", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "replace", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls
tP["lsc"]) else: kStr += (tP["lsp"] if tP["grcv"] else tP["lvp"]) kStr += ")"; if tP["grcv"] == tP["tlu"]: kStr += "*GLOBAL_LOAD_VECTOR_WIDTH_%s" % tP["tensorChar"] kStr += ";%s" % self.endLine return kStr ############################################################################## # Local Write Addresses: Unroll Assignment A/B ############################################################################## def lwaUnrollAssignment(self, kernel, tP): kStr = "" kStr += " unsigned int lw%s%s = (serial%s" \ % (tP["tensorChar"], self.unrollChar, ("/" if tP["grcg"] \ == tP["tlu"] else "%") ) if tP["grcg"]: kStr += (tP["lvc"] if tP["grcv"] else tP["lsc"]) else: kStr += (tP["lsp"] if tP["grcv"] else tP["lvp"]) kStr += ")"; if tP["grcv"] != tP["tlu"]: kStr += "*GLOBAL_LOAD_VECTOR_WIDTH_%s" % tP["tensorChar"] kStr += ";%s" % self.endLine return kStr ############################################################################## # Local Write Addresses: First Offset A/B ############################################################################## def lwaFirstOffset(self, kernel, tP): kStr = "" kStr += " unsigned int localWriteFirstOffset%s = lw%s%s + lw%s%s*(MT%s+PAD)%s;%s" \ % (tP["tensorChar"], tP["tensorChar"], tP["tileChar"], \ tP["tensorChar"], self.unrollChar, tP["tileChar"], \ " + LDS_OFFSET_B" if tP["isB"] else "", self.endLine) return kStr ############################################################################## # Local Write Addresses: Final Offsets A/B ############################################################################## def lwaFinalOffsets(self, kernel, tP): kStr = "" for perp in range(0, tP["nrp"]): for sPerp in range(0, tP["nwpv"]): for para in range(0, tP["nrc"]): for sPara in range(0, 1): # tP["nwcv"]): kStr += " unsigned int localWriteOffset%s_%u_%u_%u_%u = localWriteFirstOffset%s + (%u + %d*%s)" \ % (tP["tensorChar"], para, sPara, perp, sPerp, \ tP["tensorChar"], sPara if tP["tlu"] else sPerp, para, \ (tP["lsc"] if not tP["tlu"] else tP["lsc"]) ) if not tP["tlu"]: kStr += "*(MT%s+PAD)" % (tP["tileChar"]) kStr += " + (%u + %d*%s)" % ( sPerp if tP["tlu"] else sPara, perp, \ (tP["lsp"] if tP["tlu"] else tP["lsp"]) ) if tP["tlu"]: kStr += "*(MT%s+PAD)" % (tP["tileChar"]) kStr += ";%s" % self.endLine return kStr ############################################################################## # Local Write Addresses: Declare Addresses A/B ############################################################################## def lwaDeclareAddresses(self, kernel, tP): kStr = "" for perp in range(0, tP["nrp"]): for sPerp in range(0, tP["nwpv"]): for para in range(0, tP["nrc"]): for sPara in range(0, 1): # tP["nwcv"]): kStr += " %sDATA_TYPE *localWrite%s_%u_%u_%u_%u;%s"\ % (self.sharedPtrStr, tP["tensorChar"], \ para, sPara, perp, sPerp, self.endLine ) return kStr ############################################################################## # Local Read Addresses: Tile Assignment A ############################################################################## def lraTileAssignmentA(self, kernel, tP): kStr = "" kStr += " unsigned int lr%s = (serial %% SG%s);%s" \ % (tP["tileChar"], self.tileChar0, self.endLine) return kStr ############################################################################## # Local Read Addresses: Tile Assignment B ############################################################################## def lraTileAssignmentB(self, kernel, tP): kStr = "" kStr += " unsigned int lr%s = (serial / SG%s) %% SG%s;%s" \ % (tP["tileChar"], self.tileChar0, self.tileChar1, self.endLine) return kStr ############################################################################## # Local Read Addresses: Final Offset A ############################################################################## def lraFinalOffset(self, kernel, tP): kStr = "" kStr += " unsigned int localReadOffset%s = lr%s*VECTOR_WIDTH + sgId*(MT%s+PAD)%s;%s" \ % ( tP["tensorChar"], tP["tileChar"], tP["tileChar"], \ " + LDS_OFFSET_B" if tP["isB"] else "", self.endLine) return kStr ############################################################################## # Local Read Addresses: Declare Addresses A/B ############################################################################## def lraDeclareAddresses(self, kernel, tP): kStr = "" kStr += " %sDATA_TYPE *localRead%s;%s" % (self.sharedPtrStr, \ tP["tensorChar"], self.endLine) return kStr ############################################################################## # Declare Loop Num Iterations ############################################################################## def declareLoopNumIter(self, kernel): kStr = "" for loopIdx in kernel["ProblemType"]["IndicesSummation"]: loopChar = self.indexChars[loopIdx] kStr += "%sunsigned int numIter%s;%s" \ % (self.indent, loopChar, self.endLine) return kStr ############################################################################## # Calculate Loop Num Iterations ############################################################################## def calculateLoopNumIter(self, kernel, loopIdx): tailLoop = loopIdx < 0 if tailLoop: loopIdx = self.unrollIdx kStr = "" loopChar = self.indexChars[ \ kernel["ProblemType"]["IndicesSummation"][loopIdx]] if tailLoop: kStr += "%snumIter%s = (((size%s %% LOCAL_DEPTHU) + LOCAL_SPLITU - 1) / LOCAL_SPLITU);%s" \ % (self.indent, self.unrollChar, self.unrollChar, self.endLine) if kernel["GlobalSplitU"] > 1: kStr += "%sif (gsuSumIdx != numIterPerWgRemainder) {%s" \ % (self.indent, self.endLine) kStr += "%s numIter%s = 0;%s" \ % (self.indent, self.unrollChar, self.endLine) kStr += "%s}%s" % (self.indent, self.endLine) #kStr += "if (serial==0) printf(\\\"WG%u_%u TK:%u\\\\n\\\", get_group_id(0), get_group_id(1), numIterK);" + self.endLine else: kStr += "%snumIter%s = size%s" \ % (self.indent, loopChar, loopChar) if loopIdx == self.unrollIdx: kStr += " / LOCAL_DEPTHU" kStr += ";%s" % self.endLine if loopIdx == self.unrollIdx and kernel["GlobalSplitU"] > 1: kStr += "%sunsigned int numIterMyWg = numIter%s / GLOBAL_SPLITU;%s" \ % (self.indent, self.unrollChar, self.endLine) kStr += "%sunsigned int numIterPerWgRemainder = numIter%s %% GLOBAL_SPLITU;%s" \ % (self.indent, self.unrollChar, self.endLine) kStr += "%sif (gsuSumIdx < numIterPerWgRemainder) {%s" \ % (self.indent, self.endLine) kStr += "%s numIterMyWg++;%s" % (self.indent, self.endLine) kStr += "%s}%s" % (self.indent, self.endLine) kStr += "%snumIter%s = numIterMyWg;%s" \ % (self.indent, self.unrollChar, self.endLine) #kStr += "if (serial==0) printf(\\\"WG%u_%u UK:%u\\\\n\\\", get_group_id(0), get_group_id(1), numIterK);" + self.endLine return kStr ############################################################################## # Open Loop ############################################################################## def openLoop(self, kernel, loopIdx): tailLoop = loopIdx < 0 if tailLoop: loopIdx = self.unrollIdx kStr = "" loopChar = self.indexChars[ \ kernel["ProblemType"]["IndicesSummation"][loopIdx]] if kernel["LoopDoWhile"]: kStr += "%sdo {%s" % (self.indent, self.endLine) else: kStr += "%swhile (numIter%s-- > %u) {%s" \ % (self.indent, loopChar, \ (1 if (kernel["PrefetchGlobalRead"] and loopIdx == self.unrollIdx \ and not tailLoop) else 0), self.endLine) self.indent += " " #if tailLoop: # kStr += "if (serial==0) printf(\\\"WG%u_%u: ti=%u\\\\n\\\", get_group_id(0), get_group_id(1), numIterK);" + self.endLine #else: # kStr += "if (serial==0) printf(\\\"WG%u_%u: ui=%u\\\\n\\\", get_group_id(0), get_group_id(1), numIterK);" + self.endLine return kStr ############################################################################## # Close Loop ############################################################################## def closeLoop(self, kernel, loopIdx): kStr = "" loopChar = self.indexChars[ \ kernel["ProblemType"]["IndicesSummation"][loopIdx]] self.indent = self.indent[2:] if kernel["LoopDoWhile"]: kStr += "%s} while (--numIter%s > %u);%s" \ % (self.indent, loopChar, \ (1 if kernel["PrefetchGlobalRead"] else 0), self.endLine ) else: kStr += "%s}%s" % (self.indent, self.endLine) #kStr += "if (serial==0) printf(\\\"WG%u_%u: rc0=%.0f\\\\n\\\", get_group_id(0), get_group_id(1), rC[0]);" + self.endLine return kStr ############################################################################## # End Summation ############################################################################## def endSummation(self): return "" ############################################################################## # MAC Iteration ############################################################################## def macIter(self, kernel, black): kStr = "" kStr += "%sMAC_%ux%u" % (self.indent, \ kernel["ThreadTile0"],kernel["ThreadTile1"]) if black: kStr += "_BLK" kStr += self.endLine return kStr ############################################################################## # At Least 1 Unroll ############################################################################## def openSumAtLeastUnroll(self, kernel, prefetch): kStr = "" if kernel["GlobalSplitU"] > 1: kStr += "%sif (numIterMyWg >= 1) {%s" \ % (self.indent, self.endLine) else: kStr += "%sif (size%s >= LOCAL_DEPTHU) {%s" \ % (self.indent, self.unrollChar, self.endLine) self.indent += " " return kStr def closeSumAtLeastUnroll(self, kernel, prefetch): kStr = "" self.indent = self.indent[2:] kStr += "%s}%s" % (self.indent, self.endLine) return kStr ############################################################################## # Global Read: Increment A/B ############################################################################## def globalReadIncrement(self, kernel, loopIdx, tP): kStr = "" loopChar = self.indexChars[ \ kernel["ProblemType"]["IndicesSummation"][loopIdx]] for perp in range(0, tP["nrp"]): for sPerp in range(0, tP["nrpv"]): for para in range(0, tP["nrc"]): for sPara in range(0, 1 if tP["rc"] else tP["nrcv"]): kStr += "%sglobalRead%s_%u_%u_%u_%u = (%sDATA_TYPE const *)( ((%sDATA_TYPE const *)globalRead%s_%u_%u_%u_%u) + globalReadInc%s%s);%s" \ % (self.indent, tP["tensorChar"], para, sPara, perp, sPerp, \ self.globalPtrStr, self.globalPtrStr, tP["tensorChar"], \ para, sPara, perp, sPerp, \ tP["tensorChar"], loopChar, self.endLine) #else: # kStr += "%sglobalRead%s_%u_%u%s += globalReadInc%s%s%s;%s" \ # % (self.indent, tP["tensorChar"], para, perp, \ # (("_s%u"%s) if (tP["rtc"] \ # or tP["ruc"]) else ""), \ # tP["tensorChar"], loopChar, "" if (tP["rtc"] \ # or tP["ruc"]) else "/VECTOR_WIDTH", \ # self.endLine) return kStr ############################################################################## # Global Read: Do It A/B ############################################################################## def globalReadDo(self, kernel, guardK, tP): kStr = "" #for perp in range(0, tP["nrp"]): # for para in range(0, tP["nrc"]): # for s in range(0, numUnrollVectorComponents): for perp in range(0, tP["nrp"]): for sPerp in range(0, tP["nrpv"]): for para in range(0, tP["nrc"]): for sPara in range(0, tP["nrcv"]): kStr += "%s%s_%u_%u_%u_%u = " % (self.indent, \ tP["tensorChar"].lower(), \ para, sPara, perp, sPerp ) # guard around K if guardK: kStr += "( globalReadOffset%s%s_%u_%u + %u >= (size%s %% LOCAL_DEPTHU%s)%s )" \ % (tP["tensorChar"], self.unrollChar, \ (perp if tP["tlu"] else para), \ (sPerp if tP["tlu"] else 0), (0 if tP["tlu"] else sPara), self.unrollChar, \ (" + LOCAL_DEPTHU*gsuSumIdx" if kernel["GlobalSplitU"]>1 \ else ""), (" || !numIter%s"%self.unrollChar) \ if kernel["GlobalSplitU"] > 1 else "") # guard around edge if kernel["EdgeType"] == "Branch": if guardK: kStr += " || " kStr += "( !inBounds%s_%u )" % ( \ (tP["tensorChar"], para if tP["tlu"] else perp) ) if kernel["EdgeType"] == "Branch" or guardK: kStr += " ? SCALAR_ZERO : " kStr += "*(globalRead%s_%u_%u_%u_%u + %u);%s" \ % (tP["tensorChar"], para, 0 if tP["rc"] else sPara, perp, sPerp, sPara if tP["rc"] else 0, \ self.endLine) return kStr ############################################################################## # Local Write: Swap Offsets A/B ############################################################################## def localWriteSwapOffsets(self, kernel, tP): kStr
#!/usr/bin/env python # # meza command # import sys, getopt, os # Handle pressing of ctrl-c. Make sure to remove lock file when deploying. deploy_lock_environment = False def sigint_handler(sig, frame): print('Cancelling...') if deploy_lock_environment: print('Deploy underway...removing lock file') unlock_deploy(deploy_lock_environment) sys.exit(1) import signal signal.signal(signal.SIGINT, sigint_handler) def load_yaml ( filepath ): import yaml with open(filepath, 'r') as stream: try: return yaml.load(stream) except yaml.YAMLError as exc: print(exc) defaults = load_yaml( "/opt/meza/config/core/defaults.yml" ) # Hard-coded for now, because I'm not sure where to set it yet language = "en" i18n = load_yaml( os.path.join( defaults['m_i18n'], language+".yml" ) ) def main (argv): # meza requires a command parameter. No first param, no command. Display # help. Also display help if explicitly specifying help. if len(argv) == 0: display_docs('base') sys.exit(1) elif argv[0] in ('-h', '--help'): display_docs('base') sys.exit(0) # asking for help doesn't give error code elif argv[0] in ('-v', '--version'): import subprocess version = subprocess.check_output( ["git", "--git-dir=/opt/meza/.git", "describe", "--tags" ] ) commit = subprocess.check_output( ["git", "--git-dir=/opt/meza/.git", "rev-parse", "HEAD" ] ) print "Meza " + version.strip() print "Commit " + commit.strip() print "Mediawiki EZ Admin" print sys.exit(0) # Every command has a sub-command. No second param, no sub-command. Display # help for that specific sub-command. # sub-command "update" does not require additional directives if len(argv) == 1 and argv[0] != "update": display_docs(argv[0]) sys.exit(1) elif len(argv) == 2 and argv[1] in ('--help','-h'): display_docs(argv[0]) sys.exit(0) command = argv[0] command_fn = "meza_command_{}".format( argv[0] ).replace("-","_") # if command_fn is a valid Python function, pass it all remaining args if command_fn in globals() and callable( globals()[command_fn] ): globals()[command_fn]( argv[1:] ) else: print print "{} is not a valid command".format(command) sys.exit(1) def meza_command_deploy (argv): env = argv[0] rc = check_environment(env) lock_success = request_lock_for_deploy(env) if not lock_success: print "Deploy for environment {} in progress. Exiting".format(env) sys.exit(1) # return code != 0 means failure if rc != 0: if env == "monolith": meza_command_setup_env(env, True) else: sys.exit(rc) more_extra_vars = False # strip environment off of it argv = argv[1:] # if argv[1:] includes -o or --overwrite if len( set(argv).intersection({"-o", "--overwrite"}) ) > 0: # remove -o and --overwrite from args; argv = [value for value in argv[:] if value not in ["-o", "--overwrite"]] more_extra_vars = { 'force_overwrite_from_backup': True } # This breaks continuous integration. FIXME to get it back. # THIS WAS WRITTEN WHEN `meza` WAS A BASH SCRIPT # echo "You are about to deploy to the $ansible_env environment" # read -p "Do you want to proceed? " -n 1 -r # if [[ $REPLY =~ ^[Yy]$ ]]; then # do dangerous stuff # stuff below was in here # fi shell_cmd = playbook_cmd( 'site', env, more_extra_vars ) if len(argv) > 0: shell_cmd = shell_cmd + argv deploy_log = get_deploy_log_path(env) return_code = meza_shell_exec( shell_cmd, deploy_log ) unlock_deploy(env) meza_shell_exec_exit( return_code ) # # Intended to be used by cron job to check for changes to config and meza. Can # also be called with `meza autodeploy <env>` # def meza_command_autodeploy (argv): env = argv[0] rc = check_environment(env) lock_success = request_lock_for_deploy(env) if not lock_success: print "Deploy for environment {} in progress. Exiting".format(env) sys.exit(1) # return code != 0 means failure if rc != 0: sys.exit(rc) more_extra_vars = False # strip environment off of it argv = argv[1:] if len( argv ) > 0: more_extra_vars = { 'deploy_type': argv[0] } argv = argv[1:] # strip deploy type off if len( argv ) > 0: more_extra_vars['deploy_args'] = argv[0] argv = argv[1:] # strip deploy args off shell_cmd = playbook_cmd( 'check-for-changes', env, more_extra_vars ) if len(argv) > 0: shell_cmd = shell_cmd + argv return_code = meza_shell_exec( shell_cmd ) unlock_deploy(env) # double check meza_shell_exec_exit( return_code ) # Just a wrapper on deploy that does some notifications. This needs some # improvement. FIXME. Lots of duplication between this and meza_command_deploy # and meza_command_autodeploy def meza_command_deploy_notify (argv): env = argv[0] rc = check_environment(env) lock_success = request_lock_for_deploy(env) if not lock_success: print "Deploy for environment {} in progress. Exiting".format(env) sys.exit(1) # return code != 0 means failure if rc != 0: sys.exit(rc) more_extra_vars = False # strip environment off of it argv = argv[1:] if len( argv ) > 0: more_extra_vars = { 'deploy_type': argv[0] } argv = argv[1:] # strip deploy type off if len( argv ) > 0: more_extra_vars['deploy_args'] = argv[0] argv = argv[1:] # strip deploy args off shell_cmd = playbook_cmd( 'deploy-notify', env, more_extra_vars ) if len(argv) > 0: shell_cmd = shell_cmd + argv return_code = meza_shell_exec( shell_cmd ) unlock_deploy(env) # double check meza_shell_exec_exit( return_code ) def request_lock_for_deploy (env): import os, datetime lock_file = get_lock_file_path(env) if os.path.isfile( lock_file ): print "Deploy lock file already exists at {}".format(lock_file) return False else: print "Create deploy lock file at {}".format(lock_file) pid = str( os.getpid() ) timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S") # Before creating lock file, this global must be set in order for ctrl-c # interrupts (SIGINT) to be properly managed (SIGINT will call # sigint_handler function) global deploy_lock_environment deploy_lock_environment = env with open( lock_file, 'w' ) as f: f.write( "{}\n{}".format(pid,timestamp) ) f.close() import grp try: grp.getgrnam('apache') meza_chown( lock_file, 'meza-ansible', 'apache' ) except KeyError: print('Group apache does not exist. Set "wheel" as group for lock file.') meza_chown( lock_file, 'meza-ansible', 'wheel' ) os.chmod( lock_file, 0664 ) return { "pid": pid, "timestamp": timestamp } def unlock_deploy(env): import os lock_file = get_lock_file_path(env) if os.path.exists( lock_file ): os.remove( lock_file ) return True else: return False def get_lock_file_path(env): import os lock_file = os.path.join( defaults['m_meza_data'], "env-{}-deploy.lock".format(env) ) return lock_file # "meza deploy-check <ENV>" to return 0 on no deploy, 1 on deploy is active def meza_command_deploy_check (argv): import os env = argv[0] lock_file = get_lock_file_path(env) if os.path.isfile( lock_file ): print "Meza environment '{}' deploying; {} exists".format(env,lock_file) sys.exit(1) else: print "Meza environment '{}' not deploying".format(env) sys.exit(0) def meza_command_deploy_lock (argv): env = argv[0] success = request_lock_for_deploy(env) if success: print "Environment '{}' locked for deploy".format(env) sys.exit(0) else: print "Environment '{}' could not be locked".format(env) sys.exit(1) def meza_command_deploy_unlock (argv): env = argv[0] success = unlock_deploy(env) if success: print "Environment '{}' deploy lock removed".format(env) sys.exit(0) else: print "Environment '{}' is not deploying".format(env) sys.exit(1) def meza_command_deploy_kill (argv): env = argv[0] lock_file = get_lock_file_path(env) if os.path.isfile( lock_file ): print "Meza environment {} deploying; killing...".format(env) di = get_deploy_info(env) os.system( "kill $(ps -o pid= --ppid {})".format(di['pid']) ) import time time.sleep(2) os.system( 'wall "Meza deploy terminated using \'meza deploy-kill\' command."' ) sys.exit(0) else: print "Meza environment '{}' not deploying".format(env) sys.exit(1) def get_deploy_info (env): import os lock_file = get_lock_file_path(env) if not os.path.isfile( lock_file ): print "Environment '{}' not deploying".format(env) return False with open( lock_file, 'r' ) as f: pid = f.readline() timestamp = f.readline() f.close() return { "pid": pid, "timestamp": timestamp } def get_deploy_log_path (env): timestamp = get_deploy_info(env)["timestamp"] filename = "{}-{}.log".format( env,timestamp ) log_dir = os.path.join( defaults['m_logs'], 'deploy-output' ) log_path = os.path.join( log_dir, filename ) if not os.path.isdir( log_dir ): os.makedirs( log_dir ) return log_path def meza_command_deploy_log (argv): env = argv[0] print get_deploy_log_path(env) def meza_command_deploy_tail (argv): env = argv[0] os.system( " ".join(["tail", "-f", get_deploy_log_path(env)]) ) # env # dev # dev-networking --> vbox-networking ?? # docker def meza_command_setup (argv): sub_command = argv[0] if sub_command == "dev-networking": sub_command = "dev_networking" # hyphen not a valid function character command_fn = "meza_command_setup_" + sub_command # if command_fn is a valid Python function, pass it all remaining args if command_fn in globals() and callable( globals()[command_fn] ): globals()[command_fn]( argv[1:] ) else: print print sub_command + " is not a valid sub-command for setup" sys.exit(1) def meza_command_update (argv): import subprocess # This function executes many Git commands that need to be from /otp/meza os.chdir("/opt/meza") # Define a special git remote repository so we can control its settings # Else, a user using Vagrant may have their origin remote setup for SSH # but these commands need HTTPS. meza_remote = "mezaremote" check_remotes = subprocess.check_output( ["git", "remote" ] ).strip().split("\n") if meza_remote not in check_remotes: add_remote = subprocess.check_output( ["git", "remote", "add", meza_remote, "https://github.com/enterprisemediawiki/meza.git" ] ) # Get latest commits and tags from mezaremote fetch = subprocess.check_output( ["git", "fetch", meza_remote ] ) fetch = subprocess.check_output( ["git", "fetch", meza_remote, "--tags" ] ) tags_text = subprocess.check_output( ["git", "tag", "-l" ] ) if len(argv) == 0: # print fetch.strip() print "The following versions are available:" print tags_text.strip() print "" closest_tag = subprocess.check_output( ["git", "describe", "--tags" ] ) print "You are currently on version {}".format(closest_tag.strip()) print "To change versions, do 'sudo meza update <version>'" elif len(argv) > 1: print "Unknown argument {}".format(argv[1]) else: # Needed else 'git status' gives bad response status = subprocess.check_output( ["git", "status", "--untracked-files=no", "--porcelain" ] ) status = status.strip() if status != "": print "'git status' not empty:\n{}".format(status) version = argv[0] if status == "": tags = tags_text.split("\n") branches = subprocess.check_output( ["git", "branch", "-a" ] ).strip().split("\n") branches = map(str.strip, branches) if version in tags: version_type = "at version" tag_version = "tags/{}".format(version) checkout = subprocess.check_output( ["git", "checkout", tag_version ], stderr=subprocess.STDOUT ) elif version in branches or "* {}".format(version) in branches: version_type = "on branch" checkout = subprocess.check_output( ["git", "checkout", version ], stderr=subprocess.STDOUT ) reset = subprocess.check_output( ["git", "reset", "--hard", "mezaremote/{}".format(version) ] ) elif "remotes/{}/{}".format(meza_remote,version) in branches: version_type = "on branch" checkout = subprocess.check_output( ["git", "checkout", "-b", version, '-t', "{}/{}".format(meza_remote,version) ], stderr=subprocess.STDOUT ) else: print "{} is not a valid version or branch".format(version) sys.exit(1) print "" print "" print "Meza now {} {}".format(version_type, version) print "Now deploy changes with 'sudo meza deploy <environment>'" else: print "Files have been modified in /opt/meza. Clean them up before proceeding." print "MSG: {}".format(status) # FIXME #824: This function is big. def meza_command_setup_env (argv, return_not_exit=False): import json, string if isinstance( argv, basestring ): env = argv else: env = argv[0] if not os.path.isdir( "/opt/conf-meza" ): os.mkdir( "/opt/conf-meza" ) if not os.path.isdir( "/opt/conf-meza/secret" ): os.mkdir( "/opt/conf-meza/secret" ) if os.path.isdir( "/opt/conf-meza/secret/" + env ): print print "Environment {} already exists".format(env) sys.exit(1) fqdn = db_pass = private_net_zone = False try: opts, args = getopt.getopt(argv[1:],"",["fqdn=","db_pass=","private_net_zone="]) except Exception as e: print str(e) print 'meza setup env <env> [options]' sys.exit(1) for opt, arg in opts: if opt == "--fqdn": fqdn = arg elif opt == "--db_pass": # This will put the DB password on the command line, so should # only be done in
optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. The server will guarantee that for at least 60 minutes since the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validateOnly: Optional. If set, the backend validates the request, but doesn't actually execute it. """ backupSource_backupName = _messages.StringField(1) cluster = _messages.MessageField('Cluster', 2) clusterId = _messages.StringField(3) parent = _messages.StringField(4, required=True) requestId = _messages.StringField(5) validateOnly = _messages.BooleanField(6) class AlloydbProjectsLocationsClustersInstancesCreateRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesCreateRequest object. Fields: instance: A Instance resource to be passed as the request body. instanceId: Required. Id of the requesting object If auto-generating Id server-side, remove this field and instance_id from the method_signature of Create RPC parent: Required. The name of the parent resource. For the required format, see the comment on the Instance.name field. requestId: Optional. An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. The server will guarantee that for at least 60 minutes since the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validateOnly: Optional. If set, the backend validates the request, but doesn't actually execute it. """ instance = _messages.MessageField('Instance', 1) instanceId = _messages.StringField(2) parent = _messages.StringField(3, required=True) requestId = _messages.StringField(4) validateOnly = _messages.BooleanField(5) class AlloydbProjectsLocationsClustersInstancesDeleteRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesDeleteRequest object. Fields: name: Required. The name of the resource. For the required format, see the comment on the Instance.name field. requestId: Optional. An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. The server will guarantee that for at least 60 minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validateOnly: Optional. If set, the backend validates the request, but doesn't actually execute it. """ name = _messages.StringField(1, required=True) requestId = _messages.StringField(2) validateOnly = _messages.BooleanField(3) class AlloydbProjectsLocationsClustersInstancesFailoverRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesFailoverRequest object. Fields: failoverInstanceRequest: A FailoverInstanceRequest resource to be passed as the request body. name: Required. The name of the resource. For the required format, see the comment on the Instance.name field. """ failoverInstanceRequest = _messages.MessageField('FailoverInstanceRequest', 1) name = _messages.StringField(2, required=True) class AlloydbProjectsLocationsClustersInstancesGetRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesGetRequest object. Fields: name: Required. The name of the resource. For the required format, see the comment on the Instance.name field. """ name = _messages.StringField(1, required=True) class AlloydbProjectsLocationsClustersInstancesListRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesListRequest object. Fields: filter: Optional. Filtering results orderBy: Optional. Hint for how to order the results pageSize: Optional. Requested page size. Server may return fewer items than requested. If unspecified, server will pick an appropriate default. pageToken: A token identifying a page of results the server should return. parent: Required. The name of the parent resource. For the required format, see the comment on the Instance.name field. Additionally, you can perform an aggregated list operation by specifying a value with one of the following formats: * projects/{project}/locations/-/clusters/- * projects/{project}/locations/{region}/clusters/- """ filter = _messages.StringField(1) orderBy = _messages.StringField(2) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) parent = _messages.StringField(5, required=True) class AlloydbProjectsLocationsClustersInstancesPatchRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesPatchRequest object. Fields: instance: A Instance resource to be passed as the request body. name: Output only. The name of the instance resource with the format: * pr ojects/{project}/locations/{region}/clusters/{cluster_id}/instances/{ins tance_id} where the cluster and instance ID segments should satisfy the regex expression "[a-z0-9-]+". For more details see https://google.aip.dev/122. The prefix of the instance resource name is the name of the parent resource: * projects/{project}/locations/{region}/clusters/{cluster_id} requestId: Optional. An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. The server will guarantee that for at least 60 minutes since the first request. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). updateMask: Optional. Field mask is used to specify the fields to be overwritten in the Instance resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field will be overwritten if it is in the mask. If the user does not provide a mask then all fields will be overwritten. validateOnly: Optional. If set, the backend validates the request, but doesn't actually execute it. """ instance = _messages.MessageField('Instance', 1) name = _messages.StringField(2, required=True) requestId = _messages.StringField(3) updateMask = _messages.StringField(4) validateOnly = _messages.BooleanField(5) class AlloydbProjectsLocationsClustersInstancesRestartRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersInstancesRestartRequest object. Fields: name: Required. The name of the resource. For the required format, see the comment on the Instance.name field. restartInstanceRequest: A RestartInstanceRequest resource to be passed as the request body. """ name = _messages.StringField(1, required=True) restartInstanceRequest = _messages.MessageField('RestartInstanceRequest', 2) class AlloydbProjectsLocationsClustersListRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersListRequest object. Fields: filter: Optional. Filtering results orderBy: Optional. Hint for how to order the results pageSize: Optional. Requested page size. Server may return fewer items than requested. If unspecified, server will pick an appropriate default. pageToken: A token identifying a page of results the server should return. parent: Required. The name of the parent resource. For the required format, see the comment on the Cluster.name field. Additionally, you can perform an aggregated list operation by specifying a value with the following format: * projects/{project}/locations/- """ filter = _messages.StringField(1) orderBy = _messages.StringField(2) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) parent = _messages.StringField(5, required=True) class AlloydbProjectsLocationsClustersPatchRequest(_messages.Message): r"""A AlloydbProjectsLocationsClustersPatchRequest object. Fields: cluster: A Cluster resource to be passed as the request body. name: Output only. The name of the cluster resource with the format: * projects/{project}/locations/{region}/clusters/{cluster_id} where the cluster ID segment should satisfy the regex expression "[a-z0-9-]+". For more details see https://google.aip.dev/122. The prefix of the cluster resource name is the name of the parent resource: * projects/{project}/locations/{region} requestId: Optional. An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. The server will guarantee that for at least 60 minutes since the first request. For example, consider a situation where you make an initial request and the
False else: in_context = True inContextImportName = context + '.' + importName if not parentName: inContextParentName = context else: inContextParentName = context + '.' + parentName inContextTopName = context + '.' + topName contextTopName = JS("@{{context}}.__split('.')[0]") # Check if we already have imported this module in this context if depth > 1 and sys.modules.has_key(inContextParentName): module = sys.modules[inContextParentName] if JS("typeof @{{module}}[@{{objName}}] != 'undefined'"): if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return JS("@{{module}}[@{{objName}}]") elif sys.modules.has_key(inContextImportName): if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return sys.modules[inContextImportName] elif depth > 1 and JS("typeof (@{{module}} = $pyjs.loaded_modules[@{{inContextParentName}}]) != 'undefined'"): sys.modules[inContextParentName] = module JS("@{{module}}.__was_initialized__ = false;") module(None) if JS("typeof @{{module}}[@{{objName}}] != 'undefined'"): if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return JS("@{{module}}[@{{objName}}]") if sys.modules.has_key(inContextImportName): if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return sys.modules[inContextImportName] if JS("typeof (@{{module}} = $pyjs.loaded_modules[@{{inContextImportName}}]) != 'undefined'"): sys.modules[inContextImportName] = module JS("@{{module}}.__was_initialized__ = false;") module(module_name) if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return module # Check if the topName is a valid module, if so, we stay in_context if not sys.modules.has_key(inContextTopName): if JS("typeof (@{{module}} = $pyjs.loaded_modules[@{{inContextTopName}}]) != 'function'"): in_context = False if JS("$pyjs.options.dynamic_loading"): module = __dynamic_load__(inContextTopName) if JS("""typeof @{{module}} == 'function'"""): in_context = True if depth == 1: module(module_name) return module else: module(None) if depth == 2 and JS("typeof @{{module}}[@{{objName}}] != 'undefined'"): if get_base: return JS("$pyjs.loaded_modules[@{{inContextTopName}}]") return JS("@{{module}}[@{{objName}}]") if in_context: importName = inContextImportName parentName = inContextParentName topName = inContextTopName if not in_context: if parentName and sys.modules.has_key(parentName): module = sys.modules[parentName] if JS("typeof @{{module}}[@{{objName}}] != 'undefined'"): if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return JS("@{{module}}[@{{objName}}]") elif sys.modules.has_key(importName): if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return sys.modules[importName] elif parentName and JS("typeof (@{{module}} = $pyjs.loaded_modules[@{{parentName}}]) != 'undefined'"): sys.modules[parentName] = module JS("@{{module}}.__was_initialized__ = false;") module(None) if JS("typeof @{{module}}[@{{objName}}] != 'undefined'"): if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return JS("@{{module}}[@{{objName}}]") if sys.modules.has_key(importName): if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return sys.modules[importName] if JS("typeof (@{{module}} = $pyjs.loaded_modules[@{{importName}}]) != 'undefined'"): sys.modules[importName] = module if importName != 'pyjslib' and importName != 'sys': JS("@{{module}}.__was_initialized__ = false;") module(module_name) if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return module # If we are here, the module is not loaded (yet). if JS("$pyjs.options.dynamic_loading"): module = __dynamic_load__(importName) if JS("""typeof @{{module}}== 'function'"""): module(module_name) if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return module raise ImportError( "No module named %s, %s in context %s" % (importName, path, context)) def __dynamic_load__(importName): global __nondynamic_modules__ module = JS("""$pyjs.loaded_modules[@{{importName}}]""") if sys is None or dynamic is None or __nondynamic_modules__.has_key(importName): return module if JS("""typeof @{{module}}== 'undefined'"""): try: dynamic.ajax_import("lib/" + importName + ".__" + platform + "__.js") module = JS("""$pyjs.loaded_modules[@{{importName}}]""") except: pass if JS("""typeof @{{module}}== 'undefined'"""): try: dynamic.ajax_import("lib/" + importName + ".js") module = JS("""$pyjs.loaded_modules[@{{importName}}]""") except: pass if JS("""typeof @{{module}}== 'undefined'"""): __nondynamic_modules__[importName] = 1.0 return module def __import_all__(path, context, namespace, module_name=None, get_base=True): module = ___import___(path, context, module_name, get_base) if JS("""typeof @{{module}}['__all__'] == 'undefined'"""): for name in dir(module): if not name.startswith('_'): JS("""@{{namespace}}[@{{name}}] = @{{module}}[@{{name}}];""") else: for name in module.__all__: JS("""@{{namespace}}[@{{name}}] = @{{module}}[@{{name}}];""") class BaseException: def __init__(self, *args): self.args = args def __getitem__(self, index): return self.args.__getitem__(index) def __str__(self): if len(self.args) is 0: return '' elif len(self.args) is 1: return str(self.args[0]) return repr(self.args) def __repr__(self): if callable(self): return "<type '%s'>" % self.__name__ return self.__name__ + repr(self.args) class KeyboardInterrupt(BaseException): pass class GeneratorExit(BaseException): pass class SystemExit(BaseException): pass class Exception(BaseException): pass class StandardError(Exception): pass class ArithmeticError(StandardError): pass class StopIteration(Exception): pass class GeneratorExit(Exception): pass class AssertionError(StandardError): pass class TypeError(StandardError): pass class AttributeError(StandardError): pass class NameError(StandardError): pass class ValueError(StandardError): pass class ImportError(StandardError): pass class LookupError(StandardError): pass class RuntimeError(StandardError): pass class SystemError(StandardError): pass class KeyError(LookupError): def __str__(self): if len(self.args) is 0: return '' elif len(self.args) is 1: return repr(self.args[0]) return repr(self.args) class IndexError(LookupError): pass class NotImplementedError(RuntimeError): pass class ZeroDivisionError(ArithmeticError): pass class OverflowError(ArithmeticError): pass class UndefinedValueError(ValueError): pass def init(): # There seems to be an bug in Chrome with accessing the message # property, on which an error is thrown # Hence the declaration of 'var message' and the wrapping in try..catch JS(""" @{{_errorMapping}} = function(err) { if (err instanceof(ReferenceError) || err instanceof(TypeError)) { var message = ''; try { message = err.message; } catch (e) { } return @{{AttributeError}}(message); } return err; }; """) # The TryElse 'error' is used to implement the else in try-except-else # (to raise an exception when there wasn't any) JS(""" @{{TryElse}} = function () { }; @{{TryElse}}.prototype = new Error(); @{{TryElse}}.__name__ = 'TryElse'; """) # Patching of the standard javascript String object JS(""" String.prototype.__init__ = @{{object}}.__init__; String.prototype.rfind = function(sub, start, end) { var pos; if (typeof start != 'undefined') { /* *sigh* - python rfind goes *RIGHT*, NOT left */ pos = this.substring(start).lastIndexOf(sub); if (pos == -1) { return -1; } pos += start; } else { pos=this.lastIndexOf(sub, start); } if (typeof end == 'undefined') return pos; if (pos + sub.length>end) return -1; return pos; }; String.prototype.find = function(sub, start, end) { var pos=this.indexOf(sub, start); if (typeof end == 'undefined') return pos; if (pos + sub.length>end) return -1; return pos; }; String.prototype.index = function(sub, start, end) { var pos = this.find(sub, start, end); if (pos < 0) throw $pyce(@{{ValueError}}('substring not found')); return pos; } String.prototype.count = function(sub, start, end) { var pos, count = 0, n = sub.length; if (typeof start == 'undefined') start = 0; if (typeof end == 'undefined') end = this.length; while (start < end) { pos = this.find(sub, start, end); if (pos < 0) break; count ++; start = pos + n; } return count; } String.prototype.format = function() { var args = $p['tuple']($pyjs_array_slice.call(arguments,0,arguments.length-1)); var kw = arguments.length >= 1 ? arguments[arguments.length-1] : arguments[arguments.length]; if (typeof kw != 'object' || kw.__name__ !== 'dict' || typeof kw.$pyjs_is_kwarg == 'undefined') { if (typeof kw != 'undefined') args.__array.push(kw); kw = arguments[arguments.length+1]; } else { delete kw['$pyjs_is_kwarg']; } if (typeof kw == 'undefined') { kw = $p['dict'].__new__($p['dict']); } return $p['_string_format'](this, args, kw); } String.prototype.format.__args__ = ['args', ['kw']]; String.prototype.join = function(data) { var text=""; if (data.constructor === Array) { return data.join(this); } else if (typeof data.__iter__ == 'function') { if (typeof data.__array == 'object') { return data.__array.join(this); } var iter=data.__iter__(); if (typeof iter.__array == 'object') { return iter.__array.join(this); } data = []; var item, i = 0; if (typeof iter.$genfunc == 'function') { while (typeof (item=iter.next(true)) != 'undefined') { data[i++] = item; } } else { try { while (true) { data[i++] = iter.next(); } } catch (e) { if (!@{{isinstance}}(e['$pyjs_exc'] || e, @{{StopIteration}})) throw e; } } return data.join(this); } return text; }; String.prototype.isdigit = function() { return (this.match(/^\d+$/g) !== null); }; String.prototype.isalnum = function() { return (this.match(/^[a-zA-Z\d]+$/g) !== null); }; String.prototype.isalpha = function() { return (this.match(/^[a-zA-Z]+$/g) !== null); }; String.prototype.isupper = function() { return (this.match(/[a-z]/g) === null); }; String.prototype.islower = function() { return (this.match(/[A-Z]/g) === null); }; String.prototype.__replace=String.prototype.replace; String.prototype.$$replace = function(old, replace, count) { var do_max=false; var start=0; var new_str=""; var pos=0; if (typeof old != 'string') return this.__replace(old, replace); if (typeof count != 'undefined') do_max=true; while (start<this.length) { if (do_max && !count--) break; pos=this.indexOf(old, start); if (pos<0) break; new_str+=this.substring(start, pos) + replace; start=pos+old.length; } if (start<this.length) new_str+=this.substring(start); return new_str; }; String.prototype.__contains__ = function(s){ return this.indexOf(s)>=0; }; String.prototype.__split = String.prototype.split; String.prototype.$$split = function(sep, maxsplit) { var items=@{{list}}.__new__(@{{list}}); var do_max=false; var subject=this; var start=0; var pos=0; if (sep === null || typeof sep == 'undefined') { sep=" "; if (subject.length == 0) { return items; } subject=subject.strip(); subject=subject.$$replace(/\s+/g, sep); } else if (typeof maxsplit != 'undefined') do_max=true; if (subject.length == 0) { items.__array.push(''); return items; } while (start<subject.length) { if (do_max && !maxsplit--) break; pos=subject.indexOf(sep, start); if (pos<0) break; items.__array.push(subject.substring(start, pos)); start=pos+sep.length; } if (start<=subject.length) items.__array.push(subject.substring(start)); return items; }; String.prototype.rsplit = function(sep, maxsplit) { var items=@{{list}}.__new__(@{{list}}); var do_max=false; var subject=this; var pos=0; if (sep === null || typeof sep == 'undefined') { sep=" "; if (subject.length == 0) { return items; } subject=subject.strip(); subject=subject.$$replace(/\s+/g, sep); } else if (typeof maxsplit != 'undefined') do_max=true; if (subject.length == 0) { items.__array.push(''); return items; } while (subject.length > 0) { if (do_max && !maxsplit--) break; pos=subject.lastIndexOf(sep); if (pos<0) break; items.__array.push(subject.substr(pos+sep.length)); subject = subject.substr(0, pos); } if (subject.length > 0) items.__array.push(subject); items.__array.reverse() return items; }; String.prototype.splitlines = function(keepends) { var items = this.$$split("\\n"); if (typeof keepends != 'undefined' && keepends) { for (var i=0; i<items.__array.length; i++) { items.__array[i] = items.__array[i] + "\\n"; } } return items; } if (typeof "a"[0] == 'undefined' ) { // IE: cannot do "abc"[idx] String.prototype.__iter__ = function() { var i = 0; var s = this; return { 'next': function(noStop) { if (i >= s.length) { if (noStop === true) { return; } throw $pyce(@{{StopIteration}}());
<reponame>Carlor87/naima # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import numpy as np import astropy.units as u from astropy.table import Table, QTable from astropy import log import warnings import ast from .extern.validator import validate_array, validate_scalar __all__ = [ "generate_energy_edges", "sed_conversion", "build_data_table", "estimate_B", ] # Input validation tools def validate_column(data_table, key, pt, domain="positive"): try: column = data_table[key] array = validate_array( key, u.Quantity(column, unit=column.unit), physical_type=pt, domain=domain, ) except KeyError: raise TypeError( 'Data table does not contain required column "{0}"'.format(key) ) return array def validate_data_table(data_table, sed=None): """ Validate all columns of a data table. If a list of tables is passed, all tables will be validated and then concatenated Parameters ---------- data_table : `astropy.table.Table` or list of `astropy.table.Table`. sed : bool, optional Whether to convert the fluxes to SED. If unset, all data tables are converted to the format of the first data table. """ if isinstance(data_table, Table) or isinstance(data_table, QTable): data_table = [data_table] try: for dt in data_table: if not isinstance(dt, Table) and not isinstance(dt, QTable): raise TypeError( "An object passed as data_table is not an astropy Table!" ) except TypeError: raise TypeError( "Argument passed to validate_data_table is not a table and " "not a list" ) def dt_sed_conversion(dt, sed): f_unit, sedf = sed_conversion(dt["energy"], dt["flux"].unit, sed) # roundtrip to Table to change the units t = Table(dt) for col in ["flux", "flux_error_lo", "flux_error_hi"]: t[col].unit = f_unit ndt = QTable(t) ndt["flux"] = (dt["flux"] * sedf).to(f_unit) ndt["flux_error_lo"] = (dt["flux_error_lo"] * sedf).to(f_unit) ndt["flux_error_hi"] = (dt["flux_error_hi"] * sedf).to(f_unit) return ndt data_list = [] for group, dt in enumerate(data_table): dt_val = _validate_single_data_table(dt, group=group) data_list.append(dt_val) # concatenate input data tables data_new = data_list[0].copy() f_pt = data_new["flux"].unit.physical_type if sed is None: sed = f_pt in ["flux", "power"] data_new = dt_sed_conversion(data_new, sed) for dt in data_list[1:]: nf_pt = dt["flux"].unit.physical_type if ("flux" in nf_pt and "power" in f_pt) or ( "power" in nf_pt and "flux" in f_pt ): raise TypeError( "The physical types of the data tables could not be " "matched: Some are in flux and others in luminosity units" ) dt = dt_sed_conversion(dt, sed) for row in dt: data_new.add_row(row) return data_new def _validate_single_data_table(data_table, group=0): data = QTable() flux_types = ["flux", "differential flux", "power", "differential power"] # Energy and flux arrays data["energy"] = validate_column(data_table, "energy", "energy") data["flux"] = validate_column(data_table, "flux", flux_types) # Flux uncertainties if "flux_error" in data_table.keys(): dflux = validate_column(data_table, "flux_error", flux_types) data["flux_error_lo"] = dflux data["flux_error_hi"] = dflux elif ( "flux_error_lo" in data_table.keys() and "flux_error_hi" in data_table.keys() ): data["flux_error_lo"] = validate_column( data_table, "flux_error_lo", flux_types ) data["flux_error_hi"] = validate_column( data_table, "flux_error_hi", flux_types ) else: raise TypeError( "Data table does not contain required column" ' "flux_error" or columns "flux_error_lo"' ' and "flux_error_hi"' ) if "group" in data_table.colnames: # avoid overwriting groups data["group"] = data_table["group"] else: data["group"] = [group] * len(data["energy"]) # Energy bin edges if "energy_width" in data_table.keys(): energy_width = validate_column(data_table, "energy_width", "energy") data["energy_error_lo"] = energy_width / 2.0 data["energy_error_hi"] = energy_width / 2.0 elif "energy_error" in data_table.keys(): energy_error = validate_column(data_table, "energy_error", "energy") data["energy_error_lo"] = energy_error data["energy_error_hi"] = energy_error elif ( "energy_error_lo" in data_table.keys() and "energy_error_hi" in data_table.keys() ): energy_error_lo = validate_column( data_table, "energy_error_lo", "energy" ) data["energy_error_lo"] = energy_error_lo energy_error_hi = validate_column( data_table, "energy_error_hi", "energy" ) data["energy_error_hi"] = energy_error_hi elif "energy_lo" in data_table.keys() and "energy_hi" in data_table.keys(): energy_lo = validate_column(data_table, "energy_lo", "energy") data["energy_error_lo"] = data["energy"] - energy_lo energy_hi = validate_column(data_table, "energy_hi", "energy") data["energy_error_hi"] = energy_hi - data["energy"] else: data["energy_error_lo"], data[ "energy_error_hi" ] = generate_energy_edges(data["energy"], groups=data["group"]) # Upper limit flags if "ul" in data_table.keys(): # Check if it is a integer or boolean flag ul_col = data_table["ul"] if ul_col.dtype.type is np.int_ or ul_col.dtype.type is np.bool_: data["ul"] = np.array(ul_col, dtype=np.bool) elif ul_col.dtype.type is np.str_: strbool = True for ul in ul_col: if ul != "True" and ul != "False": strbool = False if strbool: data["ul"] = np.array( [ast.literal_eval(ul) for ul in ul_col], dtype=np.bool ) else: raise TypeError("UL column is in wrong format") else: raise TypeError("UL column is in wrong format") else: data["ul"] = np.array([False] * len(data["energy"])) if "flux_ul" in data_table.keys(): data["flux"][data["ul"]] = u.Quantity(data_table["flux_ul"])[ data["ul"] ] HAS_CL = False if "keywords" in data_table.meta.keys(): if "cl" in data_table.meta["keywords"].keys(): HAS_CL = True CL = validate_scalar( "cl", data_table.meta["keywords"]["cl"]["value"] ) data["cl"] = [CL] * len(data["energy"]) if not HAS_CL: data["cl"] = [0.9] * len(data["energy"]) if np.sum(data["ul"]) > 0: log.warning( '"cl" keyword not provided in input data table, upper limits' " will be assumed to be at 90% confidence level" ) return data # Convenience tools def sed_conversion(energy, model_unit, sed): """ Manage conversion between differential spectrum and SED """ model_pt = model_unit.physical_type ones = np.ones(energy.shape) if sed: # SED f_unit = u.Unit("erg/s") if model_pt == "power" or model_pt == "flux" or model_pt == "energy": sedf = ones elif "differential" in model_pt: sedf = energy ** 2 else: raise u.UnitsError( "Model physical type ({0}) is not supported".format(model_pt), "Supported physical types are: power, flux, differential" " power, differential flux", ) if "flux" in model_pt: f_unit /= u.cm ** 2 elif "energy" in model_pt: # particle energy distributions f_unit = u.erg else: # Differential spectrum f_unit = u.Unit("1/(s TeV)") if "differential" in model_pt: sedf = ones elif model_pt == "power" or model_pt == "flux" or model_pt == "energy": # From SED to differential sedf = 1 / (energy ** 2) else: raise u.UnitsError( "Model physical type ({0}) is not supported".format(model_pt), "Supported physical types are: power, flux, differential" " power, differential flux", ) if "flux" in model_pt: f_unit /= u.cm ** 2 elif "energy" in model_pt: # particle energy distributions f_unit = u.Unit("1/TeV") log.debug( "Converted from {0} ({1}) into {2} ({3}) for sed={4}".format( model_unit, model_pt, f_unit, f_unit.physical_type, sed ) ) return f_unit, sedf def trapz_loglog(y, x, axis=-1, intervals=False): """ Integrate along the given axis using the composite trapezoidal rule in loglog space. Integrate `y` (`x`) along given axis in loglog space. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional Independent variable to integrate over. axis : int, optional Specify the axis. Returns ------- trapz : float Definite integral as approximated by trapezoidal rule in loglog space. """ try: y_unit = y.unit y = y.value except AttributeError: y_unit = 1.0 try: x_unit = x.unit x = x.value except AttributeError: x_unit = 1.0 y = np.asanyarray(y) x = np.asanyarray(x) slice1 = [slice(None)] * y.ndim slice2 = [slice(None)] * y.ndim slice1[axis] = slice(None, -1) slice2[axis] = slice(1, None) slice1 = tuple(slice1) slice2 = tuple(slice2) if x.ndim == 1: shape = [1] * y.ndim shape[axis] = x.shape[0] x = x.reshape(shape) with warnings.catch_warnings(): warnings.simplefilter("ignore") # Compute the power law indices in each integration bin b = np.log10(y[slice2] / y[slice1]) / np.log10(x[slice2] / x[slice1]) # if local powerlaw index is -1, use \int 1/x = log(x); otherwise use # normal powerlaw integration trapzs = np.where( np.abs(b + 1.0) > 1e-10, ( y[slice1] * (x[slice2] * (x[slice2] / x[slice1]) ** b - x[slice1]) ) / (b + 1), x[slice1] * y[slice1] * np.log(x[slice2] / x[slice1]), ) tozero = (y[slice1] == 0.0) + (y[slice2] == 0.0) + (x[slice1] == x[slice2]) trapzs[tozero] = 0.0 if intervals: return trapzs * x_unit * y_unit ret = np.add.reduce(trapzs, axis) * x_unit * y_unit return ret def _generate_energy_edges_single(ene): """Generate energy edges for single group""" midene = np.sqrt((ene[1:] * ene[:-1])) elo, ehi = np.zeros(len(ene)) * ene.unit, np.zeros(len(ene)) * ene.unit elo[1:] = ene[1:] - midene ehi[:-1] = midene - ene[:-1] elo[0] = ene[0] * (1 - ene[0] / (ene[0] + ehi[0])) ehi[-1] = elo[-1] return u.Quantity([elo, ehi]) def generate_energy_edges(ene, groups=None): """Generate energy bin edges from given energy array. Generate an array of energy edges from given energy array to be used as abcissa error bar limits when no energy uncertainty or energy band is provided. Parameters ---------- ene : `astropy.units.Quantity` array instance 1-D array of energies with associated phsyical units. Returns ------- energy_err_lo, energy_error_hi : `astropy.units.Quantity` arrays Arrays of low and high energy edges corresponding to each given energy of the input array. """ if groups is None or len(ene) != len(groups): return _generate_energy_edges_single(ene)
<reponame>shashiongithub/Document-Modeling-with-External-Information from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.append('../../common') import math import os import random import sys import time import pdb import numpy as np import tensorflow as tf from model_docsum import mrr_metric, map_score, accuracy_qas_top, accuracy_qas_any, save_metrics from data_utils import DataProcessor, BatchData from my_model import MY_Model from my_flags import FLAGS def batch_load_data(data): main_batch = BatchData(None,None,None,None,None,None,None,None,None,None) step = 1 while (step * FLAGS.batch_size) <= len(data.fileindices): # Get batch data as Numpy Arrays : Without shuffling batch = data.get_batch(((step-1)*FLAGS.batch_size), (step * FLAGS.batch_size)) main_batch.extend(batch) # Increase step step += 1 # Check if any data left if (len(data.fileindices) > ((step-1)*FLAGS.batch_size)): # Get last batch as Numpy Arrays batch = data.get_batch(((step-1)*FLAGS.batch_size), len(data.fileindices)) main_batch.extend(batch) # Convert list to tensors main_batch.concat_batches() return main_batch def batch_predict_with_a_model(batch,data_type,model, session=None): step = 1 cos_sim_list = [] logits_list = [] while (step * FLAGS.batch_size) <= len(batch.docs): # Get batch data as Numpy Arrays : Without shuffling start_idx = (step-1)*FLAGS.batch_size end_idx = step * FLAGS.batch_size # not inclusive docs = batch.docs[start_idx:end_idx] labels = batch.labels[start_idx:end_idx] isf_score = batch.isf_score[start_idx:end_idx] locisf_score = batch.locisf_score[start_idx:end_idx] idf_score = batch.idf_score[start_idx:end_idx] if FLAGS.load_prediction==-1: batch_logits = session.run(model.logits,feed_dict={model.document_placeholder: docs, model.label_placeholder: labels, model.isf_score_placeholder: isf_score, model.locisf_score_placeholder: locisf_score, model.idf_score_placeholder: idf_score}) logits_list.append(batch_logits) # Increase step step += 1 # Check if any data left if (len(batch.docs) > ((step-1)*FLAGS.batch_size)): # Get last batch as Numpy Arrays start_idx = (step-1)*FLAGS.batch_size end_idx = len(batch.docs) # not inclusive docs = batch.docs[start_idx:end_idx] labels = batch.labels[start_idx:end_idx] isf_score = batch.isf_score[start_idx:end_idx] locisf_score = batch.locisf_score[start_idx:end_idx] idf_score = batch.idf_score[start_idx:end_idx] if FLAGS.load_prediction==-1: batch_logits = session.run(model.logits,feed_dict={model.document_placeholder: docs, model.label_placeholder: labels, model.isf_score_placeholder: isf_score, model.locisf_score_placeholder: locisf_score, model.idf_score_placeholder: idf_score}) logits_list.append(batch_logits) if FLAGS.load_prediction!=-1: print("Loading netword predictions and embeddings...") fn_logits = "step-a.model.ckpt.epoch-%d.%s-prediction" % (FLAGS.load_prediction,data_type) #fn_cos_sim = "step-a.model.ckpt.epoch-%d-cos_sim.%s" % (FLAGS.load_prediction,data_type) logits_list = data.load_prediction(fn_logits) #cos_sim_list = data.load_prediction(fn_cos_sim) else: # Concatenate logits and cos_sim logits_list = np.vstack(logits_list) #cos_sim_list = np.vstack(cos_sim_list) batch.logits = logits_list #batch.cos_sim = cos_sim_list return batch ######################## CPU/GPU conf functions ########################### def meta_experiment_gpu_conf(mode): # Training: use the tf default graph with tf.Graph().as_default() and tf.device('/gpu:'+FLAGS.gpu_id): config = tf.ConfigProto(allow_soft_placement = True) # Start a session with tf.Session(config = config) as sess: if mode=='train': train(sess) elif mode=='test': test(sess) elif mode=='test_train': test_train(sess) elif mode=='test_val': test_val(sess) elif mode=='train_debug': train_debug(sess) def meta_experiment_cpu_conf(mode): # Training: use the tf default graph with tf.Graph().as_default(): # Start a session with tf.Session() as sess: if mode=='train': train(sess) elif mode=='test': test(sess) elif mode=='test_train': test_train(sess) else: test_val(sess) # ######################## Train Mode ########################### def train(sess): """ Training Mode: Create a new model and train the network """ ## wrap debugger around session ### Prepare data for training print("Prepare vocab dict and read pretrained word embeddings ...") vocab_dict, word_embedding_array = DataProcessor().prepare_vocab_embeddingdict() # vocab_dict contains _PAD and _UNK but not word_embedding_array print("Prepare training data ...") train_data = DataProcessor().prepare_news_data(vocab_dict, data_type="training") print("Prepare validation data ...") # data in whole batch with padded matrixes val_batch = batch_load_data(DataProcessor().prepare_news_data(vocab_dict, data_type="validation")) # Create Model with various operations model = MY_Model(sess, len(vocab_dict)-2) init_epoch = 1 # Resume training if indicated Select the model if FLAGS.model_to_load!=-1: if (os.path.isfile(FLAGS.train_dir+"/step-a.model.ckpt.epoch-"+str(FLAGS.model_to_load))): selected_modelpath = FLAGS.train_dir+"/step-a.model.ckpt.epoch-"+str(FLAGS.model_to_load) else: print("Model not found in checkpoint folder.") exit(0) # Reload saved model and test init_epoch = FLAGS.model_to_load + 1 print("Reading model parameters from %s" % selected_modelpath) model.saver.restore(sess, selected_modelpath) print("Model loaded.") # Initialize word embedding before training print("Initialize word embedding vocabulary with pretrained embeddings ...") sess.run(model.vocab_embed_variable.assign(word_embedding_array)) ### STEP A : Start Pretraining the policy with Supervised Labels: Simple Cross Entropy Training for epoch in range(init_epoch, FLAGS.train_epoch_crossentropy+1): ep_time = time.time() # to check duration print("STEP A: Epoch "+str(epoch)+" : Start pretraining with supervised labels") print("STEP A: Epoch "+str(epoch)+" : Reshuffle training document indices") train_data.shuffle_fileindices() # Start Batch Training step = 1 while (step * FLAGS.batch_size) <= len(train_data.fileindices): # Get batch data as Numpy Arrays batch = train_data.get_batch(((step-1)*FLAGS.batch_size), (step * FLAGS.batch_size)) # Run optimizer: optimize policy and reward estimator _,batch_logits,ce_loss,merged_summ = sess.run([ model.train_op_policynet_withgold, model.logits, model.cross_entropy_loss, model.merged], feed_dict={model.document_placeholder: batch.docs, model.label_placeholder: batch.labels, model.weight_placeholder: batch.weights, #model.cnt_placeholder: batch.cnt_score, model.isf_placeholder: batch.isf_score, model.idf_placeholder: batch.idf_score, model.locisf_score_placeholder: batch.locisf_score #model.sent_len_placeholder: batch.sent_lens }) # Print the progress if (step % FLAGS.training_checkpoint) == 0: probs = sess.run(model.probs,feed_dict={model.logits_placeholder: batch_logits}) training_acc = accuracy_qas_top( probs, batch.labels, batch.weights, batch.isf_score_ids) acc_sum = sess.run( model.tstepa_accuracy_summary, feed_dict={model.train_acc_placeholder: training_acc}) print("STEP A: Epoch "+str(epoch)+" : Covered " + str(step*FLAGS.batch_size)+"/"+str(len(train_data.fileindices))+ " : Minibatch CE Loss= {:.6f}".format(ce_loss) + ", Minibatch Accuracy= {:.6f}".format(training_acc)) # Print Summary to Tensor Board model.summary_writer.add_summary(merged_summ, (epoch-1)*len(train_data.fileindices)+step*FLAGS.batch_size) model.summary_writer.add_summary(acc_sum, (epoch-1)*len(train_data.fileindices)+step*FLAGS.batch_size) # Increase step step += 1 #break #END-WHILE-TRAINING # Save Model print("STEP A: Epoch "+str(epoch)+" : Saving model after epoch completion") checkpoint_path = os.path.join(FLAGS.train_dir, "step-a.model.ckpt.epoch-"+str(epoch)) model.saver.save(sess, checkpoint_path) # Performance on the validation set print("STEP A: Epoch "+str(epoch)+" : Performance on the validation data") # Get Predictions: Prohibit the use of gold labels FLAGS.authorise_gold_label = False FLAGS.use_dropout = False val_batch = batch_predict_with_a_model(val_batch,"validation", model, session=sess) FLAGS.use_dropout = True FLAGS.authorise_gold_label = True # Validation Accuracy and Prediction probs = sess.run(model.predictions,feed_dict={model.logits_placeholder: val_batch.logits}) validation_acc = accuracy_qas_top(probs, val_batch.labels, val_batch.weights, val_batch.isf_score_ids) ce_loss_val, ce_loss_sum, acc_sum = sess.run([ model.cross_entropy_loss_val, model.ce_loss_summary_val, model.vstepa_accuracy_summary], feed_dict={model.logits_placeholder: val_batch.logits, model.label_placeholder: val_batch.labels, model.weight_placeholder: val_batch.weights, model.train_acc_placeholder: validation_acc}) # Print Validation Summary model.summary_writer.add_summary(acc_sum, epoch*len(train_data.fileindices)) model.summary_writer.add_summary(ce_loss_sum, epoch*len(train_data.fileindices)) print("STEP A: Epoch %s : Validation (%s) CE error = %.6f" % (str(epoch),str(val_batch.docs.shape[0]),ce_loss_val)) print("STEP A: Epoch %s : Validation (%s) Accuracy = %.6f" % (str(epoch),str(val_batch.docs.shape[0]),validation_acc)) # Estimate MRR on validation set mrr_score = mrr_metric(probs,val_batch.labels,val_batch.weights,val_batch.isf_score_ids) print("STEP A: Epoch %s : Validation (%s) MRR = %.6f" % (str(epoch),str(val_batch.docs.shape[0]),mrr_score)) # Estimate MAP score on validation set mapsc = map_score(probs,val_batch.labels,val_batch.weights,val_batch.isf_score_ids) print("STEP A: Epoch %s : Validation (%s) MAP = %.6f" % (str(epoch),str(val_batch.docs.shape[0]),mapsc)) print("STEP A: Epoch %d : Duration: %.4f" % (epoch,time.time()-ep_time) ) #END-FOR-EPOCH print("Optimization Finished!") def train_debug(sess): """ Training Mode: Create a new model and train the network """ ### Prepare data for training print("Prepare vocab dict and read pretrained word embeddings ...") vocab_dict, word_embedding_array = DataProcessor().prepare_vocab_embeddingdict() # vocab_dict contains _PAD and _UNK but not word_embedding_array print("Prepare training data ...") train_data = DataProcessor().prepare_news_data(vocab_dict, data_type="training") print("Training size: ",len(train_data.fileindices)) print("Prepare validation data ...") # data in whole batch with padded matrixes val_batch = batch_load_data(DataProcessor().prepare_news_data(vocab_dict, data_type="validation", normalizer=train_data.normalizer, pca_model=train_data.pca_model)) print("Validation size: ",val_batch.docs.shape[0]) #print("Prepare ROUGE reward generator ...") #rouge_generator = Reward_Generator() # Create Model with various operations model = MY_Model(sess, len(vocab_dict)-2) init_epoch = 1 # Resume training if indicated Select the model # Initialize word embedding before training print("Initialize word embedding vocabulary with pretrained embeddings ...") sess.run(model.vocab_embed_variable.assign(word_embedding_array)) ### STEP A : Start Pretraining the policy with Supervised Labels: Simple Cross Entropy Training counter = 0 for epoch in range(init_epoch, FLAGS.train_epoch_crossentropy+1): ep_time = time.time() # to check duration train_data.shuffle_fileindices() # Start Batch Training step = 1 total_ce_loss = 0 total_train_acc = 0 while (step * FLAGS.batch_size) <= len(train_data.fileindices): # Get batch data as Numpy Arrays batch = train_data.get_batch(((step-1)*FLAGS.batch_size), (step * FLAGS.batch_size)) # Run optimizer: optimize policy and reward estimator _,batch_logits,ce_loss,merged_summ = sess.run([ model.train_op_policynet_withgold, model.logits, model.cross_entropy_loss, model.merged], feed_dict={model.document_placeholder: batch.docs, model.label_placeholder: batch.labels, model.weight_placeholder: batch.weights, #model.cnt_placeholder: batch.cnt_score, model.isf_placeholder: batch.isf_score, model.idf_placeholder: batch.idf_score, model.locisf_score_placeholder: batch.locisf_score #model.sent_len_placeholder: batch.sent_lens }) total_ce_loss += ce_loss probs = sess.run(model.predictions,feed_dict={model.logits_placeholder: batch_logits}) training_acc = accuracy_qas_top( probs, batch.labels, batch.weights, batch.isf_score_ids) total_train_acc += training_acc # Print the progress if (step % FLAGS.training_checkpoint) == 0: total_train_acc /= FLAGS.training_checkpoint acc_sum = sess.run( model.tstepa_accuracy_summary, feed_dict={model.train_acc_placeholder: training_acc}) total_ce_loss /= FLAGS.training_checkpoint # Print Summary to Tensor Board model.summary_writer.add_summary(merged_summ, counter) model.summary_writer.add_summary(acc_sum, counter) # Performance on the validation set # Get Predictions: Prohibit the use of gold labels FLAGS.authorise_gold_label = False FLAGS.use_dropout = False val_batch = batch_predict_with_a_model(val_batch,"validation", model, session=sess) FLAGS.authorise_gold_label = True FLAGS.use_dropout = True # Validation Accuracy and Prediction probs = sess.run(model.probs,feed_dict={model.logits_placeholder: val_batch.logits}) validation_acc = accuracy_qas_top(probs, val_batch.labels, val_batch.weights, val_batch.isf_score_ids) ce_loss_val, ce_loss_sum, acc_sum = sess.run([ model.cross_entropy_loss_val, model.ce_loss_summary_val, model.vstepa_accuracy_summary], feed_dict={model.logits_placeholder: val_batch.logits, model.label_placeholder: val_batch.labels, model.weight_placeholder: val_batch.weights, model.isf_score_placeholder: val_batch.isf_score, model.locisf_score_placeholder: val_batch.locisf_score, model.val_acc_placeholder: validation_acc}) # Print Validation Summary model.summary_writer.add_summary(acc_sum, counter) model.summary_writer.add_summary(ce_loss_sum, counter) print("Epoch %2d, step: %2d(%2d) || CE loss || Train : %4.3f , Val : %4.3f ||| ACC || Train : %.3f , Val : %.3f" % (epoch,step,counter,total_ce_loss,ce_loss_val,total_train_acc,validation_acc)) total_ce_loss = 0 total_train_acc = 0 if (step % 5) == 0: # to have comparable tensorboard plots counter += 1 # Increase step step += 1 #END-WHILE-TRAINING ... but wait there is more print("Epoch %2d : Duration: %.4f" % (epoch,time.time()-ep_time) ) if not FLAGS.use_subsampled_dataset: print("Saving model after epoch completion") checkpoint_path = os.path.join(FLAGS.train_dir, "step-a.model.ckpt.epoch-"+str(epoch)) model.saver.save(sess,
or args.dataset == "cnormal1b" or args.dataset == "lognormal1b" or args.dataset == "normal1b" or args.dataset == "test" or "tti1m" in args.dataset or "tti1b" in args.dataset: fvecs_write(split_data_path, split_data) elif "glove" in args.dataset: hf = h5py.File(split_data_path, 'w') hf.create_dataset('dataset', data=split_data) print("Wrote to ", split_data_path, ", shape ", split_data.shape) print("arcm::write_split_data done\n"); def write_gt_data(gt_data): if "sift1b" in args.dataset or "sift1m" in args.dataset or "gist" in args.dataset or "deep1m" in args.dataset or "deepm96" in args.dataset or "deep1b" in args.dataset or "music1m" in args.dataset or args.dataset == "clognormal1m" or args.dataset == "cnormal1m" or args.dataset == "lognormal1m" or args.dataset == "normal1m" or args.dataset == "clognormal1b" or args.dataset == "cnormal1b" or args.dataset == "lognormal1b" or args.dataset == "normal1b" or args.dataset == "test" or "tti1m" in args.dataset or "tti1b" in args.dataset: ivecs_write(groundtruth_path, gt_data) elif "glove" in args.dataset: hf = h5py.File(groundtruth_path, 'w') hf.create_dataset('dataset', data=gt_data) print("Wrote to ", groundtruth_path, ", shape ", gt_data.shape) print("arcm::write_gt_data done\n"); def mmap_split(filename, N): num_per_split = int(N/args.num_split) sampling_rate = 0.1 for i in range(args.num_split): split_data = read_data(dataset_basedir, offset_=num_per_split*i, shape_=num_per_split) print("Split ", i, " / split_data.size: ", split_data.shape) print(split_data[0]) write_split_data(split_dataset_path + str(args.num_split) + "_" + str(i), split_data) if i==0: trainset = np.random.choice(num_per_split, int(sampling_rate*num_per_split), replace=False) write_split_data(split_dataset_path + "learn" + str(args.num_split) + "_" + str(i), split_data[trainset]) def split(filename, num_iter, N, D): num_per_split = int(N/args.num_split) dataset_per_iter = int(N/num_iter) dataset = np.empty((0, D), dtype=np.uint8 if 'sift1b' in args.dataset else np.float32) print("dataset_per_iter: ", dataset_per_iter, " / num_per_split: ", num_per_split) num_split_list=[] split = 0 sampling_rate = 0.1 for it in range(num_iter): print("Iter: ", it) if it==num_iter-1: dataset = np.append(dataset, read_data(dataset_basedir, offset_=it*dataset_per_iter, shape_=(N-it*dataset_per_iter)), axis=0) else: dataset = np.append(dataset, read_data(dataset_basedir, offset_=it*dataset_per_iter, shape_=dataset_per_iter), axis=0) count=0 while split<args.num_split: if (split+1)*num_per_split > dataset_per_iter*(it+1): if it!=num_iter-1: print("Entering next iter.. start index ", count*num_per_split, " ", dataset.shape[0]) dataset = dataset[count*num_per_split:] else: split_size = dataset[count*num_per_split:].shape[0] print("Split ", split, ": ", count*num_per_split, " ", N-1) print(dataset[count*num_per_split]) write_split_data(split_dataset_path + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:]) if "glove" in args.dataset: trainset = np.random.choice(split_size, int(sampling_rate*split_size), replace=False) write_split_data(split_dataset_path + args.metric + "_learn" + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:][trainset]) elif "music1m" in args.dataset or "deepm96" in args.dataset or args.dataset == "clognormal1m" or args.dataset == "cnormal1m" or args.dataset == "lognormal1m" or args.dataset == "normal1m" or args.dataset == "clognormal1b" or args.dataset == "cnormal1b" or args.dataset == "lognormal1b" or args.dataset == "normal1b": trainset = np.random.choice(split_size, int(sampling_rate*split_size), replace=False) write_split_data(split_dataset_path + "learn" + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:][trainset]) num_split_list.append(dataset[count*num_per_split:].shape[0]) split = split+1 break elif split < args.num_split: split_size = dataset[count*num_per_split:(count+1)*num_per_split].shape[0] print("Split ", split, ": ", count*num_per_split, " ", (count+1)*num_per_split) print(dataset[count*num_per_split]) write_split_data(split_dataset_path + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:(count+1)*num_per_split]) if "glove" in args.dataset: trainset = np.random.choice(split_size, int(sampling_rate*split_size), replace=False) write_split_data(split_dataset_path + args.metric + "_learn" + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:(count+1)*num_per_split][trainset]) elif "music1m" in args.dataset or "deepm96" in args.dataset or args.dataset == "clognormal1m" or args.dataset == "cnormal1m" or args.dataset == "lognormal1m" or args.dataset == "normal1m" or args.dataset == "clognormal1b" or args.dataset == "cnormal1b" or args.dataset == "lognormal1b" or args.dataset == "normal1b": trainset = np.random.choice(split_size, int(sampling_rate*split_size), replace=False) write_split_data(split_dataset_path + "learn" + str(args.num_split) + "_" + str(split), dataset[count*num_per_split:(count+1)*num_per_split][trainset]) num_split_list.append(dataset[count*num_per_split:(count+1)*num_per_split].shape[0]) split = split+1 count = count+1 print("num_split_lists: ", num_split_list) print("arcm::split done\n"); def random_split(filename, num_iter, N, D): num_per_split = int(N/args.num_split) dataset = np.empty((0, D), dtype=np.uint8 if 'sift1b' in args.dataset else np.float32) dataset_per_iter = int(N/num_iter) num_per_split = int(N/args.num_split) print("dataset_per_iter: ", dataset_per_iter, " / num_per_split: ", num_per_split) num_split_list=[] split = 0 sampling_rate = 0.1 import random random.seed(100) data_ids = list(range(N)) random.shuffle(data_ids) # print(data_ids[0:1000]) dataset = read_data(dataset_basedir) for split in range(args.num_split): if split < args.num_split: write_split_data(split_dataset_path + str(args.num_split) + "_" + str(split), dataset[data_ids[split*num_per_split:(split+1)*num_per_split]]) else: write_split_data(split_dataset_path + str(args.num_split) + "_" + str(split), dataset[data_ids[split*num_per_split:]]) np.array(data_ids, dtype=np.uint32).tofile(remapping_file_path) print("Wrote remapping index file to ", remapping_file_path) def run_groundtruth(): print("Making groundtruth file") import ctypes groundtruth_dir = dataset_basedir + "groundtruth/" if os.path.isdir(groundtruth_dir)!=True: os.mkdir(groundtruth_dir) queries = np.array(get_queries(), dtype='float32') groundtruth = np.empty([qN, 1000], dtype=np.int32) groundtruth_simil = np.empty([qN, 1000], dtype=np.float32) ypp_handles = [np.ctypeslib.as_ctypes(row) for row in queries] gpp_handles = [np.ctypeslib.as_ctypes(row) for row in groundtruth] gspp_handles = [np.ctypeslib.as_ctypes(row) for row in groundtruth_simil] ypp = (ctypes.POINTER(ctypes.c_float) * qN)(*ypp_handles) gpp = (ctypes.POINTER(ctypes.c_int) * qN)(*gpp_handles) gspp = (ctypes.POINTER(ctypes.c_float) * qN)(*gspp_handles) if(args.num_split == -1): dataset = read_data(dataset_basedir, base=True, offset_=0, shape_=None).astype('float32') xpp_handles = [np.ctypeslib.as_ctypes(row) for row in dataset] xpp = (ctypes.POINTER(ctypes.c_float) * N)(*xpp_handles) libc = ctypes.CDLL('./groundtruth.so') libc.compute_groundtruth.restype=None libc.compute_groundtruth(0, N, D, qN, xpp, ypp, gpp, gspp, True if args.metric=="dot_product" else False) write_gt_data(groundtruth) else: for num in range(args.num_split): print("Working on", str(num+1), "th out of", str(args.num_split), "splits...") num_per_split = int(N/args.num_split) partial_split_dataset_path = split_dataset_path+str(args.num_split)+"_"+str(num) dataset = read_data(partial_split_dataset_path, base=False, offset_=0, shape_=None).astype('float32') xpp_handles = [np.ctypeslib.as_ctypes(row) for row in dataset] xpp = (ctypes.POINTER(ctypes.c_float) * N)(*xpp_handles) libc = ctypes.CDLL('./groundtruth.so') libc.compute_groundtruth.restype=None libc.compute_groundtruth(num, num_per_split, D, qN, xpp, ypp, gpp, gspp, True if args.metric=="dot_product" else False) # split_gt_path = groundtruth_path write_gt_data(groundtruth) def sort_neighbors(distances, neighbors): if "dot_product" == args.metric or "angular" == args.metric: return np.take_along_axis(neighbors, np.argsort(-distances, axis=-1), -1)[:,:,:args.topk], -np.sort(-distances, axis=-1)[:,:,:args.topk] elif "squared_l2" == args.metric: return np.take_along_axis(neighbors, np.argsort(distances, axis=-1), -1)[:,:,:args.topk], np.sort(distances, axis=-1)[:,:,:args.topk] # return np.take_along_axis(neighbors, np.argsort(distances, axis=-1), -1), np.sort(distances, axis=-1) else: assert False def prepare_eval(): gt = get_groundtruth() queries = get_queries() # num_of_queries = 10000 # gt = gt[0:num_of_queries, :] # queries = queries[0:num_of_queries, :] # qN = num_of_queries print("gt shape: ", np.shape(gt)) print("queries shape: ", np.shape(queries)) # print("gt: ", gt[0]) assert gt.shape[1] == 1000 return gt, queries def print_recall(final_neighbors, gt): print("final_neighbors :", final_neighbors.shape) print("gt :", gt.shape) # print("final_neighbors :", final_neighbors[44]) # print("gt :", gt[44]) top1 = compute_recall(final_neighbors[:,:1], gt[:, :1]) top10 = compute_recall(final_neighbors[:,:10], gt[:, :10]) top100 = compute_recall(final_neighbors[:,:100], gt[:, :100]) top1000 = compute_recall(final_neighbors[:,:1000], gt[:, :1000]) # top1000_10000 = compute_recall(final_neighbors[:,:10000], gt[:, :1000]) print("Recall 1@1:", top1) print("Recall 10@10:", top10) print("Recall 100@100:", top100) print("Recall 1000@1000:", top1000) # print("Recall 1000@10000:", top1000_10000) return top1, top10, top100, top1000 def get_searcher_path(split): searcher_dir = basedir + args.program + '_searcher_' + args.metric + '/' + args.dataset + '/Split_' + str(args.num_split) + '/' os.makedirs(searcher_dir, exist_ok=True) searcher_path = searcher_dir + args.dataset + '_searcher_' + str(args.num_split)+'_'+str(split) return searcher_dir, searcher_path def check_available_search_config(program, bc, search_config): sc_list = list() if program == "scann": num_leaves, threshold, dims, metric = bc for idx, sc in enumerate(search_config): leaves_to_search = sc[0] if leaves_to_search > num_leaves or (D%dims!=0 and args.sweep==True) or (metric == 'squared_l2' and (4**(D/dims) < N)): continue elif (D/dims) <= 4: continue else: sc_list.append(idx) elif program == "faiss": L, m, log2kstar, metric = bc for idx, sc in enumerate(search_config): nprobe, args.reorder = sc[0], sc[1] if nprobe > L or (nprobe > 2048 and args.is_gpu) or (D%m!=0 and args.sweep==True) or (m > 96 and args.is_gpu) or (not args.is_gpu and log2kstar>8) or (args.is_gpu and log2kstar != 8) or (metric == 'dot_product' and ((2**log2kstar)**m < N)) or (args.opq != -1 and args.opq%m != 0): continue elif m <= 4: continue else: sc_list.append(idx) else: assert False return sc_list def run_scann(): gt, queries = prepare_eval() train_dataset = get_train() num_per_split = int(N/args.num_split) if args.sweep: if "sift1b" in args.dataset or "deep1b" in args.dataset or "tti1b" in args.dataset: # For sift 1b # build_config = [[7000, 0.55, 2, args.metric], [7000, 0.2, 4, args.metric], [7000, 0.2, 2, args.metric], [7000, 0.2, 1, args.metric], \ # [8000, 0.55, 2, args.metric], [8000, 0.2, 4, args.metric], [8000, 0.2, 2, args.metric], [8000, 0.2, 1, args.metric], \ # [6000, 0.55, 2, args.metric], [6000, 0.2, 4 , args.metric], [6000, 0.2, 2, args.metric], [6000, 0.2, 1, args.metric]] build_config = [ [20000, 0.2, 1, args.metric], [20000, 0.2, 2, args.metric], [20000, 0.2, 4, args.metric] ] # search_config = [[1, args.reorder], [16, args.reorder], [32, args.reorder], [64, args.reorder], [128, args.reorder], \ # [256, args.reorder], [320, args.reorder], [384, args.reorder], [448, args.reorder], [512, args.reorder], [576, args.reorder], [640, args.reorder], [704, args.reorder], [768, args.reorder], \ # [1024, args.reorder], [1280, args.reorder], [1536, args.reorder], [2048, args.reorder], [2560, args.reorder], [3072, args.reorder], [4096, args.reorder], [4608, args.reorder], \ # [5120, args.reorder], [5632, args.reorder], [6144, args.reorder], [6656, args.reorder], [7168, args.reorder], [7680, args.reorder], \ # [8192, args.reorder], [16384, args.reorder]] if "tti1b" in args.dataset: search_config = [[1, args.reorder], [2, args.reorder], [4, args.reorder], [8, args.reorder], [16, args.reorder], [32, args.reorder], [64, args.reorder], [128, args.reorder], [256, args.reorder], [512, args.reorder], [1024, args.reorder]] else: search_config = [[1, args.reorder], [2, args.reorder], [4, args.reorder], [8, args.reorder], [16, args.reorder], [32, args.reorder], [64, args.reorder], [128, args.reorder], [256, args.reorder]] else: # build_config = [ # [4000, 0.2, 1, args.metric],[4000, 0.2, 2, args.metric], [4000, 0.2, 3, args.metric], [4000, 0.2, 4, args.metric], [4000, 0.2, 5, args.metric], [4000, 0.2, 8, args.metric], [4000, 0.2, 10, args.metric], [4000, 0.2, 16, args.metric], [4000, 0.2, 25, args.metric], [4000, 0.2, 32, args.metric], [4000, 0.2, 50, args.metric], [4000, 0.2, 64, args.metric], \ # # [4000, 0.4, 1, args.metric], [4000, 0.4, 2, args.metric], [4000, 0.4, 3, args.metric], [4000, 0.4, 4, args.metric], [4000, 0.4, 5, args.metric], [4000, 0.4, 8, args.metric], [4000, 0.4, 10, args.metric], [4000, 0.4, 16, args.metric], [4000, 0.4, 25, args.metric], [4000, 0.4, 32, args.metric], [4000, 0.4, 50, args.metric], [4000, 0.4, 64, args.metric], \ # # [4000, 0.55, 1, args.metric], [4000, 0.55, 2, args.metric], [4000, 0.55, 3, args.metric], [4000, 0.55, 4, args.metric], [4000, 0.55, 5, args.metric], [4000, 0.55, 8, args.metric], [4000, 0.55, 10, args.metric], [4000, 0.55, 16, args.metric], [4000, 0.55, 25, args.metric], [4000, 0.55, 32, args.metric], [4000, 0.55, 50, args.metric], [4000, 0.55, 64, args.metric], \ # [2000, 0.2, 1, args.metric], [2000, 0.2, 2, args.metric], [2000, 0.2, 3, args.metric], [2000, 0.2, 4, args.metric], [2000, 0.2, 5, args.metric], [2000, 0.2, 8, args.metric], [2000, 0.2, 10, args.metric], [2000, 0.2, 16, args.metric], [2000, 0.2, 25, args.metric], [2000, 0.2, 32, args.metric], [2000, 0.2, 50, args.metric], [2000, 0.2, 64, args.metric], \ # # [2000, 0.4, 1, args.metric], [2000, 0.4, 2, args.metric], [2000, 0.4, 3, args.metric], [2000, 0.4, 4, args.metric], [2000, 0.4, 5, args.metric], [2000,
<gh_stars>1-10 #!/usr/bin/python # Copyright (c) 2014, <NAME> # Released subject to the New BSD License # Please see http://en.wikipedia.org/wiki/BSD_licenses from __future__ import print_function, unicode_literals import imp import os import random import re import string import sys import time from datetime import datetime from email.utils import make_msgid from six import binary_type, text_type, PY3, iteritems from .config import parse_config_file, create_client_from_config from .fixed_offset import FixedOffset from .imapclient import IMAPClient, DELETED, RECENT, _dict_bytes_normaliser from .response_types import Envelope, Address from .test.util import unittest from .util import to_bytes, to_unicode # TODO cleaner verbose output: avoid "__main__" and separator between classes SIMPLE_MESSAGE = 'Subject: something\r\n\r\nFoo\r\n' # Simple address in To header triggers interesting Fastmail.fm # behaviour with ENVELOPE responses. MULTIPART_MESSAGE = """\ From: <NAME> <<EMAIL>> To: Some One <<EMAIL>>, <EMAIL> Date: Tue, 16 Mar 2010 16:45:32 +0000 MIME-Version: 1.0 Subject: A multipart message Content-Type: multipart/mixed; boundary="===============1534046211==" --===============1534046211== Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable <html><body> Here is the first part. </body></html> --===============1534046211== Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Here is the second part. --===============1534046211==-- """.replace('\n', '\r\n') SMILE = '\u263a' MICRO = '\u00b5' SMILE_MESSAGE = b"""\ Subject: stuff Content-Type: text/plain; charset="UTF-8" \xe2\x98\xba """.replace(b'\n', b'\r\n') class _TestBase(unittest.TestCase): conf = None use_uid = True @classmethod def setUpClass(cls): cls.client = create_client_from_config(cls.conf) cls.client.use_uid = cls.use_uid cls.base_folder = cls.conf.namespace[0] + '__imapclient' cls.folder_delimiter = cls.conf.namespace[1] def setUp(self): self.clear_test_folders() self.unsub_all_test_folders() self.client.create_folder(self.base_folder) self.client.select_folder(self.base_folder) def tearDown(self): self.clear_test_folders() self.unsub_all_test_folders() @classmethod def tearDownClass(cls): cls.client.logout() def skip_unless_capable(self, capability, name=None): if not self.client.has_capability(capability): if not name: name = capability self.skipTest("Server doesn't support %s" % name) def just_folder_names(self, dat): if self.client.folder_encode: gmail_special_prefix = '[' else: gmail_special_prefix = b'[' ret = [] for _, _, folder_name in dat: # gmail's "special" folders start with '[' if not folder_name.startswith(gmail_special_prefix): ret.append(folder_name) return ret def all_test_folder_names(self): return self.just_folder_names(self.client.list_folders(self.base_folder)) def all_sub_test_folder_names(self): return self.just_folder_names(self.client.list_sub_folders(self.base_folder)) def clear_test_folders(self): # Some servers (e.g. newer Dovecot) don't like it when you # delete the currently selected folder. try: self.client.close_folder() except IMAPClient.Error: pass self.client.folder_encode = False folder_names = sorted(self.all_test_folder_names(), key=self.get_folder_depth, reverse=True) for folder in folder_names: try: self.client.delete_folder(folder) except IMAPClient.Error: if not self.is_fastmail(): raise self.client.folder_encode = True def get_folder_depth(self, folder): # Sort folders depth first because some implementations # (e.g. MS Exchange) will delete child folders when a # parent is deleted. return folder.count(self.folder_delimiter.encode('ascii')) def clear_folder(self, folder): self.client.select_folder(folder) self.client.delete_messages(self.client.search()) self.client.expunge() def add_prefix_to_folder(self, folder): if isinstance(folder, binary_type): return self.base_folder.encode('ascii') + \ self.folder_delimiter.encode('ascii') + folder else: return self.base_folder + self.folder_delimiter + folder def add_prefix_to_folders(self, folders): return [self.add_prefix_to_folder(folder) for folder in folders] def unsub_all_test_folders(self): for folder in self.all_sub_test_folder_names(): self.client.unsubscribe_folder(folder) def is_gmail(self): return self.client._imap.host == 'imap.gmail.com' def is_fastmail(self): return self.client._imap.host == 'mail.messagingengine.com' def is_exchange(self): # Assume that these capabilities mean we're talking to MS # Exchange. A bit of a guess really. return (self.client.has_capability('IMAP4') and self.client.has_capability('AUTH=NTLM') and self.client.has_capability('AUTH=GSSAPI')) def append_msg(self, msg, folder=None): if not folder: folder = self.base_folder self.client.append(folder, msg) if self.is_gmail(): self.client.noop() class TestGeneral(_TestBase): """ Tests that don't involve message number/UID functionality. """ def test_alternates(self): # Check alternate connection/login configurations. for name, conf in iteritems(self.conf.alternates): try: client = create_client_from_config(conf) client.logout() except Exception as err: if conf.expect_failure: if not re.search(conf.expect_failure, str(err)): self.fail( "connection test %r failed with %r, expected %r" % (name, err, conf.expect_failure)) else: self.fail("connection test %r failed unexpectedly with %r" % (name, err)) else: if conf.expect_failure: self.fail( "connection test %r didn't fail, expected %r" % (name, conf.expect_failure)) def test_capabilities(self): caps = self.client.capabilities() self.assertIsInstance(caps, tuple) self.assertGreater(len(caps), 1) for cap in caps: self.assertTrue(self.client.has_capability(cap)) self.assertFalse(self.client.has_capability('WONT EXIST')) def test_namespace(self): self.skip_unless_capable('NAMESPACE') def assertNoneOrTuple(val): assert val is None or isinstance(val, tuple), \ "unexpected namespace value %r" % val ns = self.client.namespace() self.assertEqual(len(ns), 3) assertNoneOrTuple(ns.personal) assertNoneOrTuple(ns.other) assertNoneOrTuple(ns.shared) self.assertEqual(ns.personal, ns[0]) self.assertEqual(ns.other, ns[1]) self.assertEqual(ns.shared, ns[2]) def test_select_and_close(self): resp = self.client.select_folder(self.base_folder) self.assertEqual(resp[b'EXISTS'], 0) self.assertIsInstance(resp[b'RECENT'], int) self.assertIsInstance(resp[b'FLAGS'], tuple) self.assertGreater(len(resp[b'FLAGS']), 1) self.client.close_folder() def test_select_read_only(self): self.append_msg(SIMPLE_MESSAGE) untagged = _dict_bytes_normaliser(self.client._imap.untagged_responses) self.assertNotIn(b'READ-ONLY', untagged) resp = self.client.select_folder(self.base_folder, readonly=True) untagged = _dict_bytes_normaliser(self.client._imap.untagged_responses) self.assertIn(b'READ-ONLY', untagged) self.assertEqual(resp[b'EXISTS'], 1) self.assertIsInstance(resp[b'RECENT'], int) self.assertIsInstance(resp[b'FLAGS'], tuple) self.assertGreater(len(resp[b'FLAGS']), 1) def test_list_folders(self): some_folders = ['simple', b'simple2', 'L\xffR'] if not self.is_fastmail(): some_folders.extend([r'test"folder"', br'foo\bar']) some_folders = self.add_prefix_to_folders(some_folders) for name in some_folders: self.client.create_folder(name) folders = self.all_test_folder_names() self.assertGreater(len(folders), 1, 'No folders visible on server') self.assertIn(self.base_folder, folders) for name in some_folders: self.assertIn(to_unicode(name), folders) # TODO: test LIST with wildcards def test_gmail_xlist(self): caps = self.client.capabilities() if self.is_gmail(): self.assertIn(b"XLIST", caps, "expected XLIST in Gmail's capabilities") def test_xlist(self): self.skip_unless_capable('XLIST') result = self.client.xlist_folders() self.assertGreater(len(result), 0, 'No folders returned by XLIST') foundInbox = False for flags, _, _ in result: if br'\INBOX' in [flag.upper() for flag in flags]: foundInbox = True break if not foundInbox: self.fail('INBOX not returned in XLIST output') def test_subscriptions(self): folders = self.add_prefix_to_folders([ 'foobar', b'foobar2', 'stuff & things', b'stuff & things2', 'test & \u2622', ]) for folder in folders: self.client.create_folder(folder) self.client.subscribe_folder(folder) server_folders = self.all_test_folder_names() server_folders.remove(self.base_folder) server_folders.sort() self.assertListEqual(server_folders, sorted(self.all_sub_test_folder_names())) for folder in folders: self.client.unsubscribe_folder(folder) self.assertListEqual(self.all_sub_test_folder_names(), []) # Exchange doesn't return an error when subscribing to a # non-existent folder if not self.is_exchange(): self.assertRaises(IMAPClient.Error, self.client.subscribe_folder, 'this folder is not likely to exist') def test_folders(self): self.assertTrue(self.client.folder_exists(self.base_folder)) self.assertFalse(self.client.folder_exists('this is very unlikely to exist')) folders = [ 'foobar', '123', b'foobar', b'123', ] if not self.is_fastmail(): # Fastmail doesn't appear to like double quotes in folder names folders.extend([ '"foobar"', 'foo "bar"', b'"foobar"', b'foo "bar"', ]) # Run folder tests with folder_encode off self.run_folder_tests(folders, False) # Now with folder_encode on, adding in names that only work # when this is enabled. folders.extend([ 'test & \u2622', 'stuff & things', b'stuff & things', ]) self.run_folder_tests(folders, True) def run_folder_tests(self, folder_names, folder_encode): self.client.folder_encode = folder_encode try: folder_names = self.add_prefix_to_folders(folder_names) for folder in folder_names: self.assertFalse(self.client.folder_exists(folder)) self.client.create_folder(folder) self.assertTrue(self.client.folder_exists(folder)) self.assertIn( to_unicode(folder) if folder_encode else to_bytes(folder), self.all_test_folder_names() ) self.client.select_folder(folder) self.client.close_folder() self.client.delete_folder(folder) self.assertFalse(self.client.folder_exists(folder)) finally: self.client.folder_encode = True def test_rename_folder(self): folders = self.add_prefix_to_folders([ 'foobar', b'foobar2', 'stuff & things', b'stuff & things2', '123', b'1232', 'test & \u2622', ]) for folder in folders: self.client.create_folder(folder) if isinstance(folder, binary_type): new_folder = folder + b'x' else: new_folder = folder + 'x' resp = self.client.rename_folder(folder, new_folder) self.assertIsInstance(resp, binary_type) self.assertTrue(len(resp) > 0) self.assertFalse(self.client.folder_exists(folder)) self.assertTrue(self.client.folder_exists(new_folder)) def test_status(self): # Default behaviour should return 5 keys self.assertEqual(len(self.client.folder_status(self.base_folder)), 5) new_folder = self.add_prefix_to_folder('test \u2622') self.client.create_folder(new_folder) try: status = self.client.folder_status(new_folder) self.assertEqual(status[b'MESSAGES'], 0) self.assertEqual(status[b'RECENT'], 0) self.assertEqual(status[b'UNSEEN'], 0) # Add a message to the folder, it should show up now. self.append_msg(SIMPLE_MESSAGE, new_folder) status = self.client.folder_status(new_folder) self.assertEqual(status[b'MESSAGES'], 1) if not self.is_gmail(): self.assertEqual(status[b'RECENT'], 1) self.assertEqual(status[b'UNSEEN'], 1) finally: self.client.delete_folder(new_folder) def test_idle(self): if not self.client.has_capability('IDLE'): return self.skipTest("Server doesn't support IDLE") # Start main connection idling self.client.select_folder(self.base_folder) self.client.idle() try: # Start a new connection and upload a new message client2 = create_client_from_config(self.conf) self.addCleanup(quiet_logout, client2) client2.select_folder(self.base_folder) client2.append(self.base_folder, SIMPLE_MESSAGE) # Check for the idle data responses = self.client.idle_check(timeout=5) finally: text, more_responses = self.client.idle_done() self.assertIn((1, b'EXISTS'), responses) self.assertTrue(isinstance(text, binary_type)) self.assertGreater(len(text), 0) self.assertTrue(isinstance(more_responses, list)) # Check for IDLE data returned by idle_done() # Gmail now delays updates following APPEND making this # part of the test impractical. if self.is_gmail(): return self.client.idle() try: client2.select_folder(self.base_folder) client2.append(self.base_folder, SIMPLE_MESSAGE) time.sleep(2) # Allow some time for the IDLE response to be sent finally: text, responses = self.client.idle_done() self.assertIn((2, b'EXISTS'), responses) self.assertTrue(isinstance(text, binary_type)) self.assertGreater(len(text), 0) def test_noop(self): self.client.select_folder(self.base_folder) # Initially there should be no responses text, resps = self.client.noop() self.assertTrue(isinstance(text, binary_type)) self.assertGreater(len(text), 0) self.assertEqual(resps, []) # Start a new connection and upload a new message client2 = create_client_from_config(self.conf) self.addCleanup(quiet_logout, client2) client2.select_folder(self.base_folder) client2.append(self.base_folder, SIMPLE_MESSAGE) # Check for this addition in the NOOP data msg, resps = self.client.noop() self.assertTrue(isinstance(text, binary_type)) self.assertGreater(len(text), 0) self.assertTrue(isinstance(resps, list)) self.assertIn((1, b'EXISTS'), resps) def createUidTestClass(conf, use_uid): class LiveTest(_TestBase): """ Tests could possibily involve message number/UID functionality or change behaviour based on the use_uid attribute should go here. They are tested twice: once with use_uid on and once with it off. """ def test_append_unicode(self): self.check_append(SIMPLE_MESSAGE, SIMPLE_MESSAGE) def test_append_bytes(self): self.check_append(SIMPLE_MESSAGE.encode('ascii'), SIMPLE_MESSAGE) def check_append(self, in_message, out_message): # Message time microseconds are set to 0 because the server will return # time with only seconds precision. msg_time = datetime.now().replace(microsecond=0) # Append message resp = self.client.append(self.base_folder, in_message, ('abc', 'def'), msg_time) self.assertIsInstance(resp, binary_type) # Retrieve the just added message and check that all looks well self.assertEqual(self.client.select_folder(self.base_folder)[b'EXISTS'], 1) resp = self.client.fetch(self.client.search()[0], ('RFC822', 'FLAGS', 'INTERNALDATE')) self.assertEqual(len(resp), 1) msginfo = tuple(resp.values())[0] # Time should match the time we specified returned_msg_time = msginfo[b'INTERNALDATE'] self.assertIsNone(returned_msg_time.tzinfo) self.assertEqual(returned_msg_time, msg_time) # Flags should be the same self.assertIn(b'abc', msginfo[b'FLAGS']) self.assertIn(b'def', msginfo[b'FLAGS']) # Message body should match self.assertEqual(msginfo[b'RFC822'], to_bytes(out_message)) def test_flags(self): self.append_msg(SIMPLE_MESSAGE) msg_id = self.client.search()[0] def _flagtest(func, args, expected_flags): answer = func(msg_id, *args) self.assertTrue(msg_id in answer) answer_flags = set(answer[msg_id]) answer_flags.discard(RECENT) # Might be present but don't
# -*- coding: utf-8 -*- import logging import os import socket import sys import time from copy import deepcopy from multiprocessing import Process, Queue import env import pytest import plumbum from plumbum import ( NOHUP, CommandNotFound, ProcessExecutionError, ProcessTimedOut, RemotePath, SshMachine, local, ) from plumbum._testtools import skip_on_windows, skip_without_chown from plumbum.lib import six from plumbum.machines.session import HostPublicKeyUnknown, IncorrectLogin try: import paramiko except ImportError: paramiko = None else: from plumbum.machines.paramiko_machine import ParamikoMachine pytestmark = pytest.mark.ssh def strassert(one, two): assert str(one) == str(two) # TEST_HOST = "192.168.1.143" TEST_HOST = "127.0.0.1" if TEST_HOST not in ("::1", "127.0.0.1", "localhost"): plumbum.local.env.path.append("c:\\Program Files\\Git\\bin") @pytest.fixture(scope="session") def sshpass(): try: return plumbum.local["sshpass"] except CommandNotFound: pytest.skip("Test requires sshpass") @skip_on_windows def test_connection(): SshMachine(TEST_HOST) @pytest.mark.skip( env.LINUX and env.PY[:2] == (3, 5), reason="Doesn't work on 3.5 on Linux on GHA" ) def test_incorrect_login(sshpass): with pytest.raises(IncorrectLogin): SshMachine( TEST_HOST, password="<PASSWORD>", ssh_opts=[ "-o", "PubkeyAuthentication=no", "-o", "PreferredAuthentications=password", ], ) @pytest.mark.xfail(env.LINUX, reason="TODO: no idea why this fails on linux") def test_hostpubkey_unknown(sshpass): with pytest.raises(HostPublicKeyUnknown): SshMachine( TEST_HOST, password="<PASSWORD>", ssh_opts=["-o", "UserKnownHostsFile=/dev/null", "-o", "UpdateHostKeys=no"], ) @skip_on_windows class TestRemotePath: def _connect(self): return SshMachine(TEST_HOST) def test_name(self): name = RemotePath(self._connect(), "/some/long/path/to/file.txt").name assert isinstance(name, six.string_types) assert "file.txt" == str(name) def test_dirname(self): name = RemotePath(self._connect(), "/some/long/path/to/file.txt").dirname assert isinstance(name, RemotePath) assert "/some/long/path/to" == str(name) def test_uri(self): p1 = RemotePath(self._connect(), "/some/long/path/to/file.txt") assert "ftp://" == p1.as_uri("ftp")[:6] assert "ssh://" == p1.as_uri("ssh")[:6] assert "/some/long/path/to/file.txt" == p1.as_uri()[-27:] def test_stem(self): p = RemotePath(self._connect(), "/some/long/path/to/file.txt") assert p.stem == "file" p = RemotePath(self._connect(), "/some/long/path/") assert p.stem == "path" def test_suffix(self): p1 = RemotePath(self._connect(), "/some/long/path/to/file.txt") p2 = RemotePath(self._connect(), "file.tar.gz") assert p1.suffix == ".txt" assert p1.suffixes == [".txt"] assert p2.suffix == ".gz" assert p2.suffixes == [".tar", ".gz"] strassert( p1.with_suffix(".tar.gz"), RemotePath(self._connect(), "/some/long/path/to/file.tar.gz"), ) strassert( p2.with_suffix(".other"), RemotePath(self._connect(), "file.tar.other") ) strassert( p2.with_suffix(".other", 2), RemotePath(self._connect(), "file.other") ) strassert( p2.with_suffix(".other", 0), RemotePath(self._connect(), "file.tar.gz.other"), ) strassert( p2.with_suffix(".other", None), RemotePath(self._connect(), "file.other") ) def test_newname(self): p1 = RemotePath(self._connect(), "/some/long/path/to/file.txt") p2 = RemotePath(self._connect(), "file.tar.gz") strassert( p1.with_name("something.tar"), RemotePath(self._connect(), "/some/long/path/to/something.tar"), ) strassert( p2.with_name("something.tar"), RemotePath(self._connect(), "something.tar") ) @skip_without_chown def test_chown(self): with self._connect() as rem: with rem.tempdir() as dir: p = dir / "foo.txt" p.write(six.b("hello")) # because we're connected to localhost, we expect UID and GID to be the same assert p.uid == os.getuid() assert p.gid == os.getgid() p.chown(p.uid.name) assert p.uid == os.getuid() def test_parent(self): p1 = RemotePath(self._connect(), "/some/long/path/to/file.txt") p2 = p1.parent assert str(p2) == "/some/long/path/to" def test_mkdir(self): # (identical to test_local.TestLocalPath.test_mkdir) with self._connect() as rem: with rem.tempdir() as tmp: (tmp / "a").mkdir(exist_ok=False, parents=False) assert (tmp / "a").exists() assert (tmp / "a").is_dir() (tmp / "a").mkdir(exist_ok=True, parents=False) (tmp / "a").mkdir(exist_ok=True, parents=True) with pytest.raises(OSError): (tmp / "a").mkdir(exist_ok=False, parents=False) with pytest.raises(OSError): (tmp / "a").mkdir(exist_ok=False, parents=True) (tmp / "b" / "bb").mkdir(exist_ok=False, parents=True) assert (tmp / "b" / "bb").exists() assert (tmp / "b" / "bb").is_dir() assert not tmp.exists() @pytest.mark.xfail( reason="mkdir's mode argument is not yet implemented " "for remote paths", strict=True, ) def test_mkdir_mode(self): # (identical to test_local.TestLocalPath.test_mkdir_mode) with self._connect() as rem: with rem.tempdir() as tmp: # just verify that mode argument works the same way it does for # Python's own os.mkdir, which takes into account the umask # (different from shell mkdir mode argument!); umask on my # system is 022 by default, so 033 is ok for testing this try: (tmp / "pb_333").mkdir(exist_ok=False, parents=False, mode=0o333) rem.python( "-c", "import os; os.mkdir({}, 0o333)".format( repr(str(tmp / "py_333")) ), ) pb_final_mode = oct((tmp / "pb_333").stat().st_mode) py_final_mode = oct((tmp / "py_333").stat().st_mode) assert pb_final_mode == py_final_mode finally: # we have to revert this so the tempdir deletion works if (tmp / "pb_333").exists(): (tmp / "pb_333").chmod(0o777) if (tmp / "py_333").exists(): (tmp / "py_333").chmod(0o777) assert not tmp.exists() def test_copy(self): """ tests `RemotePath.copy` for the following scenarios: * copying a simple file from `file_a` to `copy_of_a` succeeds * copying file `file_a` into a directory `a_dir/copy_of_a` succeeds * copying a directory `a_dir` over an existing directory path with `override=False` fails * copying a directory `a_dir` over an existing directory path with `override=True` succeeds """ with self._connect() as rem: with rem.tempdir() as tmp: # setup a file and make sure it exists... (tmp / "file_a").touch() assert (tmp / "file_a").exists() assert (tmp / "file_a").is_file() # setup a directory for copying into... (tmp / "a_dir").mkdir(exist_ok=False, parents=False) assert (tmp / "a_dir").exists() assert (tmp / "a_dir").is_dir() # setup a 2nd directory for testing `override=False` (tmp / "b_dir").mkdir(exist_ok=False, parents=False) assert (tmp / "b_dir").exists() assert (tmp / "b_dir").is_dir() # copying a simple file (tmp / "file_a").copy(tmp / "copy_of_a") assert (tmp / "copy_of_a").exists() assert (tmp / "copy_of_a").is_file() # copying into a directory (tmp / "file_a").copy(tmp / "a_dir/copy_of_a") assert (tmp / "a_dir/copy_of_a").exists() assert (tmp / "a_dir/copy_of_a").is_file() # copying a directory on top of an existing directory using # `override=False` (should fail with TypeError) with pytest.raises(TypeError): (tmp / "a_dir").copy(tmp / "b_dir", override=False) # copying a directory on top of an existing directory using # `override=True` (should copy transparently) (tmp / "a_dir").copy(tmp / "b_dir", override=True) assert "copy_of_a" in (tmp / "b_dir") assert not tmp.exists() class BaseRemoteMachineTest(object): TUNNEL_PROG_AF_INET = r"""import sys, socket s = socket.socket() s.bind(("", 0)) s.listen(1) sys.stdout.write("{0}\n".format(s.getsockname()[1])) sys.stdout.flush() s2, _ = s.accept() data = s2.recv(100) s2.send(b"hello " + data) s2.close() s.close() """ TUNNEL_PROG_AF_UNIX = r"""import sys, socket, tempfile s = socket.socket(family=socket.AF_UNIX) socket_location = tempfile.NamedTemporaryFile() socket_location.close() s.bind(socket_location.name) s.listen(1) sys.stdout.write("{0}\n".format(s.getsockname())) sys.stdout.flush() s2, _ = s.accept() data = s2.recv(100) s2.send(b"hello " + data) s2.close() s.close() """ def test_basic(self): with self._connect() as rem: r_ssh = rem["ssh"] r_ls = rem["ls"] r_grep = rem["grep"] lines = r_ls("-a").splitlines() assert ".bashrc" in lines or ".bash_profile" in lines with rem.cwd(os.path.dirname(os.path.abspath(__file__))): cmd = r_ssh[ "localhost", "cd", rem.cwd, "&&", r_ls, "|", r_grep["\\.py"] ] assert "'|'" in str(cmd) assert "test_remote.py" in cmd() assert "test_remote.py" in [f.name for f in rem.cwd // "*.py"] # Testing for #271 def test_double_chdir(self): with self._connect() as rem: with rem.cwd(os.path.dirname(os.path.abspath(__file__))): rem["ls"]() with rem.cwd("/tmp"): rem["pwd"]() def test_glob(self): with self._connect() as rem: with rem.cwd(os.path.dirname(os.path.abspath(__file__))): filenames = [f.name for f in rem.cwd // ("*.py", "*.bash")] assert "test_remote.py" in filenames assert "slow_process.bash" in filenames def test_glob_spaces(self): with self._connect() as rem: with rem.cwd(os.path.dirname(os.path.abspath(__file__))): filenames = [f.name for f in rem.cwd // ("*space.txt")] assert "file with space.txt" in filenames filenames = [f.name for f in rem.cwd // ("*with space.txt")] assert "file with space.txt" in filenames def test_cmd(self): with self._connect() as rem: rem.cmd.ls("/tmp") @pytest.mark.usefixtures("testdir") def test_download_upload(self): with self._connect() as rem: rem.upload("test_remote.py", "/tmp") r_ls = rem["ls"] r_rm = rem["rm"] assert "test_remote.py" in r_ls("/tmp").splitlines() rem.download("/tmp/test_remote.py", "/tmp/test_download.txt") r_rm("/tmp/test_remote.py") r_rm("/tmp/test_download.txt") def test_session(self): with self._connect() as rem: sh = rem.session() for _ in range(4): _, out, _ = sh.run("ls -a") assert ".bashrc" in out or ".bash_profile" in out def test_env(self): with self._connect() as rem: with pytest.raises(ProcessExecutionError): rem.python("-c", "import os;os.environ['FOOBAR72']") with rem.env(FOOBAR72="lala"): with rem.env(FOOBAR72="baba"): out = rem.python("-c", "import os;print(os.environ['FOOBAR72'])") assert out.strip() == "baba" out = rem.python("-c", "import os;print(os.environ['FOOBAR72'])") assert out.strip() == "lala" # path manipulation with pytest.raises(CommandNotFound): rem.which("dummy-executable") with rem.cwd(os.path.dirname(os.path.abspath(__file__))): rem.env.path.insert(0, rem.cwd / "not-in-path") p = rem.which("dummy-executable") assert p == rem.cwd / "not-in-path" / "dummy-executable" @pytest.mark.parametrize( "env", [ "lala", "-Wl,-O2 -Wl,--sort-common", "{{}}", "''", "!@%_-+=:", "'", "`", "$", "\\", ], ) def test_env_special_characters(self, env): with self._connect() as rem: with pytest.raises(ProcessExecutionError): rem.python("-c", "import os;print(os.environ['FOOBAR72'])") rem.env["FOOBAR72"] = env out = rem.python("-c", "import os;print(os.environ['FOOBAR72'])") assert out.strip() == env def test_read_write(self): with self._connect() as rem: with rem.tempdir() as dir: assert dir.is_dir() data = six.b("hello world") (dir / "foo.txt").write(data) assert (dir / "foo.txt").read() == data assert not dir.exists() def test_contains(self): with self._connect() as rem: assert "ls" in rem def test_iter_lines_timeout(self): with self._connect() as rem: try: for i, (out, err) in enumerate( rem["ping"]["-i", 0.5, "127.0.0.1"].popen().iter_lines(timeout=4) ): print("out:", out) print("err:", err) except NotImplementedError: try: pytest.skip(str(sys.exc_info()[1])) except AttributeError: return except ProcessTimedOut: assert i > 3 else: pytest.fail("Expected a timeout") def test_iter_lines_error(self): with self._connect() as rem: with pytest.raises(ProcessExecutionError) as ex: for i, lines in enumerate(rem["ls"]["--bla"].popen()): pass assert i == 1 assert "/bin/ls: " in ex.value.stderr def test_touch(self): with self._connect() as rem: rfile = rem.cwd / "sillyfile" assert not rfile.exists() rfile.touch() assert rfile.exists() rfile.delete() @skip_on_windows class TestRemoteMachine(BaseRemoteMachineTest): def _connect(self): return SshMachine(TEST_HOST) def test_tunnel(self): for tunnel_prog in (self.TUNNEL_PROG_AF_INET, self.TUNNEL_PROG_AF_UNIX): with self._connect() as rem: p = (rem.python["-u"] << tunnel_prog).popen() port_or_socket = p.stdout.readline().decode("ascii").strip() try: port_or_socket = int(port_or_socket) dhost = "localhost" except ValueError: dhost = None with rem.tunnel(12222, port_or_socket, dhost=dhost) as tun: s = socket.socket() s.connect(("localhost", 12222)) s.send(six.b("world")) data = s.recv(100) s.close() print(p.communicate()) assert data == b"hello world" def test_reverse_tunnel(self): def serve_reverse_tunnel(queue): s = socket.socket() s.bind(("", 12222)) s.listen(1) s2, _ = s.accept() data = s2.recv(100).decode("ascii").strip() queue.put(data) s2.close() s.close() with self._connect() as rem: get_unbound_socket_remote = """import sys, socket s = socket.socket() s.bind(("", 0)) s.listen(1) sys.stdout.write(str(s.getsockname()[1])) sys.stdout.flush() s.close() """ p =
board.s8b+board.s8c+board.s8d+board.s8e=='': moves = '8a8f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b8g==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f=='': moves = '8a8g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b8g==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f=='': moves = '8a8g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b8h==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f+board.s8g=='': moves = '8a8h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b8h==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f+board.s8g=='': moves = '8a8h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b8i==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f+board.s8g+board.s8h=='': moves = '8a8i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b8i==''\ and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f+board.s8g+board.s8h=='': moves = '8a8i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b6a==''\ and board.s7a=='': moves = '8a6a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b6a==''\ and board.s7a=='': moves = '8a6a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b5a==''\ and board.s7a+board.s6a=='': moves = '8a5a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b5a==''\ and board.s7a+board.s6a=='': moves = '8a5a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b4a==''\ and board.s7a+board.s6a+board.s5a=='': moves = '8a4a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b4a==''\ and board.s7a+board.s6a+board.s5a=='': moves = '8a4a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b3a==''\ and board.s7a+board.s6a+board.s5a+board.s4a=='': moves = '8a3a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b3a==''\ and board.s7a+board.s6a+board.s5a+board.s4a=='': moves = '8a3a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b2a==''\ and board.s7a+board.s6a+board.s5a+board.s4a+board.s3a=='': moves = '8a2a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b2a==''\ and board.s7a+board.s6a+board.s5a+board.s4a+board.s3a=='': moves = '8a2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b8a)and b1a==''\ and board.s7a+board.s6a+board.s5a+board.s4a+board.s3a+board.s2a=='': moves = '8a1a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b8a)and b1a==''\ and board.s7a+board.s6a+board.s5a+board.s4a+board.s3a+board.s2a=='': moves = '8a1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b6c==''\ and board.s7b=='': moves = '8a6c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b5d==''\ and board.s7b+board.s6c=='': moves = '8a5d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b4e==''\ and board.s7b+board.s6c+board.s5d=='': moves = '8a4e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b3f==''\ and board.s7b+board.s6c+board.s5d+board.s4e=='': moves = '8a3f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b2g==''\ and board.s7b+board.s6c+board.s5d+board.s4e+board.s3f=='': moves = '8a2g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b8a)and b1h==''\ and board.s7b+board.s6c+board.s5d+board.s4e+board.s3f+board.s2g=='': moves = '8a1h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b6c==''\ and board.s7b=='': moves = '8a6c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b5d==''\ and board.s7b+board.s6c=='': moves = '8a5d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b4e==''\ and board.s7b+board.s6c+board.s5d=='': moves = '8a4e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b3f==''\ and board.s7b+board.s6c+board.s5d+board.s4e=='': moves = '8a3f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b2g==''\ and board.s7b+board.s6c+board.s5d+board.s4e+board.s3f=='': moves = '8a2g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b8a)and b1h==''\ and board.s7b+board.s6c+board.s5d+board.s4e+board.s3f+board.s2g=='': moves = '8a1h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b9a !='': if re.match(r'[GK+]',Bboard.b9a)and b8a=='': moves = '9a8a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]',Bboard.b9a)and b9b=='': moves = '9a9b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|S|K',Bboard.b9a)and b8b=='': moves = '9a8b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R',Bboard.b9a)and b8a=='': moves = '9a8a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R',Bboard.b9a)and b9b=='': moves = '9a9b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]',Bboard.b9a)and b8b=='': moves = '9a8b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9c==''\ and board.s9b=='': moves = '9a9c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9c==''\ and board.s9b=='': moves = '9a9c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9d==''\ and board.s9b+board.s9c=='': moves = '9a9d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9d==''\ and board.s9b+board.s9c=='': moves = '9a9d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9e==''\ and board.s9b+board.s9c+board.s9d=='': moves = '9a9e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9e==''\ and board.s9b+board.s9c+board.s9d=='': moves = '9a9e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9f==''\ and board.s9b+board.s9c+board.s9d+board.s9e=='': moves = '9a9f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9f==''\ and board.s9b+board.s9c+board.s9d+board.s9e=='': moves = '9a9f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9g==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f=='': moves = '9a9g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9g==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f=='': moves = '9a9g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9h==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f+board.s9g=='': moves = '9a9h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9h==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f+board.s9g=='': moves = '9a9h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b9i==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f+board.s9g+board.s9h=='': moves = '9a9i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b9i==''\ and board.s9b+board.s9c+board.s9d+board.s9e+board.s9f+board.s9g+board.s9h=='': moves = '9a9i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b7a==''\ and board.s8a=='': moves = '9a7a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b7a==''\ and board.s8a=='': moves = '9a7a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b6a==''\ and board.s8a+board.s7a=='': moves = '9a6a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b6a==''\ and board.s8a+board.s7a=='': moves = '9a6a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b5a==''\ and board.s8a+board.s7a+board.s6a=='': moves = '9a5a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b5a==''\ and board.s8a+board.s7a+board.s6a=='': moves = '9a5a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b4a==''\ and board.s8a+board.s7a+board.s6a+board.s5a=='': moves = '9a4a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b4a==''\ and board.s8a+board.s7a+board.s6a+board.s5a=='': moves = '9a4a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b3a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a=='': moves = '9a3a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b3a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a=='': moves = '9a3a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b2a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a+board.s3a=='': moves = '9a2a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b2a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a+board.s3a=='': moves = '9a2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b9a)and b1a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a+board.s3a+board.s2a=='': moves = '9a1a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b9a)and b1a==''\ and board.s8a+board.s7a+board.s6a+board.s5a+board.s4a+board.s3a+board.s2a=='': moves = '9a1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b7c==''\ and board.s8b=='': moves = '9a7c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b6d==''\ and board.s8b+board.s7c=='': moves = '9a6d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b5e==''\ and board.s8b+board.s7c+board.s6d=='': moves = '9a5e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b4f==''\ and board.s8b+board.s7c+board.s6d+board.s5e=='': moves = '9a4f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b3g==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f=='': moves = '9a3g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b2h==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f+board.s3g=='': moves = '9a2h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b9a)and b1i==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f+board.s3g+board.s2h=='': moves = '9a1i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b7c==''\ and board.s8b=='': moves = '9a7c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b6d==''\ and board.s8b+board.s7c=='': moves = '9a6d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b5e==''\ and board.s8b+board.s7c+board.s6d=='': moves = '9a5e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b4f==''\ and board.s8b+board.s7c+board.s6d+board.s5e=='': moves = '9a4f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b3g==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f=='': moves = '9a3g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b2h==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f+board.s3g=='': moves = '9a2h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9a)and b1i==''\ and board.s8b+board.s7c+board.s6d+board.s5e+board.s4f+board.s3g+board.s2h=='': moves = '9a1i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b1b !='': if re.match(r'[SGK+]',Bboard.b1b)and b1a=='': moves = '1b1a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGK+]',Bboard.b1b)and b2a=='': moves = '1b2a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]',Bboard.b1b)and b2b=='': moves = '1b2b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]',Bboard.b1b)and b1c=='': moves = '1b1c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|S|K',Bboard.b1b)and b2c=='': moves = '1b2c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[PLSR]',Bboard.b1b)and b1a=='': moves = '1b1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]',Bboard.b1b)and b2a=='': moves = '1b2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R',Bboard.b1b)and b2b=='': moves = '1b2b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R',Bboard.b1b)and b1c=='': moves = '1b1c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]',Bboard.b1b)and b2c=='': moves = '1b2c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1b)and
if self.simulator.t == next_step: self.time = next_time elif self.simulator.t < next_step: # simulator exited early from hitting max_wallclock_time # add a fraction of the time until next_time equal to the fractional progress made by simulator self.time += (next_time - self.time) * (self.simulator.t - current_step) / (next_step - current_step) else: raise RuntimeError('The simulator ran to step {self.simulator.t} past the next step {next_step}.') if self.time >= next_history_time: assert self.time == next_history_time, \ f'self.time = {self.time} overshot next_history_time = {next_history_time}' self.add_config() next_history_time = get_next_history_time() for snapshot in self.snapshots: if perf_counter() >= snapshot.next_snapshot_time: snapshot.update() snapshot.next_snapshot_time = perf_counter() + snapshot.update_time # add the final configuration if it wasn't already recorded if self.time > self.times[-1]: self.add_config() # final updates for all snapshots for snapshot in self.snapshots: snapshot.update() if len(self.snapshots) == 1 and type(self.snapshots[0]) is TimeUpdate: self.snapshots.pop() print() @property def reactions(self) -> str: """ A string showing all non-null transitions in reaction notation. Each reaction is separated by newlines, so that ``print(self.reactions)`` will display all reactions. Only works with simulator method multibatch, otherwise will raise a ValueError. """ if type(self.simulator) != simulator.SimulatorMultiBatch: raise ValueError('reactions must be defined by multibatch simulator.') w = max([len(str(state)) for state in self.state_list]) reactions = [self._reaction_string(r, p, w) for (r, p) in zip(self.simulator.reactions, self.simulator.reaction_probabilities)] return '\n'.join(reactions) @property def enabled_reactions(self) -> str: """ A string showing all non-null transitions that are currently enabled. This can only check the current configuration in self.simulator. Each reaction is separated by newlines, so that ``print(self.enabled_reactions)`` will display all enabled reactions. """ if type(self.simulator) != simulator.SimulatorMultiBatch: raise ValueError('reactions must be defined by multibatch simulator.') w = max([len(str(state)) for state in self.state_list]) self.simulator.get_enabled_reactions() reactions = [] for i in range(self.simulator.num_enabled_reactions): r = self.simulator.reactions[self.simulator.enabled_reactions[i]] p = self.simulator.reaction_probabilities[self.simulator.enabled_reactions[i]] reactions.append(self._reaction_string(r, p, w)) return '\n'.join(reactions) def _reaction_string(self, reaction, p: float = 1, w: int = 1) -> str: """A string representation of a reaction.""" reactants = [self.state_list[i] for i in sorted(reaction[0:2])] products = [self.state_list[i] for i in sorted(reaction[2:])] s = '{0}, {1} --> {2}, {3}'.format(*[str(x).rjust(w) for x in reactants + products]) if p < 1: s += f' with probability {p}' return s # TODO: If this changes n, then the timescale must change def reset(self, init_config: Optional[Dict[State, int]] = None) -> None: """Reset the Simulation. Args: init_config: The configuration to reset to. Defaults to None. If None, will use the old initial configuration. """ if init_config is None: config = self.configs[0] else: config = np.zeros(len(self.state_list), dtype=np.int64) for k in init_config.keys(): config[self.state_dict[k]] += init_config[k] self.configs = [config] self.times = [0] self._history = pd.DataFrame(data=self.configs, index=pd.Index(self.times, name='time'), columns=self._history.columns) self.simulator.reset(config) # TODO: If this changes n, then the timescale must change def set_config(self, config: Union[Dict[State, int], np.ndarray]) -> None: """Change the current configuration. Args: config: The configuration to change to. This can be a dictionary, mapping states to counts, or an array giving counts in the order of state_list. """ if type(config) is dict: config_array = self.array_from_dict(config) else: config_array = np.array(config, dtype=np.int64) self.simulator.reset(config_array, self.simulator.t) self.add_config() def time_to_steps(self, time: float) -> int: """Convert length of time into number of steps. Args: time: The amount of time to convert. """ expected_steps = time * self.steps_per_time_unit if self.continuous_time: # In continuous time the number of steps is a poisson random variable # TODO: handle the case when expected_steps is larger than an int32 and numpy reports a ValueError return self.rng.poisson(expected_steps) else: # In discrete time we round up to the next step return math.ceil(expected_steps) @property def config_dict(self) -> Dict[State, int]: """The current configuration, as a dictionary mapping states to counts.""" return {self.state_list[i]: self.simulator.config[i] for i in np.nonzero(self.simulator.config)[0]} @property def config_array(self) -> np.ndarray: """The current configuration in the simulator, as an array of counts. The array is given in the same order as self.state_list. The index of state s is self.state_dict[s]. """ return np.asarray(self.simulator.config) @property def history(self) -> pd.DataFrame: """A pandas dataframe containing the history of all recorded configurations.""" h = len(self._history) if h < len(self.configs): new_history = pd.DataFrame(data=self.configs[h:], index=pd.Index(self.times_in_units(self.times[h:])), columns=self._history.columns) self._history = pd.concat([self._history, new_history]) if self.time_units is None: if self.continuous_time: self._history.index.name = 'time (continuous units)' else: self._history.index.name = f'time ({self.steps_per_time_unit} interaction steps)' return self._history def times_in_units(self, times): """If self.time_units is defined, convert time list to appropriate units.""" if self.time_units: return pd.to_timedelta(times, unit=self.time_units) else: return times def add_config(self) -> None: """Appends the current simulator configuration and time.""" self.configs.append(np.array(self.simulator.config)) self.times.append(self.time) def set_snapshot_time(self, time: float) -> None: """Updates all snapshots to the nearest recorded configuration to a specified time. Args: time (float): The parallel time to update the snapshots to. """ index = np.searchsorted(self.times, time) for snapshot in self.snapshots: snapshot.update(index=index) def set_snapshot_index(self, index: int) -> None: """Updates all snapshots to the configuration self.configs[index]. Args: index (int): The index of the configuration. """ for snapshot in self.snapshots: snapshot.update(index=index) def add_snapshot(self, snap: "Snapshot") -> None: """Add a new Snapshot to self.snapshots. Args: snap (Snapshot): The Snapshot object to be added. """ snap.simulation = self snap.initialize() snap.update() self.snapshots.append(snap) def snapshot_slider(self, var: str = 'index') -> widgets.interactive: """Returns a slider that updates all Snapshot objects. Returns a slider from the ipywidgets library. Args: var: What variable the slider uses, either 'index' or 'time'. """ if var.lower() == 'index': return widgets.interactive(self.set_snapshot_index, index=widgets.IntSlider(min=0, max=len(self.times) - 1, layout=widgets.Layout(width='100%'), step=1)) elif var.lower() == 'time': return widgets.interactive(self.set_snapshot_time, time=widgets.FloatSlider(min=self.times[0], max=self.times[-1], layout=widgets.Layout(width='100%'), step=0.01)) else: raise ValueError("var must be either 'index' or 'time'.") def sample_silence_time(self) -> float: """Starts a new trial from the initial distribution and return time until silence.""" if type(self.simulator) != simulator.SimulatorMultiBatch: raise ValueError('silence time can only be found by multibatch simulator.') self.simulator.run_until_silent(np.array(self.configs[0])) return self.time def sample_future_configuration(self, time: float, num_samples: int = 100) -> pd.DataFrame: """Repeatedly samples the configuration at a fixed future time. Args: time: The amount of time ahead to sample the configuration. num_samples: The number of samples to get. Returns: A dataframe whose rows are the sampled configuration. """ samples = [] t = self.simulator.t for _ in tqdm(range(num_samples)): self.simulator.reset(np.array(self.configs[-1]), t) end_step = t + self.time_to_steps(time) self.simulator.run(end_step) samples.append(np.array(self.simulator.config)) return pd.DataFrame(data=samples, index=pd.Index(range(num_samples), name='trial #'), columns=self._history.columns) def __getstate__(self): """Returns information to be pickled.""" # Clear _history such that it can be regenerated by self.history d = dict(self.__dict__) d['_history'] = pd.DataFrame(data=self.configs[0:1], index=pd.Index(self.times_in_units(self.times[0:1])), columns=self._history.columns) del d['simulator'] return d def __setstate__(self, state) -> None: """Instantiates from the pickled state information.""" self.__dict__ = state self.initialize_simulator(self.configs[-1]) class Plotter(Snapshot): """Base class for a Snapshot which will make a plot. Gives the option to map states to categories, for an easy way to visualize relevant subsets of the states rather than the whole state set. These require an interactive matplotlib backend to work. Attributes: fig: The matplotlib figure that is created which holds the barplot. ax: The matplotlib axis object that holds the barplot. Modifying properties of this object is the most direct way to modify the plot. state_map: A function mapping states to categories, which acts as a filter to view a subset of the states or just one field of the states. categories: A list which holds the set {state_map(state)} for all states in state_list. This gives the set of labels for the bars in the barplot. _matrix: A (# states)x(# categories) matrix such that for the configuration array self.config (indexed by states), matrix * config gives an array of counts of categories. Used internally for the update function. """ def __init__(self, state_map=None, update_time=0.5) -> None: """Initializes the StatePlotter. Args: state_map: An optional function mapping states to categories. """ self._matrix = None self.state_map = state_map self.update_time = update_time def _add_state_map(self, state_map): """An internal function called to update self.categories and self.matrix.""" self.categories = [] # categories will be ordered in the same order as state_list for state in self.simulation.state_list: if state_map(state) is not None and state_map(state) not in self.categories: self.categories.append(state_map(state)) categories_dict = {j: i for i, j in enumerate(self.categories)} self._matrix = np.zeros((len(self.simulation.state_list), len(self.categories)), dtype=np.int64) for i, state in enumerate(self.simulation.state_list): m = state_map(state) if m is not None: self._matrix[i, categories_dict[m]] += 1 def initialize(self) -> None: """Initializes the plotter by
<filename>query-opt/py/tests.py # Test cases for ImplementMe class. # The mocked objects (and therefore expected output) may change # at the point of evaluation, including into a more complex object, # but the functionality tested by each test case will not. # Your implementation should anticipate ways in which these mocks could # be more complex. # # Three cases are not yet disclosed; they will be challenging combinations # of existing test cases. import unittest import time import timeout_decorator from node import * from index import * from implement_me import ImplementMe # Insert into an empty tree class TestCase01(unittest.TestCase): @timeout_decorator.timeout(15) def test_insertion(self): btree = Index([]) key = 99 expected_output = Index([Node()]*1) expected_output.nodes[ 0 ] = Node(\ KeySet((99, -1)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insert existing key class TestCase02(unittest.TestCase): @timeout_decorator.timeout(15) def test_insertion(self): btree = Index([Node()]*1) btree.nodes[ 0 ] = Node(\ KeySet((99, -1)),\ PointerSet((0,0,0))) key = 99 expected_output = Index([Node()]*1) expected_output.nodes[ 0 ] = Node(\ KeySet((99, -1)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insert into existing node that is not full class TestCase03(unittest.TestCase): @timeout_decorator.timeout(15) def test_insertion(self): btree = Index([Node()]*1) btree.nodes[ 0 ] = Node(\ KeySet((87, -1)),\ PointerSet((0,0,0))) key = 66 expected_output = Index([Node()]*1) expected_output.nodes[ 0 ] = Node(\ KeySet((66, 87)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insert into full node. class TestCase04(unittest.TestCase): @timeout_decorator.timeout(15) def test_insertion(self): btree = Index([Node()]*1) btree.nodes[ 0 ] = Node(\ KeySet((66, 99)),\ PointerSet((0,0,0))) key = 87 expected_output = Index([Node()]*4) expected_output.nodes[0] = Node(\ KeySet((87, -1)),\ PointerSet((1,2,0))) expected_output.nodes[1] = Node(\ KeySet((66,-1)),\ PointerSet((0,0,2))) expected_output.nodes[2]=Node(\ KeySet((87,99)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insert into full node with full parent, causing root split. class TestCase05(unittest.TestCase): @timeout_decorator.timeout(25) def test_insertion(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,87)),\ PointerSet((0,0,0))) key = 99 expected_output = Index([Node()]*13) expected_output.nodes[0] = Node(\ KeySet((66, -1)),\ PointerSet((1,2,0))) expected_output.nodes[1] = Node(\ KeySet((42,-1)),\ PointerSet((4,5,0))) expected_output.nodes[2]=Node(\ KeySet((87,-1)),\ PointerSet((7,8,0))) expected_output.nodes[4]=Node(\ KeySet((7,-1)),\ PointerSet((0,0,5))) expected_output.nodes[5]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,7))) expected_output.nodes[7]=Node(\ KeySet((66,-1)),\ PointerSet((0,0,8))) expected_output.nodes[8]=Node(\ KeySet((87,99)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insert into full node with full parent, but does not cause a root split. # Note that only the path that should be affected has correct data (testing complexity) # Linearisation forces copy of some nodes to new addresses class TestCase06(unittest.TestCase): @timeout_decorator.timeout(25) def test_insertion(self): btree = Index([Node()]*13) btree.nodes[0] = Node(\ KeySet((7, -1)),\ PointerSet((1,2,0))) btree.nodes[2]=Node(\ KeySet((27,66)),\ PointerSet((7,8,9))) btree.nodes[6]=Node(\ KeySet((11,11)),\ PointerSet((0,0,90))) # Dummy data for test btree.nodes[7]=Node(\ KeySet((7,9)),\ PointerSet((0,0,8))) btree.nodes[8]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,9))) btree.nodes[9]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) key = 12 expected_output = Index([Node()]*13) expected_output.nodes[0] = Node(\ KeySet((7, 27)),\ PointerSet((1,2,3))) expected_output.nodes[2] = Node(\ KeySet((9,-1)),\ PointerSet((7,8,0))) expected_output.nodes[3]=Node(\ KeySet((66,-1)),\ PointerSet((10,11,0))) expected_output.nodes[6]=Node(\ KeySet((11,11)),\ PointerSet((0,0,90))) # Dummy data for test expected_output.nodes[7]=Node(\ KeySet((7,-1)),\ PointerSet((0,0,8))) expected_output.nodes[8]=Node(\ KeySet((9,12)),\ PointerSet((0,0,10))) expected_output.nodes[10]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,11))) expected_output.nodes[11]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Insertion causes splits that propagates at least three times # Note that only the path that should be affected has correct data (testing complexity) # Linearisation forces copy of some nodes to new addresses class TestCase07(unittest.TestCase): @timeout_decorator.timeout(25) def test_insertion(self): btree = Index([Node()]*13) btree.nodes[0] = Node(\ KeySet((7, 99)),\ PointerSet((1,2,0))) btree.nodes[2]=Node(\ KeySet((27,66)),\ PointerSet((7,8,9))) btree.nodes[7]=Node(\ KeySet((7,9)),\ PointerSet((0,0,8))) btree.nodes[8]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,9))) btree.nodes[9]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) key = 12 expected_output = Index([Node()]*40) expected_output.nodes[0] = Node(\ KeySet((27, -1)),\ PointerSet((1,2,0))) expected_output.nodes[1] = Node(\ KeySet((7, -1)),\ PointerSet((4,5,0))) expected_output.nodes[2] = Node(\ KeySet((99, -1)),\ PointerSet((7,8,0))) expected_output.nodes[5] = Node(\ KeySet((9,-1)),\ PointerSet((16,17,0))) expected_output.nodes[7]=Node(\ KeySet((66,-1)),\ PointerSet((22,23,0))) expected_output.nodes[16]=Node(\ KeySet((7,-1)),\ PointerSet((0,0,17))) expected_output.nodes[17]=Node(\ KeySet((9,12)),\ PointerSet((0,0,22))) expected_output.nodes[22]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,23))) expected_output.nodes[23]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) self.assertEqual( expected_output, ImplementMe.InsertIntoIndex( btree, key ) ) # Boundary case: lookup smallest key in tree # Fake data in last node to test complexity class TestCase08(unittest.TestCase): @timeout_decorator.timeout(15) def test_lookup(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((9,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,7)),\ PointerSet((0,0,0))) key = 9 expected_output = True self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Boundary case: lookup largest key in tree # Fake data in first node to test complexity class TestCase09(unittest.TestCase): @timeout_decorator.timeout(15) def test_lookup(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,99)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,87)),\ PointerSet((0,0,0))) key = 87 expected_output = True self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Lookup key outside range of tree's keys # Fake data in middle leaf to test complexity class TestCase10(unittest.TestCase): @timeout_decorator.timeout(15) def test_lookup(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((9,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((7,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,99)),\ PointerSet((0,0,0))) key = 7 expected_output = False self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Lookup key within tree's range but not in tree # Fake data in one leaf to test complexity class TestCase11(unittest.TestCase): @timeout_decorator.timeout(15) def test_lookup(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,9)),\ PointerSet((0,0,0))) key = 9 expected_output = False self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Lookup key strictly within the tree's range class TestCase12(unittest.TestCase): @timeout_decorator.timeout(15) def test_lookup(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((41, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,99)),\ PointerSet((0,0,0))) key = 42 expected_output = True self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Range query fully contained in one leaf node # Fake data in other node to test complexity class TestCase13(unittest.TestCase): @timeout_decorator.timeout(15) def test_range(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,68)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,99)),\ PointerSet((0,0,0))) lower_bound = 66 upper_bound = 87 expected_output = [66] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex( btree, lower_bound, upper_bound ) ) # Range query half-open to the left # Fake data in one node to test complexity. class TestCase14(unittest.TestCase): @timeout_decorator.timeout(15) def test_range(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,9)),\ PointerSet((0,0,0))) lower_bound = 0 upper_bound = 42 expected_output = [7] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex( btree, lower_bound, upper_bound ) ) # Range query half-open to the right # Fake data in one node to test complexity class TestCase15(unittest.TestCase): @timeout_decorator.timeout(15) def test_range(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,68)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,87)),\ PointerSet((0,0,0))) lower_bound = 42 upper_bound = 99 expected_output = [42,66,87] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex( btree, lower_bound, upper_bound ) ) # Range query with matching upper and lower bound # Key not in tree but found as fake data in a different node to test complexity class TestCase16(unittest.TestCase): @timeout_decorator.timeout(15) def test_range(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((7,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,7)),\ PointerSet((0,0,0))) lower_bound = 7 upper_bound = 7 expected_output = [] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex( btree, lower_bound, upper_bound ) ) # Multi-leaf range query in middle of tree # Fake data in first node to test complexity class TestCase17(unittest.TestCase): @timeout_decorator.timeout(15) def test_range(self): btree = Index([Node()]*4) btree.nodes[0] = Node(\ KeySet((42, 66)),\ PointerSet((1,2,3))) btree.nodes[1] = Node(\ KeySet((68,-1)),\ PointerSet((0,0,2))) btree.nodes[2]=Node(\ KeySet((42,-1)),\ PointerSet((0,0,3))) btree.nodes[3]=Node(\ KeySet((66,99)),\ PointerSet((0,0,0))) lower_bound = 42 upper_bound = 87 expected_output = [42,66] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex( btree, lower_bound, upper_bound ) ) # Lookup recently added key class TestCase18(unittest.TestCase): @timeout_decorator.timeout(15) def test_unknown(self): btree = Index([Node()]*13) btree.nodes[0] = Node(\ KeySet((7, 99)),\ PointerSet((1,2,3))) btree.nodes[2]=Node(\ KeySet((27,66)),\ PointerSet((7,8,9))) btree.nodes[7]=Node(\ KeySet((7,9)),\ PointerSet((0,0,8))) btree.nodes[8]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,9))) btree.nodes[9]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) key = 12 expected_output = True self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex(\ ImplementMe.InsertIntoIndex( btree, key ), key ) ) # Lookup range that includes recently added key class TestCase19(unittest.TestCase): @timeout_decorator.timeout(15) def test_unknown(self): btree = Index([Node()]*13) btree.nodes[0] = Node(\ KeySet((7, 99)),\ PointerSet((1,2,3))) btree.nodes[2]=Node(\ KeySet((27,66)),\ PointerSet((7,8,9))) btree.nodes[7]=Node(\ KeySet((7,9)),\ PointerSet((0,0,8))) btree.nodes[8]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,9))) btree.nodes[9]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) key = 12 lower_bound = 12 upper_bound = 66 expected_output = [12,27] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex(\ ImplementMe.InsertIntoIndex( btree, key ), lower_bound, upper_bound ) ) # Lookup range with nearly matching lower and upper bound equal to recently added key class TestCase20(unittest.TestCase): @timeout_decorator.timeout(15) def test_unknown(self): btree = Index([Node()]*13) btree.nodes[0] = Node(\ KeySet((7, 99)),\ PointerSet((1,2,3))) btree.nodes[2]=Node(\ KeySet((27,66)),\ PointerSet((7,8,9))) btree.nodes[7]=Node(\ KeySet((7,9)),\ PointerSet((0,0,8))) btree.nodes[8]=Node(\ KeySet((27,-1)),\ PointerSet((0,0,9))) btree.nodes[9]=Node(\ KeySet((66,88)),\ PointerSet((0,0,0))) key = 12 lower_bound = 12 upper_bound = 13 expected_output = [12] self.assertEqual( expected_output, ImplementMe.RangeSearchInIndex(\ ImplementMe.InsertIntoIndex( btree, key ), lower_bound, upper_bound ) ) # Freebie bonus for grinding out a tough semester # Look up a key in an empty tree class TestCaseB1(unittest.TestCase): @timeout_decorator.timeout(15) def test_unknown(self): btree = Index([Node()]*1) key = 9 expected_output = False self.assertEqual( expected_output, ImplementMe.LookupKeyInIndex( btree, key ) ) # Easy bonus
Cell1) assert isinstance(src, Cell1) assert tgt.rig == src.rig assert tgt.hom == src.hom self.rig = tgt.rig self.tgt = tgt self.src = src self.hom = (tgt, src) # yes it's backwards, just like shape is. Matrix.__init__(self, Lin, linss, tgt.hom[1].n) assert self.shape[1] == tgt.hom[1].n self.check() def check(self): rows, cols = self.shape tgt, src = self.hom #print( self.shape , (tgt.hom[0].n, tgt.hom[1].n) ) assert self.shape == (tgt.hom[0].n, tgt.hom[1].n) for i in range(rows): for j in range(cols): f = self[i,j] assert f.tgt == tgt[i,j], ("%s != %s"%(f.tgt.name, tgt[i,j].name)) assert f.src == src[i,j], ("%s != %s"%(f.src.name, src[i,j].name)) def homstr(self): A = self.A rows, cols = A.shape s = "["+''.join( ["["+' '.join(A[i,j].homstr() for j in range(cols))+"]" for i in range(rows)])+"]" return s __str__ = homstr @classmethod def zero(cls, tgt, src): # tgt <---- src assert isinstance(tgt, Cell1) assert isinstance(src, Cell1) assert tgt.rig == src.rig assert tgt.hom == src.hom rig = tgt.rig rows, cols = tgt.shape linss = [[Lin.zero(tgt[i,j], src[i,j]) for j in range(cols)] for i in range(rows)] return Cell2(tgt, src, linss) def transpose2(self): rows, cols = self.shape tgt, src = self.hom #A = self.A.transpose() A = self.A A = [[lin.transpose() for lin in row] for row in A] return Cell2(src, tgt, A) def __repr__(self): s = str(self.A) s = s.replace("\n", " ") return "Cell2(%s, %s, %s)"%(self.tgt, self.src, s) def __eq__(self, other): assert self.hom == other.hom return numpy.alltrue(self.A == other.A) def __mul__(self, other): "(vertical) composition of 2-morphism's" assert self.rig == other.rig assert self.src == other.tgt rig = self.rig A = self.A * other.A # compose Lin's elementwise return Cell2(self.tgt, other.src, A) def __lshift__(left, right): "horizontal composition of 2-morphism's" src = left.src * right.src tgt = left.tgt * right.tgt lins = [] for i in range(left.shape[0]): row = [] for k in range(right.shape[1]): f = reduce(Lin.direct_sum, [left[i,j]@right[j,k] for j in range(left.shape[1])]) row.append(f) lins.append(row) return Cell2(tgt, src, lins) @classmethod def send(cls, cell1, f): "apply f component-wise to construct a Cell2" #print("send", cell1.shape) A = Matrix.send(cell1, f) rows, cols = cell1.shape tgt = [[A[i,j].tgt for j in range(cols)] for i in range(rows)] tgt = Cell1(cell1.tgt, cell1.src, tgt) src = [[A[i,j].src for j in range(cols)] for i in range(rows)] src = Cell1(cell1.tgt, cell1.src, src) lin2 = Cell2(tgt, src, A) return lin2 @classmethod def identity(cls, cell1): tgt, src = cell1, cell1 rows, cols = cell1.shape A = [[cell1[i,j].identity() for j in range(cols)] for i in range(rows)] return Cell2(tgt, src, A) @classmethod def left_unitor(cls, cell1, inverse=False): m, n = cell1.hom I_m = Cell1.identity(m) tgt, src = cell1, I_m * cell1 if inverse: tgt, src = src, tgt # Bit of a hack just using .iso here! # Should use MulSpace.unitor, etc. etc. XXX rows, cols = cell1.shape A = [[Lin.iso(tgt[i,j], src[i,j]) for j in range(cols)] for i in range(rows)] return Cell2(tgt, src, A) @classmethod def right_unitor(cls, cell1, inverse=False): m, n = cell1.hom I_n = Cell1.identity(n) tgt, src = cell1, cell1 * I_n if inverse: tgt, src = src, tgt # Bit of a hack just using .iso here! # Should use MulSpace.unitor, etc. etc. XXX rows, cols = cell1.shape A = [[Lin.iso(tgt[i,j], src[i,j]) for j in range(cols)] for i in range(rows)] return Cell2(tgt, src, A) @classmethod def rand(cls, tgt, src): assert tgt.hom == src.hom shape = tgt.shape lins = [[Lin.rand(tgt[i,j], src[i,j]) for j in range(shape[1])] for i in range(shape[0])] return Cell2(tgt, src, lins) @staticmethod def reassociate(A, B, C, inverse=False): "A*(B*C) <--- (A*B)*C" assert C.tgt == B.src assert B.tgt == A.src m, n = A.shape p, q = C.shape if n*p == 0: tgt, src = A*(B*C), (A*B)*C if inverse: tgt, src = src, tgt return Cell2.zero(tgt, src) rig = A.rig ring = rig.ring def add(items): items = list(items) assert len(items) if len(items) == 1: return items[0] return AddSpace(ring, *items) ABC = numpy.empty((m, n, p, q), dtype=object) for i in range(m): for j in range(n): for k in range(p): for l in range(q): ABC[i,j,k,l] = A[i,j]@B[j,k]@C[k,l] # src AB_C = numpy.empty((m, q), dtype=object) ab_c = numpy.empty((m, q), dtype=object) for i in range(m): for l in range(q): AB_C[i, l] = add(add(A[i,j]@B[j,k] for j in range(n))@C[k,l] for k in range(p)) items = [Lin.right_distributor( add(A[i,j]@B[j,k] for j in range(n)), C[k,l]) for k in range(p)] #rd = reduce(Lin.direct_sum, items or [rig.zero.identity()]) # will need nullitor's ? rd = reduce(Lin.direct_sum, items) assert rd.src == AB_C[i, l], ("%s != %s"%(rd.src, AB_C[i,l])) ab_c[i, l] = rd src = Cell1(A.tgt, C.src, AB_C) cell1 = Cell1(A.tgt, C.src, [[ab_c[i,l].tgt for l in range(q)] for i in range(m)]) ab_c = Cell2(cell1, src, ab_c) # tgt A_BC = numpy.empty((m, q), dtype=object) a_bc = numpy.empty((m, q), dtype=object) for i in range(m): for l in range(q): A_BC[i, l] = add(A[i,j]@add(B[j,k]@C[k,l] for k in range(p)) for j in range(n)) items = [Lin.left_distributor( A[i,j], add(B[j,k]@C[k,l] for k in range(p)), inverse=True) for j in range(n)] #ld = reduce(Lin.direct_sum, items or [rig.zero.identity()]) # will need nullitor's ? ld = reduce(Lin.direct_sum, items) assert ld.tgt == A_BC[i, l] a_bc[i, l] = ld tgt = Cell1(A.tgt, C.src, A_BC) cell1 = Cell1(A.tgt, C.src, [[a_bc[i,l].src for l in range(q)] for i in range(m)]) a_bc = Cell2(tgt, cell1, a_bc) lookup = {} for k in range(p): for j in range(n): lookup[(j,k)] = len(lookup) perm = tuple(lookup[j,k] for j in range(n) for k in range(p)) def get_swap(u): assert isinstance(u, AddSpace), (u, perm) f = u.get_swap(perm) return f if len(perm) > 1: s = Cell2.send(ab_c.tgt, get_swap) assert s.tgt == a_bc.src else: s = Cell2.identity(ab_c.tgt) assert s.tgt == a_bc.src f = a_bc*s*ab_c assert f.src == src assert f.tgt == tgt if inverse: f = f.transpose2() return f @staticmethod def unit(A): assert isinstance(A, Cell1) src = Cell1.identity(A.src) tgt = A.dual * A assert tgt.hom == src.hom shape = tgt.shape n = shape[0] assert n == shape[1] rig = A.rig ring = rig.ring linss = [] for i in range(n): lins = [] # row for k in range(n): t, s = tgt[i,k], src[i,k] if i!=k: lin = Lin.zero(t, s) else: # argh... why can't we direct_sum the Lin.unit's ? a = elim.zeros(ring, t.n, s.n) idx = 0 for j in range(A.shape[0]): unit = Lin.unit(rig.one, A[j,i]) a[idx:idx+unit.shape[0], :] = unit.A idx += unit.shape[0] assert idx == t.n lin = Lin(t, s, a) lins.append(lin) linss.append(lins) return Cell2(tgt, src, linss) @staticmethod def counit(A): assert isinstance(A, Cell1) src = A * A.dual tgt = Cell1.identity(A.tgt) assert tgt.hom == src.hom shape = tgt.shape n = shape[0] assert n == shape[1] rig = A.rig ring = rig.ring linss = [] for i in range(n): lins = [] # row for k in range(n): t, s = tgt[i,k], src[i,k] if i!=k: lin = Lin.zero(t, s) else: # argh... why can't we direct_sum the Lin.counit's ? a = elim.zeros(ring, t.n, s.n) idx = 0 for j in range(A.shape[1]): counit = Lin.counit(rig.one, A[i,j]) a[:, idx:idx+counit.shape[1]] = counit.A idx += counit.shape[1] assert idx == s.n lin = Lin(t, s, a) lins.append(lin) linss.append(lins) return Cell2(tgt, src, linss) def make_frobenius(A): assert isinstance(A, Cell1) m, n = A.hom I_m = Cell1.identity(m) I_n = Cell1.identity(n) l_cup = Cell2.unit(A) l_cap = Cell2.counit(A) r_cup = Cell2.unit(A.dual) r_cap = Cell2.counit(A.dual) i_A = Cell2.identity(A) l_A = Cell2.left_unitor(A) r_A = Cell2.right_unitor(A) i_dA = Cell2.identity(A.dual) l_dA = Cell2.left_unitor(A.dual) r_dA = Cell2.right_unitor(A.dual) # getting down to business X = A * A.dual # the 'object' supporting the algebra i_X = Cell2.identity(X) unit = r_cup counit = l_cap assert unit.tgt == X assert counit.src == X left_unitor = l_A << i_dA left_unitor = left_unitor * Cell2.reassociate(I_m, A, A.dual, inverse=True) assert left_unitor.tgt == X assert left_unitor.src == I_m * X right_unitor = i_A << r_dA right_unitor = right_unitor * Cell2.reassociate(A, A.dual, I_m) assert right_unitor.tgt == X assert right_unitor.src == X * I_m mul = i_A << r_cap << i_dA assert mul.tgt == (A * I_n) * A.dual mul = (r_A << i_dA)*mul assert mul.tgt == X assert mul.src == A * (A.dual * A) * A.dual a = Cell2.reassociate(A, A.dual, A) <<
= ''' secret = f"""apiVersion: v1 kind: Secret metadata: name: seldon-init-container-secret namespace: {DEPLOY_NAMESPACE} type: Opaque stringData: AWS_ACCESS_KEY_ID: {MINIO_ACCESS_KEY} AWS_SECRET_ACCESS_KEY: {MINIO_SECRET_KEY} AWS_ENDPOINT_URL: http://{MINIO_HOST} USE_SSL: "false" """ with open("secret.yaml","w") as f: f.write(secret) run("cat secret.yaml | kubectl apply -f -", shell=True) ''' block4 = ''' sa = f"""apiVersion: v1 kind: ServiceAccount metadata: name: minio-sa namespace: {DEPLOY_NAMESPACE} secrets: - name: seldon-init-container-secret """ with open("sa.yaml","w") as f: f.write(sa) run("kubectl apply -f sa.yaml", shell=True) ''' block5 = ''' model_yaml=f"""apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: income-classifier namespace: {DEPLOY_NAMESPACE} spec: predictors: - componentSpecs: graph: implementation: SKLEARN_SERVER modelUri: s3://{MINIO_MODEL_BUCKET}/{INCOME_MODEL_PATH} envSecretRefName: seldon-init-container-secret name: classifier logger: mode: all explainer: type: AnchorTabular modelUri: s3://{MINIO_MODEL_BUCKET}/{EXPLAINER_MODEL_PATH} envSecretRefName: seldon-init-container-secret name: default replicas: 1 """ with open("model.yaml","w") as f: f.write(model_yaml) run("kubectl apply -f model.yaml", shell=True) ''' block6 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=income-classifier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' block7 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=income-classifier -o jsonpath='{{.items[1].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, block6, block7, ) html_artifact = _kale_run_code(blocks) with open("/deploy_seldon.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_seldon') _kale_mlmd_utils.call("mark_execution_complete") def test_model(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorTabular from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill import time import json from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' payload='{"data": {"ndarray": [[53,4,0,2,8,4,4,0,0,0,60,9]]}}' cmd=f"""curl -d '{payload}' \\ http://income-classifier-default.{DEPLOY_NAMESPACE}:8000/api/v1.0/predictions \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) ''' block4 = ''' payload='{"data": {"ndarray": [[53,4,0,2,8,4,4,0,0,0,60,9]]}}' cmd=f"""curl -d '{payload}' \\ http://income-classifier-default-explainer.{DEPLOY_NAMESPACE}:9000/api/v1.0/explain \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, ) html_artifact = _kale_run_code(blocks) with open("/test_model.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('test_model') _kale_mlmd_utils.call("mark_execution_complete") def deploy_outlier(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str, OUTLIER_MODEL_PATH: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" OUTLIER_MODEL_PATH = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY, OUTLIER_MODEL_PATH) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorTabular from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill import time import json from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' outlier_yaml=f"""apiVersion: serving.knative.dev/v1 kind: Service metadata: name: income-outlier namespace: {DEPLOY_NAMESPACE} spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.2.2-dev_alibidetect imagePullPolicy: IfNotPresent args: - --model_name - adultod - --http_port - '8080' - --protocol - seldon.http - --storage_uri - s3://{MINIO_MODEL_BUCKET}/{OUTLIER_MODEL_PATH} - --reply_url - http://default-broker - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.incomeod - OutlierDetector envFrom: - secretRef: name: seldon-init-container-secret """ with open("outlier.yaml","w") as f: f.write(outlier_yaml) run("kubectl apply -f outlier.yaml", shell=True) ''' block4 = ''' trigger_outlier_yaml=f"""apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: income-outlier-trigger namespace: {DEPLOY_NAMESPACE} spec: filter: sourceAndType: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1alpha1 kind: Service name: income-outlier """ with open("outlier_trigger.yaml","w") as f: f.write(trigger_outlier_yaml) run("kubectl apply -f outlier_trigger.yaml", shell=True) ''' block5 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l serving.knative.dev/service=income-outlier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, ) html_artifact = _kale_run_code(blocks) with open("/deploy_outlier.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_outlier') _kale_mlmd_utils.call("mark_execution_complete") def deploy_event_display(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorTabular from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill import time import json from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' event_display=f"""apiVersion: apps/v1 kind: Deployment metadata: name: event-display namespace: {DEPLOY_NAMESPACE} spec: replicas: 1 selector: matchLabels: &labels app: event-display template: metadata: labels: *labels spec: containers: - name: helloworld-go # Source code: https://github.com/knative/eventing-contrib/tree/master/cmd/event_display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display@sha256:f4628e97a836c77ed38bd3b6fd3d0b06de4d5e7db6704772fe674d48b20bd477 --- kind: Service apiVersion: v1 metadata: name: event-display namespace: {DEPLOY_NAMESPACE} spec: selector: app: event-display ports: - protocol: TCP port: 80 targetPort: 8080 --- apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: income-outlier-display namespace: {DEPLOY_NAMESPACE} spec: broker: default filter: attributes: type: io.seldon.serving.inference.outlier subscriber: ref: apiVersion: v1 kind: Service name: event-display """ with open("event_display.yaml","w") as f: f.write(event_display) run("kubectl apply -f event_display.yaml", shell=True) ''' block4 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/event-display -n {DEPLOY_NAMESPACE}", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, ) html_artifact = _kale_run_code(blocks) with open("/deploy_event_display.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_event_display') _kale_mlmd_utils.call("mark_execution_complete") def test_outliers(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorTabular from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill import time import json from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' def predict(): payload='{"data": {"ndarray": [[300, 4, 4, 2, 1, 4, 4, 0, 0, 0, 600, 9]]}}' cmd=f"""curl -d '{payload}' \\ http://income-classifier-default.{DEPLOY_NAMESPACE}:8000/api/v1.0/predictions \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) ''' block4 = ''' def get_outlier_event_display_logs(): cmd=f"kubectl logs $(kubectl get pod -l app=event-display -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE}) -n {DEPLOY_NAMESPACE}" ret = Popen(cmd, shell=True,stdout=PIPE) res = ret.stdout.read().decode("utf-8").split("\\n") data= [] for i in range(0,len(res)): if res[i] == 'Data,': j = json.loads(json.loads(res[i+1])) if "is_outlier"in j["data"].keys(): data.append(j) if len(data) > 0: return data[-1] else: return None j = None while j is None: predict() print("Waiting for outlier logs, sleeping") time.sleep(2) j = get_outlier_event_display_logs() print(j) print("Outlier",j["data"]["is_outlier"]==[1]) ''' block5 = ''' ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, ) html_artifact = _kale_run_code(blocks) with open("/test_outliers.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('test_outliers') _kale_mlmd_utils.call("mark_execution_complete") def explain(MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils
<filename>thingsboard_gateway/connectors/modbus/modbus_connector.py # Copyright 2022. ThingsBoard # # 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 threading import Thread from time import sleep, time from queue import Queue from random import choice from string import ascii_lowercase from thingsboard_gateway.tb_utility.tb_utility import TBUtility # Try import Pymodbus library or install it and import try: from pymodbus.constants import Defaults except ImportError: print("Modbus library not found - installing...") TBUtility.install_package("pymodbus", ">=2.3.0") TBUtility.install_package('pyserial') from pymodbus.constants import Defaults try: from twisted.internet import reactor except ImportError: TBUtility.install_package('twisted') from twisted.internet import reactor from twisted.internet import reactor from pymodbus.bit_write_message import WriteSingleCoilResponse, WriteMultipleCoilsResponse from pymodbus.register_write_message import WriteMultipleRegistersResponse, WriteSingleRegisterResponse from pymodbus.register_read_message import ReadRegistersResponseBase from pymodbus.bit_read_message import ReadBitsResponseBase from pymodbus.client.sync import ModbusTcpClient, ModbusUdpClient, ModbusSerialClient from pymodbus.client.sync import ModbusRtuFramer, ModbusSocketFramer, ModbusAsciiFramer from pymodbus.exceptions import ConnectionException from pymodbus.server.asynchronous import StartTcpServer, StartUdpServer, StartSerialServer, StopServer from pymodbus.device import ModbusDeviceIdentification from pymodbus.version import version from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext from pymodbus.datastore import ModbusSparseDataBlock from thingsboard_gateway.connectors.connector import Connector, log from thingsboard_gateway.connectors.modbus.constants import * from thingsboard_gateway.connectors.modbus.slave import Slave from thingsboard_gateway.connectors.modbus.backward_compability_adapter import BackwardCompatibilityAdapter from thingsboard_gateway.connectors.modbus.bytes_modbus_downlink_converter import BytesModbusDownlinkConverter CONVERTED_DATA_SECTIONS = [ATTRIBUTES_PARAMETER, TELEMETRY_PARAMETER] FRAMER_TYPE = { 'rtu': ModbusRtuFramer, 'socket': ModbusSocketFramer, 'ascii': ModbusAsciiFramer } SLAVE_TYPE = { 'tcp': StartTcpServer, 'udp': StartUdpServer, 'serial': StartSerialServer } FUNCTION_TYPE = { 'coils_initializer': 'co', 'holding_registers': 'hr', 'input_registers': 'ir', 'discrete_inputs': 'di' } FUNCTION_CODE_WRITE = { 'holding_registers': (6, 16), 'coils_initializer': (5, 15) } FUNCTION_CODE_READ = { 'holding_registers': 3, 'coils_initializer': 1, 'input_registers': 4, 'discrete_inputs': 2 } class ModbusConnector(Connector, Thread): process_requests = Queue(-1) def __init__(self, gateway, config, connector_type): self.statistics = {STATISTIC_MESSAGE_RECEIVED_PARAMETER: 0, STATISTIC_MESSAGE_SENT_PARAMETER: 0} super().__init__() self.__gateway = gateway self._connector_type = connector_type self.__backward_compatibility_adapter = BackwardCompatibilityAdapter(config, gateway.get_config_path()) self.__config = self.__backward_compatibility_adapter.convert() self.setName(self.__config.get("name", 'Modbus Default ' + ''.join(choice(ascii_lowercase) for _ in range(5)))) self.__connected = False self.__stopped = False self.daemon = True if self.__config.get('slave'): self.__slave_thread = Thread(target=self.__configure_and_run_slave, args=(self.__config['slave'],), daemon=True, name='Gateway as a slave') self.__slave_thread.start() if config['slave'].get('sendDataToThingsBoard', False): self.__modify_main_config() self.__slaves = [] self.__load_slaves() def is_connected(self): return self.__connected def open(self): self.__stopped = False self.start() def run(self): self.__connected = True while True: if not self.__stopped and not ModbusConnector.process_requests.empty(): thread = Thread(target=self.__process_slaves, daemon=True) thread.start() if self.__stopped: break sleep(.2) @staticmethod def __configure_and_run_slave(config): identity = None if config.get('identity'): identity = ModbusDeviceIdentification() identity.VendorName = config['identity'].get('vendorName', '') identity.ProductCode = config['identity'].get('productCode', '') identity.VendorUrl = config['identity'].get('vendorUrl', '') identity.ProductName = config['identity'].get('productName', '') identity.ModelName = config['identity'].get('ModelName', '') identity.MajorMinorRevision = version.short() blocks = {} for (key, value) in config.get('values').items(): values = {} converter = BytesModbusDownlinkConverter({}) for item in value: for section in ('attributes', 'timeseries', 'attributeUpdates', 'rpc'): for val in item.get(section, []): function_code = FUNCTION_CODE_WRITE[key][0] if val['objectsCount'] <= 1 else \ FUNCTION_CODE_WRITE[key][1] converted_value = converter.convert( {**val, 'device': config.get('deviceName', 'Gateway'), 'functionCode': function_code, 'byteOrder': config['byteOrder'], 'wordOrder': config['wordOrder']}, {'data': {'params': val['value']}}) values[val['address'] + 1] = converted_value blocks[FUNCTION_TYPE[key]] = ModbusSparseDataBlock(values) context = ModbusServerContext(slaves=ModbusSlaveContext(**blocks), single=True) SLAVE_TYPE[config['type']](context, identity=identity, address=(config.get('host'), config.get('port')) if ( config['type'] == 'tcp' or 'udp') else None, port=config.get('port') if config['type'] == 'serial' else None, framer=FRAMER_TYPE[config['method']]) def __modify_main_config(self): config = self.__config['slave'] values = config.pop('values') device = config for (register, reg_values) in values.items(): for value in reg_values: for section in ('attributes', 'timeseries', 'attributeUpdates', 'rpc'): if not device.get(section): device[section] = [] for item in value.get(section, []): device[section].append({**item, 'functionCode': FUNCTION_CODE_READ[ register] if section not in ('attributeUpdates', 'rpc') else item['functionCode']}) self.__config['master']['slaves'].append(device) def __load_slaves(self): self.__slaves = [ Slave(**{**device, 'connector': self, 'gateway': self.__gateway, 'callback': ModbusConnector.callback}) for device in self.__config.get('master', {'slaves': []}).get('slaves', [])] @classmethod def callback(cls, slave): cls.process_requests.put(slave) @property def connector_type(self): return self._connector_type def __convert_and_save_data(self, config_tuple): device, current_device_config, config, device_responses = config_tuple converted_data = {} try: converted_data = device.config[UPLINK_PREFIX + CONVERTER_PARAMETER].convert( config=config, data=device_responses) except Exception as e: log.error(e) to_send = {DEVICE_NAME_PARAMETER: converted_data[DEVICE_NAME_PARAMETER], DEVICE_TYPE_PARAMETER: converted_data[DEVICE_TYPE_PARAMETER], TELEMETRY_PARAMETER: [], ATTRIBUTES_PARAMETER: [] } if current_device_config.get('sendDataOnlyOnChange'): self.statistics[STATISTIC_MESSAGE_RECEIVED_PARAMETER] += 1 for converted_data_section in CONVERTED_DATA_SECTIONS: for current_section_dict in converted_data[converted_data_section]: for key, value in current_section_dict.items(): if device.config[LAST_PREFIX + converted_data_section].get(key) is None or \ device.config[LAST_PREFIX + converted_data_section][key] != value: device.config[LAST_PREFIX + converted_data_section][key] = value to_send[converted_data_section].append({key: value}) elif converted_data and current_device_config.get('sendDataOnlyOnChange') is None or \ not current_device_config.get('sendDataOnlyOnChange'): self.statistics[STATISTIC_MESSAGE_RECEIVED_PARAMETER] += 1 for converted_data_section in CONVERTED_DATA_SECTIONS: device.config[LAST_PREFIX + converted_data_section] = converted_data[ converted_data_section] to_send[converted_data_section] = converted_data[converted_data_section] if to_send.get(ATTRIBUTES_PARAMETER) or to_send.get(TELEMETRY_PARAMETER): self.__gateway.send_to_storage(self.get_name(), to_send) self.statistics[STATISTIC_MESSAGE_SENT_PARAMETER] += 1 def close(self): self.__stopped = True self.__stop_connections_to_masters() if reactor.running: StopServer() log.info('%s has been stopped.', self.get_name()) def get_name(self): return self.name def __process_slaves(self): # TODO: write documentation device = ModbusConnector.process_requests.get() device_responses = {'timeseries': {}, 'attributes': {}} current_device_config = {} try: for config_section in device_responses: if device.config.get(config_section) is not None: current_device_config = device.config self.__connect_to_current_master(device) if not device.config['master'].is_socket_open() or not len( current_device_config[config_section]): continue # Reading data from device for interested_data in range(len(current_device_config[config_section])): current_data = current_device_config[config_section][interested_data] current_data[DEVICE_NAME_PARAMETER] = device input_data = self.__function_to_device(device, current_data) device_responses[config_section][current_data[TAG_PARAMETER]] = { "data_sent": current_data, "input_data": input_data} log.debug("Checking %s for device %s", config_section, device) log.debug('Device response: ', device_responses) if device_responses.get('timeseries') or device_responses.get('attributes'): self.__convert_and_save_data((device, current_device_config, { **current_device_config, BYTE_ORDER_PARAMETER: current_device_config.get(BYTE_ORDER_PARAMETER, device.byte_order), WORD_ORDER_PARAMETER: current_device_config.get(WORD_ORDER_PARAMETER, device.word_order) }, device_responses)) except ConnectionException: sleep(5) log.error("Connection lost! Reconnecting...") except Exception as e: log.exception(e) def __connect_to_current_master(self, device=None): # TODO: write documentation connect_attempt_count = 5 connect_attempt_time_ms = 100 wait_after_failed_attempts_ms = 300000 if device.config.get('master') is None: device.config['master'], device.config['available_functions'] = self.__configure_master(device.config) if connect_attempt_count < 1: connect_attempt_count = 1 connect_attempt_time_ms = device.config.get('connectAttemptTimeMs', connect_attempt_time_ms) if connect_attempt_time_ms < 500: connect_attempt_time_ms = 500 wait_after_failed_attempts_ms = device.config.get('waitAfterFailedAttemptsMs', wait_after_failed_attempts_ms) if wait_after_failed_attempts_ms < 1000: wait_after_failed_attempts_ms = 1000 current_time = time() * 1000 if not device.config['master'].is_socket_open(): if device.config['connection_attempt'] >= connect_attempt_count and current_time - device.config[ 'last_connection_attempt_time'] >= wait_after_failed_attempts_ms: device.config['connection_attempt'] = 0 while not device.config['master'].is_socket_open() \ and device.config['connection_attempt'] < connect_attempt_count \ and current_time - device.config.get('last_connection_attempt_time', 0) >= connect_attempt_time_ms: device.config['connection_attempt'] = device.config[ 'connection_attempt'] + 1 device.config['last_connection_attempt_time'] = current_time log.debug("Modbus trying connect to %s", device) device.config['master'].connect() if device.config['connection_attempt'] == connect_attempt_count: log.warn("Maximum attempt count (%i) for device \"%s\" - encountered.", connect_attempt_count, device) if device.config['connection_attempt'] >= 0 and device.config['master'].is_socket_open(): device.config['connection_attempt'] = 0 device.config['last_connection_attempt_time'] = current_time @staticmethod def __configure_master(config): current_config = config current_config["rtu"] = FRAMER_TYPE[current_config['method']] if current_config.get('type') == 'tcp': master = ModbusTcpClient(current_config["host"], current_config["port"], current_config["rtu"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"]) elif current_config.get(TYPE_PARAMETER) == 'udp': master = ModbusUdpClient(current_config["host"], current_config["port"], current_config["rtu"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"]) elif current_config.get(TYPE_PARAMETER) == 'serial': master = ModbusSerialClient(method=current_config["method"], port=current_config["port"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"], baudrate=current_config["baudrate"], stopbits=current_config["stopbits"], bytesize=current_config["bytesize"], parity=current_config["parity"], strict=current_config["strict"]) else: raise Exception("Invalid Modbus transport type.") available_functions = { 1: master.read_coils, 2: master.read_discrete_inputs, 3: master.read_holding_registers, 4: master.read_input_registers, 5: master.write_coil, 6: master.write_register, 15: master.write_coils, 16: master.write_registers, } return master, available_functions def __stop_connections_to_masters(self): for slave in self.__slaves: if slave.config.get('master') is not None and slave.config.get('master').is_socket_open(): slave.config['master'].close() @staticmethod def __function_to_device(device, config): function_code = config.get('functionCode') result = None if function_code == 1: result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], count=config.get(OBJECTS_COUNT_PARAMETER, config.get("registersCount", config.get( "registerCount", 1))) * 8, unit=device.config['unitId']) elif function_code in (2, 3, 4): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], count=config.get(OBJECTS_COUNT_PARAMETER, config.get("registersCount", config.get( "registerCount", 1))), unit=device.config['unitId']) elif function_code in (5, 15): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], value=config[PAYLOAD_PARAMETER], unit=device.config['unitId'] * 8) elif function_code in (6, 16): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], values=config[PAYLOAD_PARAMETER], unit=device.config['unitId']) else: log.error("Unknown Modbus function with code: %s", function_code) log.debug("With result %s", str(result)) if "Exception" in str(result): log.exception(result) return result def on_attributes_update(self, content): try: device = tuple(filter(lambda slave: slave.name == content[DEVICE_SECTION_PARAMETER], self.__slaves))[0] for attribute_updates_command_config in device.config['attributeUpdates']: for attribute_updated in content[DATA_PARAMETER]: if attribute_updates_command_config[TAG_PARAMETER] == attribute_updated: to_process = { DEVICE_SECTION_PARAMETER: content[DEVICE_SECTION_PARAMETER], DATA_PARAMETER: { RPC_METHOD_PARAMETER: attribute_updated, RPC_PARAMS_PARAMETER: content[DATA_PARAMETER][attribute_updated] } } attribute_updates_command_config['byteOrder'] = device.byte_order or 'LITTLE' attribute_updates_command_config['wordOrder'] = device.word_order or 'LITTLE' self.__process_request(to_process, attribute_updates_command_config, request_type='attributeUpdates') except Exception as e: log.exception(e) def server_side_rpc_handler(self, server_rpc_request): try: if server_rpc_request.get(DEVICE_SECTION_PARAMETER) is not None: log.debug("Modbus connector received rpc request for %s with server_rpc_request: %s", server_rpc_request[DEVICE_SECTION_PARAMETER], server_rpc_request) device = tuple( filter( lambda slave: slave.name == server_rpc_request[DEVICE_SECTION_PARAMETER], self.__slaves ) )[0] if isinstance(device.config[RPC_SECTION], dict): rpc_command_config = device.config[RPC_SECTION].get( server_rpc_request[DATA_PARAMETER][RPC_METHOD_PARAMETER]) if rpc_command_config is not None: self.__process_request(server_rpc_request, rpc_command_config) elif isinstance(device.config[RPC_SECTION], list): for rpc_command_config in device.config[RPC_SECTION]: if rpc_command_config[TAG_PARAMETER] == server_rpc_request[DATA_PARAMETER][ RPC_METHOD_PARAMETER]: self.__process_request(server_rpc_request, rpc_command_config) break else: log.error("Received rpc request, but method %s not found in config for %s.", server_rpc_request[DATA_PARAMETER].get(RPC_METHOD_PARAMETER), self.get_name()) self.__gateway.send_rpc_reply(server_rpc_request[DEVICE_SECTION_PARAMETER], server_rpc_request[DATA_PARAMETER][RPC_ID_PARAMETER], {server_rpc_request[DATA_PARAMETER][ RPC_METHOD_PARAMETER]: "METHOD NOT FOUND!"}) else: log.debug("Received RPC to connector: %r", server_rpc_request) except Exception as e: log.exception(e) def __process_request(self, content, rpc_command_config, request_type='RPC'): log.debug('Processing %s request', request_type) if rpc_command_config is not None: device = tuple(filter(lambda slave: slave.name == content[DEVICE_SECTION_PARAMETER], self.__slaves))[0] rpc_command_config[UNIT_ID_PARAMETER] = device.config['unitId'] rpc_command_config[BYTE_ORDER_PARAMETER] = device.config.get("byteOrder", "LITTLE") rpc_command_config[WORD_ORDER_PARAMETER] = device.config.get("wordOrder", "LITTLE") self.__connect_to_current_master(device)
import os from typing import List try: from typing import Literal except ImportError: from typing_extensions import Literal # type: ignore from typing import Optional import numpy as np import pandas as pd import scanpy as sc from anndata import AnnData from rich import print WORKING_DIRECTORY = os.path.dirname(__file__) def generate_expression_table( adata, cluster: str = "all", subset_by: str = "cell_type", xlabel: str = "days", hue: str = None, use_raw: bool = None, ): """ Args: adata: Anndata object cluster: Which label of the subsets to generate the table for. Use 'all' if for all subsets. subset_by: Which label to subset the clusters by xlabel: x-axis hue: Value to color by use_raw: Whether to use adata.raw.X for the calculations Returns: Gene expression table """ if cluster == "all": cells = adata.obs_names else: cells = [True if val in cluster else False for val in adata.obs[subset_by]] if use_raw: gen_expression_table = pd.DataFrame( adata[cells].raw.X.todense(), index=adata[cells].obs_names, columns=adata[cells].raw.var_names ) else: gen_expression_table = pd.DataFrame( adata[cells].X, index=adata[cells].obs_names, columns=adata[cells].var_names ) gen_expression_table["identifier"] = adata[cells].obs["identifier"] gen_expression_table[xlabel] = adata[cells].obs[xlabel] if hue: # For multiple cluster, split internally per condition if isinstance(cluster, list) and len(cluster) > 1 and subset_by != hue: gen_expression_table[hue] = [f"{t}_{c}" for t, c in zip(adata[cells].obs[hue], adata[cells].obs[subset_by])] else: gen_expression_table[hue] = adata[cells].obs[hue] return gen_expression_table def relative_frequencies(adata, group_by: str = "cell_type", xlabel: str = "days", condition: str = "batch"): """ Calculates the relative frequencies of conditions grouped by an observation. Args: adata: AnnData Objet containing the data group_by: xlabel: x-axis label condition: Returns: Relative frequencies in a Pandas DataFrame """ freqs = adata.obs.groupby(["identifier", group_by]).size() samples = np.unique(adata.obs["identifier"]) ind = adata.obs[group_by].cat.categories relative_frequencies = [freqs[ident] / sum(freqs[ident]) for ident in samples] relative_frequencies = pd.DataFrame(relative_frequencies, columns=ind, index=samples).fillna(0) # relFreqs[xlabel] = grouping.loc[samples, xlabel] ## when using Grouping Table cell_types = {} combis = adata.obs.groupby(["identifier", xlabel]).groups.keys() for c in combis: cell_types[c[0]] = c[1] relative_frequencies[xlabel] = [cell_types[label] for label in relative_frequencies.index] # type: ignore # Todo, add for condition if condition: combis = adata.obs.groupby(["identifier", condition]).groups.keys() for c in combis: cell_types[c[0]] = c[1] relative_frequencies[condition] = [cell_types[label] for label in relative_frequencies.index] # type: ignore return relative_frequencies def relative_frequency_per_cluster(adata, group_by: str = "cell_type", xlabel: str = "days", condition=None): """ Calculates relative frequencies per cluster Args: adata: AnnData object containing the data group_by: The label to group by for the clusters xlabel: x-axis label condition: condition to combine by Returns: Pandas DataFrame of relative frequencies """ frequencies = adata.obs.groupby([group_by, xlabel]).size() celltypes = np.unique(adata.obs[group_by]) ind = adata.obs[xlabel].cat.categories relative_frequencies = [frequencies[ident] / sum(frequencies[ident]) for ident in celltypes] relative_frequencies = pd.DataFrame(relative_frequencies, columns=ind, index=celltypes).fillna(0) cell_types = {} combinations = adata.obs.groupby([group_by, xlabel]).groups.keys() for combination in combinations: cell_types[combination[0]] = combination[1] relative_frequencies[group_by] = relative_frequencies.index # type: ignore # Todo, add for condition if condition: combinations = adata.obs.groupby([group_by, condition]).groups.keys() for combination in combinations: cell_types[combination[0]] = combination[1] relative_frequencies[condition] = [cell_types[label] for label in relative_frequencies.index] # type: ignore return relative_frequencies def correlate_to_signature( adata, marker: pd.DataFrame, log_fc_threshold: float = 0.7, cell_type: str = "AT2 cells", cell_type_label: str = "cell_type", log_fc_label: str = "logfoldchange", gene_label: str = "gene", use_raw: bool = True, ): """ Correlations Score (based on cell type signature (logFC)) - alternative to sc.tl.score Args: adata: AnnData object containing the data marker: Pandas DataFrame containing marker genes log_fc_threshold: Log fold change label cell_type: Cell type to calculate the correlation for cell_type_label: Label of all cell types in the AnnData object log_fc_label: Label of fold change in the AnnData object gene_label: Label of genes in the AnnData object use_raw: Whether to use adata.raw.X Returns: List of correlations """ from scipy.sparse import issparse topmarker = marker[marker.loc[:, cell_type_label] == cell_type] topmarker = topmarker.loc[topmarker.loc[:, log_fc_label] > log_fc_threshold, [gene_label, log_fc_label]] gene_names = list(np.intersect1d(adata.var_names, topmarker.loc[:, gene_label].astype(str))) topmarker = topmarker[topmarker.loc[:, gene_label].isin(gene_names)] print(f"[bold blue]{len(gene_names)} genes used for correlation score to {cell_type}") if use_raw: if issparse(adata.raw.X): gene_expression = adata.raw[:, gene_names].X.todense() else: gene_expression = adata.raw[:, gene_names].X else: if issparse(adata.X): gene_expression = adata[:, gene_names].X.todense() else: gene_expression = adata[:, gene_names].X gene_expression = pd.DataFrame(gene_expression.T, index=gene_names) # For each cell separately gene_expression = pd.DataFrame.fillna(gene_expression, value=0) res = [ np.correlate(topmarker.loc[:, log_fc_label], gene_expression.iloc[:, c])[0] for c in range(gene_expression.shape[1]) ] return res def remove_outliers(cords, eps: int = 1, min_samples: int = 2): """ Remove outlying cells based on UMAP embeddings with DBScan (density based clustering) Call as: sub.obs["d_cluster"] = remove_outliers(sub.obsm["X_umap"], min_samples = 10) Args: cords: adata UMAP coordinates, typically adata.obsm["X_umap"] eps: Maximum distance between two clusters to still be considered neighbors min_samples: Minimum samples of a cluster Returns: Pandas DataFrame of clusters """ from natsort import natsorted from sklearn.cluster import DBSCAN clustering = DBSCAN(eps=eps, min_samples=min_samples).fit(cords) cluster = clustering.labels_.astype("U") return pd.Categorical(cluster, categories=natsorted(np.unique(cluster))) def add_percentages(adata, table, ids, group_by: str, threshold: int = 0, gene_label: str = "gene"): """ Add columns to existing diffxpy table specifying percentage of expressing cells Args: adata: AnnData object containing the data table: Table as generated by diffxpy ids: group_by: Label to group by threshold: gene_label: Label of the genes Returns: Table containing percentage of expressing cells """ for ident in ids: cells = adata.obs_names[adata.obs[group_by] == ident] data_temp = pd.DataFrame( ((adata[cells].layers["counts"] > threshold).sum(0) / adata[cells].layers["counts"].shape[0]).T, index=adata.var_names, ) if gene_label == "index": table[f"pct.{ident}s"] = data_temp.reindex(table.index.values).values else: table[f"pct.{ident}s"] = data_temp.reindex(table.loc[:, gene_label]).values return table def ranksums_between_groups( table, id1: str = "bystander", id2: str = "infected", xlabel: str = "condition", cells=None, score: str = "Axin2" ): """ Perform Wilcoxon Rank-sum test between two groups. Args: table: id1: id2: xlabel: x-axis label cells: score: Returns: Pandas DataFrame containing test statistic and p-value """ from scipy import stats if cells is not None: table = table.loc[cells].copy() group1 = table[table.loc[:, xlabel] == id1].copy() group2 = table[table.loc[:, xlabel] == id2].copy() t, p = stats.ranksums(group1.loc[:, score], group2.loc[:, score]) result = pd.DataFrame(columns=["wilcoxon_ranksum", "pval"]) result.loc[0] = [t, p] return result def generate_count_object( adata, hue: str = "disease", cell_type_label: str = "cell_type", cell_type: List[str] = None, min_samples: int = 2, min_cells: int = 5, ref: str = "healthy", subset: List[str] = None, layer: str = "counts", outliers_removal: bool = False, ): """ @Meshal what is this really supposed to do? Args: adata: AnnData object hue: Value to color by cell_type_label: Label containing cell types cell_type: Cells type to generate counts for min_samples: Minimum samples for outlier removal with DBScan min_cells: Minimal number of cells ref: subset: layer: outliers_removal: Whether to remove outliers or not Returns: AnnData object containing counts Example Call: subset = ['3d PI-KO', '3d PI-WT'] raw_counts = generate_count_object(adata, condition = "grouping", cell_type_label = "celltype_refined", cell_type = ["AT2"], ref = "3d PI-WT", subset = subset) """ adata_subset = adata[adata.obs.grouping.isin(subset)] cells = [ True if (adata_subset.obs[cell_type_label][i] in cell_type) else False for i in range(adata_subset.n_obs) # type: ignore ] # Raw count data for diffxpy obs = adata_subset[cells].obs.copy() var = adata_subset.var_names.copy() adata_raw = sc.AnnData(X=adata_subset[cells].layers[layer].copy()) adata_raw.obs = obs adata_raw.var.index = var adata_raw.obsm = adata_subset[cells].obsm.copy() # Also automate tidy up with DBScan :) if outliers_removal: adata_raw.obs["dcluster"] = remove_outliers(adata_raw.obsm["X_umap"], min_samples=min_samples) sc.pl.umap(adata_raw, color=[hue, "dcluster"]) adata_raw = adata_raw[adata_raw.obs.dcluster == "0"].copy() sc.pp.filter_genes(adata_raw, min_cells=min_cells) # Set reference as first column adata_raw.obs.loc[:, hue].cat.reorder_categories([ref, np.setdiff1d(subset, ref)[0]], inplace=True) pal = adata_subset.uns[f"{hue}_colors"] sc.pl.umap(adata_raw, color=[hue], palette=list(pal)) return adata_raw def tidy_de_table(de_test, adata, cells, ids=None, qval_thresh: float = 0.9, group_by: str = "treatment", cols=None): """ Sorts diffxpy de table and adds percentages of expression per group Args: de_test: diffxpy de test adata: AnnData object cells: ids: qval_thresh: group_by: cols: Returns: Pandas Dataframe of diffxpy table with percentages """ result = de_test.summary().sort_values(by=["qval"], ascending=True) result = result[result.qval < qval_thresh].loc[:, cols].copy() # Add percentages result = add_percentages(adata[cells], result, ids=ids, group_by=group_by) return result def correlate_means_to_gene(means: pd.DataFrame, corr_gene: str = "EOMES"): """ Calculate gene to gene correlation based on a mean expression table Args: means: corr_gene: Returns: Pandas DataFrame of correlations """ import scipy.stats genes = means.columns.values cors = pd.DataFrame(index=genes, columns=["spearman_corr", "pvalue"]) # tab = sc.get.obs_df(sub, keys = [corr_gene], layer = None, use_raw = True) table = means.loc[:, [corr_gene]].values # Loop over all genes. for gene in genes: tmp = scipy.stats.spearmanr(table, means.loc[:, [gene]]) # Spearman's rho cors.loc[gene, :] = tmp[0:2] cors.dropna(axis=0, inplace=True) cors.sort_values("spearman_corr", ascending=False, inplace=True) return cors def extended_marker_table( adata: AnnData, qval_thresh: float = 0.05, cell_type_label: str = "cell_type", gene_ranks_key: str = "rank_genes_groups", ): """ Generates an extended marker table with cell types and percentages of expressed
# # Symbol Table # from __future__ import absolute_import import re import copy import operator try: import __builtin__ as builtins except ImportError: # Py3 import builtins from .Errors import warning, error, InternalError from .StringEncoding import EncodedString from . import Options, Naming from . import PyrexTypes from .PyrexTypes import py_object_type, unspecified_type from .TypeSlots import ( pyfunction_signature, pymethod_signature, richcmp_special_methods, get_special_method_signature, get_property_accessor_signature) from . import Future from . import Code iso_c99_keywords = set( ['auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while', '_Bool', '_Complex'', _Imaginary', 'inline', 'restrict']) def c_safe_identifier(cname): # There are some C limitations on struct entry names. if ((cname[:2] == '__' and not (cname.startswith(Naming.pyrex_prefix) or cname in ('__weakref__', '__dict__'))) or cname in iso_c99_keywords): cname = Naming.pyrex_prefix + cname return cname def punycodify_name(cname, mangle_with=None): # if passed the mangle_with should be a byte string # modified from PEP489 try: cname.encode('ascii') except UnicodeEncodeError: cname = cname.encode('punycode').replace(b'-', b'_').decode('ascii') if mangle_with: # sometimes it necessary to mangle unicode names alone where # they'll be inserted directly into C, because the punycode # transformation can turn them into invalid identifiers cname = "%s_%s" % (mangle_with, cname) elif cname.startswith(Naming.pyrex_prefix): # a punycode name could also be a valid ascii variable name so # change the prefix to distinguish cname = cname.replace(Naming.pyrex_prefix, Naming.pyunicode_identifier_prefix, 1) return cname class BufferAux(object): writable_needed = False def __init__(self, buflocal_nd_var, rcbuf_var): self.buflocal_nd_var = buflocal_nd_var self.rcbuf_var = rcbuf_var def __repr__(self): return "<BufferAux %r>" % self.__dict__ class Entry(object): # A symbol table entry in a Scope or ModuleNamespace. # # name string Python name of entity # cname string C name of entity # type PyrexType Type of entity # doc string Doc string # annotation ExprNode PEP 484/526 annotation # init string Initial value # visibility 'private' or 'public' or 'extern' # is_builtin boolean Is an entry in the Python builtins dict # is_cglobal boolean Is a C global variable # is_pyglobal boolean Is a Python module-level variable # or class attribute during # class construction # is_member boolean Is an assigned class member # is_pyclass_attr boolean Is a name in a Python class namespace # is_variable boolean Is a variable # is_cfunction boolean Is a C function # is_cmethod boolean Is a C method of an extension type # is_builtin_cmethod boolean Is a C method of a builtin type (implies is_cmethod) # is_unbound_cmethod boolean Is an unbound C method of an extension type # is_final_cmethod boolean Is non-overridable C method # is_inline_cmethod boolean Is inlined C method # is_anonymous boolean Is a anonymous pyfunction entry # is_type boolean Is a type definition # is_cclass boolean Is an extension class # is_cpp_class boolean Is a C++ class # is_const boolean Is a constant # is_property boolean Is a property of an extension type: # doc_cname string or None C const holding the docstring # getter_cname string C func for getting property # setter_cname string C func for setting or deleting property # is_self_arg boolean Is the "self" arg of an exttype method # is_arg boolean Is the arg of a method # is_local boolean Is a local variable # in_closure boolean Is referenced in an inner scope # in_subscope boolean Belongs to a generator expression scope # is_readonly boolean Can't be assigned to # func_cname string C func implementing Python func # func_modifiers [string] C function modifiers ('inline') # pos position Source position where declared # namespace_cname string If is_pyglobal, the C variable # holding its home namespace # pymethdef_cname string PyMethodDef structure # signature Signature Arg & return types for Python func # as_variable Entry Alternative interpretation of extension # type name or builtin C function as a variable # xdecref_cleanup boolean Use Py_XDECREF for error cleanup # in_cinclude boolean Suppress C declaration code # enum_values [Entry] For enum types, list of values # qualified_name string "modname.funcname" or "modname.classname" # or "modname.classname.funcname" # is_declared_generic boolean Is declared as PyObject * even though its # type is an extension type # as_module None Module scope, if a cimported module # is_inherited boolean Is an inherited attribute of an extension type # pystring_cname string C name of Python version of string literal # is_interned boolean For string const entries, value is interned # is_identifier boolean For string const entries, value is an identifier # used boolean # is_special boolean Is a special method or property accessor # of an extension type # defined_in_pxd boolean Is defined in a .pxd file (not just declared) # api boolean Generate C API for C class or function # utility_code string Utility code needed when this entry is used # # buffer_aux BufferAux or None Extra information needed for buffer variables # inline_func_in_pxd boolean Hacky special case for inline function in pxd file. # Ideally this should not be necessary. # might_overflow boolean In an arithmetic expression that could cause # overflow (used for type inference). # utility_code_definition For some Cython builtins, the utility code # which contains the definition of the entry. # Currently only supported for CythonScope entries. # error_on_uninitialized Have Control Flow issue an error when this entry is # used uninitialized # cf_used boolean Entry is used # is_fused_specialized boolean Whether this entry of a cdef or def function # is a specialization # is_cgetter boolean Is a c-level getter function # TODO: utility_code and utility_code_definition serves the same purpose... inline_func_in_pxd = False borrowed = 0 init = "" annotation = None visibility = 'private' is_builtin = 0 is_cglobal = 0 is_pyglobal = 0 is_member = 0 is_pyclass_attr = 0 is_variable = 0 is_cfunction = 0 is_cmethod = 0 is_builtin_cmethod = False is_unbound_cmethod = 0 is_final_cmethod = 0 is_inline_cmethod = 0 is_anonymous = 0 is_type = 0 is_cclass = 0 is_cpp_class = 0 is_const = 0 is_property = 0 doc_cname = None getter_cname = None setter_cname = None is_self_arg = 0 is_arg = 0 is_local = 0 in_closure = 0 from_closure = 0 in_subscope = 0 is_declared_generic = 0 is_readonly = 0 pyfunc_cname = None func_cname = None func_modifiers = [] final_func_cname = None doc = None as_variable = None xdecref_cleanup = 0 in_cinclude = 0 as_module = None is_inherited = 0 pystring_cname = None is_identifier = 0 is_interned = 0 used = 0 is_special = 0 defined_in_pxd = 0 is_implemented = 0 api = 0 utility_code = None is_overridable = 0 buffer_aux = None prev_entry = None might_overflow = 0 fused_cfunction = None is_fused_specialized = False utility_code_definition = None needs_property = False in_with_gil_block = 0 from_cython_utility_code = None error_on_uninitialized = False cf_used = True outer_entry = None is_cgetter = False def __init__(self, name, cname, type, pos = None, init = None): self.name = name self.cname = cname self.type = type self.pos = pos self.init = init self.overloaded_alternatives = [] self.cf_assignments = [] self.cf_references = [] self.inner_entries = [] self.defining_entry = self def __repr__(self): return "%s(<%x>, name=%s, type=%s)" % (type(self).__name__, id(self), self.name, self.type) def already_declared_here(self): error(self.pos, "Previous declaration is here") def redeclared(self, pos): error(pos, "'%s' does not match previous declaration" % self.name) self.already_declared_here() def all_alternatives(self): return [self] + self.overloaded_alternatives def all_entries(self): return [self] + self.inner_entries def __lt__(left, right): if isinstance(left, Entry) and isinstance(right, Entry): return (left.name, left.cname) < (right.name, right.cname) else: return NotImplemented @property def cf_is_reassigned(self): return len(self.cf_assignments) > 1 class InnerEntry(Entry): """ An entry in a closure scope that represents the real outer Entry. """ from_closure = True def __init__(self, outer_entry, scope): Entry.__init__(self, outer_entry.name, outer_entry.cname, outer_entry.type, outer_entry.pos) self.outer_entry = outer_entry self.scope = scope # share state with (outermost) defining entry outermost_entry = outer_entry while outermost_entry.outer_entry: outermost_entry = outermost_entry.outer_entry self.defining_entry = outermost_entry self.inner_entries = outermost_entry.inner_entries self.cf_assignments = outermost_entry.cf_assignments self.cf_references = outermost_entry.cf_references self.overloaded_alternatives = outermost_entry.overloaded_alternatives self.inner_entries.append(self) def __getattr__(self, name): if name.startswith('__'): # we wouldn't have been called if it was there raise AttributeError(name) return getattr(self.defining_entry, name) def all_entries(self): return self.defining_entry.all_entries() class Scope(object): # name string Unqualified name #
import numpy as np def in_polygon(xp, yp, polygon, transform=None, radius=0.0): """ Check is points `xp` and `yp` are inside the `polygon`. Polygon is a `matplotlib.path.Path` object. https://stackoverflow.com/questions/21328854/shapely-and-matplotlib-point-in-polygon-not-accurate-with-geolocation Examples -------- >>> from matplotlib.path import Path >>> polygon = Path([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]) >>> x1, y1 = 0.5, 0.5 >>> x2, y2 = 1, 1 >>> x3, y3 = 0, 1.5 >>> in_polygon([x1, x2, x3], [y1, y2, y3], polygon) array([ True, False, False]) """ xp, yp = map(np.atleast_1d, (xp, yp)) points = np.atleast_2d([xp, yp]).T return polygon.contains_points(points, transform=None, radius=0.0) def gamma_G_north_atlantic(SP, pt): """ Polynomials definitions: North Atlantic. VERSION 1: WOCE dataset. """ Fit = np.array( [ [0.0, 0.0, 0.868250629754601], [1.0, 0.0, 4.40022403081395], [0.0, 1.0, 0.0324341891674178], [2.0, 0.0, -6.45929201288070], [1.0, 1.0, -9.92256348514822], [0.0, 2.0, 1.72145961018658], [3.0, 0.0, -19.3531532033683], [2.0, 1.0, 66.9856908160296], [1.0, 2.0, -12.9562244122766], [0.0, 3.0, -3.47469967954487], [4.0, 0.0, 66.0796772714637], [3.0, 1.0, -125.546334295077], [2.0, 2.0, 7.73752363817384], [1.0, 3.0, 10.1143932959310], [0.0, 4.0, 5.56029166412630], [5.0, 0.0, -54.5838313094697], [4.0, 1.0, 70.6874394242861], [3.0, 2.0, 36.2272244269615], [2.0, 3.0, -26.0173602458275], [1.0, 4.0, -0.868664167905995], [0.0, 5.0, -3.84846537069737], [6.0, 0.0, 10.8620520589394], [5.0, 1.0, 0.189417034623553], [4.0, 2.0, -36.2275575056843], [3.0, 3.0, 22.6867313196590], [2.0, 4.0, -8.16468531808416], [1.0, 5.0, 5.58313794099231], [0.0, 6.0, -0.156149127884621], ], ) gamma_NAtl = Fit[0, 2] * np.ones_like(SP) for k in range(1, len(Fit)): i = Fit[k, 0] j = Fit[k, 1] gamma_NAtl = gamma_NAtl + Fit[k, 2] * (SP ** i * pt ** j) return gamma_NAtl def gamma_G_south_atlantic(SP, pt): """ Polynomials definitions: South Atlantic. VERSION 1: WOCE dataset. """ Fit = np.array( [ [0.0, 0.0, 0.970176813506429], [1.0, 0.0, 0.755382324920216], [0.0, 1.0, 0.270391840513646], [2.0, 0.0, 10.0570534575124], [1.0, 1.0, -3.30869686476731], [0.0, 2.0, -0.702511207122356], [3.0, 0.0, -29.0124086439839], [2.0, 1.0, -3.60728647124795], [1.0, 2.0, 10.6725319826530], [0.0, 3.0, -0.342569734311159], [4.0, 0.0, 22.1708651635369], [3.0, 1.0, 61.1208402591733], [2.0, 2.0, -61.0511562956348], [1.0, 3.0, 14.6648969886981], [0.0, 4.0, -3.14312850717262], [5.0, 0.0, 13.0718524535924], [4.0, 1.0, -106.892619745231], [3.0, 2.0, 74.4131690710915], [2.0, 3.0, 5.18263256656924], [1.0, 4.0, -12.1368518101468], [0.0, 5.0, 2.73778893334855], [6.0, 0.0, -15.8634717978759], [5.0, 1.0, 51.7078062701412], [4.0, 2.0, -15.8597461367756], [3.0, 3.0, -35.0297276945571], [2.0, 4.0, 28.7899447141466], [1.0, 5.0, -8.73093192235768], [0.0, 6.0, 1.25587481738340], ], ) gamma_SAtl = Fit[0, 2] * np.ones_like(SP) for k in range(1, len(Fit)): i = Fit[k, 0] j = Fit[k, 1] gamma_SAtl = gamma_SAtl + Fit[k, 2] * (SP ** i * pt ** j) return gamma_SAtl def gamma_G_pacific(SP, pt): """ Polynomials definitions: Pacific. VERSION 1: WOCE_dataset. """ Fit = np.array( [ [0.0, 0.0, 0.990419160678528], [1.0, 0.0, 1.10691302482411], [0.0, 1.0, 0.0545075600726227], [2.0, 0.0, 5.48298954708578], [1.0, 1.0, -1.81027781763969], [0.0, 2.0, 0.673362062889351], [3.0, 0.0, -9.59966716439147], [2.0, 1.0, -11.1211267642241], [1.0, 2.0, 6.94431859780735], [0.0, 3.0, -3.35534931941803], [4.0, 0.0, -15.7911318241728], [3.0, 1.0, 86.4094941684553], [2.0, 2.0, -63.9113580983532], [1.0, 3.0, 23.1248810527697], [0.0, 4.0, -1.19356232779481], [5.0, 0.0, 48.3336456682489], [4.0, 1.0, -145.889251358860], [3.0, 2.0, 95.6825154064427], [2.0, 3.0, -8.43447476300482], [1.0, 4.0, -16.0450914593959], [0.0, 5.0, 3.51016478240624], [6.0, 0.0, -28.5141488621899], [5.0, 1.0, 72.6259160928028], [4.0, 2.0, -34.7983038993856], [3.0, 3.0, -21.9219942747555], [2.0, 4.0, 25.1352444814321], [1.0, 5.0, -5.58077135773059], [0.0, 6.0, 0.0505878919989799], ], ) gamma_Pac = Fit[0, 2] * np.ones_like(SP) for k in range(1, len(Fit)): i = Fit[k, 0] j = Fit[k, 1] gamma_Pac = gamma_Pac + Fit[k, 2] * (SP ** i * pt ** j) return gamma_Pac def gamma_G_indian(SP, pt): """ Polynomials definitions: Indian. VERSION 1: WOCE_dataset. """ Fit = np.array( [ [0.0, 0.0, 0.915127744449523], [1.0, 0.0, 2.52567287174508], [0.0, 1.0, 0.276709571734987], [2.0, 0.0, -0.531583207697361], [1.0, 1.0, -5.95006196623071], [0.0, 2.0, -1.29591003712053], [3.0, 0.0, -6.52652369460365], [2.0, 1.0, 23.8940719644002], [1.0, 2.0, -0.628267986663373], [0.0, 3.0, 3.75322031850245], [4.0, 0.0, 1.92080379786486], [3.0, 1.0, 0.341647815015304], [2.0, 2.0, -39.2270069641610], [1.0, 3.0, 14.5023693075710], [0.0, 4.0, -5.64931439477443], [5.0, 0.0, 20.3803121236886], [4.0, 1.0, -64.7046763005989], [3.0, 2.0, 88.0985881844501], [2.0, 3.0, -30.0525851211887], [1.0, 4.0, 4.04000477318118], [0.0, 5.0, 0.738499368804742], [6.0, 0.0, -16.6137493655149], [5.0, 1.0, 46.5646683140094], [4.0, 2.0, -43.1528176185231], [3.0, 3.0, 0.754772283610568], [2.0, 4.0, 13.2992863063285], [1.0, 5.0, -6.93690276392252], [0.0, 6.0, 1.42081034484842], ], ) gamma_Ind = Fit[0, 2] * np.ones_like(SP) for k in range(1, len(Fit)): i = Fit[k, 0] j = Fit[k, 1] gamma_Ind = gamma_Ind + Fit[k, 2] * (SP ** i * pt ** j) return gamma_Ind def gamma_G_southern_ocean(SP, pt, p): """ Polynomials definitions: Southern Ocean. VERSION 1: WOCE_dataset. """ Fit_N = np.array( [ [0.0, 0.0, 0.874520046342081], [1.0, 0.0, -1.64820627969497], [0.0, 1.0, 2.05462556912973], [2.0, 0.0, 28.0996269467290], [1.0, 1.0, -8.27848721520081], [0.0, 2.0, -9.03290825881587], [3.0, 0.0, -91.0872821653811], [2.0, 1.0, 34.8904015133508], [1.0, 2.0, 0.949958161544143], [0.0, 3.0, 21.4780019724540], [4.0, 0.0, 133.921771803702], [3.0, 1.0, -50.0511970208864], [2.0, 2.0, -4.44794543753654], [1.0, 3.0, -11.7794732139941], [0.0, 4.0, -21.0132492641922], [5.0, 0.0, -85.1619212879463], [4.0, 1.0, 7.85544471116596], [3.0, 2.0, 44.5061015983665], [2.0, 3.0, -32.9544488911897], [1.0, 4.0, 31.2611766088444], [0.0, 5.0, 4.26251346968625], [6.0, 0.0, 17.2136374200161], [5.0, 1.0, 13.4683704071999], [4.0, 2.0, -27.7122792678779], [3.0, 3.0, 11.9380310360096], [2.0, 4.0, 1.95823443401631], [1.0, 5.0, -10.8585153444218], [0.0, 6.0, 1.44257249650877], ], ) gamma_SOce_N = Fit_N[0, 2] * np.ones_like(SP) for k in range(1, len(Fit_N)): i = Fit_N[k, 0] j = Fit_N[k, 1] gamma_SOce_N = gamma_SOce_N + Fit_N[k, 2] * (SP ** i * pt ** j) Fit_S = np.array( [ [0.0, 0.0, 0.209190309846492], [1.0, 0.0, -1.92636557096894], [0.0, 1.0, -3.06518655463115], [2.0, 0.0, 9.06344944916046], [1.0, 1.0, 2.96183396117389], [0.0, 2.0, 39.0265896421229], [3.0, 0.0, -15.3989635056620], [2.0, 1.0, 3.87221350781949], [1.0, 2.0, -53.6710556192301], [0.0, 3.0, -215.306225218700], [4.0, 0.0, 8.31163564170743], [3.0, 1.0, -3.14460332260582], [2.0, 2.0, 3.68258441217306], [1.0, 3.0, 264.211505260770], [0.0, 4.0, 20.1983279379898], ], ) p_ref, pt_ref, c_pt = 700.0, 2.5, 0.65 gamma_A = Fit_S[0, 2] * np.ones_like(SP) for k in range(1, len(Fit_S)): i = Fit_S[k, 0] j = Fit_S[k, 1] gamma_A = gamma_A + Fit_S[k, 2] * (SP ** i * pt ** j) gamma_SOce_S = ( gamma_A * np.exp(-p / p_ref) * (1.0 / 2.0 - 1.0 / 2.0 * np.tanh((40.0 * pt - pt_ref) / c_pt)) ) gamma_SOce = gamma_SOce_N + gamma_SOce_S return gamma_SOce def gamma_GP_from_SP_pt(SP, pt, p, lon, lat): """ Global Polynomial of Neutral Density with respect to Practical Salinity and potential temperature. Calculates the Global Polynomial of Neutral Density gammma_GP using an approximate form gamma_poly of Neutral Density on each oceanic basin: North Atlantic, South Atlantic, Pacific, Indian and Southern Ocean. Each function is a polynomial of 28 terms, function of Practical Salinity, potential temperature. The function on the Southern Ocean contains another function which is a polynomial of 15 terms of Practical Salinity and potential temperature times by a pressure and a potential temperature terms which is effective close to Antarctica in shallow waters. The polynomials on each ocean basins are combined to form the Global Polynomial using tests in latitude and longitude to recognize the basin and weighting functions to make the functions zip together where the oceanic basins communicate. Parameter --------- SP : array_like Practical salinity [psu] pt : array_like Potential temperature [ITS-90 deg C] p : array_like Sea pressure [dbar] (i.e. absolute pressure - 10.1325 dbar) lon : number Longitude [0-360] lat : latitude Returns ------- gamma_GP : array Global Polynomial of Neutral Density with [kg/m^3] respect to Practical Salinity and potential temperature. Examples -------- >>> from oceans.sw_extras.gamma_GP_from_SP_pt import gamma_GP_from_SP_pt >>> SP = [35.066, 35.086, 35.089, 35.078, 35.025, 34.851, 34.696, 34.572, ... 34.531, 34.509, 34.496, 34.452, 34.458, 34.456, 34.488, 34.536, ... 34.579, 34.612, 34.642, 34.657, 34.685, 34.707, 34.72, 34.729] >>> pt = [12.25, 12.21, 12.09, 11.99, 11.69, 10.54, 9.35, 8.36, 7.86, 7.43, ... 6.87, 6.04, 5.5, 4.9, 4.04, 3.29, 2.78, 2.45, 2.211, 2.011, ... 1.894, 1.788, 1.554, 1.38] >>> p = [1.0, 48.0, 97.0, 145.0, 194.0, 291.0, 388.0, 485.0, 581.0, 678.0, ... 775.0, 872.0, 969.0, 1066.0, 1260.0, 1454.0, 1647.0, 1841.0, ... 2020.0, 2216.0, 2413.0, 2611.0, 2878.0, 3000.0] >>> lon, lat, n = [187.317, -41.6667, 24] >>> gamma_GP_from_SP_pt(SP, pt, p, lon, lat) array([26.66339976, 26.68613362, 26.71169809, 26.72286813, 26.74102625, 26.82472769, 26.91707848, 26.9874849 , 27.03564777, 27.08512861, 27.15880197, 27.24506111, 27.32438575, 27.40418818, 27.54227885, 27.67691837, 27.77693976, 27.84683646, 27.90297626, 27.9428694 , 27.98107846, 28.01323277, 28.05769996, 28.09071215]) Author ------ <NAME>, <NAME> & <NAME> [<EMAIL>] VERSION NUMBER: 1.0 (27th October, 2011) """ from matplotlib.path import Path SP, pt, p, lon, lat = list(map(np.asanyarray, (SP, pt, p, lon, lat))) SP, pt, p, lon, lat = np.broadcast_arrays(SP, pt, p, lon, lat) # Normalization of the variables. SP = SP / 42.0 pt = pt / 40.0 # Computation of
strings as index names, hence not using dictionary row apfs_file_meta = ApfsFileMeta(row[4], row[0], row[2], CommonFunctions.ReadAPFSTime(row[5]), CommonFunctions.ReadAPFSTime(row[6]), CommonFunctions.ReadAPFSTime(row[7]), CommonFunctions.ReadAPFSTime(row[8]), CommonFunctions.ReadAPFSTime(row[18]), row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17]) #extent_cnid = row[3] if row[22] != None: # uncompressed_size apfs_file_meta.logical_size = row[22] apfs_file_meta.is_compressed = True apfs_file_meta.decmpfs = row[23] apfs_file_meta.compressed_extent_size = row[24] extent = ApfsExtent(row[25], row[26], row[27]) if apfs_file_meta.is_compressed else ApfsExtent(row[19], row[20], row[21]) if prev_extent and extent.offset == prev_extent.offset: #This file may have hard links, hence the same data is in another row, skip this! pass else: apfs_file_meta.extents.append(extent) prev_extent = extent index += 1 if index == 0: # No such file! return None # Let's also get Attributes, except decmpfs and ResourceFork (we already got those in _Compressed_Files table) # TODO: Remove Logical_uncompressed_size, Extent_CNID, perhaps not needed now! attrib_query = "SELECT Name, Type, Data, Logical_uncompressed_size, Extent_CNID from {0}_Attributes WHERE cnid={1} and Name not in ('com.apple.decmpfs', 'com.apple.ResourceFork')" success, cursor, error_message = db.RunQuery(attrib_query.format(self.name, apfs_file_meta.cnid)) if success: for row in cursor: apfs_file_meta.attributes[row[0]] = [row[1], row[2], row[3], row[4]] else: log.debug('Failed to execute attribute query, error was : ' + error_message) return apfs_file_meta else: log.debug('Failed to execute GetFileMetadataByPath query, error was : ' + error_message) return None def ListItemsInFolder(self, path, db): ''' Returns a list of files and/or folders in a list Format of list = [ { 'name':'got.txt', 'type':EntryType.FILE, 'size':10, 'dates': {} }, .. ] 'path' should be linux style using forward-slash like '/var/db/xxyy/file.tdc' ''' if path.endswith('/') and path != '/': path = path[:-1] items = [] # List of dictionaries query = "SELECT t.Name, p.CNID, i.ItemType, t.Logical_Size, t.Created, t.Modified, t.Changed, t.Accessed, "\ " c.Uncompressed_size, i.TimeStamp "\ " from {0}_Paths as p "\ " left join {0}_Threads as t on p.cnid=t.cnid "\ " left join {0}_IndexNodes as i on i.CNID = t.CNID "\ " left join {0}_Compressed_Files as c on c.CNID=t.CNID "\ " WHERE t.Parent_CNID in (select CNID from {0}_Paths where path='{1}')" try: path = path.replace("'", "''") # if path contains single quote, replace with double to escape it! success, cursor, error_message = db.RunQuery(query.format(self.name, path)) if success: for row in cursor: item = { 'name':row[0] } if row[8] == None: item['size'] = row[3] else: item['size'] = row[8] item['dates'] = { 'c_time':CommonFunctions.ReadAPFSTime(row[6]), 'm_time':CommonFunctions.ReadAPFSTime(row[5]), 'cr_time':CommonFunctions.ReadAPFSTime(row[4]), 'a_time':CommonFunctions.ReadAPFSTime(row[7]), 'i_time':CommonFunctions.ReadAPFSTime(row[9]) } if row[2] == 4: item['type'] = 'Folder' elif row[2] == 8: item['type'] = 'File' elif row[2] == 10: item['type'] = 'Symlink' else: item['type'] = row[2] items.append(item) else: log.error('Failed to execute ListItemsInFolder query, error was : ' + error_message) except Exception as ex: log.error(str(ex)) return items class ApfsContainer: def __init__(self, image_file, apfs_container_size, offset=0): self.img = image_file self.apfs_container_offset = offset self.apfs_container_size = apfs_container_size self.volumes = [] self.position = 0 # For self.seek() try: self.block_size = 4096 # Default, before real size is read in self.seek(0x20) magic = self.read(4) assert magic == b'NXSB' except: raise Exception("Not an APFS image") self.seek(0) self.apfs = apfs.Apfs(KaitaiStream(self)) self.block_size = self.apfs.block_size self.containersuperblock = self.read_block(0) # get list of volume ids apfss = [x for x in self.containersuperblock.body.volumesuperblock_ids if x != 0 ] # removing the invalid ones block_map_block_num = self.containersuperblock.body.block_map_block.value self.num_volumes = len(apfss) log.debug("There are {} volumes in this container".format(self.num_volumes)) log.debug("Volume Block IDs: %s, Mapping-Btree: %d" % (apfss, block_map_block_num)) block_map = self.read_block(block_map_block_num) self.apfs_locations = {} block_map_btree_root = self.read_block(block_map.body.root.value) for _, entry in enumerate(block_map_btree_root.body.entries): self.apfs_locations[entry.key.key_value] = entry.data.block_num.value log.debug("Volume Blocks:" + str(self.apfs_locations)) index = 1 for _, volume_block_num in self.apfs_locations.items(): volume = ApfsVolume(self, 'Vol_' + str(index)) volume.read_volume_info(volume_block_num) self.volumes.append(volume) index += 1 def close(self): pass def seek(self, offset, from_what=0): if from_what == 0: # Beginning of file self.position = offset elif from_what == 1: # current position self.position += offset elif from_what == 2: # end of file (offset must be -ve) self.position = self.apfs_container_size + offset else: raise Exception('Unexpected value in from_what (only 0,1,2 are allowed), value was ' + str(from_what)) def tell(self): return self.position def read(self, size): data = self.img.read(self.apfs_container_offset + self.position, size) self.position += len(data) return data def get_block(self, idx): """ Get data of a single block """ self.seek(idx * self.block_size) return self.read(self.block_size) def read_block(self, block_num): """ Parse a singe block """ data = self.get_block(block_num) #data = memoryview(self.get_block(block_num)) # no improvement if not data: return None block = self.apfs.Block(KaitaiStream(BytesIO(data)), self.apfs, self.apfs) return block class ApfsExtent: __slots__ = ['offset', 'size', 'block_num'] def __init__(self, offset, size, block_num): self.offset = offset self.size = size self.block_num = block_num def GetData(self, container): container.seek(self.block_num * container.block_size) ## TODO: Create buffered read, in case of really large files!! return container.read(self.size) class ApfsFile(): def __init__(self, apfs_file_meta, logical_size, extents, apfs_container): self.meta = apfs_file_meta self.file_size = logical_size self.extents = extents self.container = apfs_container def _lzvn_decompress(self, compressed_stream, compressed_size, uncompressed_size): ''' Adds Prefix and Postfix bytes as required by decompressor, then decompresses and returns uncompressed bytes buffer ''' header = b'bvxn' + struct.pack('<I', uncompressed_size) + struct.pack('<I', compressed_size) footer = b'bvx$' return lzfse.decompress(header + compressed_stream + footer) def _readCompressedAll(self): '''Read compressed data''' file_content = b'' decmpfs = self.meta.decmpfs if decmpfs == None: # header & data in extent, data is inline with header decmpfs = self._GetDataFromExtents(self.extents, self.meta.compressed_extent_size) # Now decompress it according to compression_type file_content = self._DecompressInline(decmpfs) else: # we already have header, data is in extent or inline extent_data_size = self.meta.compressed_extent_size if extent_data_size == 0: # data is inline file_content = self._DecompressInline(decmpfs) else: # data is in extent (resource fork) compressed_data = self._GetDataFromExtents(self.extents, extent_data_size) # Now decompress it according to compression_type file_content = self._DecompressNotInline(decmpfs, compressed_data) return file_content def _DecompressNotInline(self, decmpfs, compressed_data): decompressed = b'' #compressed_data = compressed_data.tobytes() magic, compression_type, uncompressed_size = struct.unpack('<IIQ', decmpfs[0:16]) if compression_type == 4: # zlib in ResourceFork # Read Header (HFSPlusCmpfRsrcHead) header_size, total_size, data_size, flags = struct.unpack('>IIII', compressed_data[0:16]) # Read Block info blocks_data_size = struct.unpack('>I', compressed_data[header_size : header_size + 4])[0] num_blocks = struct.unpack('<I', compressed_data[header_size + 4 : header_size + 8])[0] base_offset = header_size + 8 # Read chunks for i in xrange(num_blocks): chunk_offset, chunk_size = struct.unpack('<II', compressed_data[base_offset + i*8 : base_offset + i*8 + 8]) #log.debug("ChunkOffset={} ChunkSize={} start={} end={}".format(chunk_offset, chunk_size, header_size + 4 + chunk_offset, header_size + 4 + chunk_offset + chunk_size)) start = header_size + 4 + chunk_offset if compressed_data[start] == b'\xFF': decompressed += compressed_data[start + 1 : start + chunk_size] else: decompressed += zlib.decompress(compressed_data[start : start + chunk_size]) elif compression_type == 8: # lzvn in ResourceFork try: # The following is only for lzvn, not encountered lzfse yet! full_uncomp = uncompressed_size chunk_uncomp = 65536 i = 0 headerSize = struct.unpack('<I', compressed_data[0:4])[0] num_chunkOffsets = headerSize/4 - 1 chunkOffsets = struct.unpack('<{}I'.format(num_chunkOffsets), compressed_data[4 : 4 + (num_chunkOffsets * 4)]) src_offset = headerSize for offset in chunkOffsets: compressed_size = offset - src_offset data = compressed_data[src_offset:offset] src_offset = offset if full_uncomp <= 65536: chunk_uncomp = full_uncomp else: chunk_uncomp = 65536 if num_chunkOffsets == i + 1: # last chunk chunk_uncomp = full_uncomp - (65536 * i) if chunk_uncomp < compressed_size and data[0] == b'\x06': decompressed += data[1:] else: decompressed += self._lzvn_decompress(data, compressed_size, chunk_uncomp) i += 1 except Exception as ex: log.exception("Exception from lzfse.decompress, decompression failed!") raise Exception("Exception from lzfse.decompress, decompression failed!") # Shouldn't be any of the following: elif compression_type in [1,3,7,11]: # types in ResourceFork log.error ("compression_type = {} in DecompressNotInline --> ERROR! Should not go here!".format(compression_type)) elif compression_type == 12: log.error ("compression_type = {} --> LZFSE Not seen before (not inline), don't know how to handle!".format(compression_type)) else: log.error ("compression_type = {} --> Not seen before (not inline), don't know how to handle!".format(compression_type)) return decompressed def _DecompressInline(self, decmpfs): decompressed = b'' #decmpfs = decmpfs.tobytes() total_len = len(decmpfs) magic, compression_type, uncompressed_size = struct.unpack('<IIQ', decmpfs[0:16]) if compression_type == 1: decompressed = decmpfs[16:] elif compression_type == 3: # zlib if (uncompressed_size <= total_len - 16) and (decmpfs[16] == b'\xFF'): decompressed = decmpfs[17:] else: decompressed = zlib.decompress(decmpfs[16:]) elif compression_type in [4, 8, 12]: # types in ResourceFork log.error ("compression_type = {} in DecompressInline --> ERROR! Should not go here!".format(compression_type)) elif compression_type == 7: # LZVN inline data = decmpfs[16:] if (uncompressed_size <= total_len - 16) and (data[0] == b'\x06'): decompressed = decmpfs[17:]
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION from ydk.errors import YPYError, YPYModelError from ydk.providers._importer import _yang_ns _meta_table = { 'LineStateEnum' : _MetaInfoEnum('LineStateEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', { 'none':'none', 'registered':'registered', 'in-use':'in_use', }, 'Cisco-IOS-XR-tty-server-oper', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper']), 'SessionOperationEnum' : _MetaInfoEnum('SessionOperationEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', { 'none':'none', 'setup':'setup', 'shell':'shell', 'transitioning':'transitioning', 'packet':'packet', }, 'Cisco-IOS-XR-tty-server-oper', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper']), 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Rs232' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Rs232', False, [ _MetaInfoClassMember('baud-rate', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Inbound/Outbound baud rate in bps ''', 'baud_rate', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('data-bits', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of databits ''', 'data_bits', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('exec-disabled', ATTRIBUTE, 'bool' , None, None, [], [], ''' Exec disabled on TTY ''', 'exec_disabled', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('framing-error-count', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Framing error count ''', 'framing_error_count', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('hardware-flow-control-status', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Hardware flow control status ''', 'hardware_flow_control_status', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('overrun-error-count', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Overrun error count ''', 'overrun_error_count', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('parity-error-count', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Parity error count ''', 'parity_error_count', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('parity-status', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Parity status ''', 'parity_status', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('stop-bits', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of stopbits ''', 'stop_bits', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'rs232', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.GeneralStatistics' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.GeneralStatistics', False, [ _MetaInfoClassMember('absolute-timeout', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Absolute timeout period ''', 'absolute_timeout', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('async-interface', ATTRIBUTE, 'bool' , None, None, [], [], ''' Usable as async interface ''', 'async_interface', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('domain-lookup-enabled', ATTRIBUTE, 'bool' , None, None, [], [], ''' DNS resolution enabled ''', 'domain_lookup_enabled', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('flow-control-start-character', ATTRIBUTE, 'int' , None, None, [('-128', '127')], [], ''' Software flow control start char ''', 'flow_control_start_character', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('flow-control-stop-character', ATTRIBUTE, 'int' , None, None, [('-128', '127')], [], ''' Software flow control stop char ''', 'flow_control_stop_character', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('idle-time', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' TTY idle time ''', 'idle_time', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('motd-banner-enabled', ATTRIBUTE, 'bool' , None, None, [], [], ''' MOTD banner enabled ''', 'motd_banner_enabled', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('private-flag', ATTRIBUTE, 'bool' , None, None, [], [], ''' TTY private flag ''', 'private_flag', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('terminal-length', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Terminal length ''', 'terminal_length', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('terminal-type', ATTRIBUTE, 'str' , None, None, [], [], ''' Terminal type ''', 'terminal_type', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('terminal-width', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Line width ''', 'terminal_width', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'general-statistics', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Exec_' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Exec_', False, [ _MetaInfoClassMember('time-stamp-enabled', ATTRIBUTE, 'bool' , None, None, [], [], ''' Specifies whether timestamp is enabled or not ''', 'time_stamp_enabled', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'exec', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Aaa' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Aaa', False, [ _MetaInfoClassMember('user-name', ATTRIBUTE, 'str' , None, None, [], [], ''' The authenticated username ''', 'user_name', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'aaa', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics', False, [ _MetaInfoClassMember('aaa', REFERENCE_CLASS, 'Aaa' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Aaa', [], [], ''' AAA related statistics ''', 'aaa', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('exec', REFERENCE_CLASS, 'Exec_' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Exec_', [], [], ''' Exec related statistics ''', 'exec_', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('general-statistics', REFERENCE_CLASS, 'GeneralStatistics' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.GeneralStatistics', [], [], ''' General statistics of line ''', 'general_statistics', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('rs232', REFERENCE_CLASS, 'Rs232' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics.Rs232', [], [], ''' RS232 statistics of console line ''', 'rs232', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'console-statistics', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.Template' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.Template', False, [ _MetaInfoClassMember('name', ATTRIBUTE, 'str' , None, None, [], [], ''' Name of the template ''', 'name', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'template', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.General' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.General', False, [ _MetaInfoClassMember('general-state', REFERENCE_ENUM_CLASS, 'LineStateEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'LineStateEnum', [], [], ''' State of the line ''', 'general_state', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('operation', REFERENCE_ENUM_CLASS, 'SessionOperationEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'SessionOperationEnum', [], [], ''' application running of on the tty line ''', 'operation', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'general', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State', False, [ _MetaInfoClassMember('general', REFERENCE_CLASS, 'General' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.General', [], [], ''' General information ''', 'general', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('template', REFERENCE_CLASS, 'Template' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State.Template', [], [], ''' Information related to template applied to the line ''', 'template', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'state', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration.TransportInput' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration.TransportInput', False, [ _MetaInfoClassMember('none', ATTRIBUTE, 'int' , None, None, [('-2147483648', '2147483647')], [], ''' Not used ''', 'none', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('protocol1', REFERENCE_ENUM_CLASS, 'TtyTransportProtocolEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_management_datatypes', 'TtyTransportProtocolEnum', [], [], ''' Transport protocol1 ''', 'protocol1', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('protocol2', REFERENCE_ENUM_CLASS, 'TtyTransportProtocolEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_management_datatypes', 'TtyTransportProtocolEnum', [], [], ''' Transport protocol2 ''', 'protocol2', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('select', REFERENCE_ENUM_CLASS, 'TtyTransportProtocolSelectEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_management_datatypes', 'TtyTransportProtocolSelectEnum', [], [], ''' Choose transport protocols ''', 'select', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'transport-input', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration', False, [ _MetaInfoClassMember('acl-in', ATTRIBUTE, 'str' , None, None, [], [], ''' ACL for inbound traffic ''', 'acl_in', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('acl-out', ATTRIBUTE, 'str' , None, None, [], [], ''' ACL for outbound traffic ''', 'acl_out', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('transport-input', REFERENCE_CLASS, 'TransportInput' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration.TransportInput', [], [], ''' Protocols to use when connecting to the terminal server ''', 'transport_input', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'connection-configuration', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration', False, [ _MetaInfoClassMember('connection-configuration', REFERENCE_CLASS, 'ConnectionConfiguration' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration.ConnectionConfiguration', [], [], ''' Conection configuration information ''', 'connection_configuration', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'configuration', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode.ConsoleLine', False, [ _MetaInfoClassMember('configuration', REFERENCE_CLASS, 'Configuration' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.Configuration', [], [], ''' Configuration information of the line ''', 'configuration', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('console-statistics', REFERENCE_CLASS, 'ConsoleStatistics' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.ConsoleStatistics', [], [], ''' Statistics of the console line ''', 'console_statistics', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('state', REFERENCE_CLASS, 'State' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine.State', [], [], ''' Line state information ''', 'state', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'console-line', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes.ConsoleNode' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes.ConsoleNode', False, [ _MetaInfoClassMember('id', ATTRIBUTE, 'str' , None, None, [], ['([a-zA-Z0-9_]*\\d+/){1,2}([a-zA-Z0-9_]*\\d+)'], ''' Node ID ''', 'id', 'Cisco-IOS-XR-tty-server-oper', True), _MetaInfoClassMember('console-line', REFERENCE_CLASS, 'ConsoleLine' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode.ConsoleLine', [], [], ''' Console line ''', 'console_line', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'console-node', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.ConsoleNodes' : { 'meta_info' : _MetaInfoClass('Tty.ConsoleNodes', False, [ _MetaInfoClassMember('console-node', REFERENCE_LIST, 'ConsoleNode' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper', 'Tty.ConsoleNodes.ConsoleNode', [], [], ''' Console line configuration on a node ''', 'console_node', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'console-nodes', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.VtyLines.VtyLine.VtyStatistics.Connection' : { 'meta_info' : _MetaInfoClass('Tty.VtyLines.VtyLine.VtyStatistics.Connection', False, [ _MetaInfoClassMember('host-address-family', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Incoming host address family ''', 'host_address_family', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('incoming-host-address', ATTRIBUTE, 'str' , None, None, [(0, 46)], [], ''' Incoming host address(max) ''', 'incoming_host_address', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('service', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Input transport ''', 'service', 'Cisco-IOS-XR-tty-server-oper', False), ], 'Cisco-IOS-XR-tty-server-oper', 'connection', _yang_ns._namespaces['Cisco-IOS-XR-tty-server-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_server_oper' ), }, 'Tty.VtyLines.VtyLine.VtyStatistics.GeneralStatistics' : { 'meta_info' : _MetaInfoClass('Tty.VtyLines.VtyLine.VtyStatistics.GeneralStatistics', False, [ _MetaInfoClassMember('absolute-timeout', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Absolute timeout period ''', 'absolute_timeout', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('async-interface', ATTRIBUTE, 'bool' , None, None, [], [], ''' Usable as async interface ''', 'async_interface', 'Cisco-IOS-XR-tty-server-oper', False), _MetaInfoClassMember('domain-lookup-enabled', ATTRIBUTE, 'bool' , None, None, [], [], ''' DNS resolution enabled ''', 'domain_lookup_enabled', 'Cisco-IOS-XR-tty-server-oper',
# -*- coding: utf-8 -*- """ other_algorithms.py: Baseline algorithms to compare against. """ import pdb import numpy as np from scipy.optimize import least_squares from pylocus.lateration import SRLS from coordinate_fitting import fit_trajectory from solvers import trajectory_recovery EPS = 1e-10 def error_measure(points_gt, points_estimated, measure='mse'): """ :param points_gt: ground truth positions (N x dim) :param points_estimated: estimated positions (N x dim) :param measure: method to use ('mae' or 'mse') """ if (points_gt.shape[0] == 0) | (points_estimated.shape[0] == 0): return None assert points_gt.shape == points_estimated.shape, f'{points_gt.shape}, {points_estimated.shape}' if measure == 'mse': return np.mean((points_gt - points_estimated)**2) elif measure == 'mae': return np.mean(np.abs(points_gt - points_estimated)) else: raise ValueError(measure) def get_anchors_and_distances(D_sq, idx, dim=2): """ Get measurements for pointwise lateration. Given squared distance matrix D and time index idx, find all latest distance measurements up to this time index. :param D_sq: squared distance matrix (N x M) :param idx: time index for which we want measurements. :return: ndarray of distances squared (nx1) , list (len n) of corresponding anchor indices. """ assert idx >= 0 and idx < D_sq.shape[0] r2 = [] anchors = [] for a_id in range(D_sq.shape[1]): indices = np.where(D_sq[:idx + 1, a_id] > 0)[0] if len(indices) > 0: latest_idx = indices[-1] r2.append(D_sq[latest_idx, a_id]) anchors.append(a_id) return np.array(r2).reshape((-1, 1)), np.array(anchors) def init_lm(coeffs_real, method='ellipse', **kwargs): if 'ellipse' in method: coeffs = np.zeros(coeffs_real.shape) center = coeffs_real[:, 0] rx = np.max(coeffs_real[0, 1:]) - np.min(coeffs_real[0, 1:]) ry = np.max(coeffs_real[1, 1:]) - np.min(coeffs_real[1, 1:]) coeffs[0, 0] = center[0] coeffs[1, 0] = center[1] coeffs[0, 1] = rx coeffs[1, 2] = ry return coeffs elif 'line' in method: # 2D line with unit speed in 45 degrees, and 0 center. coeffs = np.zeros(coeffs_real.shape) center = [0, 0] v = np.sqrt(2) coeffs[0, 0] = center[0] coeffs[1, 0] = center[1] coeffs[0, 1] = v coeffs[1, 1] = v return coeffs elif 'noise' in method: sigma = kwargs.get('sigma', 0.1) return coeffs_real + np.random.normal(scale=sigma) elif 'real' in method: return coeffs_real else: raise ValueError(method) def cost_function(C_vec, D_sq, A, F, squared=False): """ Return residuals of least squares distance error. :param C_vec: trajectory coefficients (length dim*K) :param D_sq: squared distance matrix (N x M) :param A: anchor coordinates (dim x M) :param F: trajectory basis functions (K x N) :param squared: if True, the distances in the cost function are squared. :return: vector of residuals (length N) """ dim = A.shape[0] C_k = C_vec.reshape((dim, -1)) R = C_k.dot(F) diff = R[:, :, None] - A[:, None, :] # dim x N x M D_est = np.linalg.norm(diff, axis=0) # N x M # set the missing elements to zero. D_est[D_sq == 0.0] = 0.0 if np.any(np.isnan(D_est)): raise ValueError('some nans in D_est') D = D_sq.copy() D[D > 0] = np.sqrt(D[D > 0]) if squared: nonzero = (D**2 - D_est**2)[D > 0] else: nonzero = (D - D_est)[D > 0] cost = np.power(nonzero, 2).reshape((-1, )) return cost def split_cost_function(X_vec, D_sq, A, F, squared=True): """ Return cost of distance squared, but with cost function split into coeffs and coeffs'coeffs:=L. Therefore the optimization variable is bigger but we only care about the first K*dim elements. :param X_vec: vector of trajectory coefficients and its squares, of length (dim*K+K*K) :param D_sq: squared distance matrix (N x M) :param A: anchor coordinates (dim x M) :param F: trajectory basis functions (K x N) :param squared: only here for constistency with cost_function. Has to be set to True or an error is raised. :return: vector of residuals. """ if not squared: raise ValueError('Cannot split cost without squares.') dim = A.shape[0] K = F.shape[0] N, M = D_sq.shape assert A.shape[1] == M assert len(X_vec) == dim * K + K * K ns, ms = np.where(D_sq > 0) res = [] # TODO(FD): below could be written without for loop, # but it is only used for testing so performance does not # matter. for n, m in zip(ns, ms): cost_n = 0.5 * (np.linalg.norm(A[:, m])**2 - D_sq[n, m]) t_n = np.r_[np.outer(A[:, m], F[:, n]).reshape((-1, )), np.outer(F[:, n], F[:, n]).reshape((-1, ))] assert len(t_n) == len(X_vec) cost_n = cost_n - np.inner(t_n, X_vec) res.append(cost_n) return res # TODO(FD) fix this function to pass unit tests. def cost_jacobian(C_vec, D_sq, A, F, squared=True): """ Return Jacobian of squared distances cost function. WARNING: this function does not pass its unit tests. :param C_vec: trajectory coefficients (dim x K) :param D_sq: squared distance matrix (N x M) :param A: anchor coordinates (dim x M) :param F: trajectory basis functions (K x N) :param squared: if True, the distances in the cost function are squared. Non-squared Jacobian not implemented yet. :return: (N x K*d) Jacobian matrix. """ if not squared: raise NotImplementedError('cost_jacobian for non-squared distances') l = cost_function(C_vec, D_sq, A, F, squared=True) # cost vector (N) ns, ms = np.where(D_sq > 0) N = len(l) Kd = len(C_vec) dim = A.shape[0] K = int(Kd / dim) jacobian = np.empty((N, Kd)) # N x Kd C_k = C_vec.reshape((dim, -1)) R = C_k.dot(F) for j, (l_n, m_n, n) in enumerate(zip(l, ms, ns)): f_n = F[:, n] assert len(f_n) == K # factor is the derivative of the norm squared with respect to coeffs matrix. factor = -2 * (A[:, m_n] - C_k.dot(f_n)).reshape((dim, 1)).dot(f_n.reshape((1, -1))) # dim x K if (np.abs(l_n) > EPS): jacobian_mat = -2 * np.sqrt(np.abs(l_n)) * factor else: jacobian_mat = np.zeros((dim, K)) jacobian[j, :] = jacobian_mat.reshape((-1, )) if np.any(np.isnan(jacobian)): print('Problems in cost_jacobian. Going in debugging mode.') pdb.set_trace() return jacobian def least_squares_lm(D, anchors, basis, x0, verbose=False, cost='simple', jacobian=False): """ Solve using Levenberg Marquardt. :param cost: Cost function to use, can be either: - 'squared': squared distances - 'simple': non-squared distances - 'split': split the cost in coeffs'coeffs=L and coeffs, optimize for whole thing at once. """ dim = anchors.shape[0] M = anchors.shape[1] K = basis.shape[0] N = basis.shape[1] assert D.shape == (N, M), D.shape assert len(x0) == dim * K, f'{len(x0)}!={dim}*{K}' if jacobian: print( 'Warning: the analytical jacobian will be passed to the least squares solver, but it has not passed all tests yet. This might lead to unexpected behavior.' ) if np.any(np.isnan(x0)): raise ValueError(f'invalid x0 {x0}') scipy_verbose = 2 if verbose else 0 if (cost == 'squared') and jacobian: res = least_squares(cost_function, jac=cost_jacobian, x0=x0, method='lm', args=(D, anchors, basis), kwargs={'squared': True}, verbose=scipy_verbose) # xtol=1e-20, ftol=1e-10, elif (cost == 'squared') and (not jacobian): res = least_squares(cost_function, x0=x0, method='lm', args=(D, anchors, basis), kwargs={'squared': True}, verbose=scipy_verbose) # xtol=1e-20, ftol=1e-10, elif (cost == 'simple') and (not jacobian): res = least_squares(cost_function, x0=x0, method='lm', args=(D, anchors, basis), kwargs={'squared': False}, verbose=scipy_verbose) # xtol=1e-20, ftol=1e-10, elif (cost == 'simple') and jacobian: raise NotImplementedError('Cannot do Jacobian without squares.') elif cost == 'split': C = x0.reshape((dim, K)) L = C.T.dot(C) x0_extended = np.r_[x0, L.reshape((-1, ))] res = least_squares(split_cost_function, x0=x0_extended, method='lm', args=(D, anchors, basis), verbose=scipy_verbose) # xtol=1e-20, ftol=1e-10, if not res.success: if verbose: print('LM failed with message:', res.message) return None if res.success: if verbose: print('LM succeeded with message:', res.message) # We only need to take the first K*dim elements # because for cost=='split' there are more. But this # doesn't hurt for the others. return res.x[:dim * K].reshape((dim, K)) def get_grid(anchors, grid_size=1.0): x_range, y_range = np.array([np.min(anchors, axis=1), np.max(anchors, axis=1)]).T xx, yy = np.meshgrid( np.arange(*x_range, step=grid_size), np.arange(*y_range, step=grid_size), ) grid = np.c_[xx.flatten(), yy.flatten()] return grid def RLS(anchors, r2, grid, interpolation='nearest'): """ Get RLS estimate. :param r2: list of measured distances (length M) :param anchors: anchor coordinates (M x dim) :param grid: grid coordinates (N x dim) :param interpolation: How to interpolate. - 'nearest' (default): return minimum grid point. """ assert len(r2) == anchors.shape[0] assert grid.shape[1] == anchors.shape[1] r2 = r2.flatten() D_estimated = np.linalg.norm(anchors[None, :, :] - grid[:, None, :], axis=2) # N x M cost = np.sum((D_estimated - np.sqrt(r2[None, :]))**2, axis=1) if interpolation == 'nearest': argmin = np.argmin(cost) return grid[argmin, :] def pointwise_lateration(D, anchors, traj, indices, method='srls', grid=None): """ Solve using point-wise lateration. :param indices: points at which we want to compute SRLS. :param method: Method to use. Currently supported: - 'rls': Range
<reponame>bcgov-c/wally """ Functions for aggregating data from web requests and database records """ import base64 import datetime import io import logging import requests import json import fiona import math import re import time import os import zipfile import sqlalchemy as sa from tempfile import TemporaryDirectory from geoalchemy2.elements import WKTElement from shapely import wkb from typing import Tuple, List, Optional from urllib.parse import urlencode from geojson import FeatureCollection, Feature from operator import add from shapely.geometry import Point, Polygon, MultiPolygon, shape, mapping from shapely.ops import transform from starlette.responses import Response from sqlalchemy.orm import Session from sqlalchemy import func, insert, select from fastapi import HTTPException from api.config import WATERSHED_DEBUG from api.utils import normalize_quantity from api.layers.freshwater_atlas_watersheds import FreshwaterAtlasWatersheds from api.layers.freshwater_atlas_stream_networks import FreshwaterAtlasStreamNetworks from api.v1.aggregator.helpers import transform_4326_3005, transform_3005_4326 from api.v1.hydat.controller import get_point_on_stream, get_station from api.v1.models.scsb2016.controller import get_hydrological_zone from api.v1.streams.controller import get_nearest_streams, get_nearest_hydat_stream_segments from api.v1.watersheds.db_models import GeneratedWatershed, WatershedCache from api.v1.watersheds.climate import get_mean_annual_precipitation, get_potential_evapotranspiration from api.v1.watersheds.cdem import CDEM from api.v1.watersheds.schema import ( LicenceDetails, SurficialGeologyDetails, FishObservationsDetails, WaterApprovalDetails, WatershedDataWarning, GeneratedWatershedDetails ) from api.v1.watersheds.delineate_watersheds import ( get_full_stream_catchment_area, get_upstream_catchment_area, get_watershed_using_dem, watershed_touches_border ) from api.v1.aggregator.controller import feature_search, databc_feature_search from external.docgen.controller import docgen_export_to_xlsx logging.basicConfig(level=logging.INFO) logger = logging.getLogger('WATERSHEDS') SEC_IN_YEAR = 31536000 def calculate_glacial_area(db: Session, polygon: MultiPolygon) -> Tuple[float, float]: """ Calculates percent glacial coverage using the area of `polygon` which intersects with features from the DataBC FWA Glaciers dataset. returns a tuple of floats with the form (glacial_area, coverage). """ glaciers_layer = 'freshwater_atlas_glaciers' glacial_features = feature_search(db, [glaciers_layer], polygon.minimum_rotated_rectangle)[ 0].geojson.features glacial_area = 0 polygon = transform(transform_4326_3005, polygon) for glacier in glacial_features: glacier_clipped = shape(glacier.geometry).intersection(polygon) if not glacier_clipped.area: continue glacial_area += glacier_clipped.area coverage = glacial_area / polygon.area return (glacial_area, coverage) def pcic_data_request( polygon: Polygon, output_variable: str = 'pr', dataset=None): """ Returns an average precipitation from the pacificclimate.org climate explorer service """ pcic_url = "https://services.pacificclimate.org/pcex/api/timeseries?" if not dataset: dataset = f"{output_variable}_mClim_BCCAQv2_CanESM2_historical-rcp85_r1i1p1_19810101-20101231_Canada" params = { "id_": dataset, "variable": output_variable, "area": polygon.minimum_rotated_rectangle.wkt } req_url = pcic_url + urlencode(params) if WATERSHED_DEBUG: logger.info('pcic request: %s', req_url) try: resp = requests.get(req_url) resp.raise_for_status() except requests.exceptions.HTTPError as e: raise HTTPException(status_code=e.response.status_code, detail=str(e)) return resp.json() def water_licences_summary(licences: List[Feature], polygon: Polygon) -> LicenceDetails: """ takes a list of licences and the search polygon, and returns a summary of the licences that fall within the search area. """ total_licenced_qty_m3_yr = 0 licenced_qty_by_use_type = {} active_licences_within_search_area = [] inactive_licences_within_search_area = [] # max_quantity_by_licence tracks quantities for licences # that have multiple points of diversion (PODs). The quantity # is treated differently based on the QUANTITY_FLAG attribute: # # M - QUANTITY is the max quantity for the licence, shared across multiple # points of diversion. QUANTITY should be the same for all # records under a licence with this flag and will not be summed. # T, D, P - QUANTITY is the quantity per POD record and will be summed # to determine the total quantity for the licence. # # note: the above is the explanation of how this is handled here in this function, # refer to https://catalogue.data.gov.bc.ca/dataset/5549cae0-c2b1-4b96-9777-529d9720803c # for the official quantity flag definitions. max_quantity_by_licence = {} for lic in licences: feature_shape = shape(lic.geometry) # skip licences outside search area if not feature_shape.within(polygon): continue # skip licence if not a surface water point of diversion (POD) # other pod_subtype codes are associated with groundwater. if lic.properties['POD_SUBTYPE'] != 'POD': continue licence_number = lic.properties['LICENCE_NUMBER'] qty = lic.properties['QUANTITY'] qty_unit = lic.properties['QUANTITY_UNITS'].strip() purpose = lic.properties['PURPOSE_USE'] priority_date = datetime.datetime.strptime(lic.properties['PRIORITY_DATE'], '%Y-%m-%dZ').date() \ if lic.properties.get('PRIORITY_DATE', None) else None # normalize the quantity units to m3/year. This function returns None # if the quantity cannot be normalized; for example, there is an invalid # unit (or the unit is "total flow"). In this case, the original quantity # will still be available for users to view, but the normalized m3/year # table column will be empty. The licence will also not be considered # in the sum total if the quantity cannot be converted due to invalid input. normalized_qty = normalize_quantity(qty, qty_unit) lic.properties['qty_m3_yr'] = normalized_qty # List of statuses to watch for when deciding whether or not # to consider the licenced quantity for the total licenced usage. # It may be possible to only consider POD_STATUS but we should assume # there may be data discrepancies, so skip if either POD_STATUS or LICENCE_STATUS # is an inactive code. LICENCE_STATUSES_TO_SKIP = [ 'Abandoned', 'Canceled', 'Cancelled', 'Expired', 'Inactive' ] POD_STATUSES_TO_SKIP = [ 'Inactive' ] # by default, add licence quantities together licence_qty_action_function = add # licences with a QUANTITY_FLAG of "M" need to be handled separately (see above note # for `max_quantity_by_licence`). The `max` function is used. # Some QUANTITY_FLAG values are null, so check for that before we process the value as a string. if lic.properties.get("QUANTITY_FLAG", None) and lic.properties.get("QUANTITY_FLAG", "").strip() == "M": licence_qty_action_function = max if lic.properties["LICENCE_STATUS"] not in LICENCE_STATUSES_TO_SKIP and \ lic.properties["POD_STATUS"] not in POD_STATUSES_TO_SKIP: # if the licence has a quantity that we can convert to m3/year, # use the action function (either `add` or `max`, as above). # some licences have a quantity of 0 and a unit of "total flow", # these will be skipped here. if normalized_qty is not None: max_quantity_by_licence[licence_number] = licence_qty_action_function( max_quantity_by_licence.get(licence_number, 0), normalized_qty ) active_licences_within_search_area.append(lic) else: inactive_licences_within_search_area.append(lic) # organize the licence by purpose use.The WALLY web app will primary display # licences broken down by purpose use. if purpose is not None: # move id to back of purpose name try: code, name = purpose.split(' - ') purpose = f"{name} ({code})" except ValueError: logger.error(f"Error formatting {purpose}") # format licences for each purpose type purpose_data = licenced_qty_by_use_type.setdefault(purpose, { "qty": 0, "licences": [], "inactive_licences": [] }) licence = Feature( geometry=transform(transform_3005_4326, shape(lic.geometry)), id=lic.id, properties={ "fileNumber": lic.properties["FILE_NUMBER"], "licenceNumber": lic.properties["LICENCE_NUMBER"], "status": lic.properties["LICENCE_STATUS"], "licensee": lic.properties["PRIMARY_LICENSEE_NAME"], "priorityDate": priority_date, "source": lic.properties["SOURCE_NAME"], "quantityPerSec": normalized_qty / SEC_IN_YEAR if normalized_qty else None, "quantityPerYear": normalized_qty, "quantityFlag": lic.properties["QUANTITY_FLAG"], "quantity": lic.properties["QUANTITY"], "quantityUnits": lic.properties["QUANTITY_UNITS"] } ) # add licenced quantity if the licence is not canceled. if lic.properties["LICENCE_STATUS"] not in LICENCE_STATUSES_TO_SKIP and \ lic.properties["POD_STATUS"] not in POD_STATUSES_TO_SKIP: if normalized_qty is not None: purpose_data["qty"] = licence_qty_action_function( purpose_data["qty"], normalized_qty) licenced_qty_by_use_type[purpose]["licences"].append(licence) else: licenced_qty_by_use_type[purpose]["inactive_licences"].append( licence) # create the list of purpose types. licence_purpose_type_list = [] for purpose, purpose_obj in licenced_qty_by_use_type.items(): licence_purpose_type_list.append({ "purpose": purpose, "qty": purpose_obj["qty"], "licences": purpose_obj["licences"], "inactive_licences": purpose_obj["inactive_licences"], "units": "m3/year" }) # Create the LicenceDetails summary and populate it with the licences (separated by # active/inactive), and statistics for the WALLY web client to display. return LicenceDetails( licences=FeatureCollection([ Feature( geometry=transform(transform_3005_4326, shape(feat.geometry)), id=feat.id, properties=feat.properties ) for feat in active_licences_within_search_area ]), inactive_licences=FeatureCollection([ Feature( geometry=transform(transform_3005_4326, shape(feat.geometry)), id=feat.id, properties=feat.properties ) for feat in inactive_licences_within_search_area ]), total_qty=sum(max_quantity_by_licence.values()), total_qty_by_purpose=licence_purpose_type_list, projected_geometry_area=polygon.area, ) def surface_water_rights_licences(polygon: Polygon): """ returns surface water rights licences (filtered by POD subtype)""" water_rights_layer = 'water_rights_licences' # search with a simplified rectangle representing the polygon. # we will do an intersection on the more precise polygon after polygon_rect = polygon.minimum_rotated_rectangle licences = databc_feature_search( water_rights_layer, search_area=polygon_rect) polygon_3005 = transform(transform_4326_3005, polygon) licence_summary = water_licences_summary(licences.features, polygon_3005) licence_summary.projected_geometry_area_simplified = polygon_rect.area return licence_summary def surface_water_approval_points(polygon: Polygon): """ returns surface water approval points (filtered by APPROVAL_STATUS)""" water_approvals_layer = 'water_approval_points' # search with a simplified rectangle representing the polygon. # we will do an intersection on the more precise polygon after polygon_rect = polygon.minimum_rotated_rectangle approvals = databc_feature_search( water_approvals_layer, search_area=polygon_rect) polygon_3005 = transform(transform_4326_3005, polygon) features_within_search_area = [] total_qty_m3_yr = 0 for apr in approvals.features: feature_shape = shape(apr.geometry) # skip approvals outside search area if not feature_shape.within(polygon_3005): continue # skip approval if its not an active licence # other approval status' are associated with inactive licences if apr.properties['APPROVAL_STATUS'] != 'Current': continue features_within_search_area.append(apr) # the rare water approval record has the units # as a suffix in the QUATITY property # these are considered bad data points # and will be skipped try: qty = float(apr.properties['QUANTITY']) except: continue qty_unit = apr.properties['QUANTITY_UNITS'] # null if approval is a works project, most of them are if qty and qty_unit: qty = normalize_quantity(qty, qty_unit) total_qty_m3_yr += qty apr.properties['qty_m3_yr'] = qty else: apr.properties['qty_m3_yr'] = 0 return WaterApprovalDetails( approvals=FeatureCollection([ Feature( geometry=transform(transform_3005_4326, shape(feat.geometry)), id=feat.id, properties=feat.properties ) for feat in features_within_search_area ]), total_qty=total_qty_m3_yr, projected_geometry_area=polygon.area, projected_geometry_area_simplified=polygon_rect.area ) def get_nearest_stream_name_id(nearest_stream): """ Given a row of FWA stream data, return a tuple containing the stream id, name, and the closest point. `nearest_stream` row should be output from the api.v1.streams.controller.get_nearest_streams function. """ nearest_stream_point =
<filename>google/cloud/videointelligence/v1beta2/videointelligence-v1beta2-py/google/cloud/videointelligence_v1beta2/types/video_intelligence.py # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 proto # type: ignore from google.protobuf import duration_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( package='google.cloud.videointelligence.v1beta2', manifest={ 'Feature', 'LabelDetectionMode', 'Likelihood', 'AnnotateVideoRequest', 'VideoContext', 'LabelDetectionConfig', 'ShotChangeDetectionConfig', 'ExplicitContentDetectionConfig', 'FaceDetectionConfig', 'VideoSegment', 'LabelSegment', 'LabelFrame', 'Entity', 'LabelAnnotation', 'ExplicitContentFrame', 'ExplicitContentAnnotation', 'NormalizedBoundingBox', 'FaceSegment', 'FaceFrame', 'FaceAnnotation', 'VideoAnnotationResults', 'AnnotateVideoResponse', 'VideoAnnotationProgress', 'AnnotateVideoProgress', }, ) class Feature(proto.Enum): r"""Video annotation feature.""" FEATURE_UNSPECIFIED = 0 LABEL_DETECTION = 1 SHOT_CHANGE_DETECTION = 2 EXPLICIT_CONTENT_DETECTION = 3 FACE_DETECTION = 4 class LabelDetectionMode(proto.Enum): r"""Label detection mode.""" LABEL_DETECTION_MODE_UNSPECIFIED = 0 SHOT_MODE = 1 FRAME_MODE = 2 SHOT_AND_FRAME_MODE = 3 class Likelihood(proto.Enum): r"""Bucketized representation of likelihood.""" LIKELIHOOD_UNSPECIFIED = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 POSSIBLE = 3 LIKELY = 4 VERY_LIKELY = 5 class AnnotateVideoRequest(proto.Message): r"""Video annotation request. Attributes: input_uri (str): Input video location. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see `Request URIs <https://cloud.google.com/storage/docs/request-endpoints>`__. A video URI may include wildcards in ``object-id``, and thus identify multiple videos. Supported wildcards: '*' to match 0 or more characters; '?' to match 1 character. If unset, the input video should be embedded in the request as ``input_content``. If set, ``input_content`` should be unset. input_content (bytes): The video data bytes. If unset, the input video(s) should be specified via ``input_uri``. If set, ``input_uri`` should be unset. features (Sequence[google.cloud.videointelligence_v1beta2.types.Feature]): Required. Requested video annotation features. video_context (google.cloud.videointelligence_v1beta2.types.VideoContext): Additional video context and/or feature- pecific parameters. output_uri (str): Optional. Location where the output (in JSON format) should be stored. Currently, only `Google Cloud Storage <https://cloud.google.com/storage/>`__ URIs are supported, which must be specified in the following format: ``gs://bucket-id/object-id`` (other URI formats return [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see `Request URIs <https://cloud.google.com/storage/docs/request-endpoints>`__. location_id (str): Optional. Cloud region where annotation should take place. Supported cloud regions: ``us-east1``, ``us-west1``, ``europe-west1``, ``asia-east1``. If no region is specified, a region will be determined based on video file location. """ input_uri = proto.Field( proto.STRING, number=1, ) input_content = proto.Field( proto.BYTES, number=6, ) features = proto.RepeatedField( proto.ENUM, number=2, enum='Feature', ) video_context = proto.Field( proto.MESSAGE, number=3, message='VideoContext', ) output_uri = proto.Field( proto.STRING, number=4, ) location_id = proto.Field( proto.STRING, number=5, ) class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. Attributes: segments (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): Video segments to annotate. The segments may overlap and are not required to be contiguous or span the whole video. If unspecified, each video is treated as a single segment. label_detection_config (google.cloud.videointelligence_v1beta2.types.LabelDetectionConfig): Config for LABEL_DETECTION. shot_change_detection_config (google.cloud.videointelligence_v1beta2.types.ShotChangeDetectionConfig): Config for SHOT_CHANGE_DETECTION. explicit_content_detection_config (google.cloud.videointelligence_v1beta2.types.ExplicitContentDetectionConfig): Config for EXPLICIT_CONTENT_DETECTION. face_detection_config (google.cloud.videointelligence_v1beta2.types.FaceDetectionConfig): Config for FACE_DETECTION. """ segments = proto.RepeatedField( proto.MESSAGE, number=1, message='VideoSegment', ) label_detection_config = proto.Field( proto.MESSAGE, number=2, message='LabelDetectionConfig', ) shot_change_detection_config = proto.Field( proto.MESSAGE, number=3, message='ShotChangeDetectionConfig', ) explicit_content_detection_config = proto.Field( proto.MESSAGE, number=4, message='ExplicitContentDetectionConfig', ) face_detection_config = proto.Field( proto.MESSAGE, number=5, message='FaceDetectionConfig', ) class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. Attributes: label_detection_mode (google.cloud.videointelligence_v1beta2.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in addition to video-level labels or segment-level labels. If unspecified, defaults to ``SHOT_MODE``. stationary_camera (bool): Whether the video has been shot from a stationary (i.e. non-moving) camera. When set to true, might improve detection accuracy for moving objects. Should be used with ``SHOT_AND_FRAME_MODE`` enabled. model (str): Model to use for label detection. Supported values: "builtin/stable" (the default if unset) and "builtin/latest". """ label_detection_mode = proto.Field( proto.ENUM, number=1, enum='LabelDetectionMode', ) stationary_camera = proto.Field( proto.BOOL, number=2, ) model = proto.Field( proto.STRING, number=3, ) class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. Attributes: model (str): Model to use for shot change detection. Supported values: "builtin/stable" (the default if unset) and "builtin/latest". """ model = proto.Field( proto.STRING, number=1, ) class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. Attributes: model (str): Model to use for explicit content detection. Supported values: "builtin/stable" (the default if unset) and "builtin/latest". """ model = proto.Field( proto.STRING, number=1, ) class FaceDetectionConfig(proto.Message): r"""Config for FACE_DETECTION. Attributes: model (str): Model to use for face detection. Supported values: "builtin/stable" (the default if unset) and "builtin/latest". include_bounding_boxes (bool): Whether bounding boxes be included in the face annotation output. """ model = proto.Field( proto.STRING, number=1, ) include_bounding_boxes = proto.Field( proto.BOOL, number=2, ) class VideoSegment(proto.Message): r"""Video segment. Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the video, corresponding to the start of the segment (inclusive). end_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the video, corresponding to the end of the segment (inclusive). """ start_time_offset = proto.Field( proto.MESSAGE, number=1, message=duration_pb2.Duration, ) end_time_offset = proto.Field( proto.MESSAGE, number=2, message=duration_pb2.Duration, ) class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. Attributes: segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): Video segment where a label was detected. confidence (float): Confidence that the label is accurate. Range: [0, 1]. """ segment = proto.Field( proto.MESSAGE, number=1, message='VideoSegment', ) confidence = proto.Field( proto.FLOAT, number=2, ) class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. confidence (float): Confidence that the label is accurate. Range: [0, 1]. """ time_offset = proto.Field( proto.MESSAGE, number=1, message=duration_pb2.Duration, ) confidence = proto.Field( proto.FLOAT, number=2, ) class Entity(proto.Message): r"""Detected entity from video analysis. Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google Knowledge Graph Search API <https://developers.google.com/knowledge-graph/>`__. description (str): Textual description, e.g. ``Fixed-gear bicycle``. language_code (str): Language code for ``description`` in BCP-47 format. """ entity_id = proto.Field( proto.STRING, number=1, ) description = proto.Field( proto.STRING, number=2, ) language_code = proto.Field( proto.STRING, number=3, ) class LabelAnnotation(proto.Message): r"""Label annotation. Attributes: entity (google.cloud.videointelligence_v1beta2.types.Entity): Detected entity. category_entities (Sequence[google.cloud.videointelligence_v1beta2.types.Entity]): Common categories for the detected entity. E.g. when the label is ``Terrier`` the category is likely ``dog``. And in some cases there might be more than one categories e.g. ``Terrier`` could also be a ``pet``. segments (Sequence[google.cloud.videointelligence_v1beta2.types.LabelSegment]): All video segments where a label was detected. frames (Sequence[google.cloud.videointelligence_v1beta2.types.LabelFrame]): All video frames where a label was detected. """ entity = proto.Field( proto.MESSAGE, number=1, message='Entity', ) category_entities = proto.RepeatedField( proto.MESSAGE, number=2, message='Entity', ) segments = proto.RepeatedField( proto.MESSAGE, number=3, message='LabelSegment', ) frames = proto.RepeatedField( proto.MESSAGE, number=4, message='LabelFrame', ) class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. pornography_likelihood (google.cloud.videointelligence_v1beta2.types.Likelihood): Likelihood of the pornography content.. """ time_offset = proto.Field( proto.MESSAGE, number=1, message=duration_pb2.Duration, ) pornography_likelihood = proto.Field( proto.ENUM, number=2, enum='Likelihood', ) class ExplicitContentAnnotation(proto.Message): r"""Explicit content annotation (based on per-frame visual signals only). If no explicit content has been detected in a frame, no annotations are present for that frame. Attributes: frames (Sequence[google.cloud.videointelligence_v1beta2.types.ExplicitContentFrame]): All video frames where explicit content was detected. """ frames = proto.RepeatedField( proto.MESSAGE, number=1, message='ExplicitContentFrame', ) class NormalizedBoundingBox(proto.Message): r"""Normalized bounding box. The normalized vertex coordinates are relative to the original image. Range: [0, 1]. Attributes: left (float): Left X coordinate. top (float): Top Y coordinate. right (float): Right X coordinate. bottom (float): Bottom Y coordinate. """ left = proto.Field( proto.FLOAT, number=1, ) top = proto.Field( proto.FLOAT, number=2, ) right = proto.Field( proto.FLOAT, number=3, ) bottom = proto.Field( proto.FLOAT, number=4, ) class FaceSegment(proto.Message): r"""Video segment level annotation results for face detection. Attributes: segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): Video segment where a face was detected. """ segment = proto.Field( proto.MESSAGE, number=1, message='VideoSegment', ) class FaceFrame(proto.Message): r"""Video frame level annotation results for face detection. Attributes: normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1beta2.types.NormalizedBoundingBox]): Normalized Bounding boxes in a frame. There can be more than one boxes if the same face is detected in multiple locations within the current frame. time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. """ normalized_bounding_boxes
import copy import datetime import functools import importlib import io import json import os import shutil import sys import tempfile import types from threading import Thread from requests import utils import yaml from bs4 import BeautifulSoup from fastrunner.httprunner.api import HttpRunner from fastrunner.httprunner import logger, parser from fastrunner.httprunner.exceptions import FunctionNotFound, VariableNotFound from requests.cookies import RequestsCookieJar from requests_toolbelt import MultipartEncoder from fastrunner import models from fastrunner.utils.parser import Format from FasterRunner.settings.base import BASE_DIR logger.setup_logger('DEBUG') TEST_NOT_EXISTS = { "code": "0102", "status": False, "msg": "节点下没有接口或者用例集" } def is_function(tup): """ Takes (name, object) tuple, returns True if it is a function. """ name, item = tup return isinstance(item, types.FunctionType) def is_variable(tup): """ Takes (name, object) tuple, returns True if it is a variable. """ name, item = tup if callable(item): # function or class return False if isinstance(item, types.ModuleType): # imported module return False if name.startswith("_"): # private property return False return True class FileLoader(object): @staticmethod def dump_yaml_file(yaml_file, data): """ dump yaml file """ with io.open(yaml_file, 'w', encoding='utf-8') as stream: yaml.dump( data, stream, indent=4, default_flow_style=False, encoding='utf-8', allow_unicode=True) @staticmethod def dump_json_file(json_file, data): """ dump json file """ with io.open(json_file, 'w', encoding='utf-8') as stream: json.dump( data, stream, indent=4, separators=( ',', ': '), ensure_ascii=False) @staticmethod def dump_python_file(python_file, data): """dump python file """ with io.open(python_file, 'w', encoding='utf-8') as stream: stream.write(data) @staticmethod def dump_binary_file(binary_file, data): """dump file """ with io.open(binary_file, 'wb') as stream: stream.write(data) @staticmethod def load_python_module(file_path): """ load python module. Args: file_path: python path Returns: dict: variables and functions mapping for specified python module { "variables": {}, "functions": {} } """ debugtalk_module = { "variables": {}, "functions": {} } sys.path.insert(0, file_path) module = importlib.import_module("debugtalk") # 修复重载bug importlib.reload(module) sys.path.pop(0) for name, item in vars(module).items(): if is_function((name, item)): debugtalk_module["functions"][name] = item elif is_variable((name, item)): if isinstance(item, tuple): continue debugtalk_module["variables"][name] = item else: pass return debugtalk_module def parse_validate_and_extract(list_of_dict: list, variables_mapping: dict, functions_mapping, api_variables: list): """ Args: list_of_dict (list) variables_mapping (dict): variables mapping. functions_mapping (dict): functions mapping. api_variables: (list) Returns: 引用传参,直接修改dict的内容,不需要返回 """ # 获取api中所有变量的key api_variables_key = [] for variable in api_variables: api_variables_key.extend(list(variable.keys())) for index, d in enumerate(list_of_dict): is_need_parse = True # extract: d是{'k':'v'}, v类型是str # validate: d是{'equals': ['v1', 'v2']}, v类型是list v = list(d.values())[0] try: # validate,extract 的值包含了api variable的key中,不需要替换 for key in api_variables_key: if isinstance(v, str): if key in v: is_need_parse = False elif isinstance(v, list): # v[1]需要统一转换成str类型,否则v[1]是int类型就会报错 if key in str(v[1]): is_need_parse = False if is_need_parse is True: d = parser.parse_data(d, variables_mapping=variables_mapping, functions_mapping=functions_mapping) for k, v in d.items(): v = parser.parse_string_functions(v, variables_mapping=variables_mapping, functions_mapping=functions_mapping) d[k] = v list_of_dict[index] = d except (FunctionNotFound, VariableNotFound): continue def parse_cases(testcases, name=None, config=None, project=None): testset = { "config": { "name": name, "variables": [] }, "teststeps": [ ], "path":'', "type":'testcase' } # 获取当前项目的全局变量 global_variables = models.Variables.objects.filter(project=project).all().values("key", "value") all_config_variables_keys = set().union(*(d.keys() for d in testset["config"].setdefault("variables", []))) global_variables_list_of_dict = [] for item in global_variables: if item["key"] not in all_config_variables_keys: global_variables_list_of_dict.append({item["key"]: item["value"]}) # 有variables就直接extend,没有就加一个[],再extend # 配置的variables和全局变量重叠,优先使用配置中的variables testset["config"].setdefault("variables", []).extend(global_variables_list_of_dict) for testcase in testcases: each_test = { 'name': '', 'api':'', 'api_def': { } } del testcase['desc'] each_test['name'] =testcase['name'] del testcase['rig_id'] for k,v in testcase.items(): each_test['api_def'][k]=v testset['teststeps'].append(each_test) return testset def parse_tests(testcases, debugtalk, name=None, config=None, project=None): """get test case structure testcases: list config: none or dict debugtalk: dict """ pro_map = parse_cases(testcases,debugtalk,name=None,config=None,project=None) refs = { "env": {}, "def-api": {}, "def-testcase": {}, "debugtalk": debugtalk } testset = { "config": { "name": testcases[-1]["name"], "variables": [] }, "teststeps": testcases, } if config: testset["config"] = config if name: testset["config"]["name"] = name # 获取当前项目的全局变量 global_variables = models.Variables.objects.filter(project=project).all().values("key", "value") all_config_variables_keys = set().union(*(d.keys() for d in testset["config"].setdefault("variables", []))) global_variables_list_of_dict = [] for item in global_variables: if item["key"] not in all_config_variables_keys: global_variables_list_of_dict.append({item["key"]: item["value"]}) # 有variables就直接extend,没有就加一个[],再extend # 配置的variables和全局变量重叠,优先使用配置中的variables testset["config"].setdefault("variables", []).extend(global_variables_list_of_dict) testset["config"]["refs"] = refs # 配置中的变量和全局变量合并 variables_mapping = {} if config: for variables in config['variables']: variables_mapping.update(variables) # 驱动代码中的所有函数 functions_mapping = debugtalk.get('functions', {}) # 替换extract,validate中的变量和函数,只对value有效,key无效 for testcase in testcases: extract: list = testcase.get('extract', []) validate: list = testcase.get('validate', []) api_variables: list = testcase.get('variables', []) parse_validate_and_extract(extract, variables_mapping, functions_mapping, api_variables) parse_validate_and_extract(validate, variables_mapping, functions_mapping, api_variables) return pro_map # return testset def load_debugtalk(project): """import debugtalk.py in sys.path and reload project: int """ # debugtalk.py code = models.Debugtalk.objects.get(project__id=project).code # file_path = os.path.join(tempfile.mkdtemp(prefix='FasterRunner'), "debugtalk.py") tempfile_path = tempfile.mkdtemp( prefix='FasterRunner', dir=os.path.join( BASE_DIR, 'tempWorkDir')) file_path = os.path.join(tempfile_path, 'debugtalk.py') os.chdir(tempfile_path) try: FileLoader.dump_python_file(file_path, code) debugtalk = FileLoader.load_python_module(os.path.dirname(file_path)) return debugtalk, file_path except Exception as e: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(file_path)) def debug_suite_tree_pk(testcases, project, obj, config=None, save=True, user='',log_file=None): ''' 运行多条测试用例 ''' if len(testcases) == 0: return TEST_NOT_EXISTS debugtalk = load_debugtalk(project) debugtalk_content = debugtalk[0] debugtalk_path = debugtalk[1] os.chdir(os.path.dirname(debugtalk_path)) pro_map = { "project_mapping": { "PWD": "", "functions": {}, "variables": {}, "env": {} }, "testcases": [] } # 驱动代码中的所有函数 functions_mapping = debugtalk_content.get('functions', {}) pro_map['project_mapping']['functions'] = functions_mapping try: testcases = copy.deepcopy( parse_cases( testcases, name=obj[0]['name'], config=None, project=project )) pro_map['testcases'].append(testcases) kwargs = { "failfast": False, "log_file": log_file } from fastrunner.httprunner3.api import HttpRunner as HttpRunner3 runner3 = HttpRunner3(**kwargs) runner3.run(pro_map) summary = parse_summary(runner3._summary) with open(log_file, 'r') as r: msg = r.readlines() summary['msg'] = msg if save: save_summary(f"批量运行{len(pro_map['testcases'])}条用例", summary, project, api_type=1, user=user) return summary except Exception as e: raise SyntaxError(str(e)) finally: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(debugtalk_path)) def debug_suite_tree(suite, project, obj, config=None, save=True, user='',log_file=None): ''' 运行多条测试用例 ''' if len(suite) == 0: return TEST_NOT_EXISTS debugtalk = load_debugtalk(project) debugtalk_content = debugtalk[0] debugtalk_path = debugtalk[1] os.chdir(os.path.dirname(debugtalk_path)) pro_map = { "project_mapping": { "PWD": "", "functions": {}, "variables": {}, "env": {} }, "testcases": [] } # 驱动代码中的所有函数 functions_mapping = debugtalk_content.get('functions', {}) pro_map['project_mapping']['functions'] = functions_mapping try: for index in range(len(suite)): testcases = copy.deepcopy( parse_cases( suite[index], name=obj[index]['name'], config=config[index], project=project )) pro_map['testcases'].append(testcases) kwargs = { "failfast": False, "log_file": log_file } from fastrunner.httprunner3.api import HttpRunner as HttpRunner3 runner3 = HttpRunner3(**kwargs) runner3.run(pro_map) summary = parse_summary(runner3._summary) with open(log_file, 'r') as r: msg = r.readlines() summary['msg'] = msg if save: save_summary(f"批量运行{len(pro_map['testcases'])}条用例", summary, project, api_type=1, user=user) return summary except Exception as e: raise SyntaxError(str(e)) finally: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(debugtalk_path)) def debug_suite(suite, project, obj, config=None, save=True, user='',log_file=None): """debug suite suite :list pk: int project: int """ if len(suite) == 0: return TEST_NOT_EXISTS debugtalk = load_debugtalk(project) debugtalk_content = debugtalk[0] debugtalk_path = debugtalk[1] os.chdir(os.path.dirname(debugtalk_path)) test_sets = [] ''' try: for index in range(len(suite)): # copy.deepcopy 修复引用bug # testcases = copy.deepcopy(parse_tests(suite[index], debugtalk, name=obj[index]['name'], config=config[index])) testcases = copy.deepcopy( parse_tests( suite[index], debugtalk_content, name=obj[index]['name'], config=config[index], project=project )) test_sets.append(testcases) kwargs = { "failfast": False } runner = HttpRunner(**kwargs) runner.run(test_sets) summary = parse_summary(runner.summary) if save: save_summary(f"批量运行{len(test_sets)}条用例", summary, project, type=1, user=user) return summary ''' try: # for index in range(len(suite)): # copy.deepcopy 修复引用bug # testcases = copy.deepcopy(parse_tests(suite[index], debugtalk, name=obj[index]['name'], config=config[index])) testcases = copy.deepcopy( parse_tests( suite, debugtalk_content, name=None, config=config, project=project )) # test_sets.append(testcases) print (testcases) kwargs = { "failfast": False, "log_file": log_file } from fastrunner.httprunner3.api import HttpRunner as HttpRunner3 runner3 = HttpRunner3(**kwargs) runner3.run(test_sets) summary = parse_summary(runner3._summary) if save: save_summary(f"批量运行{len(test_sets)}条用例", summary, project, type=1, user=user) return summary except Exception as e: raise SyntaxError(str(e)) finally: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(debugtalk_path)) def debug_api(api, project, name=None, config=None, save=True, user='',log_file=None): """debug api api :dict or list project: int """ print ('-----zhixing') if len(api) == 0: return TEST_NOT_EXISTS # testcases if isinstance(api, dict): """ httprunner scripts or teststeps """ api = [api] # 删除api的描述信息 for each_api in api: each_api.pop('desc') # 参数化过滤,只加载api中调用到的参数 if config and config.get('parameters'): api_params = [] for item in api: params = item['request'].get('params') or item['request'].get('json') for v in params.values(): if type(v) == list: api_params.extend(v) else: api_params.append(v) parameters = [] for index, dic in enumerate(config['parameters']): for key in dic.keys(): # key可能是key-key1这种模式,所以需要分割 for i in key.split('-'): if '$' + i in api_params: parameters.append(dic) config['parameters'] = parameters debugtalk = load_debugtalk(project) debugtalk_content = debugtalk[0] debugtalk_path = debugtalk[1] os.chdir(os.path.dirname(debugtalk_path)) ''' try: # testcase_list = [parse_tests(api, load_debugtalk(project), name=name, config=config)] testcase_list =parse_tests( api, debugtalk_content, name=name, config=config, project=project) print ('-----test_list',testcase_list) kwargs = { "failfast": False } runner = HttpRunner(**kwargs) runner.run(testcase_list) print ('--------------------runner.summary------------',runner.summary) summary = parse_summary_1(runner.summary) if save: save_summary(name, summary, project, type=1, user=user) return summary except Exception as e: raise SyntaxError(str(e)) finally: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(debugtalk_path)) ''' try: # testcase_list = [parse_tests(api, load_debugtalk(project), name=name, config=config)] testcase_list = parse_api( api, debugtalk_content, name=name, config=config, project=project) kwargs = { "failfast": False, "log_file":log_file } from fastrunner.httprunner3.api import HttpRunner as HttpRunner3 runner3 = HttpRunner3(**kwargs) runner3.run(testcase_list) # summary = runner3._summary summary = parse_summary(runner3._summary) with open(log_file,'r') as r: msg = r.readlines() summary['msg'] =msg if save: save_summary(name, summary, project, api_type=1, user=user) return summary except Exception as e: print ('-----debug_api-----',e) finally: os.chdir(BASE_DIR) shutil.rmtree(os.path.dirname(debugtalk_path)) def parse_api(api,debugtalk, name=None, config=None, project=None): ''' 对 单步调试API 进行解析 ''' pro_map = { "project_mapping":
'SA': 'Saudi Arabia', 'SN': 'Senegal', 'RS': 'Serbia', 'SC': 'Seychelles', 'SL': 'Sierra Leone', 'SG': 'Singapore', 'SK': 'Slovakia', 'SI': 'Slovenia', 'SB': 'Solomon Islands', 'SO': 'Somalia', 'ZA': 'South Africa', 'GS': 'South Georgia And Sandwich Isl.', 'ES': 'Spain', 'LK': 'Sri Lanka', 'SD': 'Sudan', 'SR': 'Suriname', 'SJ': 'Svalbard And Jan Mayen', 'SZ': 'Swaziland', 'SE': 'Sweden', 'CH': 'Switzerland', 'SY': 'Syrian Arab Republic', 'TW': 'Taiwan', 'TJ': 'Tajikistan', 'TZ': 'Tanzania', 'TH': 'Thailand', 'TL': 'Timor-Leste', 'TG': 'Togo', 'TK': 'Tokelau', 'TO': 'Tonga', 'TT': 'Trinidad And Tobago', 'TN': 'Tunisia', 'TR': 'Turkey', 'TM': 'Turkmenistan', 'TC': 'Turks And Caicos Islands', 'TV': 'Tuvalu', 'UG': 'Uganda', 'UA': 'Ukraine', 'AE': 'United Arab Emirates', 'GB': 'United Kingdom', 'US': 'United States', 'UM': 'United States Outlying Islands', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VU': 'Vanuatu', 'VE': 'Venezuela', 'VN': 'Viet Nam', 'VG': 'Virgin Islands, British', 'VI': 'Virgin Islands, U.S.', 'WF': 'Wallis And Futuna', 'EH': 'Western Sahara', 'YE': 'Yemen', 'ZM': 'Zambia', 'ZW': 'Zimbabwe', 'KP': 'Korea (Democratic Peoples Republic of)', } if (request.POST.get('ivisits_select') == "ivisits"): ivisits = emp_visits.objects.filter(pf_no=pf, v_type=1).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-entry_date') ivisits_req = "1" else: ivisits="" ivisits_req = "0" for fvisit in fvisits: fvisit.countryfull = countries[fvisit.country] if (request.POST.get('consymps_select') == "consymps"): consymps = emp_confrence_organised.objects.filter(pf_no=pf).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') consymps_req = "1" else: consymps="" consymps_req = "0" if (request.POST.get('awards_select') == "awards"): awards = emp_achievement.objects.filter(pf_no=pf).filter(a_year__range=[start,end]).order_by('-date_entry') awards_req = "1" else: awards="" awards_req = "0" if (request.POST.get('talks_select') == "talks"): talks = emp_expert_lectures.objects.filter(pf_no=pf).filter(l_date__year__range=[start,end]).filter(l_date__month__range=[star,en]).order_by('-date_entry') talks_req = "1" else: talks="" talks_req = "0" if (request.POST.get('chairs_select') == "chairs"): chairs = emp_session_chair.objects.filter(pf_no=pf).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') chairs_req = "1" else: chairs="" chairs_req = "0" if (request.POST.get('keynotes_select') == "keynotes"): keynotes = emp_keynote_address.objects.filter(pf_no=pf).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') keynotes_req = "1" else: keynotes="" keynotes_req = "0" if (request.POST.get('events_select') == "events"): events = emp_event_organized.objects.filter(pf_no=pf).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-start_date') events_req = "1" else: events="" events_req = "0" pers = get_object_or_404(faculty_about, user = request.user) design = HoldsDesignation.objects.select_related('user','working','designation').filter(working=request.user) desig=[] for i in design: desig.append(str(i.designation)) context = {'user': user, 'desig':desig, 'pf':pf, 'journal':journal, 'journal_req':journal_req, 'conference': conference, 'conference_req': conference_req, 'books': books, 'books_req': books_req, 'projects': projects, 'projects_req': projects_req, 'consultancy':consultancy, 'consultancy_req': consultancy_req, 'patents':patents, 'patents_req': patents_req, 'techtransfers':techtransfers, 'techtransfers_req': techtransfers_req, 'mtechs':mtechs, 'mtechs_req': mtechs_req, 'phds':phds, 'phds_req': phds_req, 'fvisits':fvisits, 'fvisits_req': fvisits_req, 'ivisits': ivisits, 'ivisits_req': ivisits_req, 'consymps':consymps, 'consymps_req': consymps_req, 'awards':awards, 'awards_req': awards_req, 'talks':talks, 'talks_req': talks_req, 'chairs':chairs, 'chairs_req': chairs_req, 'keynotes':keynotes, 'keynotes_req': keynotes_req, 'events':events, 'events_req': events_req, 'first_name':request.user.first_name, 'last_name': request.user.last_name, } return render_to_pdf('eisModulenew/generatereportshow.html', context) # report for dean rspc def rspc_generate_report(request): user = get_object_or_404(ExtraInfo, user=request.user) pf = user.id start = request.POST.get('syear') star_date = start+'-01-01' end = request.POST.get('lyear') star = request.POST.get('smonth') star_date = start + '-01-01' en = request.POST.get('lmonth') if(request.POST.get('journal_select')=="journal"): journal = emp_research_papers.objects.filter(rtype='Journal').order_by('-date_entry') journal_req="1" else: journal="" journal_req="0" if (request.POST.get('conference_select') == "conference"): conference = emp_research_papers.objects.filter(rtype='Conference').order_by('-date_entry') conference_req = "1" else: conference="" conference_req = "0" if (request.POST.get('books_select') == "books"): books = emp_published_books.objects.all().order_by('-date_entry') books_req = "1" else: books="" books_req = "0" if (request.POST.get('projects_select') == "projects"): projects = emp_research_projects.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-start_date') projects_req = "1" else: projects = "" projects_req = "0" if (request.POST.get('consultancy_select') == "consultancy"): consultancy = emp_consultancy_projects.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') consultancy_req = "1" else: consultancy = "" consultancy_req = "0" if (request.POST.get('patents_select') == "patents"): patents = emp_patents.objects.all().filter(p_year__range=[start,end]).filter(a_month__range=[star,en]).order_by('-date_entry') patents_req = "1" else: patents = "" patents_req = "0" if (request.POST.get('techtransfers_select') == "techtransfers"): techtransfers = emp_techtransfer.objects.all().filter(date_entry__year__range=[start,end]).filter(date_entry__month__range=[star,en]).order_by('-date_entry') techtransfers_req = "1" else: techtransfers="" techtransfers_req = "0" if (request.POST.get('mtechs_select') == "mtechs"): mtechs = emp_mtechphd_thesis.objects.filter(degree_type=1).filter(s_year__range=[start,end]).filter(a_month__range=[star,en]).order_by('-date_entry') mtechs_req = "1" else: mtechs="" mtechs_req = "0" if (request.POST.get('phds_select') == "phds"): phds = emp_mtechphd_thesis.objects.filter(degree_type=2).filter(s_year__range=[start,end]).filter(a_month__range=[star,en]).order_by('-date_entry') phds_req = "1" else: phds="" phds_req = "0" if (request.POST.get('fvisits_select') == "fvisits"): fvisits = emp_visits.objects.filter(v_type=2).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-entry_date') fvisits_req = "1" else: fvisits="" fvisits_req = "0" countries = { 'AF': 'Afghanistan', 'AX': 'Aland Islands', 'AL': 'Albania', 'DZ': 'Algeria', 'AS': 'American Samoa', 'AD': 'Andorra', 'AO': 'Angola', 'AI': 'Anguilla', 'AQ': 'Antarctica', 'AG': 'Antigua And Barbuda', 'AR': 'Argentina', 'AM': 'Armenia', 'AW': 'Aruba', 'AU': 'Australia', 'AT': 'Austria', 'AZ': 'Azerbaijan', 'BS': 'Bahamas', 'BH': 'Bahrain', 'BD': 'Bangladesh', 'BB': 'Barbados', 'BY': 'Belarus', 'BE': 'Belgium', 'BZ': 'Belize', 'BJ': 'Benin', 'BM': 'Bermuda', 'BT': 'Bhutan', 'BO': 'Bolivia', 'BA': 'Bosnia And Herzegovina', 'BW': 'Botswana', 'BV': 'Bouvet Island', 'BR': 'Brazil', 'IO': 'British Indian Ocean Territory', 'BN': 'Brunei Darussalam', 'BG': 'Bulgaria', 'BF': 'Burkina Faso', 'BI': 'Burundi', 'KH': 'Cambodia', 'CM': 'Cameroon', 'CA': 'Canada', 'CV': 'Cape Verde', 'KY': 'Cayman Islands', 'CF': 'Central African Republic', 'TD': 'Chad', 'CL': 'Chile', 'CN': 'China', 'CX': 'Christmas Island', 'CC': 'Cocos (Keeling) Islands', 'CO': 'Colombia', 'KM': 'Comoros', 'CG': 'Congo', 'CD': 'Congo, Democratic Republic', 'CK': 'Cook Islands', 'CR': 'Costa Rica', 'CI': 'Cote D\'Ivoire', 'HR': 'Croatia', 'CU': 'Cuba', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'DK': 'Denmark', 'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'EC': 'Ecuador', 'EG': 'Egypt', 'SV': 'El Salvador', 'GQ': 'Equatorial Guinea', 'ER': 'Eritrea', 'EE': 'Estonia', 'ET': 'Ethiopia', 'FK': 'Falkland Islands (Malvinas)', 'FO': 'Faroe Islands', 'FJ': 'Fiji', 'FI': 'Finland', 'FR': 'France', 'GF': 'French Guiana', 'PF': 'French Polynesia', 'TF': 'French Southern Territories', 'GA': 'Gabon', 'GM': 'Gambia', 'GE': 'Georgia', 'DE': 'Germany', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GR': 'Greece', 'GL': 'Greenland', 'GD': 'Grenada', 'GP': 'Guadeloupe', 'GU': 'Guam', 'GT': 'Guatemala', 'GG': 'Guernsey', 'GN': 'Guinea', 'GW': 'Guinea-Bissau', 'GY': 'Guyana', 'HT': 'Haiti', 'HM': 'Heard Island & Mcdonald Islands', 'VA': 'Holy See (Vatican City State)', 'HN': 'Honduras', 'HK': 'Hong Kong', 'HU': 'Hungary', 'IS': 'Iceland', 'IN': 'India', 'ID': 'Indonesia', 'IR': 'Iran, Islamic Republic Of', 'IQ': 'Iraq', 'IE': 'Ireland', 'IM': 'Isle Of Man', 'IL': 'Israel', 'IT': 'Italy', 'JM': 'Jamaica', 'JP': 'Japan', 'JE': 'Jersey', 'JO': 'Jordan', 'KZ': 'Kazakhstan', 'KE': 'Kenya', 'KI': 'Kiribati', 'KR': 'Korea', 'KW': 'Kuwait', 'KG': 'Kyrgyzstan', 'LA': 'Lao People\'s Democratic Republic', 'LV': 'Latvia', 'LB': 'Lebanon', 'LS': 'Lesotho', 'LR': 'Liberia', 'LY': 'Libyan Arab Jamahiriya', 'LI': 'Liechtenstein', 'LT': 'Lithuania', 'LU': 'Luxembourg', 'MO': 'Macao', 'MK': 'Macedonia', 'MG': 'Madagascar', 'MW': 'Malawi', 'MY': 'Malaysia', 'MV': 'Maldives', 'ML': 'Mali', 'MT': 'Malta', 'MH': 'Marshall Islands', 'MQ': 'Martinique', 'MR': 'Mauritania', 'MU': 'Mauritius', 'YT': 'Mayotte', 'MX': 'Mexico', 'FM': 'Micronesia, Federated States Of', 'MD': 'Moldova', 'MC': 'Monaco', 'MN': 'Mongolia', 'ME': 'Montenegro', 'MS': 'Montserrat', 'MA': 'Morocco', 'MZ': 'Mozambique', 'MM': 'Myanmar', 'NA': 'Namibia', 'NR': 'Nauru', 'NP': 'Nepal', 'NL': 'Netherlands', 'AN': 'Netherlands Antilles', 'NC': 'New Caledonia', 'NZ': 'New Zealand', 'NI': 'Nicaragua', 'NE': 'Niger', 'NG': 'Nigeria', 'NU': 'Niue', 'NF': 'Norfolk Island', 'MP': 'Northern Mariana Islands', 'NO': 'Norway', 'OM': 'Oman', 'PK': 'Pakistan', 'PW': 'Palau', 'PS': 'Palestinian Territory, Occupied', 'PA': 'Panama', 'PG': 'Papua New Guinea', 'PY': 'Paraguay', 'PE': 'Peru', 'PH': 'Philippines', 'PN': 'Pitcairn', 'PL': 'Poland', 'PT': 'Portugal', 'PR': 'Puerto Rico', 'QA': 'Qatar', 'RE': 'Reunion', 'RO': 'Romania', 'RU': 'Russian Federation', 'RW': 'Rwanda', 'BL': 'Saint Barthelemy', 'SH': 'Saint Helena', 'KN': 'Saint Kitts And Nevis', 'LC': 'Saint Lucia', 'MF': 'Saint Martin', 'PM': 'Saint Pierre And Miquelon', 'VC': 'Saint Vincent And Grenadines', 'WS': 'Samoa', 'SM': 'San Marino', 'ST': 'Sao Tome And Principe', 'SA': 'Saudi Arabia', 'SN': 'Senegal', 'RS': 'Serbia', 'SC': 'Seychelles', 'SL': 'Sierra Leone', 'SG': 'Singapore', 'SK': 'Slovakia', 'SI': 'Slovenia', 'SB': 'Solomon Islands', 'SO': 'Somalia', 'ZA': 'South Africa', 'GS': 'South Georgia And Sandwich Isl.', 'ES': 'Spain', 'LK': 'Sri Lanka', 'SD': 'Sudan', 'SR': 'Suriname', 'SJ': 'Svalbard And Jan Mayen', 'SZ': 'Swaziland', 'SE': 'Sweden', 'CH': 'Switzerland', 'SY': 'Syrian Arab Republic', 'TW': 'Taiwan', 'TJ': 'Tajikistan', 'TZ': 'Tanzania', 'TH': 'Thailand', 'TL': 'Timor-Leste', 'TG': 'Togo', 'TK': 'Tokelau', 'TO': 'Tonga', 'TT': 'Trinidad And Tobago', 'TN': 'Tunisia', 'TR': 'Turkey', 'TM': 'Turkmenistan', 'TC': 'Turks And Caicos Islands', 'TV': 'Tuvalu', 'UG': 'Uganda', 'UA': 'Ukraine', 'AE': 'United Arab Emirates', 'GB': 'United Kingdom', 'US': 'United States', 'UM': 'United States Outlying Islands', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VU': 'Vanuatu', 'VE': 'Venezuela', 'VN': 'Viet Nam', 'VG': 'Virgin Islands, British', 'VI': 'Virgin Islands, U.S.', 'WF': 'Wallis And Futuna', 'EH': 'Western Sahara', 'YE': 'Yemen', 'ZM': 'Zambia', 'ZW': 'Zimbabwe', 'KP': 'Korea (Democratic Peoples Republic of)', } if (request.POST.get('ivisits_select') == "ivisits"): ivisits = emp_visits.objects.filter(v_type=1).filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-entry_date') ivisits_req = "1" else: ivisits="" ivisits_req = "0" for fvisit in fvisits: fvisit.countryfull = countries[fvisit.country] if (request.POST.get('consymps_select') == "consymps"): consymps = emp_confrence_organised.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') consymps_req = "1" else: consymps="" consymps_req = "0" if (request.POST.get('awards_select') == "awards"): awards = emp_achievement.objects.all().filter(a_year__range=[start,end]).order_by('-date_entry') awards_req = "1" else: awards="" awards_req = "0" if (request.POST.get('talks_select') == "talks"): talks = emp_expert_lectures.objects.all().filter(l_date__year__range=[start,end]).filter(l_date__month__range=[star,en]).order_by('-date_entry') talks_req = "1" else: talks="" talks_req = "0" if (request.POST.get('chairs_select') == "chairs"): chairs = emp_session_chair.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') chairs_req = "1" else: chairs="" chairs_req = "0" if (request.POST.get('keynotes_select') == "keynotes"): keynotes = emp_keynote_address.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-date_entry') keynotes_req = "1" else: keynotes="" keynotes_req = "0" if (request.POST.get('events_select') == "events"): events = emp_event_organized.objects.all().filter(start_date__year__range=[start,end]).filter(start_date__month__range=[star,en]).order_by('-start_date') events_req = "1" else: events="" events_req = "0" pers = get_object_or_404(faculty_about, user = request.user) design = HoldsDesignation.objects.select_related('user','working','designation').filter(working=request.user) desig=[] for i in design: desig.append(str(i.designation)) context = {'user': user, 'pf':pf, 'desig':desig, 'journal':journal, 'journal_req':journal_req, 'conference':
立即成交,限价下单且不能成交的价格,直接撤单 if order["direction"] == "BUY" and price < ask_price or order["direction"] == "SELL" and price > bid_price: order["last_msg"] = "已撤单报单已提交" order["status"] = "FINISHED" if order["status"] == "FINISHED": self._on_order_failed(symbol, order) elif order["direction"] == "BUY" and price >= ask_price or order["direction"] == "SELL" and price <= bid_price: trade_id = order["order_id"] + "|" + str(order["volume_left"]) trade = { "user_id": order["user_id"], "order_id": order["order_id"], "trade_id": trade_id, "exchange_trade_id": order["order_id"] + "|" + str(order["volume_left"]), "exchange_id": order["exchange_id"], "instrument_id": order["instrument_id"], "direction": order["direction"], "offset": order["offset"], "price": price, "volume": order["volume_left"], "trade_date_time": self._get_trade_timestamp(), # todo: 可能导致测试结果不确定 "commission": order["volume_left"] * _get_commission(quote) } self._trades.append(trade) self._send_trade(trade) self._on_order_traded(order, trade, quote, underlying_quote) def _on_order_traded(self, order, trade, quote, underlying_quote): symbol = order["exchange_id"] + "." + order["instrument_id"] origin_frozen_margin = order["frozen_margin"] origin_frozen_premium = order["frozen_premium"] order["frozen_margin"] = 0.0 order["frozen_premium"] = 0.0 order["volume_left"] = 0 order["last_msg"] = "全部成交" order["status"] = "FINISHED" self._send_order(order) position = self._ensure_position(symbol) if order["offset"] == 'OPEN': if order["direction"] == "BUY": # 修改 position 原始字段 position["volume_long_today"] += order["volume_orign"] position["open_cost_long"] += trade["price"] * order["volume_orign"] * quote["volume_multiple"] # 多头开仓成本 position["position_cost_long"] += trade["price"] * order["volume_orign"] * quote["volume_multiple"] # 多头持仓成本 else: # 修改 position 原始字段 position["volume_short_today"] += order["volume_orign"] position["open_cost_short"] += trade["price"] * order["volume_orign"] * quote["volume_multiple"] # 空头开仓成本 position["position_cost_short"] += trade["price"] * order["volume_orign"] * quote["volume_multiple"] # 空头持仓成本 # 由 order 变化,account 需要更新的计算字段 self._adjust_account_by_order(frozen_margin=-origin_frozen_margin, frozen_premium=-origin_frozen_premium) # 由 trade 引起的 account 原始字段变化,account 需要更新的计算字段 premium = _get_premium(trade, quote) self._adjust_account_by_trade(commission=trade["commission"], premium=premium) # 由 position 字段变化,同时 account 需要更新的计算字段 buy_open = order["volume_orign"] if order["direction"] == "BUY" else 0 sell_open = 0 if order["direction"] == "BUY" else order["volume_orign"] self._adjust_position_account(symbol, quote, underlying_quote, pre_last_price=trade["price"], last_price=position["last_price"], pre_underlying_last_price=underlying_quote["last_price"] if underlying_quote else float('nan'), underlying_last_price=position["underlying_last_price"], buy_open=buy_open, sell_open=sell_open) else: # order["offset"].startswith('CLOSE') # 修改 position 原始字段 if order["exchange_id"] in ["SHFE", "INE"]: if order["offset"] == "CLOSETODAY": if order["direction"] == "BUY": position["volume_short_frozen_today"] -= order["volume_orign"] position["volume_short_today"] -= order["volume_orign"] elif order["direction"] == "SELL": position["volume_long_frozen_today"] -= order["volume_orign"] position["volume_long_today"] -= order["volume_orign"] if order["offset"] == "CLOSE": if order["direction"] == "BUY": position["volume_short_frozen_his"] -= order["volume_orign"] position["volume_short_his"] -= order["volume_orign"] elif order["direction"] == "SELL": position["volume_long_frozen_his"] -= order["volume_orign"] position["volume_long_his"] -= order["volume_orign"] elif order["direction"] == "BUY": if position["volume_short_frozen_his"] >= order["volume_orign"]: position["volume_short_frozen_his"] -= order["volume_orign"] position["volume_short_his"] -= order["volume_orign"] else: position["volume_short_frozen_today"] -= order["volume_orign"] - position["volume_short_frozen_his"] position["volume_short_today"] -= order["volume_orign"] - position["volume_short_frozen_his"] position["volume_short_his"] -= position["volume_short_frozen_his"] position["volume_short_frozen_his"] = 0 else: if position["volume_long_frozen_his"] >= order["volume_orign"]: position["volume_long_frozen_his"] -= order["volume_orign"] position["volume_long_his"] -= order["volume_orign"] else: position["volume_long_frozen_today"] -= order["volume_orign"] - position["volume_long_frozen_his"] position["volume_long_today"] -= order["volume_orign"] - position["volume_long_frozen_his"] position["volume_long_his"] -= position["volume_long_frozen_his"] position["volume_long_frozen_his"] = 0 # 修改 position 原始字段 if order["direction"] == "SELL": position["open_cost_long"] -= position["open_price_long"] * order["volume_orign"] * quote["volume_multiple"] # 多头开仓成本 position["position_cost_long"] -= position["position_price_long"] * order["volume_orign"] * quote["volume_multiple"] # 多头持仓成本 else: position["open_cost_short"] -= position["open_price_short"] * order["volume_orign"] * quote["volume_multiple"] # 空头开仓成本 position["position_cost_short"] -= position["position_price_short"] * order["volume_orign"] * quote["volume_multiple"] # 空头持仓成本 # 由 trade 引起的 account 原始字段变化,account 需要更新的计算字段 premium = _get_premium(trade, quote) close_profit = _get_close_profit(trade, quote, position) self._adjust_account_by_trade(commission=trade["commission"], premium=premium, close_profit=close_profit) # 由 position 字段变化,同时 account 需要更新的计算字段 buy_close = order["volume_orign"] if order["direction"] == "BUY" else 0 sell_close = 0 if order["direction"] == "BUY" else order["volume_orign"] self._adjust_position_account(symbol, quote, underlying_quote, pre_last_price=position["last_price"], last_price=0, pre_underlying_last_price=position["underlying_last_price"], underlying_last_price=0, buy_close=buy_close, sell_close=sell_close) self._send_position(position) self._send_account() def _on_order_failed(self, symbol, order): origin_frozen_margin = order["frozen_margin"] origin_frozen_premium = order["frozen_premium"] order["frozen_margin"] = 0.0 order["frozen_premium"] = 0.0 self._send_order(order) # 调整账户和持仓 if order["offset"] == 'OPEN': self._adjust_account_by_order(frozen_margin=-origin_frozen_margin, frozen_premium=-origin_frozen_premium) self._send_account() else: position = self._positions[symbol] if order["exchange_id"] in ["SHFE", "INE"]: if order["offset"] == "CLOSETODAY": if order["direction"] == "BUY": position["volume_short_frozen_today"] -= order["volume_orign"] else: position["volume_long_frozen_today"] -= order["volume_orign"] if order["offset"] == "CLOSE": if order["direction"] == "BUY": position["volume_short_frozen_his"] -= order["volume_orign"] else: position["volume_long_frozen_his"] -= order["volume_orign"] else: if order["direction"] == "BUY": if position["volume_short_frozen_today"] >= order["volume_orign"]: position["volume_short_frozen_today"] -= order["volume_orign"] else: position["volume_short_frozen_his"] -= order["volume_orign"] - position["volume_short_frozen_today"] position["volume_short_frozen_today"] = 0 else: if position["volume_long_frozen_today"] >= order["volume_orign"]: position["volume_long_frozen_today"] -= order["volume_orign"] else: position["volume_long_frozen_his"] -= order["volume_orign"] - position["volume_long_frozen_today"] position["volume_long_frozen_today"] = 0 self._adjust_position_volume_frozen(position) self._send_position(position) def _adjust_position_account(self, symbol, quote, underlying_quote=None, pre_last_price=float('nan'), last_price=float('nan'), pre_underlying_last_price=float('nan'), underlying_last_price=float('nan'), buy_open=0, buy_close=0, sell_open=0, sell_close=0): """ 价格变化,使得 position 中的以下计算字段需要修改,这个函数计算出需要修改的差值部分,计算出差值部分修改 position、account 有两种情况下调用 1. 委托单 FINISHED,且全部成交,分为4种:buy_open, buy_close, sell_open, sell_close 2. 行情跳动 """ position = self._positions[symbol] float_profit_long = 0 # 多头浮动盈亏 float_profit_short = 0 # 空头浮动盈亏 position_profit_long = 0 # 多头持仓盈亏,期权持仓盈亏为0 position_profit_short = 0 # 空头持仓盈亏,期权持仓盈亏为0 margin_long = 0 # 多头占用保证金 margin_short = 0 # 空头占用保证金 market_value_long = 0 # 期权权利方市值(始终 >= 0) market_value_short = 0 # 期权义务方市值(始终 <= 0) assert [buy_open, buy_close, sell_open, sell_close].count(0) >= 3 # 只有一个大于0, 或者都是0,表示价格变化导致的字段修改 if buy_open > 0: # 买开,pre_last_price 应该是成交价格,last_price 应该是 position['last_price'] float_profit_long = (last_price - pre_last_price) * buy_open * quote["volume_multiple"] if quote["ins_class"].endswith("OPTION"): market_value_long = last_price * buy_open * quote["volume_multiple"] else: margin_long = buy_open * _get_future_margin(quote) position_profit_long = (last_price - pre_last_price) * buy_open * quote["volume_multiple"] elif sell_close > 0: # 卖平,pre_last_price 应该是 position['last_price'],last_price 应该是 0 float_profit_long = -position["float_profit_long"] / position["volume_long"] * sell_close if quote["ins_class"].endswith("OPTION"): market_value_long = -pre_last_price * sell_close * quote["volume_multiple"] else: margin_long = -sell_close * _get_future_margin(quote) position_profit_long = -position["position_profit_long"] / position["volume_long"] * sell_close elif sell_open > 0: # 卖开 float_profit_short = (pre_last_price - last_price) * sell_open * quote["volume_multiple"] if quote["ins_class"].endswith("OPTION"): market_value_short = -last_price * sell_open * quote["volume_multiple"] margin_short = sell_open * _get_option_margin(quote, last_price, underlying_last_price) else: margin_short = sell_open * _get_future_margin(quote) position_profit_short = (pre_last_price - last_price) * sell_open * quote["volume_multiple"] elif buy_close > 0: # 买平 float_profit_short = -position["float_profit_short"] / position["volume_short"] * buy_close if quote["ins_class"].endswith("OPTION"): market_value_short = pre_last_price * buy_close * quote["volume_multiple"] margin_short = -buy_close * _get_option_margin(quote, pre_last_price, pre_underlying_last_price) else: margin_short = -buy_close * _get_future_margin(quote) position_profit_short = -position["position_profit_short"] / position["volume_short"] * buy_close else: float_profit_long = (last_price - pre_last_price) * position["volume_long"] * quote["volume_multiple"] # 多头浮动盈亏 float_profit_short = (pre_last_price - last_price) * position["volume_short"] * quote["volume_multiple"] # 空头浮动盈亏 if quote["ins_class"].endswith("OPTION"): margin_short = _get_option_margin(quote, last_price, underlying_last_price) * position["volume_short"] - position["margin_short"] market_value_long = (last_price - pre_last_price) * position["volume_long"] * quote["volume_multiple"] market_value_short = (pre_last_price - last_price) * position["volume_short"] * quote["volume_multiple"] else: # 期权持仓盈亏为 0 position_profit_long = float_profit_long # 多头持仓盈亏 position_profit_short = float_profit_short # 空头持仓盈亏 margin_long = _get_future_margin(quote) * position["volume_long"] - position["margin_long"] margin_short = _get_future_margin(quote) * position["volume_short"] - position["margin_short"] if any([buy_open, buy_close, sell_open, sell_close]): # 修改 position volume 相关的计算字段 # 在上面 sell_close buy_close 两种情况,计算浮动盈亏时,用到了修改前的手数,所以需改手数字段的代码放在这个位置 self._adjust_position_volume(position) self._adjust_position(quote, position, float_profit_long, float_profit_short, position_profit_long, position_profit_short, margin_long, margin_short, market_value_long, market_value_short) self._adjust_account_by_position(float_profit=float_profit_long + float_profit_short, position_profit=position_profit_long + position_profit_short, margin=margin_long + margin_short, market_value=market_value_long + market_value_short) # -------- 对于 position 的计算字段修改分为两类: # 1. 针对手数相关的修改,在下单、成交时会修改 # 2. 针对盈亏、保证金、市值的修改,由于参考合约最新价,在成交、行情跳动时会修改 def _adjust_position_volume_frozen(self, position): """position 原始字段修改后,只有冻结手数需要重新计算,有两种情况需要调用 1. 下平仓单 2. 平仓单 FINISHED, 但没有成交 """ position["volume_long_frozen"] = position["volume_long_frozen_today"] + position["volume_long_frozen_his"] position["volume_short_frozen"] = position["volume_short_frozen_today"] + position["volume_short_frozen_his"] def _adjust_position_volume(self, position): """position 原始字段修改后,手数之后需要重新计算 1. 委托单 FINISHED,且全部成交 """ position["pos_long_today"] = position["volume_long_today"] position["pos_long_his"] = position["volume_long_his"] position["pos_short_today"] = position["volume_short_today"] position["pos_short_his"] = position["volume_short_his"] position["volume_long"] = position["volume_long_today"] + position["volume_long_his"] position["volume_long_frozen"] = position["volume_long_frozen_today"] + position["volume_long_frozen_his"] position["volume_short"] = position["volume_short_today"] + position["volume_short_his"] position["volume_short_frozen"] = position["volume_short_frozen_today"] + position["volume_short_frozen_his"] def _adjust_position(self, quote, position, float_profit_long=0, float_profit_short=0, position_profit_long=0, position_profit_short=0, margin_long=0, margin_short=0, market_value_long=0, market_value_short=0): # 更新 position 计算字段,根据差值更新的字段 position["float_profit_long"] += float_profit_long position["float_profit_short"] += float_profit_short position["position_profit_long"] += position_profit_long position["position_profit_short"] += position_profit_short position["margin_long"] += margin_long position["margin_short"] += margin_short position["market_value_long"] += market_value_long position["market_value_short"] += market_value_short # 更新 position 计算字段,原地重新计算的字段 if position["volume_long"] > 0: position["open_price_long"] = position["open_cost_long"] / position["volume_long"] / quote["volume_multiple"] position["position_price_long"] = position["position_cost_long"] / position["volume_long"] / quote["volume_multiple"] else: position["open_price_long"] = float("nan") position["position_price_long"] = float("nan") if position["volume_short"] > 0: position["open_price_short"] = position["open_cost_short"] / position["volume_short"] / quote["volume_multiple"] position["position_price_short"] = position["position_cost_short"] / position["volume_short"] / quote["volume_multiple"] else: position["open_price_short"] = float("nan") position["position_price_short"] = float("nan") position["float_profit"] = position["float_profit_long"] + position["float_profit_short"] position["position_profit"] = position["position_profit_long"] + position["position_profit_short"] position["margin"] = position["margin_long"] + position["margin_short"] position["market_value"] = position["market_value_long"] + position["market_value_short"] # -------- 对于 account 的修改分为以下三类 def _adjust_account_by_trade(self, commission=0, close_profit=0, premium=0): """由成交引起的 account 原始字段变化,account 需要更新的计算字段""" # account 原始字段 self._account["close_profit"] += close_profit self._account["commission"] += commission self._account["premium"] += premium # premium变量的值有正负,正数表示收入的权利金,负数表示付出的权利金 # account 计算字段 self._account["balance"] += close_profit - commission + premium self._account["available"] += close_profit - commission + premium self._account["risk_ratio"] = self._account["margin"] / self._account["balance"] def _adjust_account_by_position(self, float_profit=0, position_profit=0, margin=0, market_value=0): """由 position 变化,account 需要更新的计算字段""" # account 计算字段,持仓字段求和的字段 self._account["float_profit"] += float_profit self._account["position_profit"] += position_profit self._account["margin"] += margin self._account["market_value"] += market_value # account 计算字段 self._account["balance"] += position_profit + market_value self._account["available"] += position_profit - margin self._account["risk_ratio"] = self._account["margin"] / self._account["balance"] def _adjust_account_by_order(self, frozen_margin=0, frozen_premium=0): """由 order 变化,account 需要更新的计算字段""" self._account["frozen_margin"] += frozen_margin self._account["frozen_premium"] += frozen_premium self._account["available"] -= (frozen_margin + frozen_premium) def _send_trade(self, trade): self._diffs.append({ "trade": { self._account_key: { "trades": { trade["trade_id"]: trade.copy() } } } }) def _send_order(self, order): self._diffs.append({ "trade": { self._account_key: { "orders": { order["order_id"]: order.copy() } } } }) def _send_position(self, position): self._diffs.append({
import os import sys sys.path.append(os.getcwd()) import cv2 import numpy as np import torch from ..dataset.mot import MOTTracking, collate_fn, read_mot_file from ..configs.config import load_config from ..utils.log import log_or_print, get_logger def voc_color_code(num_colors=100): def to_binary(val, idx): return ((val & (1 << idx)) != 0) color_code = np.zeros((num_colors, 3), dtype=np.uint8) for i in range(num_colors): r = g = b = 0 c = i for j in range(8): r |= (to_binary(c, 0) << 7 - j) g |= (to_binary(c, 1) << 7 - j) b |= (to_binary(c, 2) << 7 - j) c >>= 3 color_code[i, :] = [r, g, b] return color_code def plot_boxes( frame, boxes, obj_ids=None, show_ids=True, scores=None, show_scores=False, polygons=None, show_polygons=False, masks=None, show_masks=False, show_info=False, frame_id=0, image_scale=1, text_scale=2, line_thickness=2, fps=0. ): """ Draw a frame with bounding boxes """ im = np.copy(frame) im_h, im_w = im.shape[:2] # Determin colors first: colors = [] for i in range(len(boxes)): if obj_ids is None: colors.append((255, 0, 0)) else: obj_id = obj_ids[i] # color = get_color(abs(int(obj_id))) colors.append(tuple([int(c) for c in voc_color_code(256)[abs(int(obj_id)) % 256]])) # Draw masks first # Input should be K x H x W of float, where K is number of objects if masks is not None and show_masks: final_mask = np.zeros_like(im, dtype=np.uint8) for i, mask in enumerate(masks): mask = np.expand_dims(masks[i], axis=-1) final_mask += np.uint8(np.concatenate((mask * colors[i][0], mask * colors[i][1], mask * colors[i][2]), axis=-1)) im = cv2.addWeighted(im, 0.77, final_mask, 0.5, -1) for i, box in enumerate(boxes): if obj_ids is not None: obj_id = obj_ids[i] else: obj_id = None x1, y1, x2, y2 = box intbox = tuple(map(int, (x1, y1, x2, y2))) # Draw box if not show_polygons: cv2.rectangle(im, intbox[0:2], intbox[2:4], color=colors[i], thickness=line_thickness) # Draw Polygons polygon = None if polygons is not None and show_polygons: polygon = polygons[i] if polygon is not None: cv2.polylines(im, [polygon.reshape((-1, 1, 2))], True, (0, 255, 0), 3) # Draw id at top-left corner of box if obj_id is not None and show_ids: cv2.putText(im, f"{obj_id:d}", (int(x1), int(y1) + 20), cv2.FONT_HERSHEY_PLAIN, text_scale * 0.6, (0, 255, 255), thickness=1) # Draw scores at bottom-left corner of box score = None if scores is not None and show_scores: score = scores[i] cv2.putText(im, f"{score:.4f}", (int(x1), int(y2) - 20), cv2.FONT_HERSHEY_PLAIN, text_scale * 0.6, (0, 255, 255), thickness=1) if show_info: cv2.putText(im, "frame: %d fps: %.2f num: %d" % (frame_id, fps, len(boxes)), (0, int(15 * text_scale)), cv2.FONT_HERSHEY_PLAIN, text_scale, (0, 0, 255), thickness=2) # Resize im = cv2.resize(im, (int(im_w * image_scale), int(im_h * image_scale))) return im def get_color(idx): idx = idx * 3 color = ((37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255) return color class Content(object): def __init__(self): self.list = ["GT", "DET", "RESULT"] self.current = self.list[0] def next(self): self.current = self.list[(self.list.index(self.current) + 1) % len(self.list)] def show_mot( dataloader, dataset_root="../datasets", dataset="MOT17", which_set="train", sequence="MOT17-FRCNN-02", vis_threshold=0.1, result_root="output/results", result=None, start_frame=1, scale=1.0, ): """ Visualize MOT detections/ground truths/tracking results """ content = Content() hide_info = False hide_ids = False save_image = False save_dir = "./output/images" if not os.path.isdir(save_dir): os.makedirs(save_dir) # Load data include_result = False if result is not None: include_result = True result_path = os.path.join(result_root, dataset, result, f"{sequence}.txt") assert os.path.isfile(result_path), f"No valid result file found at '{result_path}'" log_or_print(logger, f"Loaded result file at '{result_path}'") # Load all data at once and store det_by_frame = [] gt_by_frame = [] result_by_frame = [] for frame_id, batch in enumerate(dataloader): frame_id += 1 # Start from 1 # Get MOT data _, det_boxes, det_scores, gt_boxes, gt_ids, gt_visibilities = batch # Make a detached copy to stop dataloader from using file det_boxes = det_boxes[0].detach().clone().cpu().numpy() det_scores = det_scores[0].detach().clone().cpu().numpy() gt_boxes = gt_boxes[0].detach().clone().cpu().numpy() gt_ids = gt_ids[0].detach().cpu().clone().numpy() gt_visibilities = gt_visibilities[0].detach().clone().cpu().numpy() del batch # Detections det_by_frame.append((det_boxes, det_scores)) # GT if gt_boxes is not None: # In case of test sets gt_boxes = [gt_box for i, gt_box in enumerate(gt_boxes) if gt_visibilities[i] > vis_threshold] gt_ids = [gt_id for i, gt_id in enumerate(gt_ids) if gt_visibilities[i] > vis_threshold] gt_visibilities = [gt_visibility for i, gt_visibility in enumerate(gt_visibilities) if gt_visibilities[i] > vis_threshold] gt_by_frame.append((gt_boxes, gt_ids, gt_visibilities)) else: gt_by_frame.append(([], [], [])) # Result if include_result: result_boxes, result_ids, result_scores, _ = read_mot_file(result_path, frame_id) # In case no result for the frame, empty lists are returned in that case if len(result_boxes) and len(result_ids) and len(result_scores): result_boxes = result_boxes.cpu().numpy() result_ids = result_ids.cpu().numpy() result_scores = result_scores.cpu().numpy() result_by_frame.append((result_boxes, result_scores, result_ids)) else: result_by_frame.append(([], [], [])) # Load images image_dir = os.path.join(dataset_root, dataset, which_set, sequence, "img1") file_list = os.listdir(image_dir) def get_index(x_str): return x_str[:-4] file_list = sorted(file_list, key=get_index) # Show window_name = f"MOT Visualization - {sequence}" frame_id = start_frame filename = file_list[frame_id - 1] im = draw_frame(image_dir, filename, frame_id, det_by_frame[frame_id - 1], gt_by_frame[frame_id - 1], result_by_frame[frame_id - 1], content.current, hide_info, hide_ids, scale) while True: cv2.imshow(window_name, im) # Save if toggled if save_image: cv2.imwrite(os.path.join(save_dir, f"{sequence}-{content.current}-{filename.split('.')[0]}.jpg"), im) key = cv2.waitKey(0) # Prev frame, press Key "<" if key == 44: frame_id = (frame_id - 1) % len(file_list) if frame_id == 0: frame_id = len(file_list) filename = file_list[frame_id - 1] im = draw_frame(image_dir, filename, frame_id, det_by_frame[frame_id - 1], gt_by_frame[frame_id - 1], result_by_frame[frame_id - 1], content.current, hide_info, hide_ids, scale) # Next frame, press Key ">" elif key == 46: frame_id = (frame_id + 1) % len(file_list) if frame_id == 0: frame_id = len(file_list) filename = file_list[frame_id - 1] im = draw_frame(image_dir, filename, frame_id, det_by_frame[frame_id - 1], gt_by_frame[frame_id - 1], result_by_frame[frame_id - 1], content.current, hide_info, hide_ids, scale) # Exit, press Key "q" or Esc elif key == 113 or key == 27: break # Other options else: # Rotate among GT, DET, RESULT, press Key "t" if key == 116: content.next() # Save crops, press Key "c" elif key == 99: if content.current == "GT": boxes_info = gt_by_frame[frame_id - 1] elif content.current == "DET": boxes_info = det_by_frame[frame_id - 1] elif content.current == "RESULT": boxes_info = result_by_frame[frame_id - 1] save_crops(image_dir, filename, frame_id, boxes_info, content.current, save_dir, sequence) # Save image, press key "s" elif key == 115: save_image = not save_image # Hide info in image, press key "h" elif key == 104: hide_info = not hide_info # Hide ids in image, press key "i" elif key == 105: hide_ids = not hide_ids im = draw_frame(image_dir, filename, frame_id, det_by_frame[frame_id - 1], gt_by_frame[frame_id - 1], result_by_frame[frame_id - 1], content.current, hide_info, hide_ids, scale) def draw_frame( image_dir, filename, frame_id, detections, groundtruths, results, content_selection, hide_info, hide_ids, scale ): """ Draw a frame with given detections/ground truths/results """ im = cv2.imread(os.path.join(image_dir, filename)) content_info_position = (0, 22) content_info_color = (0, 255, 255) content_info_thickness = 2 if content_selection == "DET": if not hide_info: cv2.putText(im, f"Frame: {frame_id:5d} Detections", content_info_position, cv2.FONT_HERSHEY_PLAIN, content_info_thickness, content_info_color, thickness=2) im = plot_boxes(im, detections[0], scores=detections[1], show_scores=True, image_scale=scale) elif content_selection == "GT": if not hide_info: cv2.putText(im, f"Frame: {frame_id:5d} Grount Truths", content_info_position, cv2.FONT_HERSHEY_PLAIN, content_info_thickness, content_info_color, thickness=2) im = plot_boxes(im, groundtruths[0], obj_ids=groundtruths[1], show_ids=not hide_ids, scores=groundtruths[2], show_scores=True, image_scale=scale) elif content_selection == "RESULT": if not hide_info: cv2.putText(im, f"Frame: {frame_id:5d} Results", content_info_position, cv2.FONT_HERSHEY_PLAIN, content_info_thickness, content_info_color, thickness=2) im = plot_boxes(im, results[0], scores=results[1], obj_ids=results[2], show_ids=not hide_ids, image_scale=scale) return im def save_crops(image_dir, filename, frame_id, boxes_info, content, save_dir, sequence): im = cv2.imread(os.path.join(image_dir, filename)) height, width = im.shape[:2] try: for i, box in enumerate(boxes_info[0]): log_or_print(logger, f"ID {boxes_info[1][i]} box: {boxes_info[0][i]}") crop = im[max(0, int(box[1])):min(height, int(box[1] + box[3])), max(0, int(box[0])):min(width, int(box[0] + box[2])), :] cv2.imwrite(os.path.join(save_dir, f"{sequence}-{content}-FRAME-{frame_id}-ID-{boxes_info[1][i]}.jpg"), crop) except Exception: log_or_print(logger, "No bounding boxes in current content", level="warning") if __name__ == "__main__": """ Run a visualization demo with parameters """ # arguments import argparse parser = argparse.ArgumentParser(description="MOT Visualization") parser.add_argument("--config", default="TADAM_MOT17", type=str, help="config file to load") parser.add_argument("--which-set", default="train", type=str, choices=["train", "test"], help="which sequence") parser.add_argument("--sequence", default="02", type=str, help="which sequence") parser.add_argument("--public-detection", default="FRCNN", type=str, choices=["None", "DPM", "FRCNN", "SDP"], help="public detection") parser.add_argument("--result", default=None, type=str, help="name for loading results") parser.add_argument("--start-frame", default=1, type=int, help="start frame") parser.add_argument("--scale", default=1, type=float, help="visual size of image") parser.add_argument("--vis_threshold", default=0.1, type=float, help="visibility threshold for gt") args = parser.parse_args() config, cfg_msg = load_config(args.config) logger = get_logger(name="global", save_file=False, console_verbose=False) log_or_print(logger, cfg_msg) public_detection = args.public_detection if config.NAMES.DATASET == "MOT17" else "None" dataloader = torch.utils.data.DataLoader(MOTTracking(config.PATHS.DATASET_ROOT, config.NAMES.DATASET, args.which_set, args.sequence, public_detection, args.vis_threshold), batch_size=1, shuffle=False, num_workers=4, collate_fn=collate_fn) public_detection = f"-{public_detection}" if public_detection != "None" else "" sequence = f"{config.NAMES.DATASET}-{int(args.sequence):02d}{public_detection}" # Show info log_or_print(logger, f"Showing {config.NAMES.DATASET}/{args.which_set}/{sequence}") show_mot(dataloader, config.PATHS.DATASET_ROOT,
'node', 'name', 'role') return key_attrs(self) == key_attrs(other) return NotImplemented def _populate_from_attributes(self, attributes): """Fills in an object with the desired attributes. """ self.serial = str(attributes['serial']) self.model = str(attributes['model']) self.dn = str(attributes['dn']) self.vendor = str(attributes['vendor']) self.fabricSt = str(attributes['fabricSt']) self.modify_time = str(attributes['modTs']) def _get_topsystem_info(self, working_data): """ will read in topSystem object to get more information about Node""" node_data = working_data.get_object(self.dn + '/sys') if node_data is not None: if 'topSystem' in node_data: self.ipAddress = str(node_data['topSystem']['attributes']['address']) self.tep_ip = self.ipAddress self.macAddress = str(node_data['topSystem']['attributes']['fabricMAC']) self.state = str(node_data['topSystem']['attributes']['state']) self.mode = str(node_data['topSystem']['attributes']['mode']) self.oob_mgmt_ip = str(node_data['topSystem']['attributes'].get('oobMgmtAddr')) self.inb_mgmt_ip = str(node_data['topSystem']['attributes'].get('inbMgmtAddr')) self.system_uptime = str(node_data['topSystem']['attributes'].get('systemUpTime')) # now get eqptCh for even more info node_data = working_data.get_object(self.dn + '/sys/ch') if node_data: if 'eqptCh' in node_data: self.oper_st = str(node_data['eqptCh']['attributes']['operSt']) self.operStQual = str(node_data['eqptCh']['attributes']['operStQual']) self.descr = str(node_data['eqptCh']['attributes']['descr']) # get the total number of ports = number of l1PhysIf node_data = working_data.get_subtree('l1PhysIf', self.dn + '/sys') if node_data: self.num_ports = str(len(node_data)) # get the total number of ports = number of fan slots node_data = working_data.get_subtree('eqptFtSlot', self.dn + '/sys') if node_data: self.num_fan_slots = str(len(node_data)) self.num_fan_modules = 0 if node_data: for slot in node_data: if slot['eqptFtSlot']['attributes']['operSt'] == 'inserted': self.num_fan_modules += 1 self.num_fan_modules = str(self.num_fan_modules) # get the total number of ports = number of linecard slots node_data = working_data.get_subtree('eqptLCSlot', self.dn + '/sys/ch') self.num_lc_slots = str(len(node_data)) self.num_lc_modules = 0 if node_data: for slot in node_data: if slot['eqptLCSlot']['attributes']['operSt'] == 'inserted': self.num_lc_modules += 1 self.num_lc_modules = str(self.num_lc_modules) # get the total number of ports = number of power supply slots node_data = working_data.get_subtree('eqptPsuSlot', self.dn + '/sys/ch') self.num_ps_slots = str(len(node_data)) self.num_ps_modules = 0 if node_data: for slot in node_data: if slot['eqptPsuSlot']['attributes']['operSt'] == 'inserted': self.num_ps_modules += 1 self.num_ps_modules = str(self.num_ps_modules) # get the total number of ports = number of supervisor slots node_data = working_data.get_subtree('eqptSupCSlot', self.dn + '/sys/ch') self.num_sup_slots = str(len(node_data)) self.num_sup_modules = 0 if node_data: for slot in node_data: if slot['eqptSupCSlot']['attributes']['operSt'] == 'inserted': self.num_sup_modules += 1 self.num_sup_modules = str(self.num_sup_modules) # get dynamic load balancing config self.dynamic_load_balancing_mode = 'unknown' lb_data = working_data.get_subtree('eqptSupCSlot', self.dn + '/sys') for lb_info in lb_data: if 'topoctrlLbP' in lb_info: self.dynamic_load_balancing_mode = lb_info['topoctrlLbP']['attributes']['dlbMode'] # get vxlan info self.ivxlan_udp_port = 'unknown' # node_data = working_data.get_subtree('topoctrlVxlanP', self.dn + '/sys') # for info in node_data: # if 'topoctrlVxlanP' in info: # self.ivxlan_udp_port = info['topoctrlVxlanP']['attributes']['udpPort'] @property def operSt(self): """ changed value to "oper_st" so this makes the class backward compatible :return: """ return self.oper_st def populate_children(self, deep=False, include_concrete=False): """Will populate all of the children modules such as linecards, fantrays and powersupplies, of the node. :param deep: boolean that when true will cause the entire sub-tree to be populated. When false, only the immediate children are populated :param include_concrete: boolean to indicate that concrete objects should also be populated :returns: List of children objects """ session = self._session for child_class in self._get_children_classes(): child_class.get(session, self) if include_concrete and self.role != 'controller': # todo: currently only have concrete model for switches - need to add controller query_url = '/api/mo/topology/pod-' + self.pod + '/node-' + self.node + \ '/sys.json?' working_data = WorkingData(session, Node, query_url, deep=True, include_concrete=True) for concrete_class in self._get_children_concrete_classes(): concrete_class.get(working_data, self) if deep: for child in self._children: child.populate_children(deep, include_concrete) return self._children def get_chassis_type(self): """Returns the chassis type of this node. The chassis type is derived from the model number. This is a chassis type that is compatible with Cisco's Cable Plan XML. :returns: chassis type of node of type str """ if self.model: fields = self.model.split('-') chassis_type = fields[0].lower() else: chassis_type = None return chassis_type @staticmethod def get_table(switches, title=''): """ Creates report of basic switch information :param switches: Array of Node objects :param title: optional title for this table """ headers = ['Name', 'Pod ID', 'Node ID', 'Serial Number', 'Model', 'Role', 'Fabric State', 'State', 'Firmware', 'Health', 'In-band managment IP', 'Out-of-band managment IP', 'Number of ports', 'Number of Linecards (inserted)', 'Number of Sups (inserted)', 'Number of Fans (inserted)', 'Number of Power Supplies (inserted)', 'System Uptime', 'Dynamic Load Balancing'] table = [] for switch in sorted(switches, key=attrgetter('node')): table.append([switch.name, switch.pod, switch.node, switch.serial, switch.model, switch.role, switch.fabricSt, switch.state, switch.firmware, switch.health, switch.inb_mgmt_ip, switch.oob_mgmt_ip, switch.num_ports, str(switch.num_lc_slots) + '(' + str(switch.num_lc_modules) + ')', str(switch.num_sup_slots) + '(' + str(switch.num_sup_modules) + ')', str(switch.num_fan_slots) + '(' + str(switch.num_fan_modules) + ')', str(switch.num_ps_slots) + '(' + str(switch.num_ps_modules) + ')', switch.system_uptime, switch.dynamic_load_balancing_mode]) if len(table) > 7: table_orientation = 'horizontal' else: table_orientation = 'vertical' if len(table) > 3: columns = 1 else: columns = 2 result = [Table(table, headers, title=str(title) + '' if (title != '') else '' + 'Basic Information', table_orientation=table_orientation, columns=columns)] return result def _define_searchables(self): """ Create all of the searchable terms :rtype : list of Searchable """ results = super(Node, self)._define_searchables() if self.role != 'controller': results[0].add_term('switch', self.name) results[0].add_term('switch', self.node) else: results[0].add_term('controller', self.name) results[0].add_term('controller', self.node) results[0].add_term('apic', self.name) results[0].add_term('apic', self.node) results[0].add_term('ipv4', self.inb_mgmt_ip) results[0].add_term('ipv4', self.oob_mgmt_ip) results[0].add_term('ipv4', str(self.tep_ip)) results[0].add_term('management', self.inb_mgmt_ip) results[0].add_term('management', self.oob_mgmt_ip) return results class ExternalSwitch(BaseACIPhysObject): """External Node. This class is for switch nodes that are connected to the pod, but are not ACI nodes, i.e. are not under control of the APIC. Examples would be external layer 2 switches, external routers, or hypervisor based switches. This class will look as much as possible like the Node class recognizing that not as much information is available to the APIC about them as is available about ACI nodes. Nearly all of the information used to create this class comes from LLDP. """ def __init__(self, name=None, parent=None): self.check_parent(parent) self._parent = parent self._role = None self.dn = None self.name = None self.ip = None self.mac = None self.id = None self.pod = None self.status = None self.oper_issues = None self.fabric_st = 'external' self.role = 'external_switch' self.descr = None self.type = None self.state = None self.guid = None self.oid = None super(ExternalSwitch, self).__init__(name=name, parent=parent) @classmethod def _get_parent_class(cls): """ Gets the acitoolkit class of the parent object Meant to be overridden by inheriting classes. Raises exception if not overridden. :returns: class of parent object """ return Pod @staticmethod def _get_parent_dn(dn): """ Gets the dn of the parent object Meant to be overridden by inheriting classes. Raises exception if not overridden. :returns: string containing dn """ if 'comp/' in dn: return dn.split('comp/prov-VMware/ctrlr-[DC1]-vcenter1/hv-')[0] else: return dn.split('topology/lsnode-')[0] @staticmethod def _get_name_from_dn(dn): if 'comp/' in dn: name = dn.split('comp/prov-VMware/ctrlr-[DC1]-vcenter1/hv-')[1] else: name = dn.split('topology/lsnode-')[1] return name @classmethod def _get_apic_classes(cls): """ returns list of all apic classes used to build this toolkit class :return: """ return ['fabricLooseNode', 'compHv', 'fabricLooseLink', 'pcAggrIf', 'fabricProtLooseLink', 'pcRsMbrIfs', 'lldpAdjEp'] def getRole(self): """ retrieves the node role :returns: role """ return self.role @property def role(self): """ Getter for role. :return: role """ return self._role @role.setter def role(self, value): """ Setter for role. Will check that only valid roles are used :param value: role :return:None """ valid_roles = [None, 'external_switch'] if value not in valid_roles: raise ValueError("role must be one of " + str(valid_roles) + ' found ' + str(value)) self._role = value @classmethod def get_event(cls, session): """ not yet fully implemented """ urls = cls._get_subscription_urls() for url in urls: if not session.has_events(url): continue event = session.get_event(url) for class_name in cls._get_apic_classes(): if class_name in event['imdata'][0]: break if class_name == "fabricLooseNode" or class_name == "compHv": attributes = event['imdata'][0][class_name]['attributes'] status = str(attributes['status']) dn = str(attributes['dn']) if status == 'created': name = str(attributes['name']) else: name = cls._get_name_from_dn(dn) obj = cls(name, parent=None) if url == "/api/class/fabricLooseNode.json?subscription=yes": obj._populate_physical_from_attributes(attributes) elif url == "/api/class/compHv.json?subscription=yes": obj._populate_virtual_from_attributes(attributes) obj._get_system_info(session) if status == 'deleted': obj.mark_as_deleted() return obj return @classmethod def _get_physical_switches(cls, session, parent): """Look for loose nodes and build an object for each one. """ # if parent: # if not isinstance(parent, Topology): # raise TypeError('An instance of Topology class is required') lnode_query_url = ('/api/node/class/fabricLooseNode.json?' 'query-target=self') lnodes = [] ret = session.get(lnode_query_url) lnode_data = ret.json()['imdata'] for apic_node in lnode_data: if 'fabricLooseNode' in apic_node: external_switch = cls(apic_node['fabricLooseNode']['attributes']['sysName']) external_switch._populate_physical_from_attributes(apic_node['fabricLooseNode']['attributes']) external_switch._get_system_info(session) if parent: if isinstance(parent, cls._get_parent_class()): external_switch._parent = parent external_switch._parent.add_child(external_switch) lnodes.append(external_switch) return lnodes def _populate_physical_from_attributes(self, attr): self.dn = str(attr['dn']) self.name = str(attr['sysName']) self.id = str(attr['id']) self.status = str(attr['status']) self.oper_issues = str(attr['operIssues']) self.descr = str(attr['sysDesc']) @classmethod def _get_virtual_switches(cls, session, parent): """will
'Name') value_ = self.gds_validate_string(value_, node, 'Name') self.Name = value_ self.Name_nsprefix_ = child_.prefix elif nodeName_ == 'Answer': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'Answer') value_ = self.gds_validate_string(value_, node, 'Answer') self.Answer = value_ self.Answer_nsprefix_ = child_.prefix # end class AnswerType class ProductChargesType(GeneratedsSuper): __hash__ = GeneratedsSuper.__hash__ subclass = None superclass = None def __init__(self, Duties=None, TaxesAndFees=None, VAT=None, CostOfGoods=None, SubTotal=None, gds_collector_=None, **kwargs_): self.gds_collector_ = gds_collector_ self.gds_elementtree_node_ = None self.original_tagname_ = None self.parent_object_ = kwargs_.get('parent_object_') self.ns_prefix_ = None self.Duties = Duties self.Duties_nsprefix_ = None self.TaxesAndFees = TaxesAndFees self.TaxesAndFees_nsprefix_ = None self.VAT = VAT self.VAT_nsprefix_ = None self.CostOfGoods = CostOfGoods self.CostOfGoods_nsprefix_ = None self.SubTotal = SubTotal self.SubTotal_nsprefix_ = None def factory(*args_, **kwargs_): if CurrentSubclassModule_ is not None: subclass = getSubclassFromModule_( CurrentSubclassModule_, ProductChargesType) if subclass is not None: return subclass(*args_, **kwargs_) if ProductChargesType.subclass: return ProductChargesType.subclass(*args_, **kwargs_) else: return ProductChargesType(*args_, **kwargs_) factory = staticmethod(factory) def get_ns_prefix_(self): return self.ns_prefix_ def set_ns_prefix_(self, ns_prefix): self.ns_prefix_ = ns_prefix def get_Duties(self): return self.Duties def set_Duties(self, Duties): self.Duties = Duties def get_TaxesAndFees(self): return self.TaxesAndFees def set_TaxesAndFees(self, TaxesAndFees): self.TaxesAndFees = TaxesAndFees def get_VAT(self): return self.VAT def set_VAT(self, VAT): self.VAT = VAT def get_CostOfGoods(self): return self.CostOfGoods def set_CostOfGoods(self, CostOfGoods): self.CostOfGoods = CostOfGoods def get_SubTotal(self): return self.SubTotal def set_SubTotal(self, SubTotal): self.SubTotal = SubTotal def hasContent_(self): if ( self.Duties is not None or self.TaxesAndFees is not None or self.VAT is not None or self.CostOfGoods is not None or self.SubTotal is not None ): return True else: return False def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ProductChargesType', pretty_print=True): imported_ns_def_ = GenerateDSNamespaceDefs_.get('ProductChargesType') if imported_ns_def_ is not None: namespacedef_ = imported_ns_def_ if pretty_print: eol_ = '\n' else: eol_ = '' if self.original_tagname_ is not None and name_ == 'ProductChargesType': name_ = self.original_tagname_ if UseCapturedNS_ and self.ns_prefix_: namespaceprefix_ = self.ns_prefix_ + ':' showIndent(outfile, level, pretty_print) outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = set() self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ProductChargesType') if self.hasContent_(): outfile.write('>%s' % (eol_, )) self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ProductChargesType', pretty_print=pretty_print) showIndent(outfile, level, pretty_print) outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_)) else: outfile.write('/>%s' % (eol_, )) def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ProductChargesType'): pass def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ProductChargesType', fromsubclass_=False, pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' if self.Duties is not None: namespaceprefix_ = self.Duties_nsprefix_ + ':' if (UseCapturedNS_ and self.Duties_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sDuties>%s</%sDuties>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Duties), input_name='Duties')), namespaceprefix_ , eol_)) if self.TaxesAndFees is not None: namespaceprefix_ = self.TaxesAndFees_nsprefix_ + ':' if (UseCapturedNS_ and self.TaxesAndFees_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sTaxesAndFees>%s</%sTaxesAndFees>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TaxesAndFees), input_name='TaxesAndFees')), namespaceprefix_ , eol_)) if self.VAT is not None: namespaceprefix_ = self.VAT_nsprefix_ + ':' if (UseCapturedNS_ and self.VAT_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sVAT>%s</%sVAT>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VAT), input_name='VAT')), namespaceprefix_ , eol_)) if self.CostOfGoods is not None: namespaceprefix_ = self.CostOfGoods_nsprefix_ + ':' if (UseCapturedNS_ and self.CostOfGoods_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sCostOfGoods>%s</%sCostOfGoods>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CostOfGoods), input_name='CostOfGoods')), namespaceprefix_ , eol_)) if self.SubTotal is not None: namespaceprefix_ = self.SubTotal_nsprefix_ + ':' if (UseCapturedNS_ and self.SubTotal_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sSubTotal>%s</%sSubTotal>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SubTotal), input_name='SubTotal')), namespaceprefix_ , eol_)) def build(self, node, gds_collector_=None): self.gds_collector_ = gds_collector_ if SaveElementTreeNode: self.gds_elementtree_node_ = node already_processed = set() self.ns_prefix_ = node.prefix self.buildAttributes(node, node.attrib, already_processed) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) return self def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): if nodeName_ == 'Duties': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'Duties') value_ = self.gds_validate_string(value_, node, 'Duties') self.Duties = value_ self.Duties_nsprefix_ = child_.prefix elif nodeName_ == 'TaxesAndFees': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'TaxesAndFees') value_ = self.gds_validate_string(value_, node, 'TaxesAndFees') self.TaxesAndFees = value_ self.TaxesAndFees_nsprefix_ = child_.prefix elif nodeName_ == 'VAT': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'VAT') value_ = self.gds_validate_string(value_, node, 'VAT') self.VAT = value_ self.VAT_nsprefix_ = child_.prefix elif nodeName_ == 'CostOfGoods': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'CostOfGoods') value_ = self.gds_validate_string(value_, node, 'CostOfGoods') self.CostOfGoods = value_ self.CostOfGoods_nsprefix_ = child_.prefix elif nodeName_ == 'SubTotal': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'SubTotal') value_ = self.gds_validate_string(value_, node, 'SubTotal') self.SubTotal = value_ self.SubTotal_nsprefix_ = child_.prefix # end class ProductChargesType class ShipmentChargesType(GeneratedsSuper): __hash__ = GeneratedsSuper.__hash__ subclass = None superclass = None def __init__(self, TaxesAndFees=None, AdditionalInsuranceCost=None, TransportationCost=None, SubTotal=None, gds_collector_=None, **kwargs_): self.gds_collector_ = gds_collector_ self.gds_elementtree_node_ = None self.original_tagname_ = None self.parent_object_ = kwargs_.get('parent_object_') self.ns_prefix_ = None self.TaxesAndFees = TaxesAndFees self.TaxesAndFees_nsprefix_ = None self.AdditionalInsuranceCost = AdditionalInsuranceCost self.AdditionalInsuranceCost_nsprefix_ = None self.TransportationCost = TransportationCost self.TransportationCost_nsprefix_ = None self.SubTotal = SubTotal self.SubTotal_nsprefix_ = None def factory(*args_, **kwargs_): if CurrentSubclassModule_ is not None: subclass = getSubclassFromModule_( CurrentSubclassModule_, ShipmentChargesType) if subclass is not None: return subclass(*args_, **kwargs_) if ShipmentChargesType.subclass: return ShipmentChargesType.subclass(*args_, **kwargs_) else: return ShipmentChargesType(*args_, **kwargs_) factory = staticmethod(factory) def get_ns_prefix_(self): return self.ns_prefix_ def set_ns_prefix_(self, ns_prefix): self.ns_prefix_ = ns_prefix def get_TaxesAndFees(self): return self.TaxesAndFees def set_TaxesAndFees(self, TaxesAndFees): self.TaxesAndFees = TaxesAndFees def get_AdditionalInsuranceCost(self): return self.AdditionalInsuranceCost def set_AdditionalInsuranceCost(self, AdditionalInsuranceCost): self.AdditionalInsuranceCost = AdditionalInsuranceCost def get_TransportationCost(self): return self.TransportationCost def set_TransportationCost(self, TransportationCost): self.TransportationCost = TransportationCost def get_SubTotal(self): return self.SubTotal def set_SubTotal(self, SubTotal): self.SubTotal = SubTotal def hasContent_(self): if ( self.TaxesAndFees is not None or self.AdditionalInsuranceCost is not None or self.TransportationCost is not None or self.SubTotal is not None ): return True else: return False def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipmentChargesType', pretty_print=True): imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShipmentChargesType') if imported_ns_def_ is not None: namespacedef_ = imported_ns_def_ if pretty_print: eol_ = '\n' else: eol_ = '' if self.original_tagname_ is not None and name_ == 'ShipmentChargesType': name_ = self.original_tagname_ if UseCapturedNS_ and self.ns_prefix_: namespaceprefix_ = self.ns_prefix_ + ':' showIndent(outfile, level, pretty_print) outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = set() self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShipmentChargesType') if self.hasContent_(): outfile.write('>%s' % (eol_, )) self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShipmentChargesType', pretty_print=pretty_print) showIndent(outfile, level, pretty_print) outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_)) else: outfile.write('/>%s' % (eol_, )) def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShipmentChargesType'): pass def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipmentChargesType', fromsubclass_=False, pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' if self.TaxesAndFees is not None: namespaceprefix_ = self.TaxesAndFees_nsprefix_ + ':' if (UseCapturedNS_ and self.TaxesAndFees_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sTaxesAndFees>%s</%sTaxesAndFees>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TaxesAndFees), input_name='TaxesAndFees')), namespaceprefix_ , eol_)) if self.AdditionalInsuranceCost is not None: namespaceprefix_ = self.AdditionalInsuranceCost_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalInsuranceCost_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sAdditionalInsuranceCost>%s</%sAdditionalInsuranceCost>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalInsuranceCost), input_name='AdditionalInsuranceCost')), namespaceprefix_ , eol_)) if self.TransportationCost is not None: namespaceprefix_ = self.TransportationCost_nsprefix_ + ':' if (UseCapturedNS_ and self.TransportationCost_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sTransportationCost>%s</%sTransportationCost>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TransportationCost), input_name='TransportationCost')), namespaceprefix_ , eol_)) if self.SubTotal is not None: namespaceprefix_ = self.SubTotal_nsprefix_ + ':' if (UseCapturedNS_ and self.SubTotal_nsprefix_) else '' showIndent(outfile, level, pretty_print) outfile.write('<%sSubTotal>%s</%sSubTotal>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SubTotal), input_name='SubTotal')), namespaceprefix_ , eol_)) def build(self, node, gds_collector_=None): self.gds_collector_ = gds_collector_ if SaveElementTreeNode: self.gds_elementtree_node_ = node already_processed = set() self.ns_prefix_ = node.prefix self.buildAttributes(node, node.attrib, already_processed) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) return self def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): if nodeName_ == 'TaxesAndFees': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'TaxesAndFees') value_ = self.gds_validate_string(value_, node, 'TaxesAndFees') self.TaxesAndFees = value_ self.TaxesAndFees_nsprefix_ = child_.prefix elif nodeName_ == 'AdditionalInsuranceCost': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'AdditionalInsuranceCost') value_ = self.gds_validate_string(value_, node, 'AdditionalInsuranceCost') self.AdditionalInsuranceCost = value_ self.AdditionalInsuranceCost_nsprefix_ = child_.prefix elif nodeName_ == 'TransportationCost': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'TransportationCost') value_ = self.gds_validate_string(value_, node, 'TransportationCost') self.TransportationCost = value_ self.TransportationCost_nsprefix_ = child_.prefix elif nodeName_ == 'SubTotal': value_ = child_.text value_ = self.gds_parse_string(value_, node, 'SubTotal') value_ = self.gds_validate_string(value_, node, 'SubTotal') self.SubTotal = value_ self.SubTotal_nsprefix_ = child_.prefix # end class ShipmentChargesType class TransactionChargeType(GeneratedsSuper): __hash__ = GeneratedsSuper.__hash__ subclass = None superclass = None def __init__(self, MonetaryValue=None, CurrencyCode=None, gds_collector_=None, **kwargs_): self.gds_collector_ = gds_collector_ self.gds_elementtree_node_ = None self.original_tagname_ = None self.parent_object_ = kwargs_.get('parent_object_') self.ns_prefix_ = None self.MonetaryValue = MonetaryValue self.MonetaryValue_nsprefix_ = None self.CurrencyCode = CurrencyCode self.CurrencyCode_nsprefix_ = None def factory(*args_, **kwargs_): if CurrentSubclassModule_ is not None: subclass = getSubclassFromModule_( CurrentSubclassModule_, TransactionChargeType) if subclass is not None: return subclass(*args_, **kwargs_) if TransactionChargeType.subclass: return TransactionChargeType.subclass(*args_, **kwargs_) else: return
<reponame>cthoyt/delphi #!/usr/bin/python3.6 import ast import sys import tokenize from datetime import datetime import re import argparse from functools import * import json from .genCode import * from typing import List, Dict, Iterable, Optional from itertools import chain, product import operator class PGMState: def __init__( self, lambdaFile: Optional[str], lastDefs: Optional[Dict]={}, nextDefs: Optional[Dict]={}, lastDefDefault=0, fnName=None, varTypes: Optional[Dict]={}, ): self.lastDefs = lastDefs self.nextDefs = nextDefs self.lastDefDefault = lastDefDefault self.fnName = fnName self.varTypes = varTypes self.lambdaFile = lambdaFile def copy( self, lastDefs: Optional[Dict]=None, nextDefs: Optional[Dict]=None, lastDefDefault=None, fnName=None, varTypes: Optional[Dict]=None, lambdaFile: Optional[str]=None, ): return PGMState( self.lambdaFile if lambdaFile == None else lambdaFile, self.lastDefs if lastDefs == None else lastDefs, self.nextDefs if nextDefs == None else nextDefs, self.lastDefDefault if lastDefDefault == None else lastDefDefault, self.fnName if fnName == None else fnName, self.varTypes if varTypes == None else varTypes, ) def dump(node, annotate_fields=True, include_attributes=False, indent=" "): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(node, level=0): if isinstance(node, ast.AST): fields = [(a, _format(b, level)) for a, b in ast.iter_fields(node)] if include_attributes and node._attributes: fields.extend( [ (a, _format(getattr(node, a), level)) for a in node._attributes ] ) return "".join( [ node.__class__.__name__, "(", ", ".join( (f"{field}={field}" for field in fields) if annotate_fields else (b for a, b in fields) ), ")", ] ) elif isinstance(node, list): lines = ["["] lines.extend( ( indent * (level + 2) + _format(x, level + 2) + "," for x in node ) ) if len(lines) > 1: lines.append(indent * (level + 1) + "]") else: lines[-1] += "]" return "\n".join(lines) return repr(node) if not isinstance(node, ast.AST): raise TypeError("expected AST, got %r" % node.__class__.__name__) return _format(node) def printPgm(pgmFile, pgm): pgmFile.write(json.dumps(pgm, indent=2)) def genFn(fnFile, node, fnName, returnVal, inputs): fnFile.write(f"def {fnName}({', '.join(inputs)}):\n ") code = genCode(node, PrintState("\n ")) if returnVal: fnFile.write(f"return {code}") else: lines = code.split("\n") indent = re.search("[^ ]", lines[-1]).start() lines[-1] = lines[-1][:indent] + "return " + lines[-1][indent:] fnFile.write("\n".join(lines)) fnFile.write("\n\n") def mergeDicts(dicts: Iterable[Dict]) -> Dict: fields = set(chain.from_iterable(d.keys() for d in dicts)) merged_dict = {field: [] for field in fields} for field, d in product(fields, dicts): if field in d: if isinstance(d[field], list): merged_dict[field] += d[field] else: merged_dict[field].append(d[field]) return merged_dict def getFnName(fnNames, basename): fnId = fnNames.get(basename, 0) fnName = f"{basename}_{fnId}" fnNames[basename] = fnId + 1 return fnName def getLastDef(var, lastDefs, lastDefDefault): index = lastDefDefault if var in lastDefs: index = lastDefs[var] else: lastDefs[var] = index return index def getNextDef(var, lastDefs, nextDefs, lastDefDefault): index = nextDefs.get(var, lastDefDefault + 1) nextDefs[var] = index + 1 lastDefs[var] = index return index def getVarType(annNode): # wrapped in list try: dType = annNode.slice.value.id if dType == "float": return "real" if dType == "int": return "integer" else: sys.stderr.write("Unsupported type (only float and int supported as of now).\n") except AttributeError: sys.stderr.write("Unsupported type (annNode is None).\n") sys.exit(1) def getDType(val): if isinstance(val, int): dtype = "integer" elif isinstance(val, float): dtype = "real" else: sys.stderr.write(f"num: {type(node.n)}\n") sys.exit(1) return dtype def get_body_and_functions(pgm): body = list(chain.from_iterable(stmt["body"] for stmt in pgm)) fns = list(chain.from_iterable(stmt["functions"] for stmt in pgm)) return body, fns def make_fn_dict(name, target, sources, lambdaName, node): source = [] for src in sources: if "call" in src: for source_ins in make_call_body_dict(src): source.append(source_ins) if "var" in src: variable = src["var"]["variable"] source.append({"name": variable, "type": "variable"}) fn = { "name": name, "type": "assign", "target": target["var"]["variable"], "sources": source, "body": [ {"type": "lambda", "name": lambdaName, "reference": node.lineno} ], } return fn def make_call_body_dict(source): source_list = [] name = source["call"]["function"] source_list.append({"name": name, "type": "function"}) for ip in source["call"]["inputs"][0]: if "var" in ip: variable = ip["var"]["variable"] source_list.append({"name": variable, "type": "variable"}) return source_list def make_body_dict(name, target, sources): source_list = [] for src in sources: if "var" in src: source_list.append(src["var"]) if "call" in src: for ip in src["call"]["inputs"][0]: if "var" in ip: source_list.append(ip["var"]) body = { "name": name, "output": target["var"], "input": source_list, } return body def genPgm(node, state, fnNames): types = (list, ast.Module, ast.FunctionDef) unnecessary_types = ( ast.Mult, ast.Add, ast.Sub, ast.Pow, ast.Div, ast.USub, ast.Eq, ast.LtE, ) if state.fnName is None and not any(isinstance(node, t) for t in types): if isinstance(node, ast.Call): return [{"start": node.func.id}] elif isinstance(node, ast.Expr): return genPgm(node.value, state, fnNames) elif isinstance(node, ast.If): return genPgm(node.body, state, fnNames) else: return [] if isinstance(node, list): return list( chain.from_iterable([genPgm(cur, state, fnNames) for cur in node]) ) # Function: name, args, body, decorator_list, returns elif isinstance(node, ast.FunctionDef): localDefs = state.lastDefs.copy() localNext = state.nextDefs.copy() localTypes = state.varTypes.copy() fnState = state.copy( lastDefs=localDefs, nextDefs=localNext, fnName=node.name, varTypes=localTypes, ) args = genPgm(node.args, fnState, fnNames) bodyPgm = genPgm(node.body, fnState, fnNames) body, fns = get_body_and_functions(bodyPgm) variables = list(localDefs.keys()) fnDef = { "name": node.name, "type": "container", "input": [ {"name": arg, "domain": localTypes[arg]} for arg in args ], "variables": [ {"name": var, "domain": localTypes[var]} for var in variables ], "body": body, } fns.append(fnDef) pgm = {"functions": fns} return [pgm] # arguments: ('args', 'vararg', 'kwonlyargs', 'kw_defaults', 'kwarg', 'defaults') elif isinstance(node, ast.arguments): return [genPgm(arg, state, fnNames) for arg in node.args] # arg: ('arg', 'annotation') elif isinstance(node, ast.arg): state.varTypes[node.arg] = getVarType(node.annotation) return node.arg # Load: () elif isinstance(node, ast.Load): sys.stderr.write("Found ast.Load, which should not happen\n") sys.exit(1) # Store: () elif isinstance(node, ast.Store): sys.stderr.write("Found ast.Store, which should not happen\n") sys.exit(1) # Index: ('value',) elif isinstance(node, ast.Index): genPgm(node.value, state, fnNames) # Num: ('n',) elif isinstance(node, ast.Num): return [ {"type": "literal", "dtype": getDType(node.n), "value": node.n} ] # List: ('elts', 'ctx') elif isinstance(node, ast.List): elements = reduce( (lambda x, y: x.append(y)), [genPgm(elmt, state, fnNames) for elmt in node.elts], ) return elements if len(elements) == 1 else {"list": elements} # Str: ('s',) elif isinstance(node, ast.Str): return [{"type": "literal", "dtype": "string", "value": node.s}] # For: ('target', 'iter', 'body', 'orelse') elif isinstance(node, ast.For): if genPgm(node.orelse, state, fnNames): sys.stderr.write("For/Else in for not supported\n") sys.exit(1) indexVar = genPgm(node.target, state, fnNames) if len(indexVar) != 1 or "var" not in indexVar[0]: sys.stderr.write("Only one index variable is supported\n") sys.exit(1) indexName = indexVar[0]["var"]["variable"] loopIter = genPgm(node.iter, state, fnNames) if ( len(loopIter) != 1 or "call" not in loopIter[0] or loopIter[0]["call"]["function"] != "range" ): sys.stderr.write("Can only iterate over a range\n") sys.exit(1) rangeCall = loopIter[0]["call"] if ( len(rangeCall["inputs"]) != 2 or len(rangeCall["inputs"][0]) != 1 or len(rangeCall["inputs"][1]) != 1 or ( "type" in rangeCall["inputs"][0] and rangeCall["inputs"][0]["type"] == "literal" ) or ( "type" in rangeCall["inputs"][1] and rangeCall["inputs"][1]["type"] == "literal" ) ): sys.stderr.write("Can only iterate over a constant range\n") sys.exit(1) iterationRange = { "start": rangeCall["inputs"][0][0], "end": rangeCall["inputs"][1][0], } loopLastDef = {} loopState = state.copy( lastDefs=loopLastDef, nextDefs={}, lastDefDefault=-1 ) loop = genPgm(node.body, loopState, fnNames) loopBody, loopFns = get_body_and_functions(loop) variables = [x for x in loopLastDef if x != indexName] # variables: see what changes? loopName = getFnName( fnNames, f"{state.fnName}__loop_plate__{indexName}" ) loopFn = { "name": loopName, "type": "loop_plate", "input": variables, "index_variable": indexName, "index_iteration_range": iterationRange, "body": loopBody, } loopCall = {"name": loopName, "inputs": variables, "output": {}} pgm = {"functions": loopFns + [loopFn], "body": [loopCall]} return [pgm] # If: ('test', 'body', 'orelse') elif isinstance(node, ast.If): pgm = {"functions": [], "body": []} condSrcs = genPgm(node.test, state, fnNames) condNum = state.nextDefs.get("#cond", state.lastDefDefault + 1) state.nextDefs["#cond"] = condNum + 1 condName = f"IF_{condNum}" state.varTypes[condName] = "boolean" state.lastDefs[condName] = 0 fnName = getFnName(fnNames, f"{state.fnName}__condition__{condName}") condOutput = {"variable": condName, "index": 0} lambdaName = getFnName(fnNames, f"{state.fnName}__lambda__{condName}") fn = { "name": fnName, "type": "assign", "target": condName, "sources": [ {"name": src["var"]["variable"], "type": "variable"} for src in condSrcs if "var" in src ], "body": [ { "type": "lambda", "name": lambdaName, "reference": node.lineno, } ], } body = { "name": fnName, "output": condOutput, "input": [src["var"] for src in condSrcs if "var" in src], } pgm["functions"].append(fn) pgm["body"].append(body) genFn( state.lambdaFile, node.test, lambdaName, None, [src["var"]["variable"] for src in condSrcs if "var" in src], ) startDefs = state.lastDefs.copy() ifDefs = startDefs.copy() elseDefs = startDefs.copy() ifState = state.copy(lastDefs=ifDefs) elseState = state.copy(lastDefs=elseDefs) ifPgm = genPgm(node.body, ifState, fnNames) elsePgm = genPgm(node.orelse, elseState, fnNames) pgm["functions"] += reduce( (lambda x, y: x + y["functions"]), [[]] +
36628, 'tracts': 11}, 'Huron': {'population': 33118, 'tracts': 12}, 'Ingham': {'population': 280895, 'tracts': 81}, 'Ionia': {'population': 63905, 'tracts': 13}, 'Iosco': {'population': 25887, 'tracts': 9}, 'Iron': {'population': 11817, 'tracts': 5}, 'Isabella': {'population': 70311, 'tracts': 15}, 'Jackson': {'population': 160248, 'tracts': 38}, 'Kalamazoo': {'population': 250331, 'tracts': 57}, 'Kalkaska': {'population': 17153, 'tracts': 5}, 'Kent': {'population': 602622, 'tracts': 128}, 'Keweenaw': {'population': 2156, 'tracts': 2}, 'Lake': {'population': 11539, 'tracts': 4}, 'Lapeer': {'population': 88319, 'tracts': 24}, 'Leelanau': {'population': 21708, 'tracts': 6}, 'Lenawee': {'population': 99892, 'tracts': 23}, 'Livingston': {'population': 180967, 'tracts': 61}, 'Luce': {'population': 6631, 'tracts': 3}, 'Mackinac': {'population': 11113, 'tracts': 6}, 'Macomb': {'population': 840978, 'tracts': 216}, 'Manistee': {'population': 24733, 'tracts': 9}, 'Marquette': {'population': 67077, 'tracts': 24}, 'Mason': {'population': 28705, 'tracts': 8}, 'Mecosta': {'population': 42798, 'tracts': 11}, 'Menominee': {'population': 24029, 'tracts': 7}, 'Midland': {'population': 83629, 'tracts': 19}, 'Missaukee': {'population': 14849, 'tracts': 4}, 'Monroe': {'population': 152021, 'tracts': 39}, 'Montcalm': {'population': 63342, 'tracts': 13}, 'Montmorency': {'population': 9765, 'tracts': 5}, 'Muskegon': {'population': 172188, 'tracts': 42}, 'Newaygo': {'population': 48460, 'tracts': 11}, 'Oakland': {'population': 1202362, 'tracts': 338}, 'Oceana': {'population': 26570, 'tracts': 7}, 'Ogemaw': {'population': 21699, 'tracts': 7}, 'Ontonagon': {'population': 6780, 'tracts': 4}, 'Osceola': {'population': 23528, 'tracts': 6}, 'Oscoda': {'population': 8640, 'tracts': 5}, 'Otsego': {'population': 24164, 'tracts': 6}, 'Ottawa': {'population': 263801, 'tracts': 53}, 'Presque Isle': {'population': 13376, 'tracts': 6}, 'Roscommon': {'population': 24449, 'tracts': 10}, 'Saginaw': {'population': 200169, 'tracts': 56}, 'Sanilac': {'population': 43114, 'tracts': 12}, 'Schoolcraft': {'population': 8485, 'tracts': 3}, 'Shiawassee': {'population': 70648, 'tracts': 17}, 'St. Clair': {'population': 163040, 'tracts': 49}, 'St. Joseph': {'population': 61295, 'tracts': 17}, 'Tuscola': {'population': 55729, 'tracts': 13}, '<NAME>': {'population': 76258, 'tracts': 15}, 'Washtenaw': {'population': 344791, 'tracts': 100}, 'Wayne': {'population': 1820584, 'tracts': 610}, 'Wexford': {'population': 32735, 'tracts': 8}}, 'MN': {'Aitkin': {'population': 16202, 'tracts': 6}, 'Anoka': {'population': 330844, 'tracts': 83}, 'Becker': {'population': 32504, 'tracts': 10}, 'Beltrami': {'population': 44442, 'tracts': 10}, 'Benton': {'population': 38451, 'tracts': 9}, '<NAME>': {'population': 5269, 'tracts': 3}, 'Blue Earth': {'population': 64013, 'tracts': 16}, 'Brown': {'population': 25893, 'tracts': 8}, 'Carlton': {'population': 35386, 'tracts': 7}, 'Carver': {'population': 91042, 'tracts': 19}, 'Cass': {'population': 28567, 'tracts': 10}, 'Chippewa': {'population': 12441, 'tracts': 4}, 'Chisago': {'population': 53887, 'tracts': 10}, 'Clay': {'population': 58999, 'tracts': 13}, 'Clearwater': {'population': 8695, 'tracts': 3}, 'Cook': {'population': 5176, 'tracts': 3}, 'Cottonwood': {'population': 11687, 'tracts': 4}, '<NAME>': {'population': 62500, 'tracts': 16}, 'Dakota': {'population': 398552, 'tracts': 95}, 'Dodge': {'population': 20087, 'tracts': 5}, 'Douglas': {'population': 36009, 'tracts': 9}, 'Faribault': {'population': 14553, 'tracts': 6}, 'Fillmore': {'population': 20866, 'tracts': 6}, 'Freeborn': {'population': 31255, 'tracts': 10}, 'Goodhue': {'population': 46183, 'tracts': 10}, 'Grant': {'population': 6018, 'tracts': 2}, 'Hennepin': {'population': 1152425, 'tracts': 299}, 'Houston': {'population': 19027, 'tracts': 5}, 'Hubbard': {'population': 20428, 'tracts': 7}, 'Isanti': {'population': 37816, 'tracts': 8}, 'Itasca': {'population': 45058, 'tracts': 11}, 'Jackson': {'population': 10266, 'tracts': 4}, 'Kanabec': {'population': 16239, 'tracts': 4}, 'Kandiyohi': {'population': 42239, 'tracts': 12}, 'Kittson': {'population': 4552, 'tracts': 2}, 'Koochiching': {'population': 13311, 'tracts': 4}, '<NAME>': {'population': 7259, 'tracts': 3}, 'Lake': {'population': 10866, 'tracts': 3}, 'Lake of the Woods': {'population': 4045, 'tracts': 2}, 'Le Sueur': {'population': 27703, 'tracts': 6}, 'Lincoln': {'population': 5896, 'tracts': 2}, 'Lyon': {'population': 25857, 'tracts': 7}, 'Mahnomen': {'population': 5413, 'tracts': 2}, 'Marshall': {'population': 9439, 'tracts': 4}, 'Martin': {'population': 20840, 'tracts': 6}, 'McLeod': {'population': 36651, 'tracts': 7}, 'Meeker': {'population': 23300, 'tracts': 6}, '<NAME>': {'population': 26097, 'tracts': 7}, 'Morrison': {'population': 33198, 'tracts': 8}, 'Mower': {'population': 39163, 'tracts': 11}, 'Murray': {'population': 8725, 'tracts': 3}, 'Nicollet': {'population': 32727, 'tracts': 7}, 'Nobles': {'population': 21378, 'tracts': 6}, 'Norman': {'population': 6852, 'tracts': 3}, 'Olmsted': {'population': 144248, 'tracts': 33}, '<NAME>': {'population': 57303, 'tracts': 17}, 'Pennington': {'population': 13930, 'tracts': 5}, 'Pine': {'population': 29750, 'tracts': 8}, 'Pipestone': {'population': 9596, 'tracts': 5}, 'Polk': {'population': 31600, 'tracts': 10}, 'Pope': {'population': 10995, 'tracts': 4}, 'Ramsey': {'population': 508640, 'tracts': 137}, 'Red Lake': {'population': 4089, 'tracts': 2}, 'Redwood': {'population': 16059, 'tracts': 6}, 'Renville': {'population': 15730, 'tracts': 6}, 'Rice': {'population': 64142, 'tracts': 13}, 'Rock': {'population': 9687, 'tracts': 3}, 'Roseau': {'population': 15629, 'tracts': 5}, 'Scott': {'population': 129928, 'tracts': 21}, 'Sherburne': {'population': 88499, 'tracts': 11}, 'Sibley': {'population': 15226, 'tracts': 4}, 'St. Louis': {'population': 200226, 'tracts': 66}, 'Stearns': {'population': 150642, 'tracts': 29}, 'Steele': {'population': 36576, 'tracts': 8}, 'Stevens': {'population': 9726, 'tracts': 3}, 'Swift': {'population': 9783, 'tracts': 4}, 'Todd': {'population': 24895, 'tracts': 8}, 'Traverse': {'population': 3558, 'tracts': 2}, 'Wabasha': {'population': 21676, 'tracts': 6}, 'Wadena': {'population': 13843, 'tracts': 3}, 'Waseca': {'population': 19136, 'tracts': 5}, 'Washington': {'population': 238136, 'tracts': 50}, 'Watonwan': {'population': 11211, 'tracts': 3}, 'Wilkin': {'population': 6576, 'tracts': 2}, 'Winona': {'population': 51461, 'tracts': 10}, 'Wright': {'population': 124700, 'tracts': 17}, 'Yellow Medicine': {'population': 10438, 'tracts': 4}}, 'MO': {'Adair': {'population': 25607, 'tracts': 7}, 'Andrew': {'population': 17291, 'tracts': 4}, 'Atchison': {'population': 5685, 'tracts': 2}, 'Audrain': {'population': 25529, 'tracts': 7}, 'Barry': {'population': 35597, 'tracts': 7}, 'Barton': {'population': 12402, 'tracts': 3}, 'Bates': {'population': 17049, 'tracts': 4}, 'Benton': {'population': 19056, 'tracts': 6}, 'Bollinger': {'population': 12363, 'tracts': 3}, 'Boone': {'population': 162642, 'tracts': 29}, 'Buchanan': {'population': 89201, 'tracts': 25}, 'Butler': {'population': 42794, 'tracts': 10}, 'Caldwell': {'population': 9424, 'tracts': 2}, 'Callaway': {'population': 44332, 'tracts': 8}, 'Camden': {'population': 44002, 'tracts': 11}, '<NAME>': {'population': 75674, 'tracts': 16}, 'Carroll': {'population': 9295, 'tracts': 3}, 'Carter': {'population': 6265, 'tracts': 2}, 'Cass': {'population': 99478, 'tracts': 20}, 'Cedar': {'population': 13982, 'tracts': 3}, 'Chariton': {'population': 7831, 'tracts': 3}, 'Christian': {'population': 77422, 'tracts': 14}, 'Clark': {'population': 7139, 'tracts': 3}, 'Clay': {'population': 221939, 'tracts': 44}, 'Clinton': {'population': 20743, 'tracts': 4}, 'Cole': {'population': 75990, 'tracts': 15}, 'Cooper': {'population': 17601, 'tracts': 5}, 'Crawford': {'population': 24696, 'tracts': 6}, 'Dade': {'population': 7883, 'tracts': 2}, 'Dallas': {'population': 16777, 'tracts': 3}, 'Daviess': {'population': 8433, 'tracts': 2}, 'DeKalb': {'population': 12892, 'tracts': 2}, 'Dent': {'population': 15657, 'tracts': 4}, 'Douglas': {'population': 13684, 'tracts': 3}, 'Dunklin': {'population': 31953, 'tracts': 10}, 'Franklin': {'population': 101492, 'tracts': 17}, 'Gasconade': {'population': 15222, 'tracts': 5}, 'Gentry': {'population': 6738, 'tracts': 2}, 'Greene': {'population': 275174, 'tracts': 62}, 'Grundy': {'population': 10261, 'tracts': 4}, 'Harrison': {'population': 8957, 'tracts': 3}, 'Henry': {'population': 22272, 'tracts': 6}, 'Hickory': {'population': 9627, 'tracts': 3}, 'Holt': {'population': 4912, 'tracts': 3}, 'Howard': {'population': 10144, 'tracts': 3}, 'Howell': {'population': 40400, 'tracts': 8}, 'Iron': {'population': 10630, 'tracts': 4}, 'Jackson': {'population': 674158, 'tracts': 199}, 'Jasper': {'population': 117404, 'tracts': 22}, 'Jefferson': {'population': 218733, 'tracts': 42}, 'Johnson': {'population': 52595, 'tracts': 9}, 'Knox': {'population': 4131, 'tracts': 2}, 'Laclede': {'population': 35571, 'tracts': 6}, 'Lafayette': {'population': 33381, 'tracts': 7}, 'Lawrence': {'population': 38634, 'tracts': 7}, 'Lewis': {'population': 10211, 'tracts': 4}, 'Lincoln': {'population': 52566, 'tracts': 7}, 'Linn': {'population': 12761, 'tracts': 5}, 'Livingston': {'population': 15195, 'tracts': 5}, 'Macon': {'population': 15566, 'tracts': 5}, 'Madison': {'population': 12226, 'tracts': 3}, 'Maries': {'population': 9176, 'tracts': 3}, 'Marion': {'population': 28781, 'tracts': 8}, 'McDonald': {'population': 23083, 'tracts': 4}, 'Mercer': {'population': 3785, 'tracts': 2}, 'Miller': {'population': 24748, 'tracts': 5}, 'Mississippi': {'population': 14358, 'tracts': 4}, 'Moniteau': {'population': 15607, 'tracts': 4}, 'Monroe': {'population': 8840, 'tracts': 3}, 'Montgomery': {'population': 12236, 'tracts': 4}, 'Morgan': {'population': 20565, 'tracts': 5}, 'New Madrid': {'population': 18956, 'tracts': 6}, 'Newton': {'population': 58114, 'tracts': 12}, 'Nodaway': {'population': 23370, 'tracts': 5}, 'Oregon': {'population': 10881, 'tracts': 3}, 'Osage': {'population': 13878, 'tracts': 4}, 'Ozark': {'population': 9723, 'tracts': 2}, 'Pemiscot': {'population': 18296, 'tracts': 6}, 'Perry': {'population': 18971, 'tracts': 5}, 'Pettis': {'population': 42201, 'tracts': 11}, 'Phelps': {'population': 45156, 'tracts': 10}, 'Pike': {'population': 18516, 'tracts': 5}, 'Platte': {'population': 89322, 'tracts': 20}, 'Polk': {'population': 31137, 'tracts': 4}, 'Pulaski': {'population': 52274, 'tracts': 9}, 'Putnam': {'population': 4979, 'tracts': 2}, 'Ralls': {'population': 10167, 'tracts': 3}, 'Randolph': {'population': 25414, 'tracts': 6}, 'Ray': {'population': 23494, 'tracts': 4}, 'Reynolds': {'population': 6696, 'tracts': 2}, 'Ripley': {'population': 14100, 'tracts': 4}, 'Saline': {'population': 23370, 'tracts': 8}, 'Schuyler': {'population': 4431, 'tracts': 2}, 'Scotland': {'population': 4843, 'tracts': 2}, 'Scott': {'population': 39191, 'tracts': 10}, 'Shannon': {'population': 8441, 'tracts': 2}, 'Shelby': {'population': 6373, 'tracts': 3}, 'St. Charles': {'population': 360485, 'tracts': 79}, 'St. Clair': {'population': 9805, 'tracts': 3}, 'St. Francois': {'population': 65359, 'tracts': 11}, 'St. Louis': {'population': 998954, 'tracts': 199}, 'St. Louis City': {'population': 319294, 'tracts': 106}, '<NAME>': {'population': 18145, 'tracts': 4}, 'Stoddard': {'population': 29968, 'tracts': 8}, 'Stone': {'population': 32202, 'tracts': 6}, 'Sullivan': {'population': 6714, 'tracts': 3}, 'Taney': {'population': 51675, 'tracts': 10}, 'Texas': {'population': 26008, 'tracts': 4}, 'Vernon': {'population': 21159, 'tracts': 6}, 'Warren': {'population': 32513, 'tracts': 5}, 'Washington': {'population': 25195, 'tracts': 5}, 'Wayne': {'population': 13521, 'tracts': 4}, 'Webster': {'population':
<reponame>nstarman/gaia_tools_util #!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# r""" gaia_tools helper functions Make constructing SQL queries for gaia_tools easier See gaia_tools python package by <NAME> for details ############################################################################# Copyright (c) 2018 - <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################# Planned Features """ ############################################################################# # Imports import json import os import time if __name__ == '__main__': from table_utils import add_units_to_query else: from .table_utils import add_units_to_query try: from astropy import units as u except ImportError as e: print("can't import astropy units") try: from gaia_tools.query import query as Query except ImportError as e: print("can't import gaia_tools Query, do_query is turned off") _CANQUERY = False else: _CANQUERY = True ############################################################################# # Info __author__ = "<NAME>" __copyright__ = "Copyright 2018, " __credits__ = ["<NAME>"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" ############################################################################# # Code def _make_query_defaults(fpath='default'): r"""Make default values for query loads from file or dictionary INPUTS ------ fpath: str or dict the filepath of the gaia query defaults if None: uses 'defaults' str: 'default', 'empty', or 'full' dict, assumes the dictionary is correct and returns as is default file in '/gaia/defaults.json' Dictionary Values ----------------- gaia cols gaia mags panstarrs cols asdict units """ # dictionary if issubclass(fpath.__class__, dict): # prefers a dictionary return fpath elif not isinstance(fpath, str): # must be a string, if not a dict raise ValueError('defaults must be a str') # loading file elif fpath in ('default', 'empty', 'full'): dirname = os.path.dirname(__file__) dirpath = os.path.join(dirname, 'defaults/gaia_defaults.json') with open(dirpath, 'r') as file: df = json.load(file) defaults = { 'asdict': df['asdict'], 'units': df['units'], **df[fpath] } # user file else: with open(fpath, 'r') as file: defaults = json.load(file) # Checking possible column groups if 'gaia cols' in defaults: defaults['gaia cols'] = "\n".join(defaults['gaia cols']) if 'gaia mags' in defaults: defaults['gaia mags'] = "\n".join(defaults['gaia mags']) if 'Pan-STARRS1 cols' in defaults: defaults['Pan-STARRS1 cols'] = "\n".join(defaults['Pan-STARRS1 cols']) if '2MASS cols' in defaults: defaults['2MASS cols'] = "\n".join(defaults['2MASS cols']) if 'units' in defaults: defaults['units'] = {k: eval(v) for k, v in defaults['units'].items() if v[:2] == 'u.'} return defaults def _make_query_SELECT(user_cols=None, use_AS=True, all_columns=False, gaia_mags=False, panstarrs1=False, twomass=False, query=None, defaults='default'): r"""Makes the SELECT portion of a gaia query Inputs ------ user_cols: str (or None) Data columns in addition to default columns Default: None ex: "gaia.L, gaia.B," use_AS: bool True will add 'AS __' to the data columns This is good for the outer part of the query so as to have convenient names in the output data table. Default: True all_columns: bool Whether to include all columns via ', *' Default: False gaia_mags: bool Whether to include Gaia magnitudes Default: False panstarrs1: bool to include Pan-STARRS1 magnitudes and INNER JOIN on Gaia Default: False twomass: bool to include 2MASS magnitudes and INNER JOIN on Gaia Default: False query: str (or None) experimental feature defaults: str or dict the filepath of the gaia query defaults if None: uses 'defaults' str: 'default', 'empty', or 'full' dict, assumes the dictionary is correct and returns as is default file in 'defaults/gaia_defaults.json' Returns ------- query: str the SELECT portion of a gaia query DEFAULTS -------- In a Json-esque format. See defaults/gaia_defaults.json """ #################### # Defaults defaults = _make_query_defaults(defaults) if use_AS is False: # replace with blank dict with asdict keys defaults['asdict'] = {k: '' for k in defaults['asdict']} else: for k, v in defaults['asdict'].items(): if not v: # empty defaults['asdict'][k] = '' else: defaults['asdict'][k] = ' AS ' + v # Start new query if one not provided if query is None: query = "" #################### # Building Selection # SELECT query += '--Data Columns:\nSELECT\n--GaiaDR2 Columns:\n' query += defaults['gaia cols'] if gaia_mags is True: query += ',\n--GaiaDR2 Magnitudes and Colors:\n' query += defaults['gaia mags'] if all_columns is True: query += ",\n--All Columns:\n*" if panstarrs1 is True: query += ',\n--Adding Pan-STARRS1 Columns:\n' query += defaults['Pan-STARRS1 cols'] if twomass is True: query += ',\n--Adding 2MASS Columns:\n' query += defaults['2MASS cols'] #################### # (Possible) User Input # Replacing {} with _asdict query = query.format(**defaults['asdict']) if user_cols is None: query += '\n' elif not isinstance(user_cols, str): raise TypeError('user_sel is not a (str)') elif user_cols == '': query += '\n' else: query += ',\n\n--Custom Selection & Assignement:' if user_cols[:1] != '\n': user_cols = '\n' + user_cols if user_cols[-1] == ',': user_cols = user_cols[:-1] query += user_cols #################### # Return if 'units' in defaults: return query, defaults['units'] else: return query, None def _make_query_FROM(FROM=None, inmostquery=False, _tab=' '): r"""Make the FROM portion of a gaia query INPUTS ------ FROM: str (or None) User input FROM (though should not have FROM in it) Default: None goes to 'gaiadr2.gaia_source' Useful for nesting queries as an inner query can be input here inmostquery: bool whether the query is the innermost query _tab: str the tab default: 4 spaces RETURNS: -------- query: str The query, with FROM added """ # FROM if FROM is None: FROM = 'gaiadr2.gaia_source' else: # Tab level FROM = _tab + FROM FROM = FROM.replace('\n', '\n{tab}'.format(tab=_tab)) if inmostquery is False: p1, p2 ='(\n', '\n)' else: p1, p2 ='', '' s = "\n".join(( "\n", "--SOURCE:", "FROM {p1}{userfrom}{p2} AS gaia".format( userfrom=FROM, p1=p1, p2=p2))) return s def _query_tab_level(query, tablevel, _tab=' '): r"""Add tab level to query indents the whoel query by the tab level INPUTS ------ query: str the query tablevel: int tab * tablevel tab = _tab _tab: str the tab default: 4 spaces RETURNS ------- query """ # Tab level query = (_tab * tablevel) + query query = query.replace('\n', '\n{tab}'.format(tab=_tab * tablevel)) return query def _make_query_WHERE(WHERE, random_index=False): r"""make query WHERE INPUTS ------ WHERE: str (or None) ADQL `WHERE' argument random_index: int or False the gaia.random_index for fast querying """ # query = '' if query is None else query # Selection s = "\n\n--Selections:\nWHERE" if WHERE[:1] != '\n': WHERE = '\n' + WHERE s += WHERE if random_index is not False: s += '\nAND random_index < ' + str(int(random_index)) return s def _make_query_ORDERBY(ORDERBY): r"""make query ORDERBY INPUTS ------ ORDERBY: str the orderby arguments """ # query = '' if query is None else query s ='\n\n--Ordering:\nORDER BY' if ORDERBY[:1] != '\n': ORDERBY = '\n' + ORDERBY s += ORDERBY return s def make_query(WHERE=None, ORDERBY=None, FROM=None, random_index=False, user_cols=None, all_columns=False, gaia_mags=False, panstarrs1=False, twomass=False, use_AS=False, user_ASdict=None, defaults='default', inmostquery=False, units=False, # doing the query do_query=False, local=False, # extra options _tab=' ', pprint=False): """Makes a whole Gaia query INPUTS ------ WHERE: str (or None) ADQL `WHERE' argument ORDERBY: str (or None) ADQL `ORDER BY' argument FROM: str (or None) ADQL `FFROM' argument random_index: int or False the gaia.random_index for fast querying Default: False user_cols: str (or None) Data columns in addition to default columns Default: None ex: "gaia.L, gaia.B," all_columns: bool Whether to include all columns via ', *' Default: False gaia_mags: bool Whether to include Gaia magnitudes Default: False panstarrs1: bool Whether to include Panstarrs1 g,r,i,z magnitudes and INNER JOIN on Gaia Default: False use_AS: bool True will add 'AS __'
#!/usr/bin/env python # coding: utf-8 # <div class="alert alert-block alert-info"> # <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b> # </div> # # Copyright © 2021 <NAME> and <NAME> # # Last GitHub Commit Date: 13 July 2021 # # # 5: Algorithm Building Blocks # - Three building blocks (structures): sequence, selection , repetition (loops) # - Sequence # - Selection # - Repetition # - Structured FOR loops # - Structured WHILE loops # - Representing computational processes with flowcharts, a graphical abstraction # --- # ## Objectives # # 1) Develop awareness of fundamental structures in algorithms: # # - sequence # - selection # - repetition # # 2) Develop awareness of loops, and their utility in automation. # # - To understand loop types available in Python. # - To understand and implement loops in various examples and configurations. # # 3) Develop awareness of flowcharts as a tool for: # # - Post-development documentation # - Pre-development program design # # # --- # ## Algorithm Structures # # The three fundamental structures are sequence, selection, and repetition. # ## Sequence # # Sequential processing are steps performed in sequence, one after another. A default spreadsheet computation from top-to-bottom is a sequential process. # # **Reliability Example** # Suppose we wish to estimate the reliability of a system comprised of many indetical parts iused in multiple places in a design, for instance rivets on an airplane wing. Using a Bernoulli model (which you will see in your statistics class) we can estimate the collective reliability of the system (all the parts work as desired). The reliability is expressed as the fraction of time that no parts have failed, if the fraction is small we would want to either improve part reliability, or ensure redundancy so the system can function with broken parts. # # Let $p$ be the probability a single component is good and $N$ be the total number of components in the system that work together in a "series" context. The reliability, or the percentage of time that none of the components have failed is given by the Bernoulli equation: # # $$\% = (\frac{p}{100.0})^N \cdot 100.0 $$ # # Suppose we want a script to read in a component probability and count, and estimate system reliability -- we can apply our problem solving protocol and JupyterLab to do so, and the task will be mostly sequential # # **Step 1 Problem Statement** Estimate the reliability of a component in an instrument relative to a group of components using a Bernoulli approximation. # # **Step 2 Input/Output Decomposition** Inputs are the reliability of a single component and the number of components working together in a system, output is estimate of system reliability, governing principle is the Bernoulli equation above. # # **Step 3 By-Hand Example** # Suppose the system is a small FPGA with 20 transistors, each with reliability of 96-percent. The entire array reliability is # # $$\text{percentage} = (\frac{96.0}{100.0})^{20} \cdot 100.0 = 44.2\%$$ # # **Step 4 Algorithm Development** # Decompose the computation problem as: # # 1. Read reliability of a single component # 2. Read how many components # 3. Compute reliability by bernoulli model # 4. Report result # # **Step 5 Scripting** # Written as a sequence we can have # ``` # component = float(input('Component Reliability (percentage-numeric)?')) # howmany = int(input('Number of Components (integer-numeric)?')) # reliability = 100.0*(component/100.0)**howmany # print('Component Reliability: ',round(component,1)) # print('Number of Components : ',howmany) # print('System Reliability is : ',round(reliability,1),'%') # ``` # **Step 6 Refinement** # We have tested the script with the by-hand example, no refinement really needed here, but lets apply to new conditions # ``` # component = float(input('Component Reliability (percentage-numeric)?')) # howmany = int(input('Number of Components (integer-numeric)?')) # reliability = 100.0*(component/100.0)**howmany # print('Component Reliability: ',round(component,1)) # print('Number of Components : ',howmany) # print('System Reliability is : ',round(reliability,1),'%') # ``` # --- # ## Selection Structures # Selection via conditional statements is an important step in algorithm design; its one way to control the flow of execution of a program. # # Conditional statements in Python include: # # - `if` statement is true, then do ... # - `if....else` statement is true, then do ..., otherwise do something else # - `if....elif....else` statement is true, then do ..., if something else is true then do ..., otherwise do ... # # Conditional statements are logical expressions that evaluate as TRUE or FALSE and using # these results to perform further operations based on these conditions. # All flow control in a program depends on evaluating conditions. The program will proceed # diferently based on the outcome of one or more conditions - really sophisticated AI programs are a collection of conditions and correlations. # # Expressed in a flowchart a block `if` statement looks like: # # ![](http://54.243.252.9/engr-1330-webroot/1-Lessons/Lesson05/conditional.png) # # As [psuedo code](https://towardsdatascience.com/pseudocode-101-an-introduction-to-writing-good-pseudocode-1331cb855be7): # # if(condition is true): # do stuff # # Amazon knowing what you kind of want is based on correlations of your past behavior compared to other peoples similar, but more recent behavior, and then it uses conditional statements to decide what item to offer you in your recommendation items. # It's spooky, but ultimately just a program running in the background trying to make your money theirs. # # ### Comparison # # The most common conditional operation is comparison. If we wish to compare whether two # variables are the same we use the == (double equal sign). # # For example x == y means the program will ask whether x and y have the same value. # If they do, the result is TRUE if not then the result is FALSE. # # Other comparison signs are `!=` does NOT equal, `<` smaller than, `> `larger than, `<= `less than or equal, and `>=` greater than or equal. # # There are also three logical operators when we want to build multiple compares # (multiple conditioning); these are `and`, `or`, and `not`. # # The `and` operator returns TRUE if (and only if) **all** conditions are TRUE. # For instance `5 == 5 and 5 < 6` will return a TRUE because both conditions are true. # # The `or` operator returns `TRUE` if at least one condition is true. # If **all** conditions are FALSE, then it will return a FALSE. For instance `4 > 3 or 17 > 20 or 3 == 2` will return `TRUE`because the first condition is true. # The `not` operator returns `TRUE` if the condition after the `not` keyword is false. Think of it # as a way to do a logic reversal. # # ### Block `if` statement # The `if` statement is a common flow control statement. # It allows the program to evaluate if a certain condition is satisfied and to perform a designed action based on the result of the evaluation. The structure of an `if` statement is # # if condition1 is met: # do A # elif condition 2 is met: # do b # elif condition 3 is met: # do c # else: # do e # # The `elif` means "else if". The `:` colon is an important part of the structure it tells where the action begins. Also there are no scope delimiters like (), or {} . # Instead Python uses indentation to isolate blocks of code. # # This convention is hugely important - many other coding environments use delimiters (called scoping delimiters), but Python does not. The indentation itself is the scoping delimiter. # # ### Inline `if` statement # An inline `if` statement is a simpler form of an `if` statement and is more convenient if you # only need to perform a simple conditional task. # The syntax is: # # do TaskA `if` condition is true `else` do TaskB # # An example would be # # myInt = 3 # num1 = 12 if myInt == 0 else 13 # num1 # # An alternative way is to enclose the condition in brackets for some clarity like # # myInt = 3 # num1 = 12 if (myInt == 0) else 13 # num1 # # In either case the result is that `num1` will have the value `13` (unless you set myInt to 0). # # One
<reponame>lezardrouge/tracim import typing from pyramid.config import Configurator from pyramid.httpexceptions import HTTPFound import transaction from tracim_backend.app_models.contents import content_type_list from tracim_backend.config import CFG from tracim_backend.exceptions import ConflictingMoveInChild from tracim_backend.exceptions import ConflictingMoveInItself from tracim_backend.exceptions import ContentFilenameAlreadyUsedInFolder from tracim_backend.exceptions import ContentNotFound from tracim_backend.exceptions import EmailValidationFailed from tracim_backend.exceptions import EmptyLabelNotAllowed from tracim_backend.exceptions import ParentNotFound from tracim_backend.exceptions import RoleAlreadyExistError from tracim_backend.exceptions import UnallowedSubContent from tracim_backend.exceptions import UserCantRemoveHisOwnRoleInWorkspace from tracim_backend.exceptions import UserDoesNotExist from tracim_backend.exceptions import UserIsDeleted from tracim_backend.exceptions import UserIsNotActive from tracim_backend.exceptions import UserRoleNotFound from tracim_backend.exceptions import WorkspaceLabelAlreadyUsed from tracim_backend.exceptions import WorkspacesDoNotMatch from tracim_backend.extensions import hapic from tracim_backend.lib.core.content import ContentApi from tracim_backend.lib.core.user import UserApi from tracim_backend.lib.core.userworkspace import RoleApi from tracim_backend.lib.core.workspace import WorkspaceApi from tracim_backend.lib.utils.authorization import can_create_content from tracim_backend.lib.utils.authorization import can_delete_workspace from tracim_backend.lib.utils.authorization import can_modify_workspace from tracim_backend.lib.utils.authorization import can_move_content from tracim_backend.lib.utils.authorization import can_see_workspace_information from tracim_backend.lib.utils.authorization import check_right from tracim_backend.lib.utils.authorization import is_administrator from tracim_backend.lib.utils.authorization import is_content_manager from tracim_backend.lib.utils.authorization import is_reader from tracim_backend.lib.utils.authorization import is_trusted_user from tracim_backend.lib.utils.request import TracimRequest from tracim_backend.lib.utils.utils import generate_documentation_swagger_tag from tracim_backend.lib.utils.utils import password_generator from tracim_backend.models.auth import AuthType from tracim_backend.models.context_models import ContentInContext from tracim_backend.models.context_models import UserRoleWorkspaceInContext from tracim_backend.models.data import ActionDescription from tracim_backend.models.data import Content from tracim_backend.models.revision_protection import new_revision from tracim_backend.models.roles import WorkspaceRoles from tracim_backend.views import BASE_API_V2 from tracim_backend.views.controllers import Controller from tracim_backend.views.core_api.schemas import ContentCreationSchema from tracim_backend.views.core_api.schemas import ContentDigestSchema from tracim_backend.views.core_api.schemas import ContentIdPathSchema from tracim_backend.views.core_api.schemas import ContentMoveSchema from tracim_backend.views.core_api.schemas import FilterContentQuerySchema from tracim_backend.views.core_api.schemas import NoContentSchema from tracim_backend.views.core_api.schemas import RoleUpdateSchema from tracim_backend.views.core_api.schemas import WorkspaceAndContentIdPathSchema from tracim_backend.views.core_api.schemas import WorkspaceAndUserIdPathSchema from tracim_backend.views.core_api.schemas import WorkspaceCreationSchema from tracim_backend.views.core_api.schemas import WorkspaceIdPathSchema from tracim_backend.views.core_api.schemas import WorkspaceMemberCreationSchema from tracim_backend.views.core_api.schemas import WorkspaceMemberInviteSchema from tracim_backend.views.core_api.schemas import WorkspaceMemberSchema from tracim_backend.views.core_api.schemas import WorkspaceModifySchema from tracim_backend.views.core_api.schemas import WorkspaceSchema from tracim_backend.views.swagger_generic_section import SWAGGER_TAG__ALL_SECTION from tracim_backend.views.swagger_generic_section import SWAGGER_TAG__ARCHIVE_AND_RESTORE_SECTION from tracim_backend.views.swagger_generic_section import SWAGGER_TAG__CONTENT_ENDPOINTS from tracim_backend.views.swagger_generic_section import SWAGGER_TAG__TRASH_AND_RESTORE_SECTION try: # Python 3.5+ from http import HTTPStatus except ImportError: from http import client as HTTPStatus SWAGGER_TAG__WORKSPACE_MEMBERS_SECTION = "Members" SWAGGER_TAG__WORKSPACE_ENDPOINTS = "Workspaces" SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS = generate_documentation_swagger_tag( SWAGGER_TAG__WORKSPACE_ENDPOINTS, SWAGGER_TAG__WORKSPACE_MEMBERS_SECTION ) SWAGGER_TAG__WORKSPACE_TRASH_AND_RESTORE_ENDPOINTS = generate_documentation_swagger_tag( SWAGGER_TAG__WORKSPACE_ENDPOINTS, SWAGGER_TAG__TRASH_AND_RESTORE_SECTION ) SWAGGER_TAG__CONTENT_ALL_TRASH_AND_RESTORE_ENDPOINTS = generate_documentation_swagger_tag( SWAGGER_TAG__CONTENT_ENDPOINTS, SWAGGER_TAG__ALL_SECTION, SWAGGER_TAG__TRASH_AND_RESTORE_SECTION ) SWAGGER_TAG__CONTENT_ALL_ARCHIVE_AND_RESTORE_ENDPOINTS = generate_documentation_swagger_tag( SWAGGER_TAG__CONTENT_ENDPOINTS, SWAGGER_TAG__ALL_SECTION, SWAGGER_TAG__ARCHIVE_AND_RESTORE_SECTION, ) class WorkspaceController(Controller): @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_ENDPOINTS]) @check_right(can_see_workspace_information) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.output_body(WorkspaceSchema()) def workspace(self, context, request: TracimRequest, hapic_data=None): """ Get workspace informations """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, session=request.dbsession, config=app_config # User ) return wapi.get_workspace_with_context(request.current_workspace) @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_ENDPOINTS]) @check_right(is_administrator) @hapic.output_body(WorkspaceSchema(many=True)) def workspaces(self, context, request: TracimRequest, hapic_data=None): """ Returns the list of all workspaces. This route is for admin only. Standard users must use their own route: /api/v2/users/me/workspaces """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, session=request.dbsession, config=app_config # User ) workspaces = wapi.get_all() return [wapi.get_workspace_with_context(workspace) for workspace in workspaces] @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(WorkspaceLabelAlreadyUsed, HTTPStatus.BAD_REQUEST) @check_right(can_modify_workspace) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.input_body(WorkspaceModifySchema()) @hapic.output_body(WorkspaceSchema()) def update_workspace(self, context, request: TracimRequest, hapic_data=None): """ Update a workspace. This route is for trusted users and administrators. Note : a trusted user can only update spaces on which he/she is space manager """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, session=request.dbsession, config=app_config # User ) wapi.update_workspace( request.current_workspace, label=hapic_data.body.label, description=hapic_data.body.description, agenda_enabled=hapic_data.body.agenda_enabled, save_now=True, ) wapi.execute_update_workspace_actions(request.current_workspace) return wapi.get_workspace_with_context(request.current_workspace) @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(WorkspaceLabelAlreadyUsed, HTTPStatus.BAD_REQUEST) @check_right(is_trusted_user) @hapic.input_body(WorkspaceCreationSchema()) @hapic.output_body(WorkspaceSchema()) def create_workspace(self, context, request: TracimRequest, hapic_data=None): """ Create a workspace. This route is for trusted users and administrators. """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, session=request.dbsession, config=app_config # User ) workspace = wapi.create_workspace( label=hapic_data.body.label, description=hapic_data.body.description, save_now=True, agenda_enabled=hapic_data.body.agenda_enabled, ) wapi.execute_created_workspace_actions(workspace) return wapi.get_workspace_with_context(workspace) @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_TRASH_AND_RESTORE_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @check_right(can_delete_workspace) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.NO_CONTENT) def delete_workspace(self, context, request: TracimRequest, hapic_data=None): """ Delete a workspace. This route is for trusted users and administrators. Note : a trusted user can only delete spaces on which he/she is space manager """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, session=request.dbsession, config=app_config # User ) wapi.delete(request.current_workspace, flush=True) return @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_TRASH_AND_RESTORE_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @check_right(can_delete_workspace) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.NO_CONTENT) def undelete_workspace(self, context, request: TracimRequest, hapic_data=None): """ Restore a deleted space. Note : a trusted user can only restore spaces on which he/she is space manager """ app_config = request.registry.settings["CFG"] # type: CFG wapi = WorkspaceApi( current_user=request.current_user, # User session=request.dbsession, config=app_config, show_deleted=True, ) wapi.undelete(request.current_workspace, flush=True) return @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS]) @check_right(can_see_workspace_information) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.output_body(WorkspaceMemberSchema(many=True)) def workspaces_members( self, context, request: TracimRequest, hapic_data=None ) -> typing.List[UserRoleWorkspaceInContext]: """ Returns the list of space members with their role, avatar, etc. """ app_config = request.registry.settings["CFG"] # type: CFG rapi = RoleApi( current_user=request.current_user, session=request.dbsession, config=app_config ) roles = rapi.get_all_for_workspace(request.current_workspace) return [rapi.get_user_role_workspace_with_context(user_role) for user_role in roles] @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS]) @check_right(can_see_workspace_information) @hapic.input_path(WorkspaceAndUserIdPathSchema()) @hapic.output_body(WorkspaceMemberSchema()) def workspaces_member_role( self, context, request: TracimRequest, hapic_data=None ) -> UserRoleWorkspaceInContext: """ Returns given space member with its role, avatar, etc. """ app_config = request.registry.settings["CFG"] # type: CFG rapi = RoleApi( current_user=request.current_user, session=request.dbsession, config=app_config ) role = rapi.get_one( user_id=hapic_data.path.user_id, workspace_id=hapic_data.path.workspace_id ) return rapi.get_user_role_workspace_with_context(role) @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS]) @hapic.handle_exception(UserRoleNotFound, HTTPStatus.BAD_REQUEST) @check_right(can_modify_workspace) @hapic.input_path(WorkspaceAndUserIdPathSchema()) @hapic.input_body(RoleUpdateSchema()) @hapic.output_body(WorkspaceMemberSchema()) def update_workspaces_members_role( self, context, request: TracimRequest, hapic_data=None ) -> UserRoleWorkspaceInContext: """ Update role of the given space member. This feature is for workspace managers, trusted users and administrators. """ app_config = request.registry.settings["CFG"] # type: CFG rapi = RoleApi( current_user=request.current_user, session=request.dbsession, config=app_config ) role = rapi.get_one( user_id=hapic_data.path.user_id, workspace_id=hapic_data.path.workspace_id ) workspace_role = WorkspaceRoles.get_role_from_slug(hapic_data.body.role) role = rapi.update_role(role, role_level=workspace_role.level) return rapi.get_user_role_workspace_with_context(role) @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS]) @check_right(can_modify_workspace) @hapic.handle_exception(UserRoleNotFound, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(UserCantRemoveHisOwnRoleInWorkspace, HTTPStatus.BAD_REQUEST) @hapic.input_path(WorkspaceAndUserIdPathSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.NO_CONTENT) def delete_workspaces_members_role( self, context, request: TracimRequest, hapic_data=None ) -> None: """ Remove the user from the space. This feature is for workspace managers and administrators. """ app_config = request.registry.settings["CFG"] # type: CFG rapi = RoleApi( current_user=request.current_user, session=request.dbsession, config=app_config ) rapi.delete_one(user_id=hapic_data.path.user_id, workspace_id=hapic_data.path.workspace_id) return @hapic.with_api_doc(tags=[SWAGGER_TAG__WORKSPACE_MEMBERS_ENDPOINTS]) @hapic.handle_exception(EmailValidationFailed, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(UserDoesNotExist, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(UserIsNotActive, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(UserIsDeleted, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(RoleAlreadyExistError, HTTPStatus.BAD_REQUEST) @check_right(can_modify_workspace) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.input_body(WorkspaceMemberInviteSchema()) @hapic.output_body(WorkspaceMemberCreationSchema()) def create_workspaces_members_role( self, context, request: TracimRequest, hapic_data=None ) -> UserRoleWorkspaceInContext: """ Add a member to this workspace. This feature is for workspace managers and administrators. """ newly_created = False email_sent = False app_config = request.registry.settings["CFG"] # type: CFG rapi = RoleApi( current_user=request.current_user, session=request.dbsession, config=app_config ) uapi = UserApi( current_user=request.current_user, session=request.dbsession, config=app_config, show_deactivated=True, show_deleted=True, ) try: _, user = uapi.find( user_id=hapic_data.body.user_id, email=hapic_data.body.user_email, public_name=hapic_data.body.user_public_name, ) if user.is_deleted: raise UserIsDeleted("This user has been deleted. Unable to invite him.") if not user.is_active: raise UserIsNotActive("This user is not activated. Unable to invite him") except UserDoesNotExist as exc: if not uapi.allowed_to_invite_new_user(hapic_data.body.user_email): raise exc if app_config.NEW_USER__INVITATION__DO_NOTIFY: user = uapi.create_user( auth_type=AuthType.UNKNOWN, email=hapic_data.body.user_email, password=password_generator(), do_notify=True, ) if ( app_config.EMAIL__NOTIFICATION__ACTIVATED and app_config.NEW_USER__INVITATION__DO_NOTIFY and app_config.EMAIL__PROCESSING_MODE.lower() == "sync" ): email_sent = True else: user = uapi.create_user( auth_type=AuthType.UNKNOWN, email=hapic_data.body.user_email, password=<PASSWORD>, do_notify=False, ) uapi.execute_created_user_actions(user) newly_created = True role = rapi.create_one( user=user, workspace=request.current_workspace, role_level=WorkspaceRoles.get_role_from_slug(hapic_data.body.role).level, with_notif=app_config.EMAIL__NOTIFICATION__ENABLED_ON_INVITATION, flush=True, ) return rapi.get_user_role_workspace_with_context( role, newly_created=newly_created, email_sent=email_sent ) @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_ENDPOINTS]) @check_right(is_reader) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.input_query(FilterContentQuerySchema()) @hapic.output_body(ContentDigestSchema(many=True)) def workspace_content( self, context, request: TracimRequest, hapic_data=None ) -> typing.List[ContentInContext]: """ return a list of contents of the space. This is NOT the full content list: by default, returned contents are the ones at root level. In order to get contents in a given folder, then use parent_id query filter. You can also show.hide archived/deleted contents. """ app_config = request.registry.settings["CFG"] # type: CFG content_filter = hapic_data.query api = ContentApi( current_user=request.current_user, session=request.dbsession, config=app_config, show_archived=content_filter.show_archived, show_deleted=content_filter.show_deleted, show_active=content_filter.show_active, ) contents = api.get_all( parent_ids=content_filter.parent_ids, complete_path_to_id=content_filter.complete_path_to_id, workspace=request.current_workspace, content_type=content_filter.content_type or content_type_list.Any_SLUG, label=content_filter.label, order_by_properties=[Content.label], ) contents = [api.get_content_in_context(content) for content in contents] return contents @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(UnallowedSubContent, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(ContentFilenameAlreadyUsedInFolder, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(ParentNotFound, HTTPStatus.BAD_REQUEST) @check_right(can_create_content) @hapic.input_path(WorkspaceIdPathSchema()) @hapic.input_body(ContentCreationSchema()) @hapic.output_body(ContentDigestSchema()) def create_generic_empty_content( self, context, request: TracimRequest, hapic_data=None ) -> ContentInContext: """ Creates a generic empty content. The minimum viable content has a label and a content type. Creating a content generally starts with a request to this endpoint. For specific contents like files, it is recommended to use the dedicated endpoint. This feature is accessible to contributors and higher role only. """ app_config = request.registry.settings["CFG"] # type: CFG creation_data = hapic_data.body api = ContentApi( current_user=request.current_user, session=request.dbsession, config=app_config ) parent = None if creation_data.parent_id: try: parent = api.get_one( content_id=creation_data.parent_id, content_type=content_type_list.Any_SLUG ) except ContentNotFound as exc: raise ParentNotFound( "Parent with content_id {} not found".format(creation_data.parent_id) ) from exc content = api.create( label=creation_data.label, content_type_slug=creation_data.content_type, workspace=request.current_workspace, parent=parent, ) api.save(content, ActionDescription.CREATION) api.execute_created_content_actions(content) content = api.get_content_in_context(content) return content @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_ENDPOINTS]) @check_right(is_reader) @hapic.input_path(WorkspaceAndContentIdPathSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.FOUND) def get_content_from_workspace(self, context, request: TracimRequest, hapic_data=None) -> None: """ Convenient route allowing to get detail about a content without to known routes associated to its content type. This route generate a HTTP 302 with the right url """ content = request.current_content content_type = content_type_list.get_one_by_slug(content.type).slug # TODO - G.M - 2018-08-03 - Jsonify redirect response ? raise HTTPFound( "{base_url}workspaces/{workspace_id}/{content_type}s/{content_id}".format( base_url=BASE_API_V2, workspace_id=content.workspace_id, content_type=content_type, content_id=content.content_id, ) ) @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_ENDPOINTS]) @hapic.input_path(ContentIdPathSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.FOUND) def get_content(self, context, request: TracimRequest, hapic_data=None) -> None: """ Convenient route allowing to get detail about a content without to known routes associated to its content type. This route generate a HTTP 302 with the right url
not check if path %s exists.") % path LOG.exception(msg) raise exception.HNASBackendException(msg=msg) return True def check_fs_mounted(self): command = ['df', '-a', '-f', self.fs_name] output, err = self._execute(command) if "not found" in output: msg = _("Filesystem %s does not exist or it is not available " "in the current EVS context.") % self.fs_name LOG.error(msg) raise exception.HNASItemNotFoundException(msg=msg) else: line = output.split('\n') fs = Filesystem(line[3]) return fs.mounted def mount(self): command = ['mount', self.fs_name] try: self._execute(command) except processutils.ProcessExecutionError as e: if 'file system is already mounted' not in e.stderr: msg = _("Failed to mount filesystem %s.") % self.fs_name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) def vvol_create(self, vvol_name): # create a virtual-volume inside directory path = '/shares/' + vvol_name command = ['virtual-volume', 'add', '--ensure', self.fs_name, vvol_name, path] try: self._execute(command) except processutils.ProcessExecutionError: msg = _("Failed to create vvol %s.") % vvol_name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) def vvol_delete(self, vvol_name): path = '/shares/' + vvol_name # Virtual-volume and quota are deleted together command = ['tree-delete-job-submit', '--confirm', '-f', self.fs_name, path] try: self._execute(command) except processutils.ProcessExecutionError as e: if 'Source path: Cannot access' in e.stderr: LOG.warning("Share %s does not exist.", vvol_name) else: msg = _("Failed to delete vvol %s.") % vvol_name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) def quota_add(self, vvol_name, vvol_quota): str_quota = six.text_type(vvol_quota) + 'G' command = ['quota', 'add', '--usage-limit', str_quota, '--usage-hard-limit', 'yes', self.fs_name, vvol_name] try: self._execute(command) except processutils.ProcessExecutionError: msg = _("Failed to add %(quota)s quota to vvol " "%(vvol)s.") % {'quota': str_quota, 'vvol': vvol_name} LOG.exception(msg) raise exception.HNASBackendException(msg=msg) def modify_quota(self, vvol_name, new_size): str_quota = six.text_type(new_size) + 'G' command = ['quota', 'mod', '--usage-limit', str_quota, self.fs_name, vvol_name] try: self._execute(command) except processutils.ProcessExecutionError: msg = _("Failed to update quota of vvol %(vvol)s to " "%(quota)s.") % {'quota': str_quota, 'vvol': vvol_name} LOG.exception(msg) raise exception.HNASBackendException(msg=msg) def check_vvol(self, vvol_name): command = ['virtual-volume', 'list', '--verbose', self.fs_name, vvol_name] try: self._execute(command) except processutils.ProcessExecutionError: msg = _("Virtual volume %s does not exist.") % vvol_name LOG.exception(msg) raise exception.HNASItemNotFoundException(msg=msg) def check_quota(self, vvol_name): command = ['quota', 'list', '--verbose', self.fs_name, vvol_name] try: output, err = self._execute(command) except processutils.ProcessExecutionError: msg = _("Could not check quota of vvol %s.") % vvol_name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) if 'No quotas matching specified filter criteria' in output: msg = _("Virtual volume %s does not have any" " quota.") % vvol_name LOG.error(msg) raise exception.HNASItemNotFoundException(msg=msg) def check_export(self, vvol_name, is_snapshot=False): export = self._get_export(vvol_name, is_snapshot=is_snapshot) if (vvol_name in export[0].export_name and self.fs_name in export[0].file_system_label): return else: msg = _("Export %s does not exist.") % export[0].export_name LOG.error(msg) raise exception.HNASItemNotFoundException(msg=msg) def check_cifs(self, vvol_name): output = self._cifs_list(vvol_name) cifs_share = CIFSShare(output) if self.fs_name != cifs_share.fs: msg = _("CIFS share %(share)s is not located in " "configured filesystem " "%(fs)s.") % {'share': vvol_name, 'fs': self.fs_name} LOG.error(msg) raise exception.HNASItemNotFoundException(msg=msg) def is_cifs_in_use(self, vvol_name): output = self._cifs_list(vvol_name) cifs_share = CIFSShare(output) return cifs_share.is_mounted def _cifs_list(self, vvol_name): command = ['cifs-share', 'list', vvol_name] try: output, err = self._execute(command) except processutils.ProcessExecutionError as e: if 'does not exist' in e.stderr: msg = _("CIFS share %(share)s was not found in EVS " "%(evs_id)s") % {'share': vvol_name, 'evs_id': self.evs_id} LOG.exception(msg) raise exception.HNASItemNotFoundException(msg=msg) else: msg = _("Could not list CIFS shares by vvol name " "%s.") % vvol_name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) return output def get_share_quota(self, share_id): command = ['quota', 'list', self.fs_name, share_id] output, err = self._execute(command) quota = Quota(output) if quota.limit is None: return None if quota.limit_unit == 'TB': return quota.limit * units.Ki elif quota.limit_unit == 'GB': return quota.limit else: msg = _("Share %s does not support quota values " "below 1G.") % share_id LOG.error(msg) raise exception.HNASBackendException(msg=msg) def get_share_usage(self, share_id): command = ['quota', 'list', self.fs_name, share_id] output, err = self._execute(command) quota = Quota(output) if quota.usage is None: msg = _("Virtual volume %s does not have any quota.") % share_id LOG.error(msg) raise exception.HNASItemNotFoundException(msg=msg) else: bytes_usage = strutils.string_to_bytes(six.text_type(quota.usage) + quota.usage_unit) return bytes_usage / units.Gi def _get_export(self, name, is_snapshot=False): if is_snapshot: name = '/snapshots/' + name else: name = '/shares/' + name command = ['nfs-export', 'list ', name] export_list = [] try: output, err = self._execute(command) except processutils.ProcessExecutionError as e: if 'does not exist' in e.stderr: msg = _("Export %(name)s was not found in EVS " "%(evs_id)s.") % { 'name': name, 'evs_id': self.evs_id, } LOG.exception(msg) raise exception.HNASItemNotFoundException(msg=msg) else: msg = _("Could not list NFS exports by name %s.") % name LOG.exception(msg) raise exception.HNASBackendException(msg=msg) items = output.split('Export name') if items[0][0] == '\n': items.pop(0) for i in range(0, len(items)): export_list.append(Export(items[i])) return export_list @mutils.retry(retry_param=exception.HNASConnException, wait_random=True) def _execute(self, commands): command = ['ssc', '127.0.0.1'] if self.admin_ip0 is not None: command = ['ssc', '--smuauth', self.admin_ip0] command += ['console-context', '--evs', self.evs_id] commands = command + commands mutils.check_ssh_injection(commands) commands = ' '.join(commands) if not self.sshpool: self.sshpool = mutils.SSHPool(ip=self.ip, port=self.port, conn_timeout=None, login=self.user, password=<PASSWORD>, privatekey=self.priv_key) with self.sshpool.item() as ssh: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: out, err = processutils.ssh_execute(ssh, commands, check_exit_code=True) LOG.debug("Command %(cmd)s result: out = %(out)s - err = " "%(err)s.", { 'cmd': commands, 'out': out, 'err': err, }) return out, err except processutils.ProcessExecutionError as e: if 'Failed to establish SSC connection' in e.stderr: msg = _("Failed to establish SSC connection.") LOG.debug(msg) raise exception.HNASConnException(msg=msg) else: LOG.debug("Error running SSH command. " "Command %(cmd)s result: out = %(out)s - err = " "%(err)s - exit = %(exit)s.", { 'cmd': e.cmd, 'out': e.stdout, 'err': e.stderr, 'exit': e.exit_code, }) raise @mutils.synchronized("hitachi_hnas_select_fs", external=True) def _locked_selectfs(self, op, path): if op == 'create': command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', 'console-context', '--evs', self.evs_id, 'mkdir', '-p', path] try: self._execute(command) except processutils.ProcessExecutionError as e: if "Current file system invalid: VolumeNotFound" in e.stderr: msg = _("Command to create directory %s failed due to " "context change.") % path LOG.debug(msg) raise exception.HNASSSCContextChange(msg=msg) else: msg = _("Failed to create directory %s.") % path LOG.exception(msg) raise exception.HNASBackendException(msg=msg) if op == 'delete': command = ['selectfs', self.fs_name, '\n', 'ssc', '127.0.0.1', 'console-context', '--evs', self.evs_id, 'rmdir', path] try: self._execute(command) except processutils.ProcessExecutionError as e: if 'DirectoryNotEmpty' in e.stderr: msg = _("Share %s has more snapshots.") % path LOG.debug(msg) raise exception.HNASDirectoryNotEmpty(msg=msg) elif 'cannot remove' in e.stderr and 'NotFound' in e.stderr: LOG.warning("Attempted to delete path %s but it does " "not exist.", path) elif 'Current file system invalid: VolumeNotFound' in e.stderr: msg = _("Command to delete empty directory %s failed due " "to context change.") % path LOG.debug(msg) raise exception.HNASSSCContextChange(msg=msg) else: msg = _("Failed to delete directory %s.") % path LOG.exception(msg) raise exception.HNASBackendException(msg=msg) class Export(object): def __init__(self, data): if data: split_data = data.split('Export configuration:\n') items = split_data[0].split('\n') self.export_name = items[0].split(':')[1].strip() self.export_path = items[1].split(':')[1].strip() if '*** not available ***' in items[2]: self.file_system_info = items[2].split(':')[1].strip() index = 0 else: self.file_system_label = items[2].split(':')[1].strip() self.file_system_size = items[3].split(':')[1].strip() self.file_system_free_space = items[4].split(':')[1].strip() self.file_system_state = items[5].split(':')[1] self.formatted = items[6].split('=')[1].strip() self.mounted = items[7].split('=')[1].strip() self.failed = items[8].split('=')[1].strip() self.thin_provisioned = items[9].split('=')[1].strip() index = 7 self.access_snapshots = items[3 + index].split(':')[1].strip() self.display_snapshots = items[4 + index].split(':')[1].strip() self.read_caching = items[5 + index].split(':')[1].strip() self.disaster_recovery_setting = items[6 + index].split(':')[1] self.recovered = items[7 + index].split('=')[1].strip() self.transfer_setting = items[8 + index].split('=')[1].strip() self.export_configuration = [] export_config = split_data[1].split('\n') for i in range(0, len(export_config)): if any(j.isdigit() or j.isalpha() for j in export_config[i]): self.export_configuration.append(export_config[i]) class JobStatus(object): def __init__(self, data): if data: lines = data.split("\n") self.job_id = lines[0].split()[3] self.physical_node = lines[2].split()[3] self.evs = lines[3].split()[2] self.volume_number = lines[4].split()[3] self.fs_id = lines[5].split()[4] self.fs_name = lines[6].split()[4] self.source_path = lines[7].split()[3] self.creation_time = " ".join(lines[8].split()[3:5]) self.destination_path = lines[9].split()[3] self.ensure_path_exists = lines[10].split()[5] self.job_state = " ".join(lines[12].split()[3:]) self.job_started = " ".join(lines[14].split()[2:4]) self.job_ended = " ".join(lines[15].split()[2:4]) self.job_status = lines[16].split()[2] error_details_line = lines[17].split() if len(error_details_line) > 3: self.error_details = " ".join(error_details_line[3:]) else: self.error_details = None self.directories_processed = lines[18].split()[3] self.files_processed = lines[19].split()[3] self.data_bytes_processed = lines[20].split()[4] self.directories_missing = lines[21].split()[4] self.files_missing = lines[22].split()[4] self.files_skipped = lines[23].split()[4] skipping_details_line = lines[24].split() if len(skipping_details_line) > 3: self.skipping_details = " ".join(skipping_details_line[3:]) else: self.skipping_details = None class JobSubmit(object): def __init__(self, data): if data: split_data = data.replace(".", "").split() self.request_status = " ".join(split_data[1:4]) self.job_id = split_data[8] class Filesystem(object): def __init__(self, data): if data: items = data.split() self.id = items[0] self.label = items[1] self.evs = items[2] self.size = float(items[3]) self.size_measure = items[4] if self.size_measure == 'TB': self.size = self.size * units.Ki if items[5:7] == ["Not", "mounted"]: self.mounted = False else: self.mounted = True self.used = float(items[5]) self.used_measure = items[6] if self.used_measure == 'TB': self.used = self.used * units.Ki self.dedupe = 'dedupe enabled'
<filename>dark/proteins.py<gh_stars>1-10 from __future__ import print_function, division import os from collections import defaultdict, Counter import numpy as np from os.path import dirname, exists, join from operator import itemgetter import re from six.moves.urllib.parse import quote from textwrap import fill from dark.dimension import dimensionalIterator from dark.fasta import FastaReads from dark.fastq import FastqReads from dark.filter import TitleFilter from dark.html import NCBISequenceLinkURL from dark.reads import Reads # The following regex is deliberately greedy (using .*) to consume the # whole protein name before backtracking to find the last [pathogen name] # section. That way, it will match just the last [pathogen name] in a # protein. This avoids situations in which two [...] delimited substrings # are present in a protein name (in which case we just want the last). # E.g., the following is a complete protein name: # # gi|19919894|ref|NP_612577.1| Enzymatic polyprotein [Contains: Aspartic # protease; Endonuclease; Reverse transcriptase] [Carnation etched ring # virus] # # Unfortunately the regex doesn't find the pathogen name when the protein # name has nested [...] sections, as in this example: # # gi|224808893|ref|YP_002643049.1| replication-associated protein [Tomato # leaf curl Nigeria virus-[Nigeria:2006]] # # I decided not to worry about nested [...] sections (there are only 2 # instances that I know of). _PATHOGEN_RE = re.compile(r'^(.*)\[([^\]]+)\]$') # The pathogen name assigned to proteins whose id strings cannot be parsed # for a pathogen name (see previous comment). Do not use '<', '>' or any # other HTML special chars in the following. _NO_PATHOGEN_NAME = '[no pathogen name found in sequence id]' def splitNames(names): """ Split a sequence id string like "Protein name [pathogen name]" into two pieces using the final square brackets to delimit the pathogen name. @param names: A C{str} "protein name [pathogen name]" string. @return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen name. If C{names} cannot be split on square brackets, it is returned as the first tuple element, followed by _NO_PATHOGEN_NAME. """ match = _PATHOGEN_RE.match(names) if match: proteinName = match.group(1).strip() pathogenName = match.group(2).strip() else: proteinName = names pathogenName = _NO_PATHOGEN_NAME return proteinName, pathogenName def getPathogenProteinCounts(filenames): """ Get the number of proteins for each pathogen in C{filenames}. @param filenames: Either C{None} or a C{list} of C{str} FASTA file names. If C{None} an empty C{Counter} is returned. If FASTA file names are given, their sequence ids should have the format used in the NCBI bacterial and viral protein reference sequence files, in which the protein name is followed by the pathogen name in square brackets. @return: A C{Counter} keyed by C{str} pathogen name, whose values are C{int}s with the count of the number of proteins for the pathogen. """ result = Counter() if filenames: for filename in filenames: for protein in FastaReads(filename): _, pathogenName = splitNames(protein.id) if pathogenName != _NO_PATHOGEN_NAME: result[pathogenName] += 1 return result class PathogenSampleFiles(object): """ Maintain a cache of FASTA/FASTQ file names for the samples that contain a given pathogen, create de-duplicated (by read id) FASTA/FASTQ files for each pathogen/sample pair, provide functions to write out index files of sample and pathogen numbers (which are generated here in C{self.add}), and provide a filename lookup function for pathogen/sample combinations or just pathogen names by themselves. @param proteinGrouper: An instance of C{ProteinGrouper}. @param format_: A C{str}, either 'fasta' or 'fastq' indicating the format of the files containing the reads matching proteins. @raise ValueError: If C{format_} is unknown. """ def __init__(self, proteinGrouper, format_='fasta'): self._proteinGrouper = proteinGrouper if format_ in ('fasta', 'fastq'): self._format = format_ self._readsClass = FastaReads if format_ == 'fasta' else FastqReads else: raise ValueError("format_ must be either 'fasta' or 'fastq'.") self._pathogens = {} self._samples = {} self._readsFilenames = {} def add(self, pathogenName, sampleName): """ Add a (pathogen name, sample name) combination and get its FASTA/FASTQ file name and unique read count. Write the FASTA/FASTQ file if it does not already exist. Save the unique read count into C{self._proteinGrouper}. @param pathogenName: A C{str} pathogen name. @param sampleName: A C{str} sample name. @return: A C{str} giving the FASTA/FASTQ file name holding all the reads (without duplicates, by id) from the sample that matched the proteins in the given pathogen. """ pathogenIndex = self._pathogens.setdefault(pathogenName, len(self._pathogens)) sampleIndex = self._samples.setdefault(sampleName, len(self._samples)) try: return self._readsFilenames[(pathogenIndex, sampleIndex)] except KeyError: reads = Reads() for proteinMatch in self._proteinGrouper.pathogenNames[ pathogenName][sampleName]['proteins'].values(): for read in self._readsClass(proteinMatch['readsFilename']): reads.add(read) saveFilename = join( proteinMatch['outDir'], 'pathogen-%d-sample-%d.%s' % (pathogenIndex, sampleIndex, self._format)) reads.filter(removeDuplicatesById=True) nReads = reads.save(saveFilename, format_=self._format) # Save the unique read count into self._proteinGrouper self._proteinGrouper.pathogenNames[ pathogenName][sampleName]['uniqueReadCount'] = nReads self._readsFilenames[(pathogenIndex, sampleIndex)] = saveFilename return saveFilename def lookup(self, pathogenName, sampleName): """ Look up a pathogen name, sample name combination and get its FASTA/FASTQ file name and unique read count. This method should be used instead of C{add} in situations where you want an exception to be raised if a pathogen/sample combination has not already been passed to C{add}. @param pathogenName: A C{str} pathogen name. @param sampleName: A C{str} sample name. @raise KeyError: If the pathogen name or sample name have not been seen, either individually or in combination. @return: A (C{str}, C{int}) tuple retrieved from self._readsFilenames """ pathogenIndex = self._pathogens[pathogenName] sampleIndex = self._samples[sampleName] return self._readsFilenames[(pathogenIndex, sampleIndex)] def writeSampleIndex(self, fp): """ Write a file of sample indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) in self._samples.items()) ), file=fp) def writePathogenIndex(self, fp): """ Write a file of pathogen indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) in self._pathogens.items()) ), file=fp) def pathogenIndex(self, pathogenName): """ Get the index for a pathogen. @param pathogenName: A C{str} pathogen name. @raise KeyError: If the named pathogen is unknown. @return: An C{int} giving the index for the pathogen (as set in self.add). """ return self._pathogens[pathogenName] class ProteinGrouper(object): """ Group matched proteins by the pathogen they come from. @param assetDir: The C{str} directory name where C{noninteractive-alignment-panel.py} put its HTML, blue plot and alignment panel images, and FASTA or FASTQ files. This must be relative to the filenames that will later be passed to C{addFile}. @param sampleName: A C{str} sample name. This takes precedence over C{sampleNameRegex} (the two cannot be used together, obviously). @param sampleNameRegex: A C{str} regular expression that can be used to extract a short sample name from full file names subsequently passed to C{self.addFile}. The regular expression must have a matching group (delimited by parentheses) to capture the part of the file name that should be used as the sample name. @param format_: A C{str}, either 'fasta' or 'fastq' indicating the format of the files containing the reads matching proteins. @param proteinFastaFilenames: If not C{None}, a C{list} of C{str} filenames giving the name of the FASTA file with the protein AA sequences with their associated pathogens in square brackets. This is the format used by NCBI for the bacterial and viral reference sequence protein files. If given, the contents of this file will be used to determine how many proteins each matched pathogen has. @param saveReadLengths: If C{True}, save the lengths of all reads matching proteins. @param titleRegex: A regex that pathogen names must match. Note that this matching is done on the final part of the protein title in square brackets, according to the convention used by the NCBI viral refseq database and RVDB. @param negativeTitleRegex: A regex that pathogen names must not match. Note that this matching is done on the final part of the protein title in square brackets, according to the convention used by the NCBI viral refseq database and RVDB. @param pathogenDataDir: The C{str} directory where per-pathogen information (e.g., collected reads across all samples) should be written. Will be created (in C{self.toHTML}) if it doesn't exist. @raise ValueError: If C{format_} is unknown. """ VIRALZONE = 'https://viralzone.expasy.org/search?query=' ICTV = 'https://talk.ictvonline.org/search-124283882/?q=' READCOUNT_MARKER = '*READ-COUNT*' READ_AND_HSP_COUNT_STR_SEP = '/' def __init__(self, assetDir='out', sampleName=None, sampleNameRegex=None, format_='fasta', proteinFastaFilenames=None, saveReadLengths=False, titleRegex=None, negativeTitleRegex=None, pathogenDataDir='pathogen-data'): self._assetDir = assetDir self._sampleName = sampleName self._sampleNameRegex = (re.compile(sampleNameRegex) if sampleNameRegex else None) if
<gh_stars>1-10 ''' Differentiable approximation to the mutual information (MI) metric. Implementation in PyTorch MRI atlas files were downloaded from: https://www.bic.mni.mcgill.ca/ServicesAtlases/Colin27 ''' # Imports # # ---------------------------------------------------------------------- import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt from matplotlib import cm import os import nibabel as nib from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter # Functions # # ---------------------------------------------------------------------- # Mutual information - numpy implementation for comparison # Note: This code snippet was taken from the tutorial found at: # https://matthew-brett.github.io/teaching/mutual_information.html # Fro comparison purposes def mutual_information(hgram): """Mutual information (MI) for joint histogram MI is in fact the Kullback-Leibler (KL) divergence between P_{xy}(x, y) and P_x(x) * P_y(y): I(x, y) = D_{KL}(P_{xy} || p_x * p_y) :param hgram: Joint 2D histogram :return: MI (scalar) """ # Convert bin counts to probability values pxy = hgram / float(np.sum(hgram)) px = np.sum(pxy, axis=1) # marginal for x over y py = np.sum(pxy, axis=0) # marginal for y over x # Broadcast to multiply marginals. Now we can do the calculation using the pxy, px_py 2D arrays px_py = px[:, None] * py[None, :] nzs = pxy > 0 # Only non-zero pxy values contribute to the sum # Return the KL-divergence return np.sum(pxy[nzs] * np.log(pxy[nzs] / px_py[nzs])) # Entropy - numpy implementation for comparison def entropy(hgram): """ Calculates the entropy og a given histogram :param hgram: Histogram (of any dimension) :return: Entropy (scalar) """ px = hgram / float(np.sum(hgram)) nzs = px > 0 # Only non-zero pxy values contribute to the sum x = np.sum(px[nzs] * np.log(px[nzs])) return -x # Note: This code snippet was taken from the discussion found at: # https://discuss.pytorch.org/t/differentiable-torch-histc/25865/2 # By Tony-Y class SoftHistogram1D(nn.Module): ''' Differentiable 1D histogram calculation (supported via pytorch's autograd) inupt: x - N x D array, where N is the batch size and D is the length of each data series bins - Number of bins for the histogram min - Scalar min value to be included in the histogram max - Scalar max value to be included in the histogram sigma - Scalar smoothing factor fir the bin approximation via sigmoid functions. Larger values correspond to sharper edges, and thus yield a more accurate approximation output: N x bins array, where each row is a histogram ''' def __init__(self, bins=50, min=0, max=1, sigma=10): super(SoftHistogram1D, self).__init__() self.bins = bins self.min = min self.max = max self.sigma = sigma self.delta = float(max - min) / float(bins) self.centers = float(min) + self.delta * (torch.arange(bins).float() + 0.5) # Bin centers self.centers = nn.Parameter(self.centers, requires_grad=False) # Wrap for allow for cuda support def forward(self, x): # Replicate x and for each row remove center x = torch.unsqueeze(x, 1) - torch.unsqueeze(self.centers, 1) # Bin approximation using a sigmoid function x = torch.sigmoid(self.sigma * (x + self.delta / 2)) - torch.sigmoid(self.sigma * (x - self.delta / 2)) # Sum along the non-batch dimensions x = x.sum(dim=-1) # x = x / x.sum(dim=-1).unsqueeze(1) # normalization return x # Note: This is an extension to the 2D case of the previous code snippet class SoftHistogram2D(nn.Module): ''' Differentiable 1D histogram calculation (supported via pytorch's autograd) inupt: x, y - N x D array, where N is the batch size and D is the length of each data series (i.e. vectorized image or vectorized 3D volume) bins - Number of bins for the histogram min - Scalar min value to be included in the histogram max - Scalar max value to be included in the histogram sigma - Scalar smoothing factor fir the bin approximation via sigmoid functions. Larger values correspond to sharper edges, and thus yield a more accurate approximation output: N x bins array, where each row is a histogram ''' def __init__(self, bins=50, min=0, max=1, sigma=10): super(SoftHistogram2D, self).__init__() self.bins = bins self.min = min self.max = max self.sigma = sigma self.delta = float(max - min) / float(bins) self.centers = float(min) + self.delta * (torch.arange(bins).float() + 0.5) # Bin centers self.centers = nn.Parameter(self.centers, requires_grad=False) # Wrap for allow for cuda support def forward(self, x, y): assert x.size() == y.size(), "(SoftHistogram2D) x and y sizes do not match" # Replicate x and for each row remove center x = torch.unsqueeze(x, 1) - torch.unsqueeze(self.centers, 1) y = torch.unsqueeze(y, 1) - torch.unsqueeze(self.centers, 1) # Bin approximation using a sigmoid function (can be sigma_x and sigma_y respectively - same for delta) x = torch.sigmoid(self.sigma * (x + self.delta / 2)) - torch.sigmoid(self.sigma * (x - self.delta / 2)) y = torch.sigmoid(self.sigma * (y + self.delta / 2)) - torch.sigmoid(self.sigma * (y - self.delta / 2)) # Batched matrix multiplication - this way we sum jointly z = torch.matmul(x, y.permute((0, 2, 1))) return z class MI_pytorch(nn.Module): ''' This class is a pytorch implementation of the mutual information (MI) calculation between two images. This is an approximation, as the images' histograms rely on differentiable approximations of rectangular windows. I(X, Y) = H(X) + H(Y) - H(X, Y) = \sum(\sum(p(X, Y) * log(p(Y, Y)/(p(X) * p(Y))))) where H(X) = -\sum(p(x) * log(p(x))) is the entropy ''' def __init__(self, bins=50, min=0, max=1, sigma=10, reduction='sum'): super(MI_pytorch, self).__init__() self.bins = bins self.min = min self.max = max self.sigma = sigma self.reduction = reduction # 2D joint histogram self.hist2d = SoftHistogram2D(bins, min, max, sigma) # Epsilon - to avoid log(0) self.eps = torch.tensor(0.00000001, dtype=torch.float32, requires_grad=False) def forward(self, im1, im2): ''' Forward implementation of a differentiable MI estimator for batched images :param im1: N x ... tensor, where N is the batch size ... dimensions can take any form, i.e. 2D images or 3D volumes. :param im2: N x ... tensor, where N is the batch size :return: N x 1 vector - the approximate MI values between the batched im1 and im2 ''' # Check for valid inputs assert im1.size() == im2.size(), "(MI_pytorch) Inputs should have the same dimensions." batch_size = im1.size()[0] # Flatten tensors im1_flat = im1.view(im1.size()[0], -1) im2_flat = im2.view(im2.size()[0], -1) # Calculate joint histogram hgram = self.hist2d(im1_flat, im2_flat) # Convert to a joint distribution # Pxy = torch.distributions.Categorical(probs=hgram).probs Pxy = torch.div(hgram, torch.sum(hgram.view(hgram.size()[0], -1))) # Calculate the marginal distributions Py = torch.sum(Pxy, dim=1).unsqueeze(1) Px = torch.sum(Pxy, dim=2).unsqueeze(1) # Use the KL divergence distance to calculate the MI Px_Py = torch.matmul(Px.permute((0, 2, 1)), Py) # Reshape to batch_size X all_the_rest Pxy = Pxy.reshape(batch_size, -1) Px_Py = Px_Py.reshape(batch_size, -1) # Calculate mutual information - this is an approximation due to the histogram calculation and eps, # but it can handle batches if batch_size == 1: # No need for eps approximation in the case of a single batch nzs = Pxy > 0 # Calculate based on the non-zero values only mut_info = torch.matmul(Pxy[nzs], torch.log(Pxy[nzs]) - torch.log(Px_Py[nzs])) # MI calculation else: # For arbitrary batch size > 1 mut_info = torch.sum(Pxy * (torch.log(Pxy + self.eps) - torch.log(Px_Py + self.eps)), dim=1) # Reduction if self.reduction == 'sum': mut_info = torch.sum(mut_info) elif self.reduction == 'batchmean': mut_info = torch.sum(mut_info) mut_info = mut_info / float(batch_size) return mut_info # Code tests # # ---------------------------------------------------------------------- if __name__ == '__main__': # - set gray colormap and nearest neighbor interpolation by default plt.rcParams['image.cmap'] = 'gray' plt.rcParams['image.interpolation'] = 'nearest' # Parameters # ---------------------------------------------------------------------- Nbins = 20 min = 0 max = 1 max_shift = 30 # set additional parameters Translations = np.linspace(-max_shift, max_shift, 2 * max_shift + 1).astype(int) MI_numpy_buffer = np.zeros((2 * max_shift + 1, 2 * max_shift + 1, 2 * max_shift + 1)) MI_pytorch_buffer = np.zeros((2 * max_shift + 1, 2 * max_shift + 1, 2 * max_shift + 1)) # Define classes # ---------------------------------------------------------------------- mutual_info = MI_pytorch(bins=Nbins, min=min, max=max, sigma=100, reduction='sum') # Choose dataset # ---------------------------------------------------------------------- ''' MNI example - T1 and T2 MRI templates (colin27) Data can be downloaded from: http://nist.mni.mcgill.ca/?p=947 ''' inFolder = '.' t1_name = 'colin27_t1_tal_hires.nii' t2_name = 'colin27_t2_tal_hires.nii' slice_num = 190 # Load the data t1_img = nib.load(os.path.join(inFolder, t1_name)) t1_data = t1_img.get_fdata() t2_img = nib.load(os.path.join(inFolder, t2_name)) t2_data = t2_img.get_fdata() # normalize color range t1_data = t1_data / np.max(t1_data.ravel()) t2_data = t2_data / np.max(t2_data.ravel()) depth
#!/usr/bin/env python ''' Copyright (C) 2014 <NAME> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Parrot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import sys import os import re import arsdkparser MYDIR=os.path.abspath(os.path.dirname(__file__)) PACKAGES_DIR=os.path.realpath(os.path.join(MYDIR, "../..")) sys.path.append('%(PACKAGES_DIR)s/ARSDKBuildUtils/Utils/Python' % locals()) sys.path.append('%(PACKAGES_DIR)s/libARCommands/Tools' % locals()) from ARFuncs import * from libARCommandsgen import * from ARControllerUtils import * from arsdkparser import * DEVICE_CONTROLLER_FILE_NAME = 'deviceControllers.xml' DEVICE_CONTROLLER_FILE = PACKAGES_DIR+'/libARController/Xml/'+DEVICE_CONTROLLER_FILE_NAME CTRL_DICT_KEY_H_NAME = 'ARCONTROLLER_DICTIONARY_Key.h' CTRL_DICT_KEY_C_NAME = 'ARCONTROLLER_DICTIONARY_Key.c' def generateDictionaryKeyEnum (ctx, SRC_DIR, INC_DIR): deviceControllers = parseDeviceControllersXml (DEVICE_CONTROLLER_FILE, ctx) #check deviceController list if not deviceControllers: exit (1) ARPrint ('generateDictionaryKeyEnum ...') ######################################### # Write Feature controller header file # ######################################### includeDefine = '_' + MODULE_DICTIONARY + '_KEY_H_' bref = '.h' headerFileName = CTRL_DICT_KEY_H_NAME filepath = INC_DIR + headerFileName hFile = open (filepath, 'w') hFile.write ('/**********************************************************\n') hFile.write (' * AUTOGENERATED FILE *\n') hFile.write (' * DO NOT MODIFY IT *\n') hFile.write (' * *\n') hFile.write (' * To add new commands : *\n') hFile.write (' * - Modify ../Xml/commands.xml file *\n') hFile.write (' * - Re-run generateDictionaryKeyEnum.py script *\n') hFile.write (' * *\n') hFile.write (' **********************************************************/\n') hFile.write ('\n') hFile.write ('/**\n') hFile.write ('* @file '+headerFileName+'\n') hFile.write ('* @brief '+bref+'\n') hFile.write ('*/\n') hFile.write ('\n') hFile.write ('#ifndef '+includeDefine+'\n') hFile.write ('#define '+includeDefine+'\n') hFile.write ('\n') hFile.write ('/**\n') hFile.write (' * \n') # TODO add !!!!!!!!!!!!!!!!!!!!!!!!!! hFile.write (' */\n') hFile.write ('typedef enum \n') hFile.write ('{\n') first = True for feature in ctx.features: if first: hFile.write (' '+defineNotification(feature)+' = 0, /**< Key used to define the feature <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code> */\n') first = False else: hFile.write (' '+defineNotification(feature)+', /**< Key used to define the feature <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code> */\n') for evt in feature.evts: hFile.write (' '+defineNotification(feature, evt)+', /**< Key used to define the event <code>' + ARCapitalize (format_cmd_name(evt)) + '</code> in project <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code> */\n') hFile.write (' '+AREnumValue(MODULE_DICTIONARY, 'DICTIONARY', 'KEY','MAX')+', /**< Unused, iterator maximum value */\n') hFile.write ('}'+defineNotificationDef()+';\n') hFile.write ('\n') # TODO add !!!!!!!!!!!!!!!!!!!!!!!!!! hFile.write (''+defineNotificationDef()+' ' + ARFunctionName (MODULE_DICTIONARY, 'Key', 'GetFeatureFromCommandKey')+' ('+defineNotificationDef()+' commandKey);\n') hFile.write ('#endif /* '+includeDefine+' */\n') hFile.write ('\n') hFile.write ('// END GENERATED CODE\n') hFile.close () ################################################# # Write Feature controller c file # ################################################# classTag = 'ARCONTROLLER_Device' cFileName = CTRL_DICT_KEY_C_NAME filepath = SRC_DIR + cFileName cFile = open (filepath, 'w') cFile.write ('/**********************************************************\n') cFile.write (' * AUTOGENERATED FILE *\n') cFile.write (' * DO NOT MODIFY IT *\n') cFile.write (' * *\n') cFile.write (' * To add new commands : *\n') cFile.write (' * - Modify ../Xml/commands.xml file *\n') cFile.write (' * - Re-run generateDictionaryKeyEnum.py script *\n') cFile.write (' * *\n') cFile.write (' **********************************************************/\n') cFile.write ('\n') cFile.write ('/**\n') cFile.write ('* @file '+cFileName+'\n') cFile.write ('* @brief '+bref+'\n') cFile.write ('*/\n') cFile.write ('\n') cFile.write ('#include <stdio.h>\n') cFile.write ('\n') cFile.write ('#include <libARController/ARCONTROLLER_DICTIONARY_Key.h>\n') cFile.write ('\n') cFile.write (''+defineNotificationDef()+' ' + ARFunctionName (MODULE_DICTIONARY, 'Key', 'GetFeatureFromCommandKey')+' ('+defineNotificationDef()+' commandKey)\n') cFile.write ('{\n') cFile.write (' // -- Get Feature From Command Key --\n') cFile.write (' \n') cFile.write (' '+defineNotificationDef()+' featrueKey = '+AREnumValue(MODULE_DICTIONARY, 'DICTIONARY', 'KEY','MAX')+';\n') cFile.write (' \n') cFile.write (' // find feature parameters\n') first = True for index in range(len(ctx.features)-1): feature = ctx.features[index] featureNext = ctx.features[index+1] ifOrElse = 'if' if first: ifOrElse = 'if' first = False else: ifOrElse = 'else if' nextKey = '' if index != (len(ctx.features)-1): nextKey = defineNotification(featureNext) else: nextKey = AREnumValue(MODULE_DICTIONARY, 'DICTIONARY', 'KEY','MAX') cFile.write (' '+ifOrElse+' ('+defineNotification(feature)+' <= commandKey && commandKey < '+nextKey+')\n') cFile.write (' {\n') cFile.write (' featrueKey = '+defineNotification(feature)+';\n') cFile.write (' }\n') cFile.write (' \n') cFile.write (' return featrueKey;\n') cFile.write ('}\n') cFile.write ('\n') cFile.close () def generateDictionaryKeyEnumJava (ctx, JNI_JAVA_DIR): CLASS_NAME = ARJavaEnumType (MODULE_ARCONTROLLER, 'DICTIONARY', 'Key') JFILE_NAME = JNI_JAVA_DIR + CLASS_NAME + '.java' UNKNOWN_VALUE = 'e'+ARJavaEnumValDef(MODULE_ARCONTROLLER, 'DICTIONARY', 'Key', 'UNKNOWN_ENUM_VALUE', True) jfile = open(JFILE_NAME, 'w') jfile.write(LICENCE_HEADER) jfile.write('\n') jfile.write ('package com.parrot.arsdk.'+MODULE_ARCONTROLLER.lower()+';\n') jfile.write('\n') jfile.write('import java.util.HashMap;\n') jfile.write('\n') jfile.write('/**\n') jfile.write(' * Java copy of the ' + AREnumName (MODULE_ARCONTROLLER, 'DICTIONARY', 'Key') + ' enum\n') jfile.write(' */\n') jfile.write('public enum ' + CLASS_NAME + ' {\n') jfile.write(' /** Dummy value for all unknown cases */\n') jfile.write(' ' + UNKNOWN_VALUE + ' (Integer.MIN_VALUE, "Dummy value for all unknown cases"),\n') val = 0 for feature in ctx.features: jfile.write(' /** Key used to define the feature <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code> */\n') jfile.write(' '+defineNotification(feature)+ ' (' + str(val)+ ', "Key used to define the feature <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code>"),\n') val += 1 for evt in feature.evts: jfile.write(' /** Key used to define the event <code>' + ARCapitalize (format_cmd_name(evt)) + '</code> in project <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code>*/\n') jfile.write(' '+defineNotification(feature, evt)+' (' + str(val)+ ', "Key used to define the event <code>' + ARCapitalize (format_cmd_name(evt)) + '</code> in project <code>' + ARCapitalize (get_ftr_old_name(feature)) + '</code>"),\n') val += 1 jfile.write(' /** Unused, iterator maximum value */\n') jfile.write(' ARCONTROLLER_DICTIONARY_DICTIONARY_KEY_MAX (' + str(val)+ ', "Unused, iterator maximum value");\n') jfile.write('\n') jfile.write(' private final int value;\n') jfile.write(' private final String comment;\n'); jfile.write(' static HashMap<Integer, ' + CLASS_NAME + '> valuesList;\n') jfile.write('\n') jfile.write(' ' + CLASS_NAME + ' (int value) {\n') jfile.write(' this.value = value;\n') jfile.write(' this.comment = null;\n') jfile.write(' }\n') jfile.write('\n') jfile.write(' ' + CLASS_NAME + ' (int value, String comment) {\n') jfile.write(' this.value = value;\n') jfile.write(' this.comment = comment;\n') jfile.write(' }\n') jfile.write('\n') jfile.write(' /**\n') jfile.write(' * Gets the int value of the enum\n') jfile.write(' * @return int value of the enum\n') jfile.write(' */\n') jfile.write(' public int getValue () {\n') jfile.write(' return value;\n') jfile.write(' }\n') jfile.write('\n') jfile.write(' /**\n') jfile.write(' * Gets the ' + CLASS_NAME + ' instance from a C enum value\n') jfile.write(' * @param value C value of the enum\n') jfile.write(' * @return The ' + CLASS_NAME + ' instance, or null if the C enum value was not valid\n') jfile.write(' */\n') jfile.write(' public static ' + CLASS_NAME + ' getFromValue (int value) {\n') jfile.write(' if (null == valuesList) {\n') jfile.write(' ' + CLASS_NAME + ' [] valuesArray = ' + CLASS_NAME + '.values ();\n') jfile.write(' valuesList = new HashMap<Integer, ' + CLASS_NAME + '> (valuesArray.length);\n') jfile.write(' for (' + CLASS_NAME + ' entry : valuesArray) {\n') jfile.write(' valuesList.put (entry.getValue (), entry);\n') jfile.write(' }\n') jfile.write(' }\n') jfile.write(' ' + CLASS_NAME + ' retVal = valuesList.get (value);\n') jfile.write(' if (retVal == null) {\n') jfile.write(' retVal = ' + UNKNOWN_VALUE + ';\n') jfile.write(' }\n') jfile.write(' return retVal;') jfile.write(' }\n') jfile.write('\n') jfile.write(' /**\n') jfile.write(' * Returns the enum comment as a description string\n') jfile.write(' * @return The enum description\n') jfile.write(' */\n') jfile.write(' public String toString () {\n') jfile.write(' if (this.comment != null) {\n') jfile.write(' return this.comment;\n') jfile.write(' }\n') jfile.write(' return super.toString ();\n') jfile.write(' }\n') jfile.write('}\n') jfile.close() def list_files_dict_key (ctx, SRC_DIR, INC_DIR): ''' Print device dictionary key generated files ''' print INC_DIR + CTRL_DICT_KEY_H_NAME print SRC_DIR + CTRL_DICT_KEY_C_NAME def list_files_dict_key_java (ctx, JNI_JAVA_DIR): ''' Print device dictionary key generated
<gh_stars>1-10 #!/usr/bin/env python """ The module using a base path as guider searches all possible paths around the vehicle toward to base path and finds the best path for the car to follow Module functions: 1) List of possible paths : A list of candidate paths for the vehicle to follow 2) Objects around the car: The position and orientation ot objects like other cars and pedestrian relative to our car """ # ============================================================================== # --General imports ------------------------------------------------------------ # ============================================================================== import sys sys.path.append('./DynamicPolynomialPlanner') from DynamicPolynomialPlanner import frenet_paths from DynamicPolynomialPlanner import cubic_spline_planner from evaluation import * from time import sleep import numpy as np import math import copy # ============================================================================== # -- ROS imports --------------------------------------------------------------- # ============================================================================== import rospy import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from perception.msg import Object from route_planner.srv import RoutePath, RoutePathRequest, RoutePathResponse from perception.msg import ObjectsList from perception.msg import Waypoint from perception.msg import WaypointsList from perception.msg import TrajectoriesList from perception.msg import Lane from maneuver_generator.msg import ManeuverDataROS from local_path_planner.msg import LocalOptimalPath # ============================================================================== # -- Implementation ------------------------------------------------------------ # ============================================================================== # Global variables MANEUVERS_TO_EXCLUDE_VEHICLES = ["VehicleFollow"] END_PATH_OFFSET = 50 # Number of waypoints from the end of the path to consider that vehicle reaches the end GLOBAL_DRAW = True def generate_target_course(x, y): csp = cubic_spline_planner.Spline2D(x, y) s = np.arange(0, csp.s[-1], 0.1) rx, ry, ryaw, rk = [], [], [], [] for i_s in s: ix, iy = csp.calc_position(i_s) rx.append(ix) ry.append(iy) ryaw.append(csp.calc_yaw(i_s)) rk.append(csp.calc_curvature(i_s)) return rx, ry, ryaw, rk, csp, s def calc_min_lateral_dist(x_base, y_base, x_v, y_v, x0=0, offset=1000000, step=1): if len(x_base) != len(y_base): return None t1 = x0 - offset if (x0 - offset) > 0 else 0 t2 = x0 + offset if (x0 + offset) < (len(x_base) - 1) else len(x_base) min_dist = float("inf") index = x0 for i in range(0, t2 - t1, step): dist = math.sqrt((x_base[t1 + i] - x_v) ** 2 + (y_base[t1 + i] - y_v) ** 2) if min_dist > dist: min_dist = dist index = t1 + i return min_dist, index class ManeuverDataLocPlan: def __init__(self, left_road_width=-5, right_road_width=5, lateral_offset=None, speed=8.34, path_number=11, from_time=2.0, to_time=3.0, time_step=1.0, dt=0.3, direct_control=False, maneuver_type="Other"): self.maneuver_type = maneuver_type self.dt = dt # Time for traveling distance self.from_time = from_time self.to_time = to_time self.time_sample_step = time_step self.direct_control = direct_control # Position self.target_lateral_offset = lateral_offset self.left_road_width = left_road_width # maximum road width to the left [m] <-- Maneuver self.right_road_width = right_road_width # maximum road width to the right [m] <-- Maneuver self.num_of_paths_samples = path_number # number of alternative paths <-- Compromise # Speed self.target_speed = speed # target speed [m/s] <-- Maneuver self.sampling_length = 0.15*self.target_speed # target speed sampling length [m/s] <-- Compromise self.num_of_speed_samples = 1 # sampling number of target speed <-- Compromise def get_lateral_point_list(self): return [self.left_road_width + i * (self.right_road_width - self.left_road_width) / (self.num_of_paths_samples - 1) for i in range(self.num_of_paths_samples)] def get_speed_points_list(self): return [self.target_speed - i * self.sampling_length for i in range(self.num_of_speed_samples + 1)] + \ [self.target_speed + i * self.sampling_length for i in range(1, self.num_of_speed_samples + 1)] def get_time_points_list(self): return [self.from_time + i * self.time_sample_step for i in range(int((self.to_time - self.from_time) / self.time_sample_step) + 1)] class LocalPathPlanner: def __init__(self): self.vehicles = [] self.pedestrians = [] self.route_path = [] self.candidate_paths = [] self.client_get_route_path() self.maneuver_data = None self.stop_vehicle = False self.emergency_stop = False # Base path spline values initialization self.tx, self.ty, self.t_yaw, self.tc, self.t_csp, self.t_s = generate_target_course( [w.x for w in self.route_path], [w.y for w in self.route_path]) self.loc_index = 0 # Vehicle location relative to base path self.KD = 1.0 # weight for distance of the candidate path from base path # --- ROS --- rospy.init_node('Local_path_planner_node', anonymous=True) self.ego_vehicle = Object() self.current_lane = Lane() self.subscriber_ego_vehicle = rospy.Subscriber("ego_vehicle_msg", Object, self.callback_ego_vehicle, queue_size=1) self.subscriber_vehicles_list = rospy.Subscriber('vehicles_list_msg', ObjectsList, self.callback_vehicles_list, queue_size=1) self.subscriber_pedestrians_list = rospy.Subscriber('pedestrians_list_msg', ObjectsList, self.callback_pedestrians_list, queue_size=1) self.subscriber_maneuver_data = rospy.Subscriber('maneuver_data_msg', ManeuverDataROS, self.callback_maneuver_data, queue_size=1) self.subscriber_current_lane = rospy.Subscriber('current_lane_information_msg', Lane, self.callback_current_lane, queue_size=1) self.pub_optimal_local_path = rospy.Publisher('optimal_local_path_msg', LocalOptimalPath, queue_size=1) self.optimal_path = self.init_optimal_path() # Draw trajectories if GLOBAL_DRAW: self.pub_candidate_paths_draw = rospy.Publisher('candidate_paths_draw_msg', TrajectoriesList, queue_size=1) def init_optimal_path(self): ego_vehicle = copy.deepcopy(self.ego_vehicle) # Optimal path initialization # Vehicle position relative to base path curve(to the right or to the left) Ax, Ay = self.tx[0], self.ty[0] Bx, By = self.tx[3], self.ty[3] curve_side = np.sign((Bx - Ax) * (ego_vehicle.y - Ay) - (By - Ay) * (ego_vehicle.x - Ax)) curve_side = 1.0 if curve_side == 0.0 else curve_side # initial state c_speed = ego_vehicle.speed / 3.6 # current speed [m/s] dist_from_route = math.hypot(self.route_path[0].y - ego_vehicle.y, self.route_path[0].x - ego_vehicle.x) c_d = curve_side * dist_from_route # current lateral position [m] c_d = 0.1 if c_d < 0.1 else c_d c_d_d = 0.0 # current lateral speed [m/s] c_d_dd = 0.0 # current lateral acceleration [m/s] s0 = 0.0 # current course position fn_paths = frenet_paths.frenet_planning(self.t_csp, s0, c_speed, c_d, c_d_d, c_d_dd) d = close_to_base_path(fn_paths) return fn_paths[d.index(max(d))] def find_optimal_local_path(self): ego_vehicle = copy.deepcopy(self.ego_vehicle) maneuver_data = copy.deepcopy(self.maneuver_data) # Localization dist, self.loc_index = calc_min_lateral_dist(x_base=self.tx, y_base=self.ty, x_v=ego_vehicle.x, y_v=ego_vehicle.y, x0=self.loc_index, offset=400) # Condition if vehicle reaches the end of the path if (len(self.tx) - self.loc_index) < END_PATH_OFFSET: self.publish_optimal_local_path() return None # Vehicle position relative to curve Ax, Ay = self.tx[self.loc_index], self.ty[self.loc_index] Bx, By = self.tx[self.loc_index + 3], self.ty[self.loc_index + 3] curve_side = np.sign((Bx - Ax) * (ego_vehicle.y - Ay) - (By - Ay) * (ego_vehicle.x - Ax)) curve_side = 1 if curve_side == 0 else curve_side # Position relative to previous path id_next = 1 for j in range(len(self.optimal_path.s)): if self.optimal_path.s[j] > self.t_s[self.loc_index]: id_next = j break s0 = self.t_s[self.loc_index] c_d = curve_side * dist c_d_d = 0.0 # self.optimal_path.d_d[id_next] c_d_dd = 0.0 # self.optimal_path.d_dd[id_next] c_speed = self.optimal_path.s_d[id_next] stop_flag = False if maneuver_data is not None: if maneuver_data.target_speed < 1: maneuver_data.target_speed = 3 stop_flag = True self.candidate_paths = frenet_paths.frenet_planning(self.t_csp, s0, c_speed, c_d, c_d_d, c_d_dd, maneuver_data) if stop_flag: for i in range(len(self.candidate_paths)): self.candidate_paths[i].s_d = [0]*len(self.candidate_paths[i].s_d) self.evaluate_paths() self.publish_optimal_local_path() if GLOBAL_DRAW: self.publish_candidate_paths_draw() ''' # Draw paths if GLOBAL_DRAW: all_paths = [] for j in range(len(candidate_paths)): all_paths.append([]) for ii in range(len(candidate_paths[j].x)): all_paths[j].append(carla.Location(x=candidate_paths[j].x[ii], y=candidate_paths[j].y[ii])) self.local_map.draw_paths(paths=all_paths, life_time=1.2, color=[250, 0, 0], same_color=True) # self.local_map.draw_paths(paths=[self.base_path], life_time=1.2, color=[0, 0, 250], same_color=True)''' def evaluate_paths(self, lane_borders=None): self.emergency_stop = False ego_vehicle = copy.deepcopy(self.ego_vehicle) pedestrians = copy.deepcopy(self.pedestrians) vehicles = copy.deepcopy(self.vehicles) maneuver_data = copy.deepcopy(self.maneuver_data) lateral_offset_goal = 0.0 if maneuver_data is None else maneuver_data.target_lateral_offset front_vehicle_id = self.current_lane.front_vehicle.object_id front_front_vehicle_id = self.current_lane.front_front_vehicle.object_id if maneuver_data is not None: if maneuver_data.maneuver_type in MANEUVERS_TO_EXCLUDE_VEHICLES: vehicles = [obj_i for obj_i in vehicles if obj_i.object_id != front_vehicle_id and obj_i.object_id != front_front_vehicle_id] # Vehicles collision W = [] if len(vehicles) != 0: d1, vehicle_collision = far_away_from_objects(self.candidate_paths, vehicles, ego_vehicle) else: d1 = [1.0]*len(self.candidate_paths) vehicle_collision = False d2 = close_to_lateral_offset_target(self.candidate_paths, lateral_offset_goal) d3 = path_close_to_previous_one(self.candidate_paths, self.optimal_path) # Pedestrians collision if len(pedestrians) != 0: _, stop_vehicle_pedestrian = far_away_from_objects(self.candidate_paths, pedestrians, ego_vehicle) else: stop_vehicle_pedestrian = False self.stop_vehicle = vehicle_collision or stop_vehicle_pedestrian if self.stop_vehicle and ego_vehicle.speed < 1: sleep(0.2) for i in range(len(self.candidate_paths)-1): W.append(d2[i]) else: for i in range(len(self.candidate_paths) - 1): W.append(self.KD * d2[i] + 0.2 * self.KD * d3[i]) # Return best path, check if collides with any object maxW = max(W) while not rospy.is_shutdown(): maxW = max(W) best_index = W.index(maxW) if d1[best_index] != 0.0: break else: if len(W) > 1: W.pop(best_index) else: self.stop_vehicle = True self.optimal_path.s_d = [0] * len(self.optimal_path.s_d) return False self.optimal_path = self.candidate_paths[W.index(maxW)] _, pedestrian_collision = far_away_from_objects([self.optimal_path], pedestrians, ego_vehicle) if pedestrian_collision: print("stop pedestrian collision") if self.stop_vehicle or pedestrian_collision: print("-----------> Vehicle had to stop") self.emergency_stop = True self.optimal_path.s_d = [0]*len(self.optimal_path.s_d) # -------- ROS functions --------- def callback_ego_vehicle(self, ros_data): self.ego_vehicle = ros_data #rospy.loginfo(ros_data) def callback_vehicles_list(self, ros_data): self.vehicles = ros_data.objects_list #rospy.loginfo(ros_data) def callback_pedestrians_list(self, ros_data): self.pedestrians = ros_data.objects_list #rospy.loginfo(ros_data) def callback_current_lane(self, ros_data): self.current_lane = ros_data #rospy.loginfo(ros_data) def callback_maneuver_data(self, ros_data): self.maneuver_data = ManeuverDataLocPlan(left_road_width=ros_data.left_road_width, right_road_width=ros_data.right_road_width, lateral_offset=ros_data.target_lateral_offset, speed=ros_data.target_speed, path_number=ros_data.num_of_paths_samples, from_time=ros_data.from_time, to_time=ros_data.to_time, time_step=ros_data.time_sample_step, dt=ros_data.dt, direct_control=ros_data.direct_control, maneuver_type=ros_data.maneuver_type[0]) #rospy.loginfo(ros_data) def publish_optimal_local_path(self): pub = self.pub_optimal_local_path optimal_path = LocalOptimalPath() optimal_path.x = self.optimal_path.x optimal_path.y = self.optimal_path.y optimal_path.yaw = self.optimal_path.yaw optimal_path.s_d = self.optimal_path.s_d optimal_path.emergency_stop = self.emergency_stop if self.maneuver_data is not None: optimal_path.direct_control = self.maneuver_data.direct_control optimal_path.direct_target_speed = self.maneuver_data.target_speed else: optimal_path.direct_control = False optimal_path.direct_target_speed = 0 #rospy.loginfo(optimal_path) pub.publish(optimal_path) def publish_candidate_paths_draw(self): pub = self.pub_candidate_paths_draw candidate_paths = [] for fn_path in self.candidate_paths: trajectory = [] for i in range(len(fn_path.yaw)): ros_w = Waypoint() ros_w.x = fn_path.x[i] ros_w.y = fn_path.y[i] ros_w.yaw = fn_path.yaw[i] trajectory.append(ros_w) ros_trajectory = WaypointsList() ros_trajectory.waypoints_list = trajectory candidate_paths.append(ros_trajectory) ros_candidate_paths = TrajectoriesList() ros_candidate_paths.trajectories_list = candidate_paths #rospy.loginfo(ros_candidate_paths) pub.publish(ros_candidate_paths) def client_get_route_path(self): rospy.wait_for_service('route_path_srv') try: route_path_srv =
import unittest import sam from math import log, sqrt import numpy as np from scipy.stats import multivariate_normal from scipy.special import logit def logProb1(x, gradient, getGradient): if getGradient: gradient[0] = sam.gammaDLDX(x[0], 20, 40) gradient[1] = sam.normalDLDX(x[1], 5, 1) return sam.gammaLogPDF(x[0], 20, 40) + sam.normalLogPDF(x[1], 5, 1) def logProb2(x): return sam.betaLogPDF(x[0], 15, 20) def logProb3(x, gradient, getGradient): assert not getGradient return sam.betaLogPDF(x[0], 20, 40) + sam.normalLogPDF(x[1], 5, 1) _logProb4_ = multivariate_normal(cov=[[1., .3], [.3, 1]]).logpdf def logProb4(x): return _logProb4_(x) def raisesLogProb(x): if x > np.inf: raise ValueError("x can never be good enough!") return -1 class SamTester(unittest.TestCase): def testErrorHandling(self): a = sam.Sam(raisesLogProb, [.5, .5], [0., -np.inf]) self.assertIsNone(a.results) self.assertIsNone(a.samples) self.assertRaises(AssertionError, a.getStats) self.assertRaises(AssertionError, a.summary) self.assertRaises(ValueError, a.run, 1000, [.5, .5]) self.assertRaises(AttributeError, a.gradientDescent, [.5, .5]) self.assertRaises(ValueError, a.simulatedAnnealing, [.5, .5]) self.assertRaises(AssertionError, a.getSampler, 2) self.assertRaises(OverflowError, a.getSampler, -3) self.assertRaises(ValueError, sam.normalCDF, 1, 0, -1) def testModelSelection(self): # This is a roundabout way to test them, but it does work def rightModel(x): return sam.normalLogPDF(x, 0, 1.) def wrongModel(x): return sam.normalLogPDF(x, 0, 2.) def flatPrior(x): return 0. a = sam.Sam(rightModel, .5) a.run(100000, .5, showProgress=False) b = sam.Sam(wrongModel, .5) b.run(100000, .5, showProgress=False) assert not any(np.isnan(a.resultsLogProb)) assert not any(np.isnan(b.resultsLogProb)) # DIC right = a.getDIC(flatPrior) wrong = b.getDIC(flatPrior) self.assertLessEqual(right, wrong) self.assertAlmostEqual(right, 3., delta=.2) self.assertAlmostEqual(wrong, 4.4, delta=.2) # AIC right = a.getAIC(flatPrior) wrong = b.getAIC(flatPrior) self.assertLessEqual(right, wrong) self.assertAlmostEqual(right, 3.837, delta=.01) self.assertAlmostEqual(wrong, 5.224, delta=.01) # BIC right = a.getBIC(flatPrior, 1000) wrong = b.getBIC(flatPrior, 1000) self.assertLessEqual(right, wrong) self.assertAlmostEqual(right, 8.74, delta=.01) self.assertAlmostEqual(wrong, 10.13, delta=.01) return def testACF(self): x = [np.pi] for i in range(10000): x.append(np.pi + .9*x[-1] + sam.normalRand()) sampleACF = sam.acf(x, 30) theoryACF = .9**np.arange(30) self.assertTrue(np.allclose(sampleACF, theoryACF, .1, .1)) return def testLogit(self): x = [.234124, 1.-1e-13, 1e-13] self.assertAlmostEqual(sam.logit(x[0]), logit(x[0]), 13) self.assertAlmostEqual(sam.logit(x[1]), logit(x[1]), 13) self.assertAlmostEqual(sam.logit(x[2]), logit(x[2]), 13) return def testGaussianProcess(self): x = np.linspace(0, 10, 100) y = np.sin(x) y2 = np.cos(x) f = sam.GaussianProcess(x, y, 'exp') loglike = f.logLikelihood(np.array([10, .5, 0])) gpMean, gpVar = f.predict(np.array([5.])) gpVar = np.sqrt(np.diag(gpVar)) with self.assertRaises(ValueError): f.gradient(3.5) self.assertAlmostEqual(gpMean[0], -0.957698488, delta=.01) self.assertAlmostEqual(gpVar[0], 0.0502516, delta=.01) self.assertAlmostEqual(loglike, 109.90324, delta=.01) f.setY(y2) gpMean = f.predict(np.array([5.]), False) self.assertAlmostEqual(gpMean[0], np.cos(5.), delta=.01) def testGaussianProcess2D(self): x = np.linspace(0, 1, 400).reshape(200, 2) z = np.sin(np.sum(x, axis=-1)) f = sam.GaussianProcess(x, z, 'matern32') loglike = f.logLikelihood(np.array([1, .5, 0])) gpMean, gpVar = f.predict([[.5, .5]]) gpVar = np.sqrt(np.diag(gpVar)) grad = f.gradient([.5, .5]) self.assertAlmostEqual(grad[0], 0.537, delta=.01) self.assertAlmostEqual(grad[1], 0.542, delta=.01) self.assertAlmostEqual(loglike, 1107.363, delta=.01) self.assertAlmostEqual(gpMean[0], 0.841, delta=.01) self.assertAlmostEqual(gpVar[0], 0.00217, delta=.01) def test1DMetropolis(self): a = sam.Sam(logProb2, .5, 0., 1.) samples = a.run(100000, 1, showProgress=False) self.assertGreaterEqual(a.getAcceptance()[0], 0.) self.assertLessEqual(a.getAcceptance()[0], 1.) self.assertTrue((samples >= 0).all()) self.assertTrue((samples <= 1).all()) self.assertAlmostEqual(samples.mean(), sam.betaMean(15, 20), delta=.01) self.assertAlmostEqual(samples.std(), sam.betaStd(15, 20), delta=.01) def testSummary(self): a = sam.Sam(logProb2, .5, 0., 1.) with self.assertRaises(AssertionError): a.summary() a.run(100000, .5, showProgress=False) self.assertGreaterEqual(len(a.summary(None, True)), 0) def testGetCovar(self): a = sam.Sam(logProb4, np.ones(2)) a.addMetropolis() c = a.getProposalCov() for i, j in zip(c.flatten(), [1, 0., 0., 1]): self.assertAlmostEqual(i, j) a.clearSamplers() a.addMetropolis(np.array([[1, .1], [.1, 1.]])/2.) c = a.getProposalCov(0) for i, j in zip(c.flatten(), np.array([1, .1, .1, 1])/2.): self.assertAlmostEqual(i, j) a.clearSamplers() a.addHMC(10, .1) c = a.getProposalCov() for i, j in zip(c.flatten(), [1, 0., 0., 1]): self.assertAlmostEqual(i, j) a.clearSamplers() a.addAdaptiveMetropolis(np.array([[1, .1], [.1, 1.]])/2.) c = a.getProposalCov(0) # The covariance output is the sample covariance, which should be 0 for i, j in zip(c.flatten(), [0, 0, 0, 0.]): self.assertAlmostEqual(i, j) def test2DMetropolis(self): a = sam.Sam(logProb1, [.5, .5], [0., -np.inf]) samples = a.run(100000, [.5, .5], 1000, showProgress=False) self.assertGreaterEqual(a.getAcceptance()[0], 0.) self.assertLessEqual(a.getAcceptance()[0], 1.) self.assertGreaterEqual(a.getAcceptance()[1], 0.) self.assertLessEqual(a.getAcceptance()[1], 1.) self.assertTrue((samples[:, 0] >= 0).all()) self.assertAlmostEqual(samples[:, 0].mean(), sam.gammaMean(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 0].std(), sam.gammaStd(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 1].mean(), 5., delta=.1) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.1) for i in range(50000): self.assertAlmostEqual(a.samplesLogProb[i], logProb1(a.samples[i], None, False)) def testThreading(self): a = sam.Sam(logProb1, [.5, .5], lowerBounds=[0., -np.inf]) samples = a.run(100000, [.5, .5], 1000, threads=5, showProgress=False) for i in a.getAcceptance(): self.assertGreaterEqual(i[0], 0.) self.assertLessEqual(i[0], 1.) self.assertGreaterEqual(i[1], 0.) self.assertLessEqual(i[1], 1.) self.assertEqual(len(a.results.shape), 2) self.assertEqual(a.results.shape[0], 5*100000) self.assertEqual(a.results.shape[1], 2) self.assertEqual(len(a.samples.shape), 3) self.assertEqual(a.samples.shape[0], 5) self.assertEqual(a.samples.shape[1], 100000) self.assertEqual(a.samples.shape[2], 2) self.assertNotEqual(samples[0, -1, -1], samples[1, -1, -1]) samples = np.concatenate([samples[0], samples[1]], axis=1) self.assertTrue((samples[:, 0] >= 0).all()) self.assertAlmostEqual(samples[:, 0].mean(), sam.gammaMean(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 0].std(), sam.gammaStd(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 1].mean(), 5., delta=.1) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.1) for i in range(100000): for j in range(5): self.assertAlmostEqual(a.samplesLogProb[j, i], logProb1(a.samples[j, i], None, False)) def testThreading2(self): a = sam.Sam(logProb1, [.5, .5], lowerBounds=[0., -np.inf]) samples = a.run(100000, np.random.rand(5, 2), 1000, threads=5, showProgress=False) for i in a.getAcceptance(): self.assertGreaterEqual(i[0], 0.) self.assertLessEqual(i[0], 1.) self.assertGreaterEqual(i[1], 0.) self.assertLessEqual(i[1], 1.) with self.assertRaises(AttributeError): a.samples = np.ones(5) self.assertEqual(samples.shape[0], 5) self.assertEqual(samples.shape[1], 100000) self.assertEqual(samples.shape[2], 2) self.assertNotEqual(samples[0, -1, -1], samples[1, -1, -1]) samples = np.concatenate([samples[0], samples[1]], axis=1) self.assertTrue((samples[:, 0] >= 0).all()) self.assertAlmostEqual(samples[:, 0].mean(), sam.gammaMean(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 0].std(), sam.gammaStd(20, 40), delta=.01) self.assertAlmostEqual(samples[:, 1].mean(), 5., delta=.1) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.1) for i in range(len(a.resultsLogProb)): self.assertAlmostEqual(a.resultsLogProb[i], logProb1(a.results[i], None, False)) def test2DHMC(self): a = sam.Sam(logProb1, [1, 1], lowerBounds=[0., -np.inf]) a.addHMC(10, .1) samples = a.run(50000, [.5, .5], 10, showProgress=False) self.assertTrue((samples[:, 0] >= 0).all()) self.assertAlmostEqual(samples[:, 0].mean(), sam.gammaMean(20, 40), delta=.05) self.assertAlmostEqual(samples[:, 0].std(), sam.gammaStd(20, 40), delta=.05) self.assertAlmostEqual(samples[:, 1].mean(), 5., delta=.2) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.2) def testCorrelatedMetropolis(self): a = sam.Sam(logProb4, np.ones(2)) a.addMetropolis(np.array([[1, .1], [.1, 1.]])/2.) samples = a.run(100000, 5*np.ones(2), 1000, showProgress=False) self.assertAlmostEqual(samples[:, 0].mean(), 0., delta=.05) self.assertAlmostEqual(samples[:, 0].std(), 1., delta=.1) self.assertAlmostEqual(samples[:, 1].mean(), 0., delta=.05) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.1) def testAdaptiveMetropolis(self): a = sam.Sam(logProb4, np.ones(2)) a.addAdaptiveMetropolis(np.array([[1, .1], [.1, 1.]])/2., scaling=4.) samples = a.run(50000, 5*np.ones(2), 1000, showProgress=False) self.assertAlmostEqual(samples[:, 0].mean(), 0., delta=.1) self.assertAlmostEqual(samples[:, 0].std(), 1., delta=.1) self.assertAlmostEqual(samples[:, 1].mean(), 0., delta=.1) self.assertAlmostEqual(samples[:, 1].std(), 1., delta=.1) def test2DGradientDescent(self): a = sam.Sam(logProb1, [.5, .5], lowerBounds=[0., -np.inf]) posteriorMax = a.gradientDescent([.5, .5], step=.05) self.assertAlmostEqual(posteriorMax[0], 19./40., delta=1e-4) self.assertAlmostEqual(posteriorMax[1], 5., delta=1e-4) def testRunningStats(self): a = sam.Sam(logProb3, [.5, .5], lowerBounds=[0., -np.inf], upperBounds=[1., np.inf]) a.addMetropolis() samples = a.run(100000, [.5, .5], 1000, recordStop=0, collectStats=True, showProgress=False) self.assertEqual(samples.size, 0) self.assertAlmostEqual(a.getStats()[0][0], sam.betaMean(20, 40), delta=.01) self.assertAlmostEqual(a.getStats()[1][0], sam.betaStd(20, 40), delta=.01) self.assertAlmostEqual(a.getStats()[0][1], 5, delta=.1) self.assertAlmostEqual(a.getStats()[1][1], 1, delta=.1) def testExceptionsRaised(self): a = sam.Sam(None, np.ones(1)) with self.assertRaises(RuntimeError): a(np.ones(1)) class DistributionTester(unittest.TestCase): # ===== Special Functions ===== def testSpecialFunctions(self): self.assertAlmostEqual(sam.incBeta(.8, 3.4, 2.1), .04811402) self.assertAlmostEqual(sam.beta(.7, 2.5), 0.7118737432) self.assertAlmostEqual(sam.gamma(2.5), 1.329340388) self.assertAlmostEqual(sam.digamma(12.5), 2.4851956512) # ===== Distributions ===== def testNormalDistribution(self): with self.assertRaises(ValueError): sam.normalPDF(0, 1, -3) with self.assertRaises(ValueError): sam.normalCDF(0., 1., 0.) with self.assertRaises(ValueError): sam.normalLogPDF(0, 1, -5.) self.assertAlmostEqual(sam.normalPDF(1, 3, 4), 0.08801633) self.assertAlmostEqual(sam.normalMean(2, 4), 2.) self.assertAlmostEqual(sam.normalVar(2, 4), 16.) self.assertAlmostEqual(sam.normalStd(2, 4), 4.) self.assertAlmostEqual(sam.normalLogPDF(1, 3, 4), log(0.08801633)) a = [sam.normalRand(3, 2) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 3., delta=3*.01) def testMvNormalDistribution(self): targetCov = np.random.rand(3, 3) targetCov = targetCov*targetCov.T/2. + np.eye(3) a = np.empty((100000, 3)) a = np.array([sam.mvNormalRand(np.array([1., 5., -3.]), targetCov) for i in range(100000)]) self.assertAlmostEqual(np.mean(a[:, 0]), 1., delta=.05) self.assertAlmostEqual(np.mean(a[:, 1]), 5., delta=.05) self.assertAlmostEqual(np.mean(a[:, 2]), -3., delta=.05) for i, c in enumerate(np.cov(a.T, ddof=0).flatten()): self.assertAlmostEqual(targetCov.flatten()[i], c, delta=.05) targetChol = np.linalg.cholesky(targetCov) a = np.array([sam.mvNormalRand(np.array([1., 5., -3.]), targetChol, isChol=True) for i in range(100000)]) self.assertAlmostEqual(np.mean(a[:, 0]), 1., delta=.05) self.assertAlmostEqual(np.mean(a[:, 1]), 5., delta=.05) self.assertAlmostEqual(np.mean(a[:, 2]), -3., delta=.05) for i, c in enumerate(np.cov(a.T, ddof=0).flatten()): self.assertAlmostEqual(targetCov.flatten()[i], c, delta=.2) self.assertAlmostEqual(sam.mvNormalLogPDF(np.ones(3), np.zeros(3), targetCov.copy()), multivariate_normal.logpdf(np.ones(3), np.zeros(3), targetCov)) self.assertAlmostEqual(sam.mvNormalPDF(np.ones(3), np.zeros(3), targetCov.copy()), multivariate_normal.pdf(np.ones(3), np.zeros(3), targetCov)) def testUniformDistribution(self): self.assertAlmostEqual(sam.uniformMean(2, 4), 3.) self.assertAlmostEqual(sam.uniformVar(2, 4), 4./12.) self.assertAlmostEqual(sam.uniformStd(2, 4), 2./sqrt(12.)) self.assertAlmostEqual(sam.uniformPDF(3, 2, 4), 0.5) self.assertAlmostEqual(sam.uniformLogPDF(3, 2, 4), log(0.5)) self.assertAlmostEqual(sam.uniformCDF(2.5, 2, 4), 0.25) a = [sam.uniformRand(3, 4) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 3.5, delta=3.5*.01) def testGammaDistribution(self): with self.assertRaises(ValueError): sam.gammaPDF(4., 1, -3) with self.assertRaises(ValueError): sam.gammaCDF(2., 0., 1.) with self.assertRaises(ValueError): sam.gammaMode(10., -np.inf) self.assertAlmostEqual(sam.gammaMean(3, 4), .75) self.assertAlmostEqual(sam.gammaVar(3, 4), 3./16) self.assertAlmostEqual(sam.gammaStd(3, 4), sqrt(3)/4.) self.assertAlmostEqual(sam.gammaPDF(1, 3, 4), .586100444) self.assertAlmostEqual(sam.gammaLogPDF(1, 3, 4), log(.586100444)) self.assertAlmostEqual(sam.gammaCDF(1, 3, 4), 0.7618966944464) a = [sam.gammaRand(3, 4) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 3./4, delta=.75*.01) def testInvGammaDistribution(self): with self.assertRaises(ValueError): sam.invGammaPDF(4., 1, -3) with self.assertRaises(ValueError): sam.invGammaCDF(2., 0., 1.) with self.assertRaises(ValueError): sam.invGammaMode(10., -np.inf) self.assertAlmostEqual(sam.invGammaMean(3, 4), 2.) self.assertAlmostEqual(sam.invGammaVar(3, 4), 4.) self.assertAlmostEqual(sam.invGammaStd(3, 4), 2.) self.assertAlmostEqual(sam.invGammaPDF(1, 3, 4), .0060843811) self.assertAlmostEqual(sam.invGammaLogPDF(1, 3, 4), log(.0060843811)) self.assertAlmostEqual(sam.invGammaCDF(1, 3, 4), .002161, delta=.001) a = [sam.invGammaRand(3, 4) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 2., delta=2*.01) def testBetaDistribution(self): with self.assertRaises(ValueError): sam.betaPDF(.3, 1, -3) with self.assertRaises(ValueError): sam.betaCDF(2., 0., 1.) with self.assertRaises(ValueError): sam.betaMode(10., -np.inf) self.assertAlmostEqual(sam.betaMean(3, 4), 3./7) self.assertAlmostEqual(sam.betaVar(3, 4), .0306122) self.assertAlmostEqual(sam.betaStd(3, 4), 0.17496355305) self.assertAlmostEqual(sam.betaPDF(.5, 3, 4), 1.875) self.assertAlmostEqual(sam.betaLogPDF(.5, 3, 4), log(1.875)) self.assertAlmostEqual(sam.betaCDF(.5, 3, 4), .65625) a = [sam.betaRand(3, 4) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 3./7, delta=3./7.*.01) def testPoissonDistribution(self): with self.assertRaises(ValueError): sam.poissonPDF(3, -1.5) with self.assertRaises(ValueError): sam.poissonStd(0.) with self.assertRaises(ValueError): sam.betaMode(-1., 3.) self.assertAlmostEqual(sam.poissonMean(2.4), 2.4) self.assertAlmostEqual(sam.poissonVar(2.4), 2.4) self.assertAlmostEqual(sam.poissonStd(2.4), sqrt(2.4)) self.assertAlmostEqual(sam.poissonPDF(3, 2.4), .2090141643) self.assertAlmostEqual(sam.poissonLogPDF(3, 2.4), log(.2090141643)) self.assertAlmostEqual(sam.poissonCDF(3.2, 2.4), 0.7787229) a = [sam.poissonRand(3.4) for i in range(100000)] self.assertAlmostEqual(np.mean(a), 3.4, delta=3.4*.01) def testExponentialDistribution(self): with self.assertRaises(ValueError): sam.exponentialPDF(3, -1.5)
''' // Copyright 2017 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import sublime, sublime_plugin import re class GetHelpCommand(sublime_plugin.WindowCommand): help_dict = [ ' ', '**Note that these key mappings are for Windows machines.**', '**Linux and Mac mappings are included, but might differ from this menu.**' ' ', ' ', 'Native Commands', ' ', 'Ctrl + X Cut line', 'Ctrl + Enter Insert line after', 'Ctrl + Shift + Enter Insert line before', 'Ctrl + Shift + ↑ Move line/selection up', 'Ctrl + Shift + ↓ Move line/selection down', 'Ctrl + L Select line - Repeat to select next lines', 'Ctrl + D Select word - Repeat select others occurrences', 'Ctrl + M Jump to closing parentheses Repeat to jump to opening parentheses', 'Ctrl + Shift + M Select all contents of the current parentheses', 'Ctrl + Shift + K Delete Line', 'Ctrl + KK Delete from cursor to end of line', 'Ctrl + ] Indent current line(s)', 'Ctrl + [ Un-indent current line(s)', 'Ctrl + Shift + D Duplicate line(s)', 'Ctrl + J Join line below to the end of the current line', 'Ctrl + / Comment/un-comment current line', 'Ctrl + Y Redo, or repeat last keyboard shortcut command', 'Ctrl + Shift + V Paste and indent correctly', 'Ctrl + Space Select next auto-complete suggestion', 'Ctrl + U soft undo; jumps to your last change before undoing change when repeated', 'Shift + Del delete current line, shift up', 'Ctrl + ; Goto word in current file', 'Ctrl + F Find', 'Ctrl + H Replace', 'Ctrl + PgUp Cycle up through tabs', 'Ctrl + PgDn Cycle down through tabs', 'Ctrl + F2 Toggle bookmark', 'F2 Next bookmark', 'Shift + F2 Previous bookmark', 'Ctrl + Shift + F2 Clear bookmarks', 'Ctrl + KU Transform to Uppercase', 'Ctrl + KL Transform to Lowercase', ' ', 'PPCL Commands', ' ', 'Enter Add line number', 'Ctrl + Shift + H Open Help', 'Ctrl + Shift + L Line number increment', 'Ctrl + Alt + D Toggle off all DEFINE statements', 'Ctrl + Alt + R Toggle on all DEFINE statements', 'Ctrl + Alt + U Toggle point names with periods to underscores', 'Ctrl + Alt + P Toggle point names with underscores to periods', 'Ctrl + Shift + C Make a copy of the selected code a user-defined number of times', 'Ctrl + Alt + N Enumerate the selected text <Start>:<Interval>. If start starts with a leading 0, it will make numbers leading with 0s', ] def run(self,): self.window.show_quick_panel(self.help_dict, self._on_select) def _on_select(self, idx): pass # if idx > -1: # selected = self.help_dict[idx] # sublime.message_dialog(selected) class InsertCommentCommand(sublime_plugin.TextCommand): ''' This command will insert a comment (01000 tab C ) when ctrl+/ is pressed over all the selected lines. ''' def run(self, edit): rows = set() counter = 1 # determine all the rows in the selection for region in self.view.sel(): lines_tuple = self.view.split_by_newlines(region) for region in lines_tuple: rows.add(int(self.view.rowcol(region.begin())[0])) commented_rows = self.determine_toggle(rows) if all(commented_rows[0] == item for item in commented_rows): switch_all = True else: switch_all = False for row in rows: if (((switch_all==True) and (commented_rows[0]==False)) or switch_all==False): line = self.view.substr(self.view.line( sublime.Region(self.view.text_point(row, 0)))) commentedLine = self.toggle_on(line) self.view.replace(edit, self.view.line( sublime.Region(self.view.text_point(row, 0))), commentedLine) elif (switch_all==True) and (commented_rows[0]==True): line = self.view.substr(self.view.line( sublime.Region(self.view.text_point(row, 0)))) commentedLine = self.toggle_off(line) self.view.replace(edit, self.view.line( sublime.Region(self.view.text_point(row, 0))), commentedLine) def determine_toggle(self, rows): ''' make a boolean list to determine which lines need to have comments added and/or removed. ''' commented_rows = [] for row in rows: line = self.view.substr(self.view.line( sublime.Region(self.view.text_point(row, 0)))) lineNum = re.search(r'(^[0-9]+)([\t]|[ ]+)(C ?)?', line) if (lineNum.groups()[-1] == 'C') or (lineNum.groups()[-1] == 'C '): commented_rows.append(1) else: commented_rows.append(0) return commented_rows def toggle_on(self,line): ''' add a comment to the beginning. ''' try: lineNum = re.search(r'(^[0-9]+)([\t]|[ ]+)(C ?)?', line) return (line.replace(lineNum.groups()[0] + lineNum.groups()[1], lineNum.groups()[0] + lineNum.groups()[1] + 'C ')) except: pass def toggle_off(self,line): ''' remove a comment from the beginning. ''' try: lineNum = re.search(r'(^[0-9]+)([\t]|[ ]+)(C ?)', line) tempstring = '' for group in lineNum.groups(): tempstring += str(group) return (line.replace(tempstring, tempstring.replace('C ', '').replace('C', ''))) except: pass class ToggleDefineCommand(sublime_plugin.TextCommand): ''' This function will toggle the DEFINE statement strings. Toggle OFF will replace all the %..% with the assocaited string. Toggle OFF will replace all occurences of the assocaited string with %..%. ''' def run(self, edit, toggle): # print ("made it =", kwargs) content = self.view.substr(sublime.Region(0, self.view.size())) define_map, define_lines = self.get_defines(content) if toggle == 'off': newcontent = self.toggle_off(content, define_map) if toggle == 'on': newcontent = self.toggle_on(content, define_map, define_lines) # replace the existing text with the modified text selections = sublime.Region(0, self.view.size()) self.view.replace(edit, selections, newcontent) def get_defines(self, content): ''' regex search for all the define statements, return a dict of the associations with the %X% as the key, return the line numbers associated ''' # compile for regex, find DEFINE lines, parameters, and associated strings p = re.compile(r'(^[0-9]+)([\t]|[ ]+)(DEFINE[\t ]?\()([A-Z0-9]*)(\, ?")(.*)"', re.MULTILINE) define_terms = re.findall(p, content) print (define_terms) define_map = {} define_lines = [] for item in define_terms: define_map['%'+item[3]+'%'] = item[5] define_lines.append(item[0]) return define_map, define_lines def toggle_on(self, content, define_map, define_lines): ''' toggle on the define statements, meaning put the %X% back ''' newcontent = '' p = re.compile(r'(^[0-9]+)([\t]|[ ]+)') first_line=True for line in content.split('\n'): nextline = line # index the regex search to get just the number try: # this means the line has a line number linenum = re.findall(p, line)[0][0] except: break if any(word in nextline for word in define_map.values()) and linenum not in define_lines: for key in define_map.keys(): nextline = nextline.replace(define_map[key], key) # this is silly, but necessary # we don't wanna add a \n to the end of the last line if first_line: newcontent += nextline else: newcontent += '\n' + nextline first_line=False return newcontent def toggle_off(self, content, define_map): ''' toggle off the define statements, meaning replace %X% ''' # define_map = self.get_defines() print (define_map) for key in define_map.keys(): content = content.replace(key, define_map[key]) return content class ToggleUnderscoresAndDotsCommand(sublime_plugin.TextCommand): ''' This function toggles the "." and the "_" in point names for Desigo CC-friendly programming If there are both underscores and periods in point names, the default behavior will be to return all point names to period separation. ''' def run(self, edit, toggle): # print ("made it =", kwargs) content = self.view.substr(sublime.Region(0, self.view.size())) points = self.get_points(content) newcontent = self.toggle_points(content, points, toggle) # replace the existing text with the modified text selections = sublime.Region(0, self.view.size()) self.view.replace(edit, selections, newcontent) def get_points(self, content): ''' Get all the point names in the document, return the set ''' points = set() p = re.compile(r'\"[A-Za-z0-9][A-Z0-9 :_\./-]+\"') for line in content.split('\n'): PointsFoundInLine = re.findall(p, line) for point in PointsFoundInLine: print (point) # if not ('.AND.' in point) not ('.LT.' in point) points.add(point) return list(points) def toggle_points(self, content, points, toggle): ''' Toggle from "_" to "." or vice versa ptou means periods to underscores utop means underscores to periods Return the new content ''' newcontent = content if toggle == 'ptou': new_points = [point.replace('.', '_') for point in points] if toggle == 'utop': new_points = [point.replace('_', '.') for point in points] for point, newpoint in zip(points, new_points): newcontent = newcontent.replace(point, newpoint) return newcontent class CallCopyCodeCommand(sublime_plugin.TextCommand): ''' This class calls the user_input_window, gets the user response then calls the adjust_line_numbers command as an external command. ''' def __init__(self, view): self.view = view self.number_of_copies = 1 def run(self, edit): # get the start and end rows, even with multiple selections # beginning_row, ending_row = self.get_rows() # get the user input for the start and the increment self.edit = edit self.get_number_of_copies() def get_number_of_copies(self): inputView = sublime.Window.show_input_panel(sublime.active_window(), '<Number of Copies>', '{}'.format(self.number_of_copies), self.on_done, None, None) def on_done(self, text): ''' this function just sets the number of copies selected by the user because I couldnt figure out how to do that in the show_input_panel function. ''' try: number_of_copies = text self.number_of_copies = int(number_of_copies) except: self.number_of_copies = None if self.number_of_copies != None: # self.main_functions() self.view.run_command("copy_code", {'number_of_copies': self.number_of_copies}) class CopyCodeCommand(sublime_plugin.TextCommand): ''' This function copies the selected code the number of specified times. ''' def run(self, edit, number_of_copies): # print ("made it =", kwargs) start_pos, end_pos = self.get_region() selected_content = self.view.substr(sublime.Region(start_pos, end_pos)) # print ('selected\n\n\n\n\n', selected_content) new_content = self.make_new_content(selected_content, number_of_copies) # print ('new\n\n\n\n\n', new_content) total_content = self.view.substr(sublime.Region(0, self.view.size())) replacement_content = total_content.replace(selected_content, new_content) # print ('replacement\n\n\n\n\n', replacement_content) # replace the existing text with the modified text selections = sublime.Region(0, self.view.size()) self.view.replace(edit, selections, replacement_content) def get_region(self): ''' return the beginning and ending row numbers of the selection. ''' start_pos = None end_pos = 0 for region in self.view.sel(): selectedLines = self.view.lines(region) if start_pos is None: start_pos = selectedLines[0].begin() else: start_pos = min(start_pos, selectedLines[0].begin()) end_pos = max(end_pos, selectedLines[-1].end()) return start_pos, end_pos def make_new_content(self, content_to_copy, number_of_copies): '''this returns the selection copied the number of times desired.''' new_content = '' for number in range(0, number_of_copies): new_content += content_to_copy + '\n' return new_content class CallEnumerateCommand(sublime_plugin.TextCommand): ''' This class calls the user_input_window, gets the user response then
<filename>discord/message.py # -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2017 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import asyncio import re import discord.abc from . import utils from .user import User from .reaction import Reaction from .emoji import Emoji from .object import Object from .calls import CallMessage from .enums import MessageType, try_enum from .errors import InvalidArgument, ClientException from .embeds import Embed class Message: """Represents a message from Discord. There should be no need to create one of these manually. Attributes ----------- edited_timestamp: Optional[datetime.datetime] A naive UTC datetime object containing the edited time of the message. tts: bool Specifies if the message was done with text-to-speech. type: :class:`MessageType` The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for :attr:`system_content`. author A :class:`Member` that sent the message. If :attr:`channel` is a private channel, then it is a :class:`User` instead. content: str The actual contents of the message. nonce The value used by the discord guild and the client to verify that the message is successfully sent. This is typically non-important. embeds: List[:class:`Embed`] A list embeds the message has. channel The :class:`Channel` that the message was sent from. Could be a :class:`PrivateChannel` if it's a private message. In :issue:`very rare cases <21>` this could be a :class:`Object` instead. For the sake of convenience, this :class:`Object` instance has an attribute ``is_private`` set to ``True``. call: Optional[:class:`CallMessage`] The call that the message refers to. This is only applicable to messages of type :attr:`MessageType.call`. mention_everyone: bool Specifies if the message mentions everyone. .. note:: This does not check if the ``@everyone`` text is in the message itself. Rather this boolean indicates if the ``@everyone`` text is in the message **and** it did end up mentioning everyone. mentions: list A list of :class:`Member` that were mentioned. If the message is in a private message then the list will be of :class:`User` instead. For messages that are not of type :attr:`MessageType.default`\, this array can be used to aid in system messages. For more information, see :attr:`system_content`. .. warning:: The order of the mentions list is not in any particular order so you should not rely on it. This is a discord limitation, not one with the library. channel_mentions: list A list of :class:`Channel` that were mentioned. If the message is in a private message then the list is always empty. role_mentions: list A list of :class:`Role` that were mentioned. If the message is in a private message then the list is always empty. id: int The message ID. webhook_id: Optional[int] If this message was sent by a webhook, then this is the webhook ID's that sent this message. attachments: list A list of attachments given to a message. pinned: bool Specifies if the message is currently pinned. reactions : List[:class:`Reaction`] Reactions to a message. Reactions can be either custom emoji or standard unicode emoji. """ __slots__ = ( 'edited_timestamp', 'tts', 'content', 'channel', 'webhook_id', 'mention_everyone', 'embeds', 'id', 'mentions', 'author', '_cs_channel_mentions', '_cs_raw_mentions', 'attachments', '_cs_clean_content', '_cs_raw_channel_mentions', 'nonce', 'pinned', 'role_mentions', '_cs_raw_role_mentions', 'type', 'call', '_cs_system_content', '_cs_guild', '_state', 'reactions' ) def __init__(self, *, state, channel, data): self._state = state self.id = int(data['id']) self.reactions = [Reaction(message=self, data=d) for d in data.get('reactions', [])] self._update(channel, data) def __repr__(self): return '<Message id={0.id} pinned={0.pinned} author={0.author!r}>'.format(self) def _try_patch(self, data, key, transform): try: value = data[key] except KeyError: pass else: setattr(self, key, transform(value)) def _add_reaction(self, data): emoji = self._state.get_reaction_emoji(data['emoji']) reaction = utils.find(lambda r: r.emoji == emoji, self.reactions) is_me = data['me'] = int(data['user_id']) == self._state.self_id if reaction is None: reaction = Reaction(message=self, data=data, emoji=emoji) self.reactions.append(reaction) else: reaction.count += 1 if is_me: reaction.me = is_me return reaction def _remove_reaction(self, data): emoji = self._state.get_reaction_emoji(data['emoji']) reaction = utils.find(lambda r: r.emoji == emoji, self.reactions) if reaction is None: # already removed? raise ValueError('Emoji already removed?') # if reaction isn't in the list, we crash. This means discord # sent bad data, or we stored improperly reaction.count -= 1 if int(data['user_id']) == self._state.self_id: reaction.me = False if reaction.count == 0: # this raises ValueError if something went wrong as well. self.reactions.remove(reaction) return reaction def _update(self, channel, data): self.channel = channel self._try_patch(data, 'edited_timestamp', utils.parse_time) self._try_patch(data, 'pinned', bool) self._try_patch(data, 'mention_everyone', bool) self._try_patch(data, 'tts', bool) self._try_patch(data, 'type', lambda x: try_enum(MessageType, x)) self._try_patch(data, 'content', str) self._try_patch(data, 'attachments', lambda x: x) self._try_patch(data, 'embeds', lambda x: list(map(Embed.from_data, x))) self._try_patch(data, 'nonce', lambda x: x) for handler in ('author', 'mentions', 'mention_roles', 'call'): try: getattr(self, '_handle_%s' % handler)(data[handler]) except KeyError: continue # clear the cached properties cached = filter(lambda attr: attr.startswith('_cs_'), self.__slots__) for attr in cached: try: delattr(self, attr) except AttributeError: pass def _handle_author(self, author): self.author = self._state.store_user(author) if self.guild is not None: found = self.guild.get_member(self.author.id) if found is not None: self.author = found def _handle_mentions(self, mentions): self.mentions = [] if self.guild is None: self.mentions = [self._state.store_user(m) for m in mentions] return for mention in mentions: id_search = int(mention['id']) member = self.guild.get_member(id_search) if member is not None: self.mentions.append(member) def _handle_mention_roles(self, role_mentions): self.role_mentions = [] if self.guild is not None: for role_id in map(int, role_mentions): role = utils.get(self.guild.roles, id=role_id) if role is not None: self.role_mentions.append(role) def _handle_call(self, call): if call is None or self.type is not MessageType.call: self.call = None return # we get the participant source from the mentions array or # the author participants = [] for uid in map(int, call.get('participants', [])): if uid == self.author.id: participants.append(self.author) else: user = utils.find(lambda u: u.id == uid, self.mentions) if user is not None: participants.append(user) call['participants'] = participants self.call = CallMessage(message=self, **call) @utils.cached_slot_property('_cs_guild') def guild(self): """Optional[:class:`Guild`]: The guild that the message belongs to, if applicable.""" return getattr(self.channel, 'guild', None) @utils.cached_slot_property('_cs_raw_mentions') def raw_mentions(self): """A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content. This allows you receive the user IDs of mentioned users even in a private message context. """ return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_channel_mentions') def raw_channel_mentions(self): """A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_role_mentions') def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_channel_mentions') def channel_mentions(self): if self.guild is None: return [] it = filter(None, map(lambda m: self.guild.get_channel(m), self.raw_channel_mentions)) return utils._unique(it) @utils.cached_slot_property('_cs_clean_content') def clean_content(self): """A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. """ transformations = { re.escape('<#{0.id}>'.format(channel)): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@{0.id}>'.format(member)): '@' + member.display_name for member in self.mentions } # add the <@!user_id> cases as well.. second_mention_transforms = { re.escape('<@!{0.id}>'.format(member)): '@' + member.display_name for member in self.mentions } transformations.update(mention_transforms) transformations.update(second_mention_transforms) if self.guild is not None: role_transforms = { re.escape('<@&{0.id}>'.format(role)): '@' + role.name for role in self.role_mentions } transformations.update(role_transforms) def repl(obj): return
<reponame>gglin001/poptorch<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2020 Graphcore Ltd. All rights reserved. import torch import pytest import poptorch import helpers non_differentiable_ops = [ torch.ceil, torch.floor, torch.round, torch.sign, torch.trunc, torch.argmax, torch.argmin, torch.remainder, torch.floor_divide ] def op_harness(op, inputs, assert_func, test_training=False, out_fn=None): is_unary = len(inputs) == 1 if not is_unary: assert len(inputs) == 2 if test_training and not op in non_differentiable_ops: model = helpers.ModelWithWeights(op, inputs[0].shape, out_fn) # Run on CPU. native_out, _ = model(tuple(inputs)) # The LR should be large enough that a single training step will # definitely cause weights to change optim = torch.optim.AdamW(model.parameters(), lr=0.1) # Run on IPU. poptorch_model = poptorch.trainingModel(model, optimizer=optim) poptorch_out, _ = poptorch_model(tuple(inputs)) # Training test - check weights have changed poptorch_model.assert_weights_changed() else: class Model(torch.nn.Module): def __init__(self, op): super().__init__() self.op = op if is_unary: Model.forward = lambda self, x: self.op(x) else: Model.forward = lambda self, x, y: self.op(x, y) model = Model(op) # Run on CPU. native_out = model(*inputs) # Run on IPU. poptorch_model = poptorch.inferenceModel(model) poptorch_out = poptorch_model(*inputs) assert_func(native_out, poptorch_out) unary_ops_float = [ torch.abs, torch.acos, torch.acosh, torch.asin, torch.asinh, torch.atan, torch.atanh, # torch.angle, torch.ceil, torch.cos, torch.cosh, # torch.conj, torch.digamma torch.erf, torch.erfc, #torch.erfinv, torch.exp, torch.expm1, torch.floor, torch.frac, # torch.imag, torch.lgamma, torch.log, torch.log10, torch.log1p, torch.log2, # torch.logical_not, torch.mvlgamma, torch.neg, # torch.real, torch.reciprocal, torch.round, torch.rsqrt, torch.sigmoid, torch.sign, torch.sin, torch.sinh, torch.sqrt, torch.square, torch.tan, torch.tanh, torch.trunc, ] @pytest.mark.parametrize("op", unary_ops_float) def test_unary_ops_float(op): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def assert_(native_out, poptorch_out): helpers.assert_allclose(expected=native_out, actual=poptorch_out, atol=1e-03, rtol=1e-03, equal_nan=True) op_harness(op, [input], assert_, test_training=True) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize("exponent", [4.0, 3, 2.5]) def test_binary_pow(inplace, exponent): torch.manual_seed(42) input = torch.randn([1, 2, 10, 200]) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out) def op(x): if inplace: # Although inplace would work, the native and poptorch output will # naturally not match as the input is changed x = x + 0 return x.pow_(exponent) return torch.pow(x, exponent) op_harness(op, [input], assert_) unary_ops_int = [ torch.bitwise_not, ] @pytest.mark.parametrize("op", unary_ops_int) def test_unary_ops_int(op): torch.manual_seed(42) input = torch.randint(-1000, 1000, [1, 2, 10, 200]) def assert_(native_out, poptorch_out): helpers.assert_allequal(actual=poptorch_out, expected=native_out) op_harness(op, [input], assert_) unary_ops_bool = [ torch.bitwise_not, ] @pytest.mark.parametrize("op", unary_ops_bool) def test_unary_ops_bool(op): torch.manual_seed(42) input = torch.randint(2, [1, 2, 10, 200]) > 0 def assert_(native_out, poptorch_out): helpers.assert_allequal(actual=poptorch_out, expected=native_out) op_harness(op, [input], assert_) # Parameterize torch.clamp unittests for different supported overloads clamp_inputs = [{"min": 0.2, "max": 0.8}, {"min": 0.2}, {"max": 0.8}] @pytest.mark.parametrize("args", clamp_inputs) def test_clamp(args): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def op_clamp(x): return x.clamp(**args) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out) op_harness(op_clamp, [input], assert_, test_training=True) @pytest.mark.parametrize("args", clamp_inputs) def test_clamp_(args): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def op_clamp_(x): return x.clamp_(**args) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out) op_harness(op_clamp_, [input], assert_, test_training=True) @pytest.mark.parametrize( "op", [torch.clamp_min, torch.clamp_min_, torch.clamp_max, torch.clamp_max_]) def test_clamp_min(op): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def op_clamp(x): return op(x, 0.5) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out) op_harness(op_clamp, [input], assert_, test_training=True) binary_ops_float = [ torch.add, torch.atan2, torch.div, torch.sub, torch.fmod, torch.floor_divide, torch.mul, torch.remainder, torch.true_divide ] @pytest.mark.parametrize("op", binary_ops_float) def test_binary_ops_float(op): torch.manual_seed(42) input1 = torch.randn([1, 2, 5, 1]) * 100.0 input2 = torch.randn([1, 2, 5, 1]) * 10.0 def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-05, rtol=1e-05, equal_nan=True) op_harness(op, [input1, input2], assert_, test_training=True) binary_ops_basic_element_wise_float = [ torch.add, torch.div, torch.sub, torch.mul, ] @pytest.mark.parametrize("op", binary_ops_basic_element_wise_float) def test_binary_ops_elementwise_edgecases(op): torch.manual_seed(42) input1 = torch.randn([1, 2, 10, 10]) input2 = torch.randn([1]) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-04, rtol=1e-04, equal_nan=True) class Model(torch.nn.Module): def __init__(self, op): super().__init__() self.op = op # Constant on LHS Model.forward = lambda self, x, _y: self.op(x, 4.0) op_harness(Model(op), [input1, input2], assert_, test_training=True) # Constant on RHS Model.forward = lambda self, x, _y: self.op(2.5, x) op_harness(Model(op), [input1, input2], assert_, test_training=True) # Constant on LHS wrong type. Model.forward = lambda self, x, _y: self.op(x, 4) op_harness(Model(op), [input1, input2], assert_, test_training=True) # Constant on RHS wrong type Model.forward = lambda self, x, _y: self.op(134, x) op_harness(Model(op), [input1, input2], assert_, test_training=True) binary_ops_basic_element_wise_bool = [ torch.add, torch.mul, ] @pytest.mark.parametrize("op", binary_ops_basic_element_wise_bool) def test_binary_ops_elementwise_bools(op): input1 = torch.tensor([False, True, False, True]) input2 = torch.tensor([False, False, True, True]) def assert_(native_out, poptorch_out): helpers.assert_allequal(actual=poptorch_out, expected=native_out) class Model(torch.nn.Module): def __init__(self, op): super().__init__() self.op = op # Both bools Model.forward = lambda self, x, y: self.op(x, y) op_harness(Model(op), [input1, input2], assert_) # Float on LHS Model.forward = lambda self, x, y: self.op(x.to(torch.float) + 1.0, y) op_harness(Model(op), [input1, input2], assert_) # Float on RHS Model.forward = lambda self, x, y: self.op(x, y.to(torch.float) + 1.0) op_harness(Model(op), [input1, input2], assert_) # Int on LHS Model.forward = lambda self, x, y: self.op(x.to(torch.int) + 1, y) op_harness(Model(op), [input1, input2], assert_) # Int on RHS Model.forward = lambda self, x, y: self.op(x, y.to(torch.int) + 1) op_harness(Model(op), [input1, input2], assert_) @pytest.mark.parametrize("op", [torch.fmod, torch.remainder]) def test_modulo_mixed_sign(op): input1 = torch.tensor([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]) input2 = torch.tensor([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-05, rtol=1e-05, equal_nan=True) op_harness(op, [input1, input2], assert_) def __and__(x, y): return x & y def __or__(x, y): return x | y def __xor__(x, y): return x ^ y binary_op_int = [ torch.bitwise_and, torch.bitwise_or, torch.bitwise_xor, __and__, __or__, __xor__ ] @pytest.mark.parametrize("op", binary_op_int) def test_binary_int_ops(op): input1 = torch.tensor([-4, 7, 5, 4, -7, 8], dtype=torch.int) input2 = torch.tensor([2, -3, 8, -2, 3, 5], dtype=torch.int) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-05, rtol=1e-05, equal_nan=True) op_harness(op, [input1, input2], assert_) binary_op_bool = [ torch.bitwise_and, torch.bitwise_or, # torch.bitwise_xor, TODO(T43716) torch.logical_and, torch.logical_or, #torch.logical_xor TODO(T43716) ] @pytest.mark.parametrize("op", binary_op_bool) def test_binary_bool_ops(op): input1 = torch.tensor([-4, 7, 5, 4, -7, 8]) > 0 input2 = torch.tensor([2, -3, 8, -2, 3, 5]) > 0 def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-05, rtol=1e-05, equal_nan=True) op_harness(op, [input1, input2], assert_) # These functions support API 1 - op(input) reduction_ops_api1 = [ torch.amax, torch.amin, torch.argmax, torch.argmin, # torch.dist, torch.mean, torch.median, # torch.mode, torch.norm, torch.prod, #torch.std, torch.std_mean, torch.sum, #torch.unique, torch.unique_consecutive,torch.var, torch.var_mean, ] # These functions support API 2 - op(input,dim,keep_dim) reduction_ops_api2 = [ torch.amax, torch.amin, torch.argmax, torch.argmin, # torch.dist, torch.mean, torch.median, # torch.mode, torch.norm, torch.prod, torch.logsumexp, # logsumexp doesn't support API 1. #torch.std, torch.std_mean, torch.sum, #torch.unique, torch.unique_consecutive,torch.var, torch.var_mean, ] @pytest.mark.parametrize("op", reduction_ops_api1) def test_reduction_ops_float(op): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def assert_(native_out, poptorch_out): poptorch_out = poptorch_out.reshape(native_out.shape) if native_out.dtype == torch.float32: helpers.assert_allclose(actual=poptorch_out, expected=native_out, atol=1e-05, rtol=1e-05, equal_nan=True) else: helpers.assert_allequal(actual=poptorch_out, expected=native_out) op_harness(op, [input], assert_, test_training=True) @pytest.mark.parametrize("op", reduction_ops_api2) @pytest.mark.parametrize("dim", range(4)) @pytest.mark.parametrize("keepdim", [False, True]) def test_reduction_ops_float_api2(op, dim, keepdim): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def operation(x): return op(x, dim=dim, keepdim=keepdim) def assert_(native_out, poptorch_out): if op is torch.median: # Median returns values and indices with API 2. helpers.assert_allclose(actual=poptorch_out[0], expected=native_out.values) helpers.assert_allequal(actual=poptorch_out[1].to(torch.int64), expected=native_out.indices) elif native_out.dtype == torch.float32: helpers.assert_allclose(actual=poptorch_out, expected=native_out) elif torch.numel(native_out) > 1: # Work around not returning longs from popart. helpers.assert_allequal(actual=poptorch_out.to(torch.int64), expected=native_out) else: helpers.assert_allequal(actual=poptorch_out, expected=native_out) # This check must be repeated here because we need to check the op before we # wrap the function otherwise it won't match in the test harness test_training = not op in non_differentiable_ops out_fn = (lambda x: x.values) if op is torch.median else None op_harness(operation, [input], assert_, test_training=test_training, out_fn=out_fn) @pytest.mark.parametrize("op", [torch.min, torch.max]) @pytest.mark.parametrize("dim", range(3)) @pytest.mark.parametrize("keepdim", [False, True]) def test_minmax_tuple_out(op, dim, keepdim): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def operation(x): return op(x, dim=dim, keepdim=keepdim) def assert_(native_out, poptorch_out): assert isinstance(native_out, tuple) and isinstance( poptorch_out, tuple) assert len(native_out) == len(poptorch_out) for i, native in enumerate(native_out): helpers.assert_allclose(actual=poptorch_out[i], expected=native) out_fn = lambda x: x.values op_harness(operation, [input], assert_, test_training=True, out_fn=out_fn) # Interesting p-values for testing torch.norm(X, p=<>) norm_pvals = ['fro', float('inf'), float('-inf'), 1, 1.0, 2, 2.0, 3, 3.0] @pytest.mark.parametrize("p", norm_pvals) def test_norm_p_values(p): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def operation(x): return torch.norm(x, p=p) def assert_(native_out, poptorch_out): helpers.assert_allclose(actual=poptorch_out, expected=native_out) op_harness(operation, [input], assert_, test_training=True) comparison_ops = [ # torch.allclose, # Not supported in trace, seems to get optimized out. # torch.argsort, # Not in Onnx. TODO(T23319) torch.eq, # torch.equal, # Not supported as the return of trace in JIT. torch.ge, torch.gt, # torch.kthvalue, # Not in Onnx. torch.le, torch.lt, torch.max, torch.min, torch.ne, # torch.sort, # Not in Onnx (could be added via TopK if onnx supported TODO(T23319)) ] @pytest.mark.parametrize("op", comparison_ops) def test_compare_operations(op): torch.manual_seed(42) lhs = torch.randn([1, 2, 10, 200]) rhs = torch.randn([1, 2, 10, 200]) indices = torch.randint(0, 200, [30]) # Make a few of the indices equal. for i in indices: lhs[0][0][0][i] = rhs[0][0][0][i] def assert_(native_out, poptorch_out): helpers.assert_allequal(actual=poptorch_out, expected=native_out) op_harness(op, [lhs, rhs], assert_) if op not in (torch.min, torch.max): constant_rhs = lambda x: op(x, 0.34) op_harness(constant_rhs, [lhs], assert_) comparison_unity_nan_inf_ops = [ # torch.isfinite, torch.isinf, # Not in Onnx torch.isnan, ] @pytest.mark.parametrize("op", comparison_unity_nan_inf_ops) def test_compare_unity_nan_inf_ops(op): torch.manual_seed(42) input = torch.tensor([ 1.0, float('inf'), 2.0, float('-inf'), float('nan'), float('-nan'), 13.0 ]) def assert_(native_out, poptorch_out): helpers.assert_allequal(actual=poptorch_out, expected=native_out) op_harness(op, [input], assert_) comparison_unity = [torch.max, torch.min] @pytest.mark.parametrize("op", comparison_unity) def test_compare_unity_operations(op): torch.manual_seed(42) input = torch.randn([1, 2, 10, 10]) def operation(x): return
@param client: An instance of the identity client @type: client: `clientmanager.identity` @param faker: An instance of the faker object @type faker: `faker.Factory` @param keeper: Reference to the keeper @type keeper: `keeper.Keeper` """ self.native = client self.cache = cache self.faker = faker self.keeper = keeper self.spam = lambda: None self.spam.projects = lambda: None self.spam.users = lambda: None self.spam.projects.create = self.spam_project_create self.spam.projects.delete = self.spam_project_delete self.spam.projects.update = self.spam_project_update self.spam.users.create = self.spam_user_create self.spam.users.delete = self.spam_user_delete self.spam.users.update = self.spam_user_update @cache def spam_project_create(self): while True: name = self.faker.word() if not self.keeper.get("keystone", "projects", "name", lambda x: x == name): break try: log.info("Creating project with name {}".format(name)) created = self.native.projects.create( name=name, domain="default", description="Project {}".format(name), enabled=True) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return # quotas update try: log.info("Update cinder quotas for project " "{}".format(created.name)) self.keeper.client_factory.cinder().quotas.update( created.id, backup_gigabytes=-1, backups=-1, gigabytes=-1, per_volume_gigabytes=-1, snapshots=-1, volumes=-1) log.info( "Update neutron quotas for project {}".format(created.name)) self.keeper.client_factory.neutron().quotas.update( created.id, subnet=-1, network=-1, floatingip=-1, subnetpool=-1, port=-1, security_group_rule=-1, security_group=-1, router=-1, rbac_policy=-1) log.info("Update nova quotas for project {}".format(created.name)) self.keeper.client_factory.nova().quotas.update( created.id, cores=-1, fixed_ips=-1, floating_ips=-1, injected_file_content_bytes=-1, injected_file_path_bytes=-1, injected_files=-1, instances=-1, key_pairs=-1, metadata_items=-1, ram=-1, security_group_rules=-1, security_groups=-1, server_group_members=-1, server_groups=-1) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return created @uncache def spam_project_delete(self): projects = self.keeper.get("keystone", "projects", None, (lambda x, y: x != "admin" and y in self.cache["keystone"]["projects"]), "name", "id") if len(projects) > 0: project = random.choice(projects) else: log.warning("There is no projects for removing, skipping...") return try: log.info("Removing project {}".format(project.name)) self.native.projects.delete(project) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return project.id def spam_project_update(self): while True: name = self.faker.word() if not self.keeper.get("keystone", "projects", "name", lambda x: x == name): break projects = self.keeper.get("keystone", "projects", None, (lambda x, y: x != "admin" and y in self.cache["keystone"]["projects"]), "name", "id") if len(projects) > 0: project = random.choice(projects) else: log.warning("There is no project for updating, skipping...") return try: log.info("Trying to update project {}".format(project.name)) updated = self.native.projects.update( project=project, name=name, domain="default", description="Project {}".format(name), enabled=True) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return updated @cache def spam_user_create(self): while True: name = self.faker.name() if not self.keeper.get("keystone", "users", "name", lambda x: x == name): break password = self.faker.password() email = self.faker.safe_email() projects = self.keeper.get( "keystone", "projects", "id", lambda x: x in self.cache["keystone"]["projects"]) if len(projects) > 0: project = random.choice(projects) else: log.warning("There is no projects, skipping user creating...") return try: log.info("Creating user with name {user_name}" " in project {project}".format(user_name=name, project=project.name)) created = self.native.users.create( name=name, domain="default", password=password, email=email, description="User with name {}".format(name), enabled=True, default_project=project) log.info("User with id {} was created".format(created.id)) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return try: log.info("Granting role to user {}".format(created.id)) self.native.roles.grant( self.native.roles.find(name="admin"), created, project=project) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return self.cache["users"][name] = {"username": created.name, "password": password, "project_name": project.name, "project_domain_id": project.domain_id, "user_domain_id": created.domain_id} return created @uncache def spam_user_delete(self): users = self.keeper.get("keystone", "users", None, (lambda x, y: x != "admin" and y in self.cache["keystone"]["users"]), "name", "id") if len(users) > 0: user = random.choice(users) else: log.warning("There is no users, skipping user removing...") return try: log.info("Trying to delete user {}".format(user.name)) self.native.users.delete(user) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return user.id def spam_user_update(self): while True: name = self.faker.name() if not self.keeper.get("keystone", "users", "name", lambda x: x == name): break users = self.keeper.get("keystone", "users", None, (lambda x, y: x != "admin" and y in self.cache["keystone"]["users"]), "name", "id") if len(users) > 0: user = random.choice(users) else: log.warning("There is no users for updating, skipping...") return log.info("Trying to update user {}".format(user.id)) password = self.faker.password() email = self.faker.safe_email() self.cache["users"][name] = {"username": name, "password": password, "project_name": self.cache["users"] [user.name]["project_name"], "project_domain_id": self.cache["users"] [user.name]["project_domain_id"], "user_domain_id": self.cache["users"] [user.name]["user_domain_id"]} del self.cache["users"][user.name] try: updated = self.native.users.update( user=user, name=name, domain="default", password=password, email=email, description="User with name {}".format(name), enabled=True) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return updated class SpamNeutron(object): def __init__(self, cache, client, faker=None, keeper=None): """Create `SpamNeutron` class instance. @param cache: Cache @type cache: `cache.Cache` @param client: An instance of the identity client @type: client: `clientmanager.identity` @param faker: An instance of the faker object @type faker: `faker.Factory` @param keeper: Reference to the keeper @type keeper: `keeper.Keeper` """ self.native = client self.cache = cache self.faker = faker self.keeper = keeper self.spam = lambda: None self.spam.networks = lambda: None self.spam.ports = lambda: None self.spam.routers = lambda: None self.spam.security_groups = lambda: None self.spam.subnets = lambda: None self.spam.networks.create = self.spam_network_create self.spam.networks.delete = self.spam_network_delete self.spam.networks.update = self.spam_network_update self.spam.ports.create = self.spam_port_create self.spam.ports.delete = self.spam_port_delete self.spam.ports.update = self.spam_port_update self.spam.routers.create = self.spam_router_create self.spam.routers.delete = self.spam_router_delete self.spam.routers.update = self.spam_router_update self.spam.security_groups.create = self.spam_security_group_create self.spam.security_groups.delete = self.spam_security_group_delete self.spam.security_groups.update = self.spam_security_group_update self.spam.subnets.create = self.spam_subnet_create self.spam.subnets.delete = self.spam_subnet_delete self.spam.subnets.update = self.spam_subnet_update @cache def spam_network_create(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "networks", "name", lambda x: x == name): break try: log.info("Creating network {}".format(name)) created = self.native.networks.create( name=name, description="Network with name {}".format(name), shared=True) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return created @uncache def spam_network_delete(self): networks = self.keeper.get( "neutron", "networks", "id", lambda x: x in self.cache["neutron"]["networks"]) if len(networks) > 0: network = random.choice(networks) else: log.warning("There is no network for removing, skipping...") return # Deleting all the sub-resources of the network # --------------------------------------------------------------------# routers = self.keeper.get("neutron", "routers", None, (lambda x, y: x == network.id and y in self.cache["neutron"]["routers"]), "network_id", "id") subnets = self.keeper.get("neutron", "subnets", None, (lambda x, y: x == network.id and y in self.cache["neutron"]["routers"]), "network_id", "id") ports = self.keeper.get("neutron", "ports", None, (lambda x, y: x == network.id and y in self.cache["neutron"]["ports"]), "network_id", "id") floatingips = self.keeper.get( "neutron", "floatingips", None, (lambda x, y: x == network.id and y in self.cache["neutron"]["floatingips"]), "network_id", "id") try: for router in routers: self.native.routers.delete(router.id) for subnet in subnets: self.native.subnets.delete(subnet.id) for port in ports: self.native.ports.delete(port.id) for floatingip in floatingips: self.native.floatingips.delete(floatingip.id) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return # --------------------------------------------------------------------# try: log.info("Deleting network with id {}".format(network.id)) self.native.networks.delete(network.id) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return network.id def spam_network_update(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "networks", "name", lambda x: x == name): break networks = self.keeper.get( "neutron", "networks", "id", lambda x: x in self.cache["neutron"]["networks"]) if len(networks) > 0: network = random.choice(networks) else: log.warning("There is no networks for updating, skipping") return try: log.info("Updating network {}".format(network.id)) updated = self.native.networks.update( network.id, name=name, description="Network with name {}".format(name)) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return updated @cache def spam_port_create(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "ports", "name", lambda x: x == name): break networks = self.keeper.get( "neutron", "networks", "id", lambda x: x in self.cache["neutron"]["networks"]) if len(networks) > 0: network = random.choice(networks) else: log.warning("There is no networks for port creating, skipping...") return try: log.info("Creating port with name {}".format(name)) created = self.native.ports.create( name=name, description="Port with name {}".format(name), network_id=network.id) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return created @uncache def spam_port_delete(self): ports = self.keeper.get( "neutron", "ports", "id", lambda x: x in self.cache["neutron"]["ports"]) if len(ports) > 0: port = random.choice(ports) else: log.warning("There is no ports for removing, skipping...") return try: log.info("Removing port with id {}".format(port.id)) self.native.ports.delete(port.id) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return port.id def spam_port_update(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "ports", "name", lambda x: x == name): break ports = self.keeper.get( "neutron", "ports", "id", lambda x: x in self.cache["neutron"]["ports"]) if len(ports) > 0: port = random.choice(ports) else: log.warning("There is no ports for updating, skipping...") return try: log.info("Update port with id {}".format(port.id)) updated = self.native.ports.update( port.id, name=name, description="Port with name {}".format(name)) except Exception as exc: log.critical("Exception: {}".format(exc)) traceback.print_exc() return return updated @cache def spam_router_create(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "routers", "name", lambda x: x == name): break try: log.info("Creating router with name {}".format(name)) created = self.native.routers.create( name=name, description="Router with name {}".format(name)) except Exception as exc: log.critical("Excepttion: {}".format(exc)) traceback.print_exc() return return created @uncache def spam_router_delete(self): routers = self.keeper.get( "neutron", "routers", "id", lambda x: x in self.cache["neutron"]["routers"]) if len(routers) > 0: router = random.choice(routers) else: log.warning("There is no routers for removing, skipping...") return try: log.info("Removing router with id {}".format(router.id)) self.native.routers.delete(router.id) except Exception as exc: log.critical("Excepttion: {}".format(exc)) traceback.print_exc() return return router.id def spam_router_update(self): while True: name = self.faker.word() if not self.keeper.get("neutron", "routers", "name", lambda x: x
<reponame>vimm0/python_exercise<gh_stars>0 # Section 1. Very simple exercises # # This selection of exercises is intended for developers # to get a basic understanding of logical operators and loops in Python # import re # 1. Max of two numbers. def max_num( a, b ): if a > b: return a return b # 2. Max of three numbers. def max_of_three( a, b, c ): return max_num( a, max_num( b, c ) ) # 3. Calculates the length of a string. def str_len( string ): count = 0 for letter in string: count += 1 return count # 4. Returns whether the passed letter is a vowel. def is_vowel( letter ): vowels = 'aeiou' return letter in vowels # 5. Translates an English frase into `Robbers language`. # Sample: # # This is fun # Tothohisos isos fofunon # def translate( string ): consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ' translated = '' for letter in string: if letter in consonants: parsed = '%so%s' % ( letter, letter.lower() ) translated = translated + parsed else: translated = translated + letter return translated # 6. Sum. # Sums all the numbers in a list. def sum( items ): total = 0 for a in items: total += a return total # 6.1. Multiply. # Multiplies all the items in a list. def multiply( items ): total = items[ 0 ] for x in items: total *= x return total # 7. Reverse. # Reverses a string. # 'I am testing' -> 'gnitset ma I' def reverse( string ): truncated = '' index = len( string ) # Loop over the string inversively while index > 0: truncated += string[ index - 1 ] index = index - 1 return truncated # 8. Is palindrome. # Checks whether a string is palindrome. # 'radar' > reversed : 'radar' def is_palindrome( string ): if string == reverse( string ): return True return False # 9. Is member. # Checks whether a value x is contained in a group of values. # 1 -> [ 2, 1, 0 ] : True def is_member( x, group ): for value in group: if x == value: return True return False # 10. Overlapping. # Checks whether two lists have at least one number in common def overlapping( a, b ): # Using `is_member()` method for x in a: if is_member( x, b ): return True return False # Nested loop way of doing it # for x in a: # for y in b: # if x == y: # return True # return False # 11. Generate n chars. # Generates `n` number of characters of the given one. # # generate_n_chars( 5, 'n' ) # -> nnnnn # def generate_n_chars( times, char ): output = '' while( times > 0 ): output += char times = times - 1 return output # 12. Historigram. # Takes a list of integers and prints a historigram of it. # historigram( [ 1, 2, 3 ] ) -> # * # ** # *** # def historigram( items ): for x in items: chars = generate_n_chars( x, '*' ) print( chars ) # 13. Max in list. # Gets the larges number in a list of numbers. def max_in_list( list ): max = list[ 0 ] for x in list: if x > max: max = x return max # 14. Map words to numbers. # Gets a list of words and returns a list of integers # representing the length of each word. # # [ 'one', 'two', 'three' ] -> [ 3, 3, 5 ] # def map_words( words ): result = [] for word in words: result.append( str_len( word ) ) return result # 15. Find longest wors. # Receives a list of words and returns the length # of the longest one. # # [ 'one', 'two', 'three', 'four' ] -> 5 # def longest_word( words ): # Asume the first word is the longest one longest = str_len( words[ 0 ] ) for word in words: if str_len( word ) > longest: longest = str_len( word ) return longest # 16. Filter long words. # Receives a list of words and an integer `n` and returns # a list of the words that are longer than n. def filter_long_words( words, x ): result = [] for word in words: if str_len( word ) >= x: result.append( word ) return result # 17. Version of palindrome that ignores punctuation, capitalization and # spaces, so that a larger range of frases can be clasified as palindromes. # # ( "Dammit, I'm mad!" ) -> is palindrome # def is_palindrome_advanced( string ): stripped = re.sub( r'[^a-zA-z]+', '', string ) reversed = reverse( stripped ) if stripped.lower() == reversed.lower(): return True return False # 18. Is pangram. # Checks whether a phrase is pangram, that is, if # it contains all the letters of the alphabet. def is_pangram( phrase ): abec = [ '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' ] for a in phrase: if a in abec: i = abec.index( a ) abec.pop( i ) if len( abec ) == 0: return True return False # 19. 99 Bottles of beer. # 99 Bottles of beer is a traditional song in the United States and Canada. # It has a very repetitive lyrics and it is popular to sing it in very long trips. # The lyrics of the song are as follows. # # 99 bottles of beer in the wall, 99 bottles of beer. # Take one down, pass it arrown, 98 bottles of beer. # # The song is repeated having one less bottle each time until there are no more # bottles to count. # def sing_99_bottles_of_beer(): for i in reversed( range( 1, 100 ) ): print '{} bottle{} of beer in the wall, {} bottle{} of beer.'.format( i, 's' if i != 1 else '', i, 's' if i != 1 else '' ) print 'Take one down, pass it around, {} bottle{} of beer on the wall.'.format( i - 1, 's' if i - 1 != 1 else '' ) # 20. Note: exercise number 20 is the same as exercise # 30 # 21. Character frequency. # Counts how many characters of the same letter there are in # a string. # # ( 'aabbccddddd' ) -> { 'a': 2, 'b': 2, 'c': 2, d: 5 } # def char_freq( string ): dict = {} for a in string: keys = dict.keys() if a in keys: dict[ a ] += 1 else: dict[ a ] = 1 return dict # 22. ROT-13: Encrypt. # Encrypts a string in ROT-13. # # rot_13_encrypt( 'Caesar cipher? I much prefer Caesar salad!' ) -> # Pnrfne pvcure? V zhpu cersre Pnrfne fnynq! # def rot_13_encrypt( string ): # Magnitud of rotation and dictionary rotate_by, dictionary = 13, {} abec = 'abcdefghijklmnopqrstuvwxyz' i = 0 while i < len( abec ): index = i + rotate_by if index > 25: index = index - 26 dictionary[ abec[ i ] ] = abec[ index ] i += 1 # Build phrase # Pass any character that is not in abec encrypted = '' for char in string: is_upper = char.istitle() char = char.lower() if not char in abec: encrypted = encrypted + char else: char = dictionary[ char ] char = char if not is_upper else char.upper() encrypted = encrypted + char return encrypted; # 22.1 ROT-13: Decrypt. # # rot_13_decrypt( 'Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!' ) -> # Caesar cipher? I much prefer Caesar salad! # # Since we're dealing with offset 13 it means that decrypting a string # can be accomplished with the encrypt function given that the alphabet contains # 26 letters. def rot_13_decrypt( string ): return rot_13_encrypt( string ) # 23. Correct. # Takes a string and sees that 1) two or more occurences of a space # are compressed into one. 2) Adds a space betweet a letter and a period # if they have not space. # # correct( 'This is very funny and cool.Indeed!' ) # -> This is very funny and cool. Indeed! # def correct( string ): # Replace multiple whitespaces with one only string = re.sub( r'\s{2,}', ' ', string ) # Add space after dots followed inmediatelly by a word string = re.sub( r'(?<=\.)(?=[a-zA-Z])', ' ', string
self.request.wants_json: return formatted_get_docs( self, "/acme-order/{ID}/acme-server/deactivate-authorizations.json", ) return HTTPSeeOther( "%s?result=error&operation=acme+server+deactivate+authorizations&message=HTTP+POST+required" % self._focus_url ) try: if not dbAcmeOrder.is_can_acme_server_deactivate_authorizations: raise errors.InvalidRequest( "ACME Server Deactivate Authorizations is not allowed for this AcmeOrder" ) result = lib_db.actions_acme.do__AcmeV2_AcmeOrder__acme_server_deactivate_authorizations( self.request.api_context, dbAcmeOrder=dbAcmeOrder, ) if self.request.wants_json: return { "result": "success", "operation": "acme-server/deactivate-authorizations", "AcmeOrder": dbAcmeOrder.as_json, } return HTTPSeeOther( "%s?result=success&operation=acme+server+deactivate+authorizations" % self._focus_url ) except ( errors.AcmeError, errors.InvalidRequest, ) as exc: if self.request.wants_json: return { "result": "error", "operation": "acme-server/deactivate-authorizations", "error": str(exc), } return HTTPSeeOther( "%s?result=error&error=%s&operation=acme+server+deactivate+authorizations" % (self._focus_url, exc.as_querystring) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @view_config( route_name="admin:acme_order:focus:acme_server:download_certificate", renderer=None, ) @view_config( route_name="admin:acme_order:focus:acme_server:download_certificate|json", renderer="json", ) @docify( { "endpoint": "/acme-order/{ID}/acme-server/download-certificate.json", "section": "acme-order", "about": """AcmeOrder focus: AcmeServer download-certificate""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/acme-server/download-certificate.json", } ) def acme_server_download_certificate(self): """ This endpoint is for Immediately Renewing the AcmeOrder with overrides on the keys """ dbAcmeOrder = self._focus(eagerload_web=True) if self.request.method != "POST": if self.request.wants_json: return formatted_get_docs( self, "/acme-order/{ID}/acme-server/download-certificate.json", ) return HTTPSeeOther( "%s?result=error&operation=acme+server+download+certificate&message=HTTP+POST+required" % self._focus_url ) try: dbAcmeOrder = ( lib_db.actions_acme.do__AcmeV2_AcmeOrder__download_certificate( self.request.api_context, dbAcmeOrder=dbAcmeOrder, ) ) if self.request.wants_json: return { "result": "success", "operation": "acme-server/download-certificate", "AcmeOrder": dbAcmeOrder.as_json, } return HTTPSeeOther( "%s?result=success&operation=acme+server+download+certificate" % self._focus_url ) except ( errors.AcmeError, errors.InvalidRequest, ) as exc: if self.request.wants_json: return { "result": "error", "operation": "acme-server/download-certificate", "error": str(exc), } return HTTPSeeOther( "%s?result=error&error=%s&operation=acme+server+download+certificate" % (self._focus_url, exc.as_querystring) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @view_config(route_name="admin:acme_order:focus:acme_process", renderer=None) @view_config(route_name="admin:acme_order:focus:acme_process|json", renderer="json") @docify( { "endpoint": "/acme-order/{ID}/acme-process.json", "section": "acme-order", "about": """AcmeOrder focus: AcmeServer acme-process""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/acme-process.json", } ) def process_order(self): """ only certain orders can be processed """ dbAcmeOrder = self._focus(eagerload_web=True) if self.request.method != "POST": if self.request.wants_json: return formatted_get_docs(self, "/acme-order/{ID}/acme-process.json") return HTTPSeeOther( "%s?result=error&operation=acme+process&message=HTTP+POST+required" % self._focus_url ) try: if not dbAcmeOrder.is_can_acme_process: raise errors.InvalidRequest( "ACME Process is not allowed for this AcmeOrder" ) dbAcmeOrder = lib_db.actions_acme.do__AcmeV2_AcmeOrder__process( self.request.api_context, dbAcmeOrder=dbAcmeOrder, ) if self.request.wants_json: return { "result": "success", "operation": "acme-process", "AcmeOrder": dbAcmeOrder.as_json, } return HTTPSeeOther( "%s?result=success&operation=acme+process" % self._focus_url ) except ( errors.AcmeError, errors.InvalidRequest, ) as exc: if self.request.wants_json: return { "result": "error", "operation": "acme-process", "error": str(exc), } return HTTPSeeOther( "%s?result=error&error=%s&operation=process+order" % (self._focus_url, exc.as_querystring) ) @view_config(route_name="admin:acme_order:focus:acme_finalize", renderer=None) @view_config( route_name="admin:acme_order:focus:acme_finalize|json", renderer="json" ) @docify( { "endpoint": "/acme-order/{ID}/acme-finalize.json", "section": "acme-order", "about": """AcmeOrder focus: acme-finalize""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/acme-finalize.json", } ) def finalize_order(self): """ only certain orders can be finalized """ dbAcmeOrder = self._focus(eagerload_web=True) if self.request.method != "POST": if self.request.wants_json: return formatted_get_docs(self, "/acme-order/{ID}/acme-finalize.json") return HTTPSeeOther( "%s?result=error&operation=acme+finalize&message=HTTP+POST+required" % self._focus_url ) try: if not dbAcmeOrder.is_can_acme_finalize: raise errors.InvalidRequest( "ACME Finalize is not allowed for this AcmeOrder" ) dbAcmeOrder = lib_db.actions_acme.do__AcmeV2_AcmeOrder__finalize( self.request.api_context, dbAcmeOrder=dbAcmeOrder, ) if self.request.wants_json: return { "result": "success", "operation": "finalize-order", "AcmeOrder": dbAcmeOrder.as_json, } return HTTPSeeOther( "%s?result=success&operation=acme+finalize" % self._focus_url ) except ( errors.AcmeError, errors.InvalidRequest, ) as exc: if self.request.wants_json: return { "result": "error", "operation": "finalize-order", "error": str(exc), } return HTTPSeeOther( "%s?result=error&error=%s&operation=acme+finalize" % (self._focus_url, exc.as_querystring) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @view_config(route_name="admin:acme_order:focus:mark", renderer=None) @view_config(route_name="admin:acme_order:focus:mark|json", renderer="json") @docify( { "endpoint": "/acme-order/{ID}/mark.json", "section": "acme-order", "about": """AcmeOrder focus: Mark""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/mark.json", "form_fields": { "action": "The action", }, "valid_options": { "action": [ "invalid", "deactivate", "renew_auto", "renew_manual", ] }, } ) def mark_order(self): """ Mark an order """ dbAcmeOrder = self._focus(eagerload_web=True) if self.request.method != "POST": if self.request.wants_json: return formatted_get_docs(self, "/acme-order/{ID}/mark.json") return HTTPSeeOther( "%s?result=error&operation=mark&message=HTTP+POST+required" % self._focus_url ) action = self.request.params.get("action", None) try: if action == "invalid": if not dbAcmeOrder.is_can_mark_invalid: raise errors.InvalidRequest("Can not mark this order as 'invalid'.") lib_db.actions_acme.updated_AcmeOrder_status( self.request.api_context, dbAcmeOrder, { "status": "invalid", }, transaction_commit=True, ) elif action == "deactivate": lib_db.update.update_AcmeOrder_deactivate( self.request.api_context, dbAcmeOrder, ) elif action == "renew_auto": event_status = lib_db.update.update_AcmeOrder_set_renew_auto( self.request.api_context, dbAcmeOrder, ) elif action == "renew_manual": event_status = lib_db.update.update_AcmeOrder_set_renew_manual( self.request.api_context, dbAcmeOrder, ) else: raise errors.InvalidRequest("invalid `action`") if self.request.wants_json: return { "result": "success", "operation": "mark", "action": action, "AcmeOrder": dbAcmeOrder.as_json, } return HTTPSeeOther( "%s?result=success&operation=mark&action=%s" % (self._focus_url, action) ) except (errors.InvalidRequest, errors.InvalidTransition) as exc: if self.request.wants_json: return { "result": "error", "operation": "mark", "error": str(exc), } url_failure = "%s?result=error&error=%s&operation=mark" % ( self._focus_url, exc.as_querystring, ) if action: url_failure = "%s&action=%s" % (url_failure, action) return HTTPSeeOther(url_failure) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @view_config(route_name="admin:acme_order:focus:retry", renderer=None) @view_config(route_name="admin:acme_order:focus:retry|json", renderer="json") @docify( { "endpoint": "/acme-order/{ID}/retry.json", "section": "acme-order", "about": """AcmeOrder focus: Retry""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/retry.json", } ) def retry_order(self): """ Retry should create a new order """ dbAcmeOrder = self._focus(eagerload_web=True) try: if self.request.method != "POST": if self.request.wants_json: return formatted_get_docs(self, "/acme-order/{ID}/retry.json") if not dbAcmeOrder.is_can_acme_server_sync: raise errors.InvalidRequest( "ACME Retry is not allowed for this AcmeOrder" ) try: dbAcmeOrderNew = lib_db.actions_acme.do__AcmeV2_AcmeOrder__retry( self.request.api_context, dbAcmeOrder=dbAcmeOrder, ) except errors.AcmeOrderCreatedError as exc: # unpack a `errors.AcmeOrderCreatedError` to local vars dbAcmeOrderNew = exc.acme_order exc = exc.original_exception if self.request.wants_json: return { "result": "error", "error": exc.args[0], "AcmeOrder": dbAcmeOrderNew.as_json, } return HTTPSeeOther( "%s/acme-order/%s?result=error&error=%s&opertion=retry+order" % ( self.request.admin_url, dbAcmeOrderNew.id, exc.as_querystring, ) ) if self.request.wants_json: return { "result": "success", "AcmeOrder": dbAcmeOrderNew.as_json, } return HTTPSeeOther( "%s/acme-order/%s?result=success&operation=retry+order" % (self.request.admin_url, dbAcmeOrderNew.id) ) except ( errors.AcmeError, errors.InvalidRequest, ) as exc: if self.request.wants_json: return { "result": "error", "error": exc.args[0], } return HTTPSeeOther( "%s?result=error&error=%s&operation=retry+order" % (self._focus_url, exc.as_querystring) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @view_config(route_name="admin:acme_order:focus:renew:custom", renderer=None) @view_config(route_name="admin:acme_order:focus:renew:custom|json", renderer="json") @docify( { "endpoint": "/acme-order/{ID}/renew/custom.json", "section": "acme-order", "about": """AcmeOrder focus: Renew Custom""", "POST": True, "GET": None, "example": "curl {ADMIN_PREFIX}/acme-order/1/renew/custom.json", "form_fields": { "processing_strategy": "How should the order be processed?", "account_key_option": "How is the AcmeAccount specified?", "account_key_reuse": "pem_md5 of the existing account key. Must/Only submit if `account_key_option==account_key_reuse`", "account_key_global_default": "pem_md5 of the Global Default account key. Must/Only submit if `account_key_option==account_key_global_default`", "account_key_existing": "pem_md5 of any key. Must/Only submit if `account_key_option==account_key_existing`", "account_key_file_pem": "pem of the account key file. Must/Only submit if `account_key_option==account_key_file`", "acme_account_provider_id": "account provider. Must/Only submit if `account_key_option==account_key_file` and `account_key_file_pem` is used.", "account_key_file_le_meta": "LetsEncrypt Certbot file. Must/Only submit if `account_key_option==account_key_file` and `account_key_file_pem` is not used", "account_key_file_le_pkey": "LetsEncrypt Certbot file", "account_key_file_le_reg": "LetsEncrypt Certbot file", "private_key_option": "How is the PrivateKey being specified?", "private_key_reuse": "pem_md5 of existing key", "private_key_existing": "pem_md5 of existing key", "private_key_file_pem": "pem to upload", "private_key_cycle__renewal": "how should the PrivateKey be cycled on renewals?", }, "form_fields_related": [ ["account_key_file_pem", "acme_account_provider_id"], [ "account_key_file_le_meta", "account_key_file_le_pkey", "account_key_file_le_reg", ], ], "valid_options": { "acme_account_provider_id": "{RENDER_ON_REQUEST}", "account_key_option": model_utils.AcmeAccontKey_options_b, "processing_strategy": model_utils.AcmeOrder_ProcessingStrategy.OPTIONS_ALL, "private_key_option": model_utils.PrivateKey_options_b, "AcmeAccount_GlobalDefault": "{RENDER_ON_REQUEST}", "private_key_cycle__renewal": model_utils.PrivateKeyCycle._options_AcmeOrder_private_key_cycle, }, "requirements": [ "Submit corresponding field(s) to account_key_option. If `account_key_file` is your intent, submit either PEM+ProviderID or the three LetsEncrypt Certbot files." ], "instructions": [ """curl --form 'account_key_option=account_key_reuse' --form 'account_key_reuse=ff00ff00ff00ff00' 'private_key_option=private_key_reuse' --form 'private_key_reuse=ff00ff00ff00ff00' {ADMIN_PREFIX}/acme-order/1/renew/custom.json""", ], } ) def renew_custom(self): """ This endpoint is for Immediately Renewing the AcmeOrder with overrides on the keys """ self._load_AcmeAccount_GlobalDefault() self._load_AcmeAccountProviders() if self.request.method == "POST": return self._renew_custom__submit() return self._renew_custom__print() def _renew_custom__print(self): dbAcmeOrder = self._focus() if self.request.wants_json: return formatted_get_docs(self, "/acme-order/{ID}/renew/custom.json") if not dbAcmeOrder.is_renewable_custom: raise errors.DisplayableError("This AcmeOrder can not use Renew Custom") return render_to_response( "/admin/acme_order-focus-renew-custom.mako", { "AcmeOrder": dbAcmeOrder, "AcmeAccount_GlobalDefault": self.dbAcmeAccount_GlobalDefault, "AcmeAccountProviders": self.dbAcmeAccountProviders, }, self.request, ) def _renew_custom__submit(self): dbAcmeOrder = self._focus() try: (result, formStash) = formhandling.form_validate( self.request, schema=Form_AcmeOrder_renew_custom, validate_get=False, ) if not result: raise formhandling.FormInvalid() if not dbAcmeOrder.is_renewable_custom: # `formStash.fatal_form()` will raise `FormInvalid()` formStash.fatal_form("This AcmeOrder can not use RenewCustom") (acmeAccountSelection, privateKeySelection) = form_utils.form_key_selection( self.request, formStash, require_contact=None, ) processing_strategy = formStash.results["processing_strategy"] private_key_cycle__renewal = formStash.results["private_key_cycle__renewal"] try: dbAcmeOrderNew = lib_db.actions_acme.do__AcmeV2_AcmeOrder__renew_custom( self.request.api_context, private_key_cycle__renewal=private_key_cycle__renewal, processing_strategy=processing_strategy, dbAcmeOrder=dbAcmeOrder, dbAcmeAccount=acmeAccountSelection.AcmeAccount, dbPrivateKey=privateKeySelection.PrivateKey, ) except errors.AcmeOrderCreatedError as exc: # unpack a `errors.AcmeOrderCreatedError` to local vars dbAcmeOrderNew = exc.acme_order exc = exc.original_exception if self.request.wants_json: return
external system def get_form_class_and_data(data): if not data: return ReservationForm, {} def exclude(value): if as_internal_id(value['desc']) == 'email': return True if is_payment_key(value['key']): return True @lru_cache() def generate_form_class(formcode): return parse_form(formcode, ReservationForm) def separate_code_from_data(data): fields = [] values = {} for form in sorted(data.values(), key=lambda f: f['desc']): fieldset = form['desc'] fields.append(f"# {fieldset}") for v in sorted(form['values'], key=lambda r: r['sortkey']): label = v['desc'] id = as_internal_id(f"{fieldset} {label}") # defined on the reservation form if id == 'email': continue if isinstance(v['value'], bool): fields.append(f"{label} = ___") values[id] = v['value'] and "Ja" or "Nein" elif isinstance(v['value'], str): fields.append(f"{label} = ___") values[id] = v['value'] elif isinstance(v['value'], datetime): fields.append(f"{label} = YYYY.MM.DD HH:MM") values[id] = v['value'] elif isinstance(v['value'], date): fields.append(f"{label} = YYYY.MM.DD") values[id] = v['value'] elif isinstance(v['value'], int): fields.append(f"{label} = ___") values[id] = str(v['value']) elif isinstance(v['value'], list): fields.append(f"{label} = ___") values[id] = ', '.join(v['value']) else: raise NotImplementedError(( f"No conversion for {v['value']} " f" ({type(v['value'])}" )) return '\n'.join(fields), values formcode, formdata = separate_code_from_data(data) return generate_form_class(formcode), formdata def handle_import(request, app): session = app.session() # disable search indexing during import if hasattr(app, 'es_orm_events'): app.es_orm_events.stopped = True # map the old UUIDs to the resources print("Mapping resources") mapping = {m.old_uuid: m for m in ( Mapping(request.app.libres_context, r.old_url, r.new_url, r.type) for r in tqdm(records, unit=' resources') )} print("Clearing existing submissions") session.execute(text(""" DELETE FROM submissions WHERE submissions.meta->>'origin' IN :resources """), { 'resources': tuple(m.old_uuid.hex for m in mapping.values()) }) print("Clearing existing ticket messages") session.execute(text(""" DELETE from messages WHERE channel_id IN ( SELECT number FROM tickets WHERE tickets.handler_data->>'origin' IN :resources ) """), { 'resources': tuple(m.old_uuid.hex for m in mapping.values()) }) print("Clearing existing tickets") session.execute(text(""" DELETE FROM tickets WHERE tickets.handler_data->>'origin' IN :resources """), { 'resources': tuple(m.old_uuid.hex for m in mapping.values()) }) payment_ids = tuple(r[0] for r in session.execute(text(""" SELECT payment_id FROM payments_for_reservations_payment WHERE reservations_id IN ( SELECT id FROM reservations WHERE resource IN :resources ) """), { 'resources': tuple(m.resource.id for m in mapping.values()) })) if payment_ids: print("Clearing existing payments") session.execute(text(""" DELETE FROM payments_for_reservations_payment WHERE payment_id IN :payments """), { 'payments': payment_ids }) session.execute(text(""" DELETE FROM payments WHERE id IN :payments """), { 'payments': payment_ids }) print("Clearing existing reservations") session.execute(text(""" DELETE FROM reservations WHERE resource IN :resources """), { 'resources': tuple(m.resource.id for m in mapping.values()) }) print("Clearing existing reserved slots") session.execute(text(""" DELETE FROM reserved_slots WHERE allocation_id IN ( SELECT id FROM allocations WHERE allocations.mirror_of IN :resources ) """), { 'resources': tuple(m.resource.id for m in mapping.values()) }) print("Clearing existing allocations") session.execute(text(""" DELETE FROM allocations WHERE allocations.mirror_of IN :resources """), { 'resources': tuple(m.resource.id for m in mapping.values()) }) session.flush() print(f'Resources: {mapping.keys()}') print(f"Fetching remote allocations after {start_date}") count, rows = select_with_count(remote, f""" SELECT * FROM allocations WHERE mirror_of IN :resources AND _end >= '{start_date}'::date ORDER BY allocations.resource """, resources=tuple(mapping.keys())) # we use a separate id space, so we need to keep track allocation_ids = {} # the resource might be mapped, but it is not a given def row_resource(row): if row['resource'] not in mapping: return row['resource'] return mapping[row['resource']].new_uuid # create the new allocations print("Writing allocations") for row in tqdm(rows, unit=' allocations', total=count): resource_type = mapping[row['mirror_of']].type if row['partly_available'] and resource_type != 'room': raise RuntimeError(( f"Cannot migrate partly_available allocation " f"to a {resource_type} resource" )) if row['approve_manually']: raise RuntimeError(( f"Manually approved allocation found (id: {row['id']}), " f"manually approved allocations are not supported" )) allocation = Allocation( resource=row_resource(row), mirror_of=mapping[row['mirror_of']].new_uuid, group=row['group'], quota=row['quota'], quota_limit=getattr( row, 'quota_limit', getattr(row, 'reservation_quota_limit')), partly_available=row['partly_available'], approve_manually=row['approve_manually'], # the timezone was ignored in seantis.reservation timezone='Europe/Zurich', _start=replace_timezone(row['_start'], 'Europe/Zurich'), _end=replace_timezone(row['_end'], 'Europe/Zurich'), data=json.loads(getattr(row, 'data', "{}")), _raster=row['_raster'], created=replace_timezone(row['created'], 'UTC'), modified=utcnow(), type='custom', ) session.add(allocation) session.flush() allocation_ids[row['id']] = allocation.id # fetch the reserved slots that should be migrated count, rows = select_with_count( remote, """ SELECT * FROM reserved_slots WHERE allocation_id IN ( SELECT id FROM allocations WHERE mirror_of IN :resources AND id in :parsed ) """, resources=tuple(mapping.keys()), parsed=tuple(allocation_ids.keys()) ) # create the reserved slots with the mapped values print("Writing reserved slots") known = set() for row in tqdm(rows, unit=" slots", total=count): r = row_resource(row) s = replace_timezone(row['start'], 'Europe/Zurich') e = replace_timezone(row['end'], 'Europe/Zurich') # it's possible for rows to become duplicated after replacing # the timezone, if the reserved slot passes over daylight # savings time changes if (r, s) in known: continue known.add((r, s)) session.add(ReservedSlot( resource=r, start=s, end=e, allocation_id=allocation_ids[row['allocation_id']], reservation_token=row['reservation_token'] )) session.flush() # fetch the reservations that should be migrated count, rows = select_with_count( remote, f""" SELECT * FROM reservations re WHERE resource IN :resources AND re.status = 'approved' AND re.end >= '{start_date}'::date ORDER BY re.resource """, resources=tuple(mapping.keys()), ) def targeted_allocations(group): return session.query(Allocation).filter_by(group=group) # keep track of custom reservation data, for the creation of tickets reservation_data = {} payment_states = {} print(f"Writing reservations after {start_date}") for row in tqdm(rows, unit=' reservations', total=count): reservation_data[row['token']] = { 'data': json.loads(row['data']), 'email': row['email'], 'origin': row['resource'], 'origin_url': mapping[row['resource']].old_url, 'created': replace_timezone(row['created'], 'UTC'), 'modified': replace_timezone(row['modified'], 'UTC'), } if row['quota'] > 1: type_ = mapping[row.resource].type if type_ not in ('daypass', 'daily-item'): raise RuntimeError( "Reservations with multiple quotas for " f"type {type_} cannot be migrated" ) # onegov.reservation does not support group targets, so we # translate those into normal allocations and create multiple # reservations with a shared token shared = dict( token=row['token'], target_type='allocation', resource=mapping[row['resource']].new_uuid, timezone='Europe/Zurich', status=row['status'], data={"accepted": True, "migrated": True}, email=row['email'], quota=row['quota'], created=replace_timezone(row['created'], 'UTC'), modified=replace_timezone(row['modified'], 'UTC'), type='custom', ) r = mapping[row['resource']].resource if r.pricing_method == 'per_item': payment = ManualPayment( amount=r.price_per_item * row['quota'], currency='CHF') elif r.pricing_method == 'per_hour': raise NotImplementedError() else: payment = None if row['target_type'] == 'group': targets = tuple(targeted_allocations(group=row['target'])) if not targets: raise RuntimeError(f"No rows for target {row['target']}") for allocation in targets: allocation.group = uuid4() reservation = Reservation( target=allocation.group, start=allocation.start, end=allocation.end, **shared ) if payment: reservation.payment = payment session.add(reservation) else: reservation = Reservation( target=row['target'], start=replace_timezone(row['start'], 'Europe/Zurich'), end=replace_timezone(row['end'], 'Europe/Zurich'), **shared ) if payment: reservation.payment = payment session.add(reservation) if reservation.payment: if was_paid(row['data']): reservation.payment.state = 'paid' payment_states[row['token']] = 'paid' else: payment_states[row['token']] = 'unpaid' session.flush() # tie reservations to tickets/submissions tickets = TicketCollection(session) forms = FormCollection(session) # the responsible user is the first admin that was added user = session.query(User)\ .filter_by(role='admin')\ .order_by(User.created).first() print("Writing tickets") email_validator = Email('Invalid Email') for token, data in tqdm(reservation_data.items(), unit=" tickets"): form_class, form_data = get_form_class_and_data(data['data']) if form_data: # fix common form errors if data['email']: if data['email'].endswith('.c'): data['email'] = data['email'] + 'h' try: email_validator(None, Bunch(data=data['email'])) except Exception as e: e.message = f'Email {data["email"]} not valid' raise e form_data['email'] = data['email'] form = form_class(data=form_data) # wtforms requires raw_data for some validators for key, value in form_data.items(): getattr(form, key).raw_data = [value] submission = forms.submissions.add_external( form=form, state='complete', id=token ) submission.meta['migrated'] = True submission.meta['origin'] = data['origin'].hex with session.no_autoflush: ticket = tickets.open_ticket( handler_code='RSV', handler_id=token.hex) ticket.handler_data['migrated'] = True ticket.handler_data['origin'] = data['origin'].hex ticket.handler_data['origin_url'] = data['origin_url'] ticket.muted = True ticket.state = 'closed' ticket.last_state_change = ticket.timestamp() ticket.reaction_time = 0 ticket.user = user ticket.created = data['created'] ticket.modified = data['modified'] TicketNote.create(ticket, request, ( f"Migriert von {data['origin_url']}" f"/reservations?token={token}", ), owner=user.username) return handle_import @cli.command(context_settings={'default_selector': '*'}) @click.option('--dry-run', default=False, is_flag=True, help="Do not write any changes into the database.") @pass_group_context def fix_tags(group_context, dry_run): def fixes_german_tags_in_db(request, app): session = request.session de_transl = app.translations.get('de_CH') DEFINED_TAGS = [t[0] for t in TAGS] DEFINED_TAG_IDS = [str(s) for s in DEFINED_TAGS] def translate(text): return text.interpolate(de_transl.gettext(text)) form_de_to_en = {translate(text): str(text) for text in DEFINED_TAGS} predefined = { 'Theater / Tanz': ('Dancing', 'Theater'), 'Cultur': ('Culture',), 'Vortrag / Lesung': ('Talk', 'Reading') } msg_log = [] def replace_with_predefined(tags): new_tags = tags.copy() for t in tags: predef = predefined.get(t) if predef: new_tags.remove(t) new_tags.extend(predef) if dry_run: msg_log.append( f'{t} -> {", ". join(predef)}') return new_tags undefined_msg_ids = set() def handle_occurrence_tags(occurrence): tags = occurrence.tags.copy() tags = replace_with_predefined(tags) for tag in occurrence.tags: if tag in predefined: continue if tag not in DEFINED_TAG_IDS: if tag in form_de_to_en: tags.remove(tag) tags.append(form_de_to_en[tag]) msg_log.append( f'{tag} -> {form_de_to_en[tag]}') else: undefined_msg_ids.add(tag) if tags != occurrence.tags: if not dry_run: occurrence.tags = tags for event_ in session.query(Event): handle_occurrence_tags(event_) for occurrence in session.query(Occurrence): handle_occurrence_tags(occurrence) if dry_run: print("\n".join(set(msg_log))) assert not undefined_msg_ids, f'Define ' \ f'{", ".join(undefined_msg_ids)}' \ f' in org/forms/event.py' return fixes_german_tags_in_db def close_ticket(ticket, user, request): if ticket.state == 'open': ticket.accept_ticket(user) TicketMessage.create( ticket, request, 'opened' ) TicketMessage.create( ticket, request, 'closed' ) ticket.close_ticket() @cli.command('fetch') @pass_group_context @click.option('--source', multiple=True) @click.option('--tag', multiple=True) @click.option('--location', multiple=True) @click.option('--create-tickets', is_flag=True,
not parent.rmObj(oldname, update=update): # for dir, parent will if empty return False deltype = "DelD" if dir else "DelF" log(joinPath(path, oldname), obj.oid, deltype) return True # print info about an object, including memory address (for debugging only) def printObj(obj, prefix="", children=False): fsprt(prefix+str(obj)) if children and obj.isDir: for child in obj.children: fsprt(" "+str(obj.obj(child))) # move or rename a directory or file, or copy a single file def movecopy(srcname, tgtname, copy=False): # get full paths of source and target if srcname == "/": # can't move root, copying it would be recursive return False if tgtname == ".": tgtname = g.curnm fulltgt = tgtname # save original name for later # get source and target object and name information srcpath, srcobj = dirpath(srcname) tgtpath, tgtparent, tgtname = dirpath(tgtname, parentRef=True) if not srcobj or not tgtparent: return False # don't allow recursive copy if tgtpath.startswith(srcpath+"/"): return False # cannot copy a complete directory if copy and srcobj.isDir: return False dbprt("source:", srcpath, srcobj.oid) dbprt("target:", tgtpath, tgtparent.oid, tgtname) srcname = splitPath(srcpath)[1] # if target is simply "/", must have a file name to continue if not tgtname: tgtname = srcname # if target is a directory, make it new parent and copy source filename if tgtparent.contains(tgtname) and tgtparent.obj(tgtname).isDir: tgtpath, tgtparent = dirpath(fulltgt) tgtname = srcname dbprt("new target info:", tgtpath, tgtname, tgtparent.oid) # now that we have all the object info, make sure not moving object to self srcparent = srcobj.parent if srcparent == tgtparent and srcname == tgtname: dbprt("Move to self!") return False # if target already exists, decide what needs to be done (quite complex!) remtobj = None # flag to delete old target object if tgtparent.contains(tgtname): # if the target is a directory if tgtparent.obj(tgtname).isDir: # and the source is a file if srcobj.isFile: # if target contains new object name, it must be a file if tgtparent.obj(tgtname).contains(srcname): if tgtparent.obj(tgtname).obj(srcname).isDir: return False # it's a file, so we must remove it else: remtobj = tgtparent.obj(tgtname).obj(srcname) # the target is a file else: # if the source is a directory, can't move it to a file if srcobj.isDir: return False # source is a file if not copy: remtobj = tgtparent.obj(tgtname) dbprt("tgt exists:", ("remove "+str(remtobj.oid)) if remtobj else "") # we're finally ready to move something dbprt("mvcp:", srcpath,srcname,srcobj.oid, tgtpath,tgtname,tgtparent.oid) # if copy, create a copy of the source object if copy: newobj = pyobjcopy(srcobj) # new python object, copy of srcobj newobj.oid = useNextOID else: # move (move original object, make copy in source for deletion) newobj = srcobj # newobj is srcobj (same python object) srcobj = pyobjcopy(newobj) # create new python object copy for srcobj if not srcparent.replObj(srcname, srcobj): # replace srcobj ref in parent return False # set target object's parent and state newobj.parent = tgtparent if newobj.isDir: newobj.isNew = True status = "New" else: newobj.isModified = True status = "Mod" # if necessary, remove existing file that is being replaced if remtobj: remoid = tgtparent.obj(tgtname).oid if not tgtparent.rmObj(tgtname): return False log(joinPath(tgtpath, tgtname), remoid, "DelF") # put moved/copied object in its new home tgtparent.addObj(tgtname, newobj) # put object under target name log(joinPath(tgtpath, tgtname), newobj.oid, status) # for move, remove object from its old home if not copy: if not srcparent.rmObj(srcname, verifyEmpty=False): # rem src from parent fsprt("Error: cannot remove source object for move; object copied.") return False deltype = "DelF" if srcobj.isFile else "DelD" dbprt("Creating log:", deltype, srcpath, srcobj.oid) log(srcpath, srcobj.oid, deltype) if g.debug: printObj(newobj, "mvcp new: ") printObj(srcobj, "mvcp src: ") return True # copy a directory's contents to an existing directory recursively def copyrecurs(inloc, outloc): # get source and target object and name information if outloc == ".": outloc = g.curnm srcpath, srcobj = dirpath(inloc) tgtpath, tgtobj = dirpath(outloc) if not srcobj or not tgtobj: return False # don't allow recursive copy if tgtpath.startswith(srcpath+"/"): return False # both source and target must be existing directories if not srcobj.isDir or not tgtobj.isDir: return False # recursively copy files and directories return dfs(srcobj, srcpath, copyObj, (srcpath, tgtpath)) # make a copy of a single file or directory (invoked through dfs()) def copyObj(desc, dirobj, path, name, moreparams): srcfname, tgtfname = moreparams if desc not in ("file", "dir"): return True dbprt("copyObj:", desc, dirobj.oid, path, name, srcfname, tgtfname) addpath = path[len(srcfname):] if addpath: tgtdir = tgtfname + addpath else: tgtdir = tgtfname newname = joinPath(tgtdir, name) if desc == "file": oldname = joinPath(path, name) dbprt("Copying file", oldname, "to", newname) return movecopy(oldname, newname, copy=True) elif desc == "dir": dbprt("Creating directory", newname) if not makeObj(newname, dir=True): return False # should copy other attributes from source to new dir here, if needed return True ########################################################################### # routines used in generating indexes # ########################################################################### # write a full index to a file (uses dfs to descend entire tree) def fullIndex(fn): global indexLevel, Log fullfn = fn + "-full.xml" with open(fullfn, "w") as fh: fh.write("<fullindex>\n") indexLevel = 0 # used only for indentation of xml indexEnt("dir", g.root, "/", None, ("full", fh)) result = dfs(g.root, "/", indexEnt, ("full", fh)) fh.write("</fullindex>\n") Log = {} # clear log after writing an index if not result: fsprt("Error occurred creating full index") return result # write an incremental index to a file def incrIndex(fn): global indexLevel, Log success = True incrfn = fn + "-incr.xml" with open(incrfn, "w") as fh: fh.write("<incrementalindex>\n") indexLevel = 0 # used for indentation and to close paths # always start with an entry for the root dir, whether or not it's in log indexEnt("dir", g.root, "/", "", ("incr", fh)) indexLevel += 1 lastpath = "/" pathindir = None # process all log entries sorted in name,oid order for logKey in sorted(Log): # get full name, oid, log entry type and timestamp for this log entry fullname, oid = logKey.rsplit("#", 1) if fullname == "/" and oid == "0": # we already did the root dir continue path, name = splitPath(fullname) reason, ts = Log[logKey] # if debugging, show log entry dbprt("Log entry: %s (%i) %s %s\n" % (fullname, int(oid), reason, ts)) # get object reference for log target obj = dirpath(fullname)[1] # already have full name, need obj # didn't find object for this entry, error unless it was for deletion if not obj and not reason.startswith("Del"): dbprt("Object matching log entry not found", fullname, oid) success = False break # found the same name but a different oid, also bad unless delete if not reason.startswith("Del") and obj.oid != int(oid): dbprt("Object oids do not match:", fullname, oid, obj.oid) continue # close out unneeded directories from prior object lastdirs = lastpath.split("/")[1:] if lastpath != "/" else [] newdirs = path.split("/")[1:] if path != "/" else [] newLevel = len(newdirs) lastmatch = -1 for i in range(min(len(lastdirs), len(newdirs))+1): if len(lastdirs) > i and len(newdirs) > i: if lastdirs[i] == newdirs[i]: continue lastmatch = i-1 break i = 0 # inialize in case following loops null for i in range(len(lastdirs)-1, lastmatch, -1): fh.write(" " * (i+1) + " </contents>\n") fh.write(" " * (i+1) + "</directory>\n") # build new directory path structure as needed for object for i in range(lastmatch+1, newLevel): prefix = " " * (i+1) temppath = "/".join(['']+newdirs[:i+1]) # full path name of dir if temppath == pathindir: # if we just added this dir continue # to the index, skip it fh.write(prefix + "<directory>\n") fh.write(prefix + " <name>" + newdirs[i] + "</name>\n") tempobj = dirpath(temppath)[1] if tempobj.isModified: # parent dir may have updated modtime fh.write(prefix + " <time>"+str(tempobj.modTime)+"</time>\n") tempobj.isModified = False fh.write(prefix + " <contents>\n") indexLevel = newLevel + 1 pathindir = None # process Deletes here rather than using indexEnt() if reason.startswith("Del"): lastpath = path # make sure to save last path for deletes as well if obj: if obj.oid == int(oid): dbprt("Found deleted object in file system", fullname, oid) success = False break else: continue # don't delete object if it's been
<filename>IM_test/UI2.py ''' Created on 2015-3-24 @author: zhangq ''' import wx import sent_key import parseIrkey #import format_case import globalVariable import os import re class ExamplePanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.main_path=os.getcwd() self.IP="10.209.157.84" self.port="7777" self.card="BKS" self.delay="1000" self.temtext="" self.name="" self.Stream_Std="DTMB" self.Stream_File="\\10.209.157.77" self.Stream_Freq="584" self.Stream_Bandwidth="4" self.Stream_Modulation="4" self.filename=[] self.filepath=[] self.is_import=1 self.tag=[] self.key_index=1 self.TT_TAG=0 self.B1=[] self.B2=[] self.B3=[] self.B4=[] self.B5=[] self.B6=[] self.B7=[] self.case_list=[] # create some sizers self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.hSizer = wx.BoxSizer(wx.HORIZONTAL) self.grid = wx.GridBagSizer(hgap=5, vgap=5) self.grid_stream = wx.GridBagSizer(hgap=5, vgap=5) self.grid_box = wx.GridBagSizer(hgap=5, vgap=5) self.grid_delay = wx.GridBagSizer(hgap=5, vgap=5) self.grid_button = wx.GridBagSizer(hgap=5, vgap=5) self.case = wx.GridSizer(20,4,0,0) self.gs = wx.GridBagSizer(hgap=1, vgap=1) self.gs_case = wx.GridBagSizer(hgap=1, vgap=1) #self.gs = wx.GridSizer(20,3,0,0) #input case box self.logger = wx.TextCtrl(self, size=(320,580), style=wx.TE_MULTILINE ) self.Bind(wx.EVT_TEXT, self.BoxText, self.logger) #video button self.button_video_cap =wx.Button(self, label="video_cap",size=(70, 25)) self.button_video_cap.SetBackgroundColour("Navy") self.button_video_cap.SetForegroundColour("white") self.Bind(wx.EVT_BUTTON, self.video_cap,self.button_video_cap) self.grid_button.Add(self.button_video_cap, pos=(3,1), span=(1,1)) #start button self.button_start =wx.Button(self, label="start",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.start_case,self.button_start) self.grid_button.Add(self.button_start, pos=(1,1), span=(1,1)) #SAVE button self.button =wx.Button(self, label="Save",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.OnClick_SAVE,self.button) self.grid_button.Add(self.button, pos=(1,0), span=(1,1)) #format case button self.button =wx.Button(self, label="format",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.format_file,self.button) self.grid_button.Add(self.button, pos=(1,2), span=(1,1)) """ #Delete button self.button =wx.Button(self, label="Delete") self.Bind(wx.EVT_BUTTON, self.OnClick_Del,self.button) self.grid_button.Add(self.button, pos=(1,2), span=(1,1)) """ #Open case button self.button =wx.Button(self, label="Open case",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.OnClick_Open_case,self.button) self.grid_button.Add(self.button, pos=(2,1), span=(1,1)) #Open caselist button self.button =wx.Button(self, label="caselist",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.OnClick_Open_case_list,self.button) self.grid_button.Add(self.button, pos=(2,2), span=(1,1)) #scan case button self.button =wx.Button(self, label="scan_case",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.OnClick_Scan_case,self.button) self.grid_button.Add(self.button, pos=(2,0), span=(1,1)) # Radio Boxes radioList = ['libra2', 'librasd', 'Sunplus'] self.rb = wx.RadioBox(self, label="Choose the IR_KEY MAP ", pos=(20, 210), choices=radioList, majorDimension=3,style=wx.RA_SPECIFY_COLS) self.grid.Add(self.rb, pos=(0,0), span=(1,2)) self.Bind(wx.EVT_RADIOBOX, self.Evt_Change_IR_MAP, self.rb) print "~~~~~~~~" print self.rb.GetItemLabel(self.rb.GetSelection()) print "~~~~~~~~" """ #test type box test_type = ['normal_test', 'mem_test'] self.tt = wx.RadioBox(self, label="Choose the test type ", pos=(20, 210), choices=test_type, majorDimension=2,style=wx.RA_SPECIFY_COLS) self.grid.Add(self.tt, pos=(1,0), span=(1,2)) self.Bind(wx.EVT_RADIOBOX, self.Evt_test_type, self.tt) """ # Case name. self.lblname = wx.StaticText(self, label="Case name :") self.grid_box.Add(self.lblname, pos=(0,0)) self.editname = wx.TextCtrl(self, value="APP-", size=(140,-1)) self.grid_box.Add(self.editname, pos=(0,1)) self.Bind(wx.EVT_TEXT, self.EvtName, self.editname) #input stream button self.button_stream =wx.Button(self, label="-->",size=(70,25)) self.Bind(wx.EVT_BUTTON, self.OnClick_stream,self.button_stream) self.grid_stream.Add(self.button_stream, pos=(0,0), span=(1,1)) #IP drop down box self.sampleList = ['10.209.157.84', '10.209.157.83', '10.209.157.77'] self.lblhear = wx.StaticText(self, label=" ip") self.grid_stream.Add(self.lblhear, pos=(1,0)) self.edithear = wx.ComboBox(self, value="10.209.156.203", size=(95, -1), choices=self.sampleList, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(1,1)) self.Bind(wx.EVT_COMBOBOX, self.EvtIP, self.edithear) self.Bind(wx.EVT_TEXT, self.EvtIP,self.edithear) #port drop down box self.sampleList1 = ['7777', '8080', '21', '777'] self.lblhear = wx.StaticText(self, label=" port") self.grid_stream.Add(self.lblhear, pos=(2,0)) self.edithear = wx.ComboBox(self, value="7777",size=(95, -1), choices=self.sampleList1, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(2,1)) self.Bind(wx.EVT_COMBOBOX, self.EvtPORT, self.edithear) self.Bind(wx.EVT_TEXT, self.EvtPORT,self.edithear) #card drop down box self.sampleList2 = ['BKS', 'DTK'] self.lblhear = wx.StaticText(self, label=" card") self.grid_stream.Add(self.lblhear, pos=(3,0)) self.edithear = wx.ComboBox(self,value="BKS", size=(95, -1), choices=self.sampleList2, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(3,1)) self.Bind(wx.EVT_COMBOBOX, self.EvtCARD, self.edithear) self.Bind(wx.EVT_TEXT, self.EvtCARD,self.edithear) #Stream_Bandwidth drop down box self.sampleList3 = ['4', '8', '16', '32'] self.lblhear = wx.StaticText(self, label="Bandwidth") self.grid_stream.Add(self.lblhear, pos=(4,0)) self.edithear = wx.ComboBox(self,value="4", size=(95, -1), choices=self.sampleList3, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(4,1)) self.Bind(wx.EVT_COMBOBOX, self.Evt_Stream_Bandwidth, self.edithear) self.Bind(wx.EVT_TEXT, self.Evt_Stream_Bandwidth,self.edithear) #Stream_Modulation drop down box self.sampleList4 = ['4','8','16', '32', '64'] self.lblhear = wx.StaticText(self, label="Modulation") self.grid_stream.Add(self.lblhear, pos=(5,0)) self.edithear = wx.ComboBox(self,value="4", size=(95, -1), choices=self.sampleList4, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(5,1)) self.Bind(wx.EVT_COMBOBOX, self.Evt_Stream_Modulation, self.edithear) self.Bind(wx.EVT_TEXT, self.Evt_Stream_Modulation,self.edithear) #Stream_Modulation drop down box self.sampleList5 = ['DTMB','dvb'] self.lblhear = wx.StaticText(self, label=" Stream_Std") self.grid_stream.Add(self.lblhear, pos=(6,0)) self.edithear = wx.ComboBox(self, value="DTMB",size=(95, -1), choices=self.sampleList5, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(6,1)) self.Bind(wx.EVT_COMBOBOX, self.Evt_Stream_Std, self.edithear) self.Bind(wx.EVT_TEXT, self.Evt_Stream_Std,self.edithear) #Stream_Modulation drop down box self.sampleList6 = ['F:\\zhangq\\0.3.0_loader_stream.ts','\\\\10.209.156.121\\111.ts'] self.lblhear =wx.Button(self, label="Stream_File",size=(70, 25)) self.Bind(wx.EVT_BUTTON, self.Choose_ts_file,self.lblhear) self.grid_stream.Add(self.lblhear, pos=(7,0),span=(1,1)) self.tsfile = wx.TextCtrl(self, value="input stream file path", size=(140,-1)) self.grid_stream.Add(self.tsfile, pos=(7,1)) #self.Bind(wx.EVT_COMBOBOX, self.Evt_Stream_File, self.tsfile) self.Bind(wx.EVT_TEXT, self.Evt_Stream_File,self.tsfile) #Stream_Modulation drop down box self.sampleList7 = ['474','714','666'] self.lblhear = wx.StaticText(self, label=" Stream_Freq") self.grid_stream.Add(self.lblhear, pos=(8,0)) self.edithear = wx.ComboBox(self, value="474",size=(95, -1), choices=self.sampleList7, style=wx.CB_DROPDOWN) self.grid_stream.Add(self.edithear, pos=(8,1)) self.Bind(wx.EVT_COMBOBOX, self.Evt_Stream_Freq, self.edithear) self.Bind(wx.EVT_TEXT, self.Evt_Stream_Freq,self.edithear) #hSizer.Add(self.button, 0, wx.CENTER) self.grid.Add(self.grid_box, pos=(2,0)) self.grid.Add(self.grid_stream, pos=(4,0)) self.grid.Add(self.grid_button, pos=(5,0)) self.hSizer.Add(self.grid, 0, wx.ALL, 5) """ #add case_group_button self.case = wx.GridSizer(1000,3,0,0) self.case_list = self.scan_case((os.getcwd()+'\caseInfo'+'\Case'),postfix='.conf') self.gs_case = wx.GridBagSizer() self.Add_case(self.case_list) self.gs_case.Add(self.case,pos=(0,0)) self.hSizer.Add(self.gs_case) """ #add logger window self.hSizer.Add(self.logger) self.Evt_Change_IR_MAP('libra2') #self.hSizer.Add(self.gs) #mainSizer.Add(self.gs, 0, wx.CENTER) self.mainSizer.Add(self.hSizer, 0, wx.CENTER, 5) self.s_key=sent_key.send_key() self.SetSizerAndFit(self.mainSizer) def scan_case(self,directory,prefix=None,postfix=None): files_list=[] for root, sub_dirs, files in os.walk(directory): for special_file in files: if postfix: if special_file.endswith(postfix): files_list.append(((special_file),(os.path.join(root,special_file)))) elif prefix: if special_file.startswith(prefix): files_list.append(((special_file),(os.path.join(root,special_file)))) else: files_list.append(((special_file),(os.path.join(root,special_file)))) return files_list def EvtIP(self, event): #self.logger.AppendText('EvtIP: %s\n' % event.GetString()) self.IP='%s' % event.GetString() #self.logger.AppendText('%s\n' % self.IP) def EvtPORT(self, event): #self.logger.AppendText('EvtIP: %s\n' % event.GetString()) self.port='%s' % event.GetString() #self.logger.AppendText('%s\n' % self.port) def EvtCARD(self, event): #self.logger.AppendText('EvtIP: %s\n' % event.GetString()) self.card='%s' % event.GetString() #self.logger.AppendText('%s\n' % self.card) def Evt_Stream_Std(self, event): self.Stream_Std='%s' % event.GetString() def Evt_Stream_File(self, event): self.Stream_File='%s' % event.GetString() def Evt_Stream_Freq(self, event): self.Stream_Freq='%s' % event.GetString() def Evt_Stream_Bandwidth(self, event): self.Stream_Bandwidth='%s' % event.GetString() def Evt_Stream_Modulation(self, event): self.Stream_Modulation='%s' % event.GetString() def EvtRadioBox(self, event): self.logger.AppendText('%s' % event.GetString()) def EvtComboBox(self, event): self.logger.AppendText('%s' % event.GetString()) def OnClick(self,event,mark): if self.temtext: index_list=re.findall(r"Input_(.)",self.temtext) if index_list: self.position=self.logger.GetInsertionPoint() self.current_text=self.logger.GetRange(0,self.position) self.tag=self.current_text.split("\n") if self.tag[-2]: print "~~~~~~~~~~~~~~~~~%s" % self.tag[-2] if re.search('F*,',self.tag[-2]): self.is_import=0 self.logger.WriteText("%s , %s , F , 1\n" % (mark, self.delay)) #if self.is_import: # self.logger.AppendText("[Input_%s]\nIRList=" % (str(self.key_index))) if re.search("Input_(.)",self.tag[-2])or re.search('duration',self.tag[-2]): self.logger.WriteText("IRList=%s , %s , F , 1\n" % (mark, self.delay)) print self.delay self.is_import=1 self.s_key.send_one_key(mark) def OnClick_SAVE(self,event): #self.s_key.send_one_key('MENU') #self.logger.AppendText(" Stream_ServerIp= %s\nStream_ServerPORT=%s\nCard_Type=%s\n" % (self.IP, self.port, self.card)) print self.name main_dir=os.path.join(os.getcwd(),'caseInfo') if self.name=="caselist.txt": tmp_case=open(os.path.join(main_dir,'caselist.txt'),"wb") tmp_case.write(self.temtext) tmp_case.close else: case=open(os.path.join(main_dir,'Case',self.name),"wb") case.write(self.temtext) case.close def OnClick_Scan_case(self,event): self.case_list = self.scan_case((os.getcwd()+'\caseInfo'+'\Case'),postfix='.conf') """ #refresh case button self.gs_case.Hide(self.case) self.gs_case.Remove(self.case) self.gs_case.Layout() self.case = wx.GridSizer(20,1,0,0) self.case_list = self.scan_case((os.getcwd()+'\caseInfo'+'\Case'),postfix='.conf') self.Add_case(self.case_list) self.gs_case.Add(self.case,pos=(0,0)) self.hSizer.Layout() """ #add cast list to caselist.txt #f = open(os.path.join(main_dir,'caselist.txt'),"a") #f.truncate() self.editname.Clear() self.editname.AppendText('%s' % 'caselist.txt') self.logger.Clear() for i in self.case_list: self.logger.AppendText(i[0]+"\n") #f.close() """ def OnClick_Del(self,event): print self.name file_dir=os.path.join(os.getcwd(),'caseInfo','Case',self.name) print file_dir os.remove (file_dir) #refresh case button self.gs_case.Hide(self.case) self.gs_case.Remove(self.case) self.case = wx.GridSizer(20,1,0,0) self.case_list = self.scan_case((os.getcwd()+'\caseInfo'+'\Case'),postfix='.conf') self.Add_case(self.case_list) self.gs_case.Add(self.case,pos=(0,0)) self.hSizer.Layout() """ def Choose_file(self,event): dialog = wx.FileDialog(self,"Open file...",os.getcwd(),style=wx.OPEN,wildcard="*.bmp") if dialog.ShowModal() == wx.ID_OK: self.filepath.append(dialog.GetPath()) self.filename.append(dialog.GetPath().split('\\')[-1]) print self.filename[-1] self.logger.AppendText("bmpFile=%s\n" % (self.filename[-1])) self.is_import=1 dialog.Destroy() os.system ("copy %s %s" % (self.filepath[-1], os.path.join(self.main_path,'caseInfo', 'Case_pic'))) def Choose_ircase_file(self,event): dialog = wx.FileDialog(self,"Open file...",os.getcwd(),style=wx.OPEN,wildcard="*.ircase") if dialog.ShowModal() == wx.ID_OK: filename=(dialog.GetPath().split('\\')[-1]) print self.filename self.logger.AppendText("[Input_%s]\nIRFile=%s\n" % (str(self.key_index-1),filename)) self.is_import=1 dialog.Destroy() def Choose_ts_file(self,event): #dialog = wx.FileDialog(self,"Open file...",os.getcwd(),style=wx.OPEN,wildcard="TS files (*.ts)|*.ts|TRP files (*.trp)|*.trp") #dialog = wx.FileDialog(self,"Open file...",defaultDir="//bjfile02/BJShare/Public/TS",style=wx.OPEN,wildcard="TS files (*.ts)|*.ts|TRP files (*.trp)|*.trp") dialog = wx.FileDialog(self,"Open file...",defaultDir="//bjfile02/BJShare/Department/FAE/Soc/AVL8332/Stream/DTMB",style=wx.OPEN,wildcard="TS files (*.ts)|*.ts|TRP files (*.trp)|*.trp") if dialog.ShowModal() == wx.ID_OK: filename=(dialog.GetPath()) print self.filename #self.logger.AppendText("[Input_%s]\nIRFile=%s\n" % (str(self.key_index-1),filename)) self.tsfile.Clear() self.tsfile.AppendText('%s' % filename) dialog.Destroy() def OnClick_Open_case(self,event): default_pwd="<PASSWORD>" dialog = wx.FileDialog(self,"Open file...",defaultDir=default_pwd,style=wx.OPEN,wildcard="conf files (*.conf)|*.conf|all files (*.*)|*.*") if dialog.ShowModal() == wx.ID_OK: filepath=(dialog.GetPath()) filename=(dialog.GetPath().split('\\')[-1]) #filename.SetValue(filepath) print filepath f = open(filepath,"rb") print f content=f.read() self.editname.Clear() self.editname.AppendText('%s' % filename) self.logger.Clear() self.logger.AppendText("%s" % content) print '~~~~~~~~~~~~' print content f.close() dialog.Destroy() def OnClick_Open_case_list(self,event): dialog = wx.FileDialog(self,"Open file...",defaultDir="caseInfo",style=wx.OPEN,wildcard="*.txt") if dialog.ShowModal() == wx.ID_OK: filepath=(dialog.GetPath()) filename=(dialog.GetPath().split('\\')[-1]) #filename.SetValue(filepath) print filepath f = open(filepath,"rb") print f content=f.read() self.editname.Clear() self.editname.AppendText('%s' % filename) self.logger.Clear() self.logger.AppendText("%s" % content) print '~~~~~~~~~~~~' print content f.close() dialog.Destroy() #fopen = open(self.filepath) #fcontent = fopen.read() #self.logger.AppendText("%s" % fcontent) #contents.SetValue(fcontent) #fopen.close() def mem_file(self,event): self.logger.AppendText("cmdfile=meminfo.txt\n"); def EvtText(self, event): self.delay='%s' % event.GetString() #self.logger.AppendText('EvtText: %s\n' % event.GetString()) def EvtChar(self, event): self.logger.AppendText('EvtChar: %d\n' % event.GetKeyCode()) event.Skip() """ def Evt_test_type(self,event): if self.TT_TAG==1: self.Evt_Change_IR_MAP(self.rb.GetItemLabel(self.rb.GetSelection())) if event.GetString()=='run_case': self.case = wx.GridSizer(20,1,0,0) #self.hSizer.Hide(self.gs) #self.hSizer.Remove(self.gs) #self.hSizer.Layout() #self.gs_case = wx.GridBagSizer() #self.Add_case(self.case_list) #self.gs_case.Add(self.case,pos=(0,0)) #self.hSizer.Add(self.gs_case) self.hSizer.Layout() self.TT_TAG=1 elif event.GetString()=='mem_test': self.logger.Clear() self.logger.AppendText('[Input_1]\ncommand=meminfo\nduration=600\n') elif event.GetString()=='normal_test': self.logger.Clear() #self.Evt_Change_IR_MAP(self.rb.GetItemLabel(self.rb.GetSelection())) """ def Evt_Change_IR_MAP(self, event): self.TT_TAG=0 globalVariable.IRK_MAP = {} #parseIrkey.ParseIrkey.insertIrk2Map() self.B1=[] self.B2=[] self.B3=[] self.B4=[] self.B5=[] self.B6=[] self.B7=[] if isinstance(event, wx._core.CommandEvent): globalVariable.serial_config['target_type'] = ('%s' % event.GetString()) #print event.GetString() else: globalVariable.serial_config['target_type'] = ('%s' % event) #print event #ADD GS self.hSizer.Hide(self.gs) self.hSizer.Remove(self.gs) self.hSizer.Layout() globalVariable.IRK_MAP = {} parseIrkey.ParseIrkey() N=globalVariable.IRK_MAP M=self.sort_IRK_MAP(N) self.gs = wx.GridBagSizer() self.gs1 = wx.GridBagSizer(1,3) self.gs2 = wx.GridBagSizer(5,3) self.gs3 = wx.GridBagSizer(5,3) self.gs4 = wx.GridBagSizer(4,3) self.gs5 = wx.GridSizer(1,3,0,3) self.gs6 = wx.GridSizer(2,3,0,3) self.gs7 = wx.GridSizer(20,3,0,3) self.grid_delay = wx.GridBagSizer(hgap=5, vgap=5) self.grid_tool = wx.GridBagSizer(hgap=5, vgap=5) self.Add_button(self.B1) self.Add_button2(self.B2) self.Add_button3(self.B3) self.Add_button4(self.B4) self.Add_button5(self.B5) self.Add_button6(self.B6) self.Add_button7(self.B7) self.Add_tool_button() self.Add_grid_delay() self.gs.Add(self.grid_tool,pos=(0,0)) self.gs.Add(self.grid_delay,pos=(1,0)) self.gs.Add(self.gs1,pos=(2,0)) self.gs.Add(self.gs2,pos=(3,0)) self.gs.Add(self.gs3,pos=(5,0)) self.gs.Add(self.gs4,pos=(4,0)) self.gs.Add(self.gs5,pos=(6,0)) self.gs.Add(self.gs6,pos=(7,0)) self.gs.Add(self.gs7,pos=(8,0)) self.hSizer.Add(self.gs) self.hSizer.Layout() def Add_case(self,M):
<reponame>jeppetrost/plaso # -*- coding: utf-8 -*- """This file contains MRUListEx Windows Registry plugins.""" from __future__ import unicode_literals import abc from dtfabric.runtime import data_maps as dtfabric_data_maps from plaso.containers import time_events from plaso.containers import windows_events from plaso.lib import errors from plaso.lib import definitions from plaso.parsers import logger from plaso.parsers import winreg from plaso.parsers.shared import shell_items from plaso.parsers.winreg_plugins import dtfabric_plugin from plaso.parsers.winreg_plugins import interface class MRUListExStringRegistryKeyFilter( interface.WindowsRegistryKeyWithValuesFilter): """Windows Registry key with values filter.""" _IGNORE_KEY_PATH_SEGMENTS = frozenset([ '\\BagMRU\\'.upper(), '\\Explorer\\ComDlg32\\OpenSavePidlMRU\\'.upper()]) _IGNORE_KEY_PATH_SUFFIXES = frozenset([ '\\BagMRU'.upper(), '\\Explorer\\StreamMRU'.upper(), '\\Explorer\\ComDlg32\\OpenSavePidlMRU'.upper()]) _VALUE_NAMES = ['0', 'MRUListEx'] def __init__(self): """Initializes Windows Registry key filter object.""" super(MRUListExStringRegistryKeyFilter, self).__init__(self._VALUE_NAMES) def Match(self, registry_key): """Determines if a Windows Registry key matches the filter. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: bool: True if the Windows Registry key matches the filter. """ key_path_upper = registry_key.path.upper() # Prevent this filter matching non-string MRUListEx values. for ignore_key_path_suffix in self._IGNORE_KEY_PATH_SUFFIXES: if key_path_upper.endswith(ignore_key_path_suffix): return False for ignore_key_path_segment in self._IGNORE_KEY_PATH_SEGMENTS: if ignore_key_path_segment in key_path_upper: return False return super(MRUListExStringRegistryKeyFilter, self).Match(registry_key) class BaseMRUListExWindowsRegistryPlugin( dtfabric_plugin.DtFabricBaseWindowsRegistryPlugin): """Class for common MRUListEx Windows Registry plugin functionality.""" _SOURCE_APPEND = ': MRUListEx' _DEFINITION_FILE = 'mru.yaml' @abc.abstractmethod def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): MRUListEx entry index. entry_number (int): entry number. Returns: str: MRUList entry value. """ def _ParseMRUListExValue(self, registry_key): """Parses the MRUListEx value in a given Registry key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. Returns: mrulistex_entries: MRUListEx entries or None if not available. """ mrulistex_value = registry_key.GetValueByName('MRUListEx') # The key exists but does not contain a value named "MRUList". if not mrulistex_value: return None mrulistex_entries_map = self._GetDataTypeMap('mrulistex_entries') context = dtfabric_data_maps.DataTypeMapContext(values={ 'data_size': len(mrulistex_value.data)}) return self._ReadStructureFromByteStream( mrulistex_value.data, 0, mrulistex_entries_map, context=context) def _ParseMRUListExKey( self, parser_mediator, registry_key, codepage='cp1252'): """Extract event objects from a MRUListEx Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. codepage (Optional[str]): extended ASCII string codepage. """ try: mrulistex = self._ParseMRUListExValue(registry_key) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning( 'unable to parse MRUListEx value with error: {0!s}'.format(exception)) return if not mrulistex: return values_dict = {} found_terminator = False for entry_index, entry_number in enumerate(mrulistex): # The MRU list is terminated with -1 (0xffffffff). if entry_number == -1: break if found_terminator: parser_mediator.ProduceExtractionWarning(( 'found additional MRUListEx entries after terminator in key: ' '{0:s}.').format(registry_key.path)) # Only create one parser error per terminator. found_terminator = False value_string = self._ParseMRUListExEntryValue( parser_mediator, registry_key, entry_index, entry_number, codepage=codepage) value_text = 'Index: {0:d} [MRU Value {1:d}]'.format( entry_index + 1, entry_number) values_dict[value_text] = value_string event_data = windows_events.WindowsRegistryEventData() event_data.key_path = registry_key.path event_data.offset = registry_key.offset event_data.regvalue = values_dict event_data.source_append = self._SOURCE_APPEND event = time_events.DateTimeValuesEvent( registry_key.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN) parser_mediator.ProduceEventWithEventData(event, event_data) class MRUListExStringWindowsRegistryPlugin(BaseMRUListExWindowsRegistryPlugin): """Windows Registry plugin to parse a string MRUListEx.""" NAME = 'mrulistex_string' DESCRIPTION = 'Parser for Most Recently Used (MRU) Registry data.' FILTERS = frozenset([MRUListExStringRegistryKeyFilter()]) URLS = [ 'http://forensicartifacts.com/2011/02/recentdocs/', 'https://github.com/libyal/winreg-kb/wiki/MRU-keys'] # pylint: disable=arguments-differ def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): MRUListEx entry index. entry_number (int): entry number. Returns: str: MRUList entry value. """ value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'missing MRUListEx value: {0:d} in key: {1:s}.'.format( entry_number, registry_key.path)) elif value.DataIsString(): value_string = value.GetDataAsObject() elif value.DataIsBinaryData(): utf16le_string_map = self._GetDataTypeMap('utf16le_string') try: value_string = self._ReadStructureFromByteStream( value.data, 0, utf16le_string_map) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning(( 'unable to parse MRUListEx entry value: {0:d} with error: ' '{1!s}').format(entry_number, exception)) value_string = value_string.rstrip('\x00') return value_string # pylint: disable=arguments-differ def ExtractEvents( self, parser_mediator, registry_key, codepage='cp1252', **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. codepage (Optional[str]): extended ASCII string codepage. """ self._ParseMRUListExKey(parser_mediator, registry_key, codepage=codepage) class MRUListExShellItemListWindowsRegistryPlugin( BaseMRUListExWindowsRegistryPlugin): """Windows Registry plugin to parse a shell item list MRUListEx.""" NAME = 'mrulistex_shell_item_list' DESCRIPTION = 'Parser for Most Recently Used (MRU) Registry data.' FILTERS = frozenset([ interface.WindowsRegistryKeyPathFilter( 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\' 'Explorer\\ComDlg32\\OpenSavePidlMRU'), interface.WindowsRegistryKeyPathFilter( 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\' 'Explorer\\StreamMRU')]) # pylint: disable=arguments-differ def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): MRUListEx entry index. entry_number (int): entry number. codepage (Optional[str]): extended ASCII string codepage. Returns: str: MRUList entry value. """ value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'missing MRUListEx value: {0:d} in key: {1:s}.'.format( entry_number, registry_key.path)) elif not value.DataIsBinaryData(): logger.debug(( '[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' '{2:s}.').format(self.NAME, entry_number, registry_key.path)) elif value.data: shell_items_parser = shell_items.ShellItemsParser(registry_key.path) shell_items_parser.ParseByteStream( parser_mediator, value.data, codepage=codepage) value_string = 'Shell item path: {0:s}'.format( shell_items_parser.CopyToPath()) return value_string # pylint: disable=arguments-differ def ExtractEvents( self, parser_mediator, registry_key, codepage='cp1252', **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. codepage (Optional[str]): extended ASCII string codepage. """ if registry_key.name != 'OpenSavePidlMRU': self._ParseMRUListExKey(parser_mediator, registry_key, codepage=codepage) if registry_key.name == 'OpenSavePidlMRU': # For the OpenSavePidlMRU MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in registry_key.GetSubkeys(): self._ParseMRUListExKey(parser_mediator, subkey, codepage=codepage) class MRUListExStringAndShellItemWindowsRegistryPlugin( BaseMRUListExWindowsRegistryPlugin): """Windows Registry plugin to parse a string and shell item MRUListEx.""" NAME = 'mrulistex_string_and_shell_item' DESCRIPTION = 'Parser for Most Recently Used (MRU) Registry data.' FILTERS = frozenset([ interface.WindowsRegistryKeyPathFilter( 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\' 'Explorer\\RecentDocs')]) # pylint: disable=arguments-differ def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): MRUListEx entry index. entry_number (int): entry number. codepage (Optional[str]): extended ASCII string codepage. Returns: str: MRUList entry value. """ value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'missing MRUListEx value: {0:d} in key: {1:s}.'.format( entry_number, registry_key.path)) elif not value.DataIsBinaryData(): logger.debug(( '[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: ' '{2:s}.').format(self.NAME, entry_number, registry_key.path)) elif value.data: utf16le_string_map = self._GetDataTypeMap('utf16le_string') context = dtfabric_data_maps.DataTypeMapContext() try: path = self._ReadStructureFromByteStream( value.data, 0, utf16le_string_map, context=context) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning(( 'unable to parse MRUListEx entry value: {0:d} with error: ' '{1!s}').format(entry_number, exception)) return value_string path = path.rstrip('\x00') shell_item_data = value.data[context.byte_size:] if not shell_item_data: parser_mediator.ProduceExtractionWarning(( 'missing shell item in MRUListEx value: {0:d} in key: ' '{1:s}.').format(entry_number, registry_key.path)) value_string = 'Path: {0:s}'.format(path) else: shell_items_parser = shell_items.ShellItemsParser(registry_key.path) shell_items_parser.ParseByteStream( parser_mediator, shell_item_data, codepage=codepage) value_string = 'Path: {0:s}, Shell item: [{1:s}]'.format( path, shell_items_parser.CopyToPath()) return value_string # pylint: disable=arguments-differ def ExtractEvents( self, parser_mediator, registry_key, codepage='cp1252', **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. codepage (Optional[str]): extended ASCII string codepage. """ self._ParseMRUListExKey(parser_mediator, registry_key, codepage=codepage) if registry_key.name == 'RecentDocs': # For the RecentDocs MRUListEx we also need to parse its subkeys # since the Registry key path does not support wildcards yet. for subkey in registry_key.GetSubkeys(): self._ParseMRUListExKey(parser_mediator, subkey, codepage=codepage) class MRUListExStringAndShellItemListWindowsRegistryPlugin( BaseMRUListExWindowsRegistryPlugin): """Windows Registry plugin to parse a string and shell item list MRUListEx.""" NAME = 'mrulistex_string_and_shell_item_list' DESCRIPTION = 'Parser for Most Recently Used (MRU) Registry data.' FILTERS = frozenset([ interface.WindowsRegistryKeyPathFilter( 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\' 'Explorer\\ComDlg32\\LastVisitedPidlMRU')]) # pylint: disable=arguments-differ def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): """Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): MRUListEx entry index. entry_number (int): entry number. codepage (Optional[str]): extended ASCII string codepage. Returns: str: MRUList entry value. """ value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'missing MRUListEx value: {0:d} in key: {1:s}.'.format( entry_number, registry_key.path)) elif not value.DataIsBinaryData(): logger.debug(( '[{0:s}]
<gh_stars>100-1000 #!/usr/bin/python3 import re, glob N = 131 def assert_static_area(fp, i, name): if i < 3: srl32,srl16,fd = (0,0,i) else: srl32 = i // 32 if (i % 32) == 0: srl16 = 0 fd = 0 elif (i % 32) == 1: srl16 = 0 fd = 1 elif (i % 32) <= 17: srl16 = 1 fd = (i % 32) - 16 else: srl32 += 1 srl16 = 0 fd = 0 fp.write(''' `ifndef _AUTOTB module __test ; wire [4095:0] assert_area = "cd; select t:FD* -assert-count {0}; select t:SRL16E -assert-count {1}; select t:SRLC32E -assert-count {2}; cd {3}_{4}; select t:BUFG t:FD* t:SRL16E t:SRLC32E %% %n t:* %i -assert-none"; endmodule `endif '''.format(fd, srl16, srl32, name, i)) def assert_dynamic_area(fp, i, name): if i < 3: srl32,srl16,fd = (0,0,i) lut3 = 1 if i > 1 else 0 lut5 = 0 else: srl32 = i // 32 if (i % 128) == 0 or (i % 32) == 0: srl16 = 0 fd = 0 elif (i % 128) == 1: srl16 = 0 fd = 1 elif (i % 32) <= 16: srl16 = 1 fd = 0 else: srl32 += 1 srl16 = 0 fd = 0 lut3 = 1 if i > 128 and i < 257 else 0 lut5 = 1 if i > 256 else 0 muxf8 = (srl32+srl16) // 4 if ((srl32 + srl16) % 4) == 0: muxf7 = muxf8 * 2 elif ((srl32 + srl16) % 4) == 3: muxf8 += 1 muxf7 = muxf8 * 2 else: muxf7 = (srl32+srl16) // 2 fp.write(''' `ifndef _AUTOTB module __test ; wire [4095:0] assert_area = "cd; select t:FD* -assert-count {0}; select t:SRL16E -assert-count {1}; select t:SRLC32E -assert-count {2}; select t:MUXF7 -assert-count {3}; select t:MUXF8 -assert-count {4}; select t:LUT3 -assert-count {5}; select t:LUT5 -assert-count {6}; cd {7}_{8}; select t:BUFG t:FD* t:SRL16E t:SRLC32E t:MUXF7 t:MUXF8 t:LUT3 t:LUT5 %% %n t:* %i -assert-none"; endmodule `endif '''.format(fd, srl16, srl32, muxf7, muxf8, lut3, lut5, name, i)) # Test 1: pos_clk_no_enable_no_init_not_inferred for i in range(1,N+1): with open('pos_clk_no_enable_no_init_not_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module pos_clk_no_enable_no_init_not_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, output [width-1:0] q); generate wire [depth:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin assign int[w][0] = i[w]; for (d = 0; d < depth; d=d+1) begin \$_DFFE_PP_ r(.C(clk), .D(int[w][d]), .E(1'b1), .Q(int[w][d+1])); end assign q[w] = int[w][depth]; end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'pos_clk_no_enable_no_init_not_inferred') # Test 2: pos_clk_with_enable_no_init_not_inferred for i in range(1,N+1): with open('pos_clk_with_enable_no_init_not_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module pos_clk_with_enable_no_init_not_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, output [width-1:0] q); generate wire [depth:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin assign int[w][0] = i[w]; for (d = 0; d < depth; d=d+1) begin \$_DFFE_PP_ r(.C(clk), .D(int[w][d]), .E(e), .Q(int[w][d+1])); end assign q[w] = int[w][depth]; end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'pos_clk_with_enable_no_init_not_inferred') # Test 3: pos_clk_with_enable_with_init_inferred for i in range(1,N+1): with open('pos_clk_with_enable_with_init_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module pos_clk_with_enable_with_init_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, output [width-1:0] q); generate reg [depth-1:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin for (d = 0; d < depth; d=d+1) initial int[w][d] <= ~((d+w) % 2); if (depth == 1) begin always @(posedge clk) if (e) int[w] <= i[w]; assign q[w] = int[w]; end else begin always @(posedge clk) if (e) int[w] <= {{ int[w][depth-2:0], i[w] }}; assign q[w] = int[w][depth-1]; end end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'pos_clk_with_enable_with_init_inferred') # Test 4: neg_clk_no_enable_no_init_not_inferred for i in range(1,N+1): with open('neg_clk_no_enable_no_init_not_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_no_enable_no_init_not_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, output [width-1:0] q); generate wire [depth:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin assign int[w][0] = i[w]; for (d = 0; d < depth; d=d+1) begin \$_DFFE_NP_ r(.C(clk), .D(int[w][d]), .E(1'b1), .Q(int[w][d+1])); end assign q[w] = int[w][depth]; end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'neg_clk_no_enable_no_init_not_inferred') # Test 5: neg_clk_no_enable_no_init_inferred for i in range(1,N+1): with open('neg_clk_no_enable_no_init_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_no_enable_no_init_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, output [width-1:0] q); generate reg [depth-1:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin if (depth == 1) begin always @(negedge clk) int[w] <= i[w]; assign q[w] = int[w]; end else begin always @(negedge clk) int[w] <= {{ int[w][depth-2:0], i[w] }}; assign q[w] = int[w][depth-1]; end end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'neg_clk_no_enable_no_init_inferred') # Test 6: neg_clk_with_enable_with_init_inferred for i in range(1,N+1): with open('neg_clk_with_enable_with_init_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_with_enable_with_init_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, output [width-1:0] q); generate reg [depth-1:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin for (d = 0; d < depth; d=d+1) initial int[w][d] <= ~((d+w) % 2); if (depth == 1) begin always @(negedge clk) if (e) int[w] <= i[w]; assign q[w] = int[w]; end else begin always @(negedge clk) if (e) int[w] <= {{ int[w][depth-2:0], i[w] }}; assign q[w] = int[w][depth-1]; end end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'neg_clk_with_enable_with_init_inferred') # Test 10: pos_clk_no_enable_no_init_not_inferred_var_len for i in range(1,N+1): with open('pos_clk_no_enable_no_init_not_inferred_var_len_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module pos_clk_no_enable_no_init_not_inferred_var_len_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input [31:0] l, output [width-1:0] q); generate wire [depth:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin assign int[w][0] = i[w]; for (d = 0; d < depth; d=d+1) begin \$_DFFE_PP_ r(.C(clk), .D(int[w][d]), .E(1'b1), .Q(int[w][d+1])); end wire [depth-1:0] t; assign t = int[w][depth:1]; assign q[w] = t[l]; end endgenerate endmodule '''.format(i)) assert_dynamic_area(fp, i, 'pos_clk_no_enable_no_init_not_inferred_var_len') # Test 11: neg_clk_with_enable_with_init_inferred_var_len for i in range(1,N+1): with open('neg_clk_with_enable_with_init_inferred_var_len_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_with_enable_with_init_inferred_var_len_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, input [31:0] l, output [width-1:0] q); generate reg [depth-1:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin for (d = 0; d < depth; d=d+1) initial int[w][d] <= ~((d+w) % 2); if (depth == 1) begin always @(negedge clk) if (e) int[w] <= i[w]; assign q[w] = int[w]; end else begin always @(negedge clk) if (e) int[w] <= {{ int[w][depth-2:0], i[w] }}; assign q[w] = int[w][l]; end end endgenerate endmodule '''.format(i)) assert_dynamic_area(fp, i, 'neg_clk_with_enable_with_init_inferred_var_len') import lfsr_area re_lfsr = re.compile(r'lfsr_(\d+)\.v') for fn in glob.glob('lfsr_*.v'): m = re_lfsr.match(fn) if not m: continue W = int(m.group(1)) with open(fn, 'a') as f: print(''' `ifndef _AUTOTB module __test ; wire [4095:0] assert_area = "%s"; endmodule `endif ''' % lfsr_area.area[W], file=f) # Test 15: pos_clk_no_enable_no_init_not_inferred for i in range(128+1,128+N+1): with open('pos_clk_no_enable_no_init_not_inferred_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module pos_clk_no_enable_no_init_not_inferred_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, output [width-1:0] q); generate wire [depth:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin assign int[w][0] = i[w]; for (d = 0; d < depth; d=d+1) begin \$_DFFE_PP_ r(.C(clk), .D(int[w][d]), .E(1'b1), .Q(int[w][d+1])); end assign q[w] = int[w][depth]; end endgenerate endmodule '''.format(i)) assert_static_area(fp, i, 'pos_clk_no_enable_no_init_not_inferred') # Test 16: neg_clk_with_enable_with_init_inferred_var_len for i in range(128+1,128+N+1): with open('neg_clk_with_enable_with_init_inferred_var_len_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_with_enable_with_init_inferred_var_len_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, input [31:0] l, output [width-1:0] q); generate reg [depth-1:0] int [width-1:0]; genvar w, d; for (w = 0; w < width; w=w+1) begin for (d = 0; d < depth; d=d+1) initial int[w][d] <= ~((d+w) % 2); if (depth == 1) begin always @(negedge clk) if (e) int[w] <= i[w]; assign q[w] = int[w]; end else begin always @(negedge clk) if (e) int[w] <= {{ int[w][depth-2:0], i[w] }}; assign q[w] = int[w][l]; end end endgenerate endmodule '''.format(i)) assert_dynamic_area(fp, i, 'neg_clk_with_enable_with_init_inferred_var_len') # Test 18: neg_clk_with_enable_with_init_inferred2 for i in range(1,N+1): with open('neg_clk_with_enable_with_init_inferred2_%d.v' % i, 'w') as fp: fp.write(''' (* top *) module neg_clk_with_enable_with_init_inferred2_{0} #(parameter width=1, depth={0}) (input clk, input [width-1:0] i, input e, output [width-1:0] q); generate reg [width-1:0] int [depth-1:0]; genvar w, d; for (d = 0; d < depth; d=d+1) begin for (w = 0; w < width; w=w+1) begin //initial int[d][w] <= ~((d+w) % 2); if (d == 0) begin always @(negedge clk) if (e) int[d][w]
headers=self.json_headers) body = resp.json assert resp.status_code == 200 assert resp.content_type == CONTENT_TYPE_APP_JSON assert "process" in resp.json and isinstance(body["process"], dict) process = body["process"] assert "id" in process and isinstance(process["id"], str) assert process["id"] == resources.TEST_REMOTE_PROCESS_WPS1_ID assert "title" in process and isinstance(process["title"], str) assert "description" in process and isinstance(process["description"], str) # evaluated in separate test (test_get_provider_process_description_with_version) # assert "version" in process and isinstance(process["version"], str) assert "keywords" in process and isinstance(process["keywords"], list) assert "metadata" in process and isinstance(process["metadata"], list) assert len(body["jobControlOptions"]) == 1 assert EXECUTE_CONTROL_OPTION_ASYNC in body["jobControlOptions"] assert len(body["outputTransmission"]) == 1 assert EXECUTE_TRANSMISSION_MODE_REFERENCE in body["outputTransmission"] assert "inputs" in process and isinstance(process["inputs"], list) assert all(isinstance(p_io, dict) and "id" in p_io for p_io in process["inputs"]) assert "outputs" in process and isinstance(process["outputs"], list) assert all(isinstance(p_io, dict) and "id" in p_io for p_io in process["outputs"]) @mocked_remote_server_requests_wps1([ resources.TEST_REMOTE_SERVER_URL, resources.TEST_REMOTE_PROCESS_GETCAP_WPS1_XML, [resources.TEST_REMOTE_PROCESS_DESCRIBE_WPS1_XML], ]) def test_get_provider_process_description_ogc_schema(self): self.register_provider() path = "/providers/{}/processes/{}".format(self.remote_provider_name, resources.TEST_REMOTE_PROCESS_WPS1_ID) resp = self.app.get(path, headers=self.json_headers) assert resp.status_code == 200 assert resp.content_type == CONTENT_TYPE_APP_JSON assert "process" not in resp.json and isinstance(resp.json, dict) process = resp.json assert "id" in process and isinstance(process["id"], str) assert process["id"] == resources.TEST_REMOTE_PROCESS_WPS1_ID assert "title" in process and isinstance(process["title"], str) assert "description" in process and isinstance(process["description"], str) # evaluated in separate test (test_get_provider_process_description_with_version) # assert "version" in process and isinstance(process["version"], str) and len(process["version"]) assert "keywords" in process and isinstance(process["keywords"], list) assert "metadata" in process and isinstance(process["metadata"], list) assert len(process["jobControlOptions"]) == 1 assert EXECUTE_CONTROL_OPTION_ASYNC in process["jobControlOptions"] assert len(process["outputTransmission"]) == 1 assert EXECUTE_TRANSMISSION_MODE_REFERENCE in process["outputTransmission"] assert "inputs" in process and isinstance(process["inputs"], dict) assert all(isinstance(p_io, str) and isinstance(process["inputs"][p_io], dict) for p_io in process["inputs"]) assert all("id" not in process["inputs"][p_io] for p_io in process["inputs"]) assert "outputs" in process and isinstance(process["outputs"], dict) assert all(isinstance(p_io, str) and isinstance(process["outputs"][p_io], dict) for p_io in process["outputs"]) assert all("id" not in process["outputs"][p_io] for p_io in process["outputs"]) @mocked_remote_server_requests_wps1([ resources.TEST_REMOTE_SERVER_URL, resources.TEST_REMOTE_PROCESS_GETCAP_WPS1_XML, [resources.WPS_NO_INPUTS_XML], ]) def test_get_provider_process_no_inputs(self): """ Process that takes no inputs should be permitted and its description must allow generation of empty map/list. """ self.register_provider() path = "/providers/{}/processes/{}".format(self.remote_provider_name, resources.WPS_NO_INPUTS_ID) resp = self.app.get(path, params={"schema": PROCESS_SCHEMA_OLD}, headers=self.json_headers) assert resp.status_code == 200 assert resp.content_type == CONTENT_TYPE_APP_JSON inputs = resp.json["process"]["inputs"] assert isinstance(inputs, list) and len(inputs) == 0 path = "/providers/{}/processes/{}".format(self.remote_provider_name, resources.WPS_NO_INPUTS_ID) resp = self.app.get(path, params={"schema": PROCESS_SCHEMA_OGC}, headers=self.json_headers) assert resp.status_code == 200 assert resp.content_type == CONTENT_TYPE_APP_JSON inputs = resp.json["inputs"] assert isinstance(inputs, dict) and len(inputs) == 0 @mocked_remote_server_requests_wps1([ resources.TEST_REMOTE_SERVER_URL, resources.TEST_REMOTE_PROCESS_GETCAP_WPS1_XML, # don't care [resources.WPS_LITERAL_VALUES_IO_XML], ]) def test_get_provider_process_literal_values(self): """ Test conversion of I/O of supported values defined as literal data domains from provider process. """ self.register_provider() path = "/providers/{}/processes/{}".format(self.remote_provider_name, resources.WPS_LITERAL_VALUES_IO_ID) resp = self.app.get(path, params={"schema": PROCESS_SCHEMA_OLD}, headers=self.json_headers) assert resp.status_code == 200 assert resp.content_type == CONTENT_TYPE_APP_JSON inputs = resp.json["process"]["inputs"] outputs = resp.json["process"]["outputs"] assert isinstance(inputs, list) and len(inputs) == 15 assert isinstance(outputs, list) and len(outputs) == 2 # inputs have different combinations of minOccurs/maxOccurs, Allowed/Supported Values, Ranges, Types, etc. assert inputs[0]["id"] == "lat" assert inputs[0]["title"] == "Latitude" assert inputs[0]["minOccurs"] == 1 assert inputs[0]["maxOccurs"] == 100 assert "default" not in inputs[0] assert "literalDataDomains" in inputs[0] and len(inputs[0]["literalDataDomains"]) == 1 assert inputs[0]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[0]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert "defaultValue" not in inputs[0]["literalDataDomains"][0] assert inputs[1]["id"] == "lon" assert inputs[1]["title"] == "Longitude" assert inputs[1]["minOccurs"] == 1 assert inputs[1]["maxOccurs"] == 100 assert "default" not in inputs[1] assert "literalDataDomains" in inputs[1] and len(inputs[1]["literalDataDomains"]) == 1 assert inputs[1]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[1]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert "defaultValue" not in inputs[1]["literalDataDomains"][0] assert inputs[2]["id"] == "start_date" assert inputs[2]["title"] == "Initial date" assert inputs[2]["minOccurs"] == 0 assert inputs[2]["maxOccurs"] == 1 assert "default" not in inputs[2] assert "literalDataDomains" in inputs[2] and len(inputs[2]["literalDataDomains"]) == 1 assert inputs[2]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[2]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert "defaultValue" not in inputs[2]["literalDataDomains"][0] assert inputs[3]["id"] == "end_date" assert inputs[3]["title"] == "Final date" assert inputs[3]["minOccurs"] == 0 assert inputs[3]["maxOccurs"] == 1 assert "default" not in inputs[3] assert "literalDataDomains" in inputs[3] and len(inputs[3]["literalDataDomains"]) == 1 assert inputs[3]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[3]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert "defaultValue" not in inputs[3]["literalDataDomains"][0] assert inputs[4]["id"] == "ensemble_percentiles" assert inputs[4]["title"] == "Ensemble percentiles" assert inputs[4]["minOccurs"] == 0 assert inputs[4]["maxOccurs"] == 1 assert "default" not in inputs[4] assert "literalDataDomains" in inputs[4] and len(inputs[4]["literalDataDomains"]) == 1 assert inputs[4]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[4]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert inputs[4]["literalDataDomains"][0]["defaultValue"] == "10,50,90" assert inputs[5]["id"] == "dataset_name" assert inputs[5]["title"] == "Dataset name" assert inputs[5]["minOccurs"] == 0 assert inputs[5]["maxOccurs"] == 1 assert "default" not in inputs[5] assert "literalDataDomains" in inputs[5] and len(inputs[5]["literalDataDomains"]) == 1 assert inputs[5]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[5]["literalDataDomains"][0]["valueDefinition"] == ["bccaqv2"] assert "defaultValue" not in inputs[5]["literalDataDomains"][0] assert "allowedValues" not in inputs[5] assert inputs[6]["id"] == "rcp" assert inputs[6]["title"] == "RCP Scenario" assert inputs[6]["minOccurs"] == 1 assert inputs[6]["maxOccurs"] == 1 assert "default" not in inputs[6] assert "literalDataDomains" in inputs[6] and len(inputs[6]["literalDataDomains"]) == 1 assert inputs[6]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[6]["literalDataDomains"][0]["valueDefinition"] == ["rcp26", "rcp45", "rcp85"] assert "defaultValue" not in inputs[6]["literalDataDomains"][0] assert inputs[7]["id"] == "models" assert inputs[7]["title"] == "Models to include in ensemble" assert inputs[7]["minOccurs"] == 0 assert inputs[7]["maxOccurs"] == 1000 assert "default" not in inputs[7] assert "literalDataDomains" in inputs[7] and len(inputs[7]["literalDataDomains"]) == 1 assert inputs[7]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[7]["literalDataDomains"][0]["valueDefinition"] == [ "24MODELS", "PCIC12", "BNU-ESM", "CCSM4", "CESM1-CAM5", "CNRM-CM5", "CSIRO-Mk3-6-0", "CanESM2", "FGOALS-g2", "GFDL-CM3", "GFDL-ESM2G", "GFDL-ESM2M", "HadGEM2-AO", "HadGEM2-ES", "IPSL-CM5A-LR", "IPSL-CM5A-MR", "MIROC-ESM-CHEM", "MIROC-ESM", "MIROC5", "MPI-ESM-LR", "MPI-ESM-MR", "MRI-CGCM3", "NorESM1-M", "NorESM1-ME", "bcc-csm1-1-m", "bcc-csm1-1" ] assert inputs[7]["literalDataDomains"][0]["defaultValue"] == "24MODELS" assert inputs[8]["id"] == "window" assert inputs[8]["title"] == "Window" assert inputs[8]["minOccurs"] == 0 assert inputs[8]["maxOccurs"] == 1 assert "default" not in inputs[8] assert "literalDataDomains" in inputs[8] and len(inputs[8]["literalDataDomains"]) == 1 assert inputs[8]["literalDataDomains"][0]["dataType"]["name"] == "integer" assert inputs[8]["literalDataDomains"][0]["valueDefinition"] == {"anyValue": False} assert inputs[8]["literalDataDomains"][0]["defaultValue"] == 6 assert inputs[9]["id"] == "freq" assert inputs[9]["title"] == "Frequency" assert inputs[9]["minOccurs"] == 0 assert inputs[9]["maxOccurs"] == 1 assert "default" not in inputs[9] assert "literalDataDomains" in inputs[9] and len(inputs[9]["literalDataDomains"]) == 1 assert inputs[9]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[9]["literalDataDomains"][0]["valueDefinition"] == ["YS", "MS", "QS-DEC", "AS-JUL"] assert inputs[9]["literalDataDomains"][0]["defaultValue"] == "YS" assert inputs[10]["id"] == "check_missing" assert inputs[10]["title"] == "Missing value handling method" assert inputs[10]["minOccurs"] == 0, "original XML minOccurs=1, but detected defaultValue should correct to 0" assert inputs[10]["maxOccurs"] == 1 assert "default" not in inputs[10] assert "literalDataDomains" in inputs[10] and len(inputs[10]["literalDataDomains"]) == 1 assert inputs[10]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[10]["literalDataDomains"][0]["valueDefinition"] == [ "any", "wmo", "pct", "at_least_n", "skip", "from_context" ] assert inputs[10]["literalDataDomains"][0]["defaultValue"] == "any" assert inputs[11]["id"] == "missing_options" assert inputs[11]["title"] == "Missing method parameters" assert inputs[11]["minOccurs"] == 0 assert inputs[11]["maxOccurs"] == 1 assert "default" not in inputs[11] assert "literalDataDomains" not in inputs[11], "Complex input of the process should not have literal domains" assert "formats" in inputs[11] and len(inputs[11]["formats"]) == 1 assert inputs[11]["formats"][0]["mediaType"] == CONTENT_TYPE_APP_JSON assert inputs[11]["formats"][0]["default"] is True, \ "format is specified as default one explicitly, but should be regardless since it is the only one supported" # see test 'test_get_provider_process_complex_maximum_megabytes' # assert inputs[11]["formats"][0]["maximumMegabytes"] == 200 assert inputs[12]["id"] == "cf_compliance" assert inputs[12]["title"] == "Strictness level for CF-compliance input checks." assert inputs[12]["minOccurs"] == 0, "original XML minOccurs=1, but detected defaultValue should correct to 0" assert inputs[12]["maxOccurs"] == 1 assert "default" not in inputs[12] assert "literalDataDomains" in inputs[12] and len(inputs[12]["literalDataDomains"]) == 1 assert inputs[12]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[12]["literalDataDomains"][0]["valueDefinition"] == ["log", "warn", "raise"] assert inputs[12]["literalDataDomains"][0]["defaultValue"] == "warn" assert inputs[13]["id"] == "data_validation" assert inputs[13]["title"] == "Strictness level for data validation input checks." assert inputs[13]["minOccurs"] == 0, "original XML minOccurs=1, but detected defaultValue should correct to 0" assert inputs[13]["maxOccurs"] == 1 assert "default" not in inputs[13] assert "literalDataDomains" in inputs[13] and len(inputs[13]["literalDataDomains"]) == 1 assert inputs[13]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[13]["literalDataDomains"][0]["valueDefinition"] == ["log", "warn", "raise"] assert inputs[13]["literalDataDomains"][0]["defaultValue"] == "raise" assert inputs[14]["id"] == "output_format" assert inputs[14]["title"] == "Output format choice" assert inputs[14]["minOccurs"] == 0 assert inputs[14]["maxOccurs"] == 1 assert "default" not in inputs[14] assert "literalDataDomains" in inputs[14] and len(inputs[14]["literalDataDomains"]) == 1 assert inputs[14]["literalDataDomains"][0]["dataType"]["name"] == "string" assert inputs[14]["literalDataDomains"][0]["valueDefinition"] == ["netcdf", "csv"] assert inputs[14]["literalDataDomains"][0]["defaultValue"] == "netcdf" assert outputs[0]["id"] == "output" assert len(outputs[0]["formats"]) == 2 assert outputs[0]["formats"][0]["mediaType"] == CONTENT_TYPE_APP_NETCDF assert outputs[0]["formats"][0]["encoding"] == "base64" assert outputs[0]["formats"][0]["default"] is True assert "maximumMegabytes" not in outputs[0]["formats"][0] # never applies, even with OWSLib update assert outputs[0]["formats"][1]["mediaType"] == CONTENT_TYPE_APP_ZIP assert outputs[0]["formats"][1]["encoding"] == "base64" assert outputs[0]["formats"][1]["default"] is False assert "maximumMegabytes" not in outputs[0]["formats"][1] # never applies, even with OWSLib update assert outputs[1]["id"] == "output_log" assert len(outputs[1]["formats"])
pico_num("PICO_TOO_MANY_SEGMENTS"), 0 if segments == 0: return pico_num("PICO_NOT_ENOUGH_SEGMENTS"), 0 self._segments = segments self.info.memps = self.info.memory return pico_num("PICO_OK"), self.info.memory def set_simple_trigger(self, enabled, source, threshold, direction, delay=0, waitfor=0): """ Sets simple trigger (Doh...). If Advanced already on - remove it. :param enabled: enable the trigger or... not. hm... :type enabled: bool :param source: trigger channel/source as in TriggerChannels :type source: int :param threshold: vertical ratio of the current channel range as value from <-1.0, 1.0> :type threshold: float :param direction: trigger direction as in TriggerChannelDirections :type direction: int :param delay: delay trigger detection by times of sample interval :type delay: int :param waitfor: autotrigger time in miliseconds, 0 to wait for eva... :type waitfor: int :returns: status of the calls :rtype int: """ if self._handle <= 0: return pico_num("PICO_INVALID_HANDLE") if self.info.has_adv_trigger: if True in [c.is_set() for c in self.trigger_conditions]: self.set_advanced_trigger(conditions=None) if True in [c.is_set() for c in self.pwq_conditions]: self.set_pwq_trigger(conditions=None) adc = int((threshold * 1.0 - int(threshold * 0.999999)) * self.info.max_adc) status = ldlib.SetTrigger(self._chandle, c_int16(source if enabled else self.m.TriggerChannels.Off), c_int16(adc), c_int16(self.m.ThresholdDirections.to_simple(direction)), c_float(-100.0 * self.trigg_ratio), c_int16(waitfor)) if status != 0: self.trigger = enabled self.trigg_source = source self.trigg_threshold = threshold self.trigg_direction = direction self.trigg_wait = waitfor return pico_num("PICO_OK") return pico_num("PICO_INVALID_PARAMETER") def set_horizontal_trigger_ratio(self, ratio): """ Sets horizontal ration of Trigger Events :param ratio: collection block ratio to set trigger to as in <0.0, 1.0> :type ratio: float :returns: status of the call :rtype: int """ if self._handle <= 0: return pico_num("PICO_INVALID_HANDLE") ratio = abs(ratio) % 1 if ratio != self.trigg_ratio: if self.trigger: adc = int((self.trigg_threshold * 1.0 - int(self.trigg_threshold * 0.999999)) * self.info.max_adc) status = ldlib.SetTrigger(self._chandle, c_int16(self.trigg_source), c_int16(adc), c_int16(self.m.ThresholdDirections.to_simple(self.trigg_direction)), c_float(-100.0 * ratio), c_int16(self.trigg_wait)) if status == 0: return pico_num("PICO_INVALID_PARAMETER") elif self.info.has_adv_trigger and (True in [c.is_set() for c in self.trigger_conditions]): status = ldlib.SetAdvTriggerDelay(self._chandle, c_uint32(0), c_float(-100.0 * ratio)) if status == 0: return pico_num("PICO_INVALID_PARAMETER") self.trigg_ratio = ratio return pico_num("PICO_OK") def collect_segment(self, segment, interval=None, event_handle=None, timebase=None, block=True, bulk=False, overlapped=False): """ Runs Block data collection on(from) given segment. Can explicitly use supplied timebase if given or calculate one. Buffers have to be set at least on one channel to make this call work. :param segment: memory segment number to start the collection on (from) :type segment: int :param interval: sample interval in nanoseconds :type interval: float :param event_handle: event handle to use during the collection, once device is ready, it is set :type event_handle: Event :param timebase: explicit (forced) timebase value :type timebase: int :param block: whether to block the call, requires event_handle if False :type block: bool :param bulk: collect segments in bulk, better use collect_segments call :type bulk: bool :param overlapped: use overlapped buffer in collection :type overlapped: bool :returns: status of the call :rtype int """ if self._handle <= 0: return pico_num("PICO_INVALID_HANDLE") if bulk or overlapped: return pico_num("PICO_NOT_SUPPORTED_BY_THIS_DEVICE") if segment > self._segments: return pico_num("PICO_SEGMENT_OUT_OF_RANGE") """ We expect only one collection at the time """ for e in (self._collect_event, self._recording_event, self._async_event): if e is not None and e.is_set(): return pico_num("PICO_BUSY") """ Locate buffers taking part in collection """ indexes = () for index in self._buffers.keys(): if self._buffers[index].segment == segment: indexes += (index,) if len(indexes) == 0: return pico_num("PICO_INVALID_BUFFER") """ pick the longest sample number from defined buffers """ samples = 0 for index in indexes: with self._buffers[index].access_lock: if self._buffers[index].segment == segment: if self._buffers[index].mode == self.m.RatioModes.none: samples = max(samples, self._buffers[index].samples) else: samples = max(samples, self._buffers[index].samples * self._buffers[index].downsample) break if samples == 0: return pico_num("PICO_INVALID_BUFFER") """ ets setup """ if self._ets.mode != self._ets.last: if self._ets.mode == self.m.ETSModes.off: self._ets.status = ldlib.SetEts(self._chandle, c_int32(self.m.ETSModes.off), c_int16(self._ets.cycles), c_int16(self._ets.interleave), None) if self._ets.status == pico_num("PICO_OK"): self._ets.last = self.m.ETSModes.off elif (self.trigger or True in [c.is_set() for c in (self.trigger_conditions + self.pwq_conditions)]) \ and len([1 for p in self._port_set.keys() if self._port_set[p].enabled]) == 0: picos = c_int32(0) self._ets.status = ldlib.SetEts(self._chandle, c_int32(self._ets.mode), c_int16(self._ets.cycles), c_int16(self._ets.interleave), byref(picos)) if self._ets.status == pico_num("PICO_OK"): self._ets.last = self._ets.mode self._ets.picos = picos.value if self._ets.last != self.m.ETSModes.off: timebase = 1 """ calculate timebase from interval """ finterval = c_int32(0) linterval = c_int32(0) if isinstance(interval, float): interval = int(interval) if timebase is not None and self._ets.last == self.m.ETSModes.off: status = self._get_timebase(timebase=timebase, samples=samples, ref_interval=byref(finterval), oversample=0, ref_maxsamples=None, segment=segment) if status != pico_num("PICO_OK"): return status if timebase is None: for index in indexes: with self._buffers[index].access_lock: if self._buffers[index].last_interval is not None \ and self._buffers[index].last_timebase is not None: if self._buffers[index].last_interval == interval: timebase = self._buffers[index].last_timebase finterval.value = self._buffers[index].real_interval break if timebase is None: last = 0 status = pico_num("PICO_OK") for pwr in range(0, 32): rough = 1 << pwr status = self._get_timebase(timebase=rough, samples=samples, ref_interval=byref(finterval), oversample=0, ref_maxsamples=None, segment=segment) if status not in (pico_num("PICO_OK"), pico_num("PICO_INVALID_TIMEBASE")) \ or finterval.value >= interval: break last = rough else: rough = last if status == pico_num("PICO_TOO_MANY_SAMPLES"): return status if last == rough or finterval.value == interval: timebase = rough else: if last <= 32: fine = rough for fine in range(int(last / 2), 64): status = self._get_timebase(timebase=fine, samples=samples, ref_interval=byref(finterval), oversample=0, ref_maxsamples=None, segment=segment) if status == pico_num("PICO_OK") and finterval.value >= interval: break linterval.value = finterval.value if abs(interval - finterval.value) <= abs(interval - linterval.value): timebase = fine else: timebase = max(1, fine - 1) finterval.value = linterval.value if linterval.value > 0 else interval else: """ bubble :) """ i = 1 linterval.value = finterval.value fine = rough while timebase is None: if i >= 32: timebase = fine break elif linterval.value > interval: fine -= int((rough - last) / pow(2, i)) elif linterval.value < interval: fine += int((rough - last) / pow(2, i)) else: timebase = fine continue status = self._get_timebase(timebase=fine, samples=samples, ref_interval=byref(finterval), oversample=0, ref_maxsamples=None, segment=segment) if status == pico_num("PICO_OK") and finterval.value in (interval, linterval.value): timebase = fine continue linterval.value = finterval.value i += 1 for index in indexes: with self._buffers[index].access_lock: self._buffers[index].last_interval = interval self._buffers[index].last_timebase = timebase self._buffers[index].real_interval = finterval.value self._lock_buffer(index) if event_handle is not None: self._collect_event = event_handle if self._collect_event.is_set(): self._collect_event.clear() try: self._collect_event.set() to_sleep = (interval * samples / 5.0) / 1000000000 status = ldlib.RunBlock(self._chandle, c_int32(samples), c_int16(timebase), c_int16(1), None) if status == 0: return pico_num("PICO_INVALID_PARAMETER") while True: if not self._collect_event.is_set(): break status = ldlib.Ready(self._chandle) if status < 0: return pico_num("PICO_NOT_RESPONDING") elif status > 0: self._collect_event.clear() break sleep(to_sleep) finally: self._collect_event.clear() buffers = {} handles = {} aggregates = {} averages = {} decimates = {} for c in self.m.Channels.map: if c in self._channel_set.keys() and self._channel_set[c].enabled: buffers[c] = np.empty(samples, c_int16) handles[c] = buffers[c].ctypes else: buffers[c] = None handles[c] = None overvoltaged = c_int16(0) status = ldlib.GetValues(self._chandle, handles[self.m.Channels.A], handles[self.m.Channels.B], handles[self.m.Channels.C], handles[self.m.Channels.D], byref(overvoltaged), c_int32(samples)) if status == 0: return pico_num("PICO_INVALID_PARAMETER") for index in indexes: with self._buffers[index].access_lock: c = self._buffers[index].channel if self._buffers[index].mode == self.m.RatioModes.raw: self._buffers[index].data = buffers[c] else: if buffers[c] is not None: l = int(samples / self._buffers[index].downsample) * self._buffers[index].downsample t = buffers[c][:l].reshape(-1, self._buffers[index].downsample) if self._buffers[index].mode == self.m.RatioModes.agg: if c not in aggregates.keys(): aggregates[c] = {"max": None, "min": None} if buffers[c] is not None: aggregates[c]["max"] = t.max(axis=1) aggregates[c]["min"] = t.min(axis=1) self._buffers[index].data = aggregates[c]["max"] self._buffers[index].data_min = aggregates[c]["min"] elif self._buffers[index].mode == self.m.RatioModes.avg: if c not in averages.keys(): averages[c] = None if buffers[c] is not None: averages[c] = t.mean(axis=1) self._buffers[index].data = averages[c] elif self._buffers[index].mode == self.m.RatioModes.dec: if c not in decimates.keys(): decimates[c] = None if buffers[c] is not None: decimates[c] = t[:, 0] self._buffers[index].data = decimates[c] self._channel_set[c].overvoltaged = overvoltaged.value & (1 << c) != 0 return pico_num("PICO_OK") def collect_segments(self, start_segment, stop_segment, interval=None, event_handle=None, timebase=None, block=True): """ Initiates Rapid Block Collection :param start_segment: number of segment to start the collection from :type start_segment: int :param stop_segment: number of last segment to be collected :type stop_segment: int :param interval: nanoseconds per sample, optional if timebase specified :type interval: int :param event_handle: reference to the event object to notify about completion :type event_handle: threading._Event :param timebase: optional timebase to skip internal calculation from interval :type timebase: int :return: picostatus number of the call :rtype: int """ if self._handle <= 0: return pico_num("PICO_INVALID_HANDLE") return pico_num("PICO_NOT_SUPPORTED_BY_THIS_DEVICE") def collect_segment_overlapped(self, segment, interval=None, event_handle=None, timebase=None, block=True): """ Runs Block data collection on(from) given segment in overlapped setup. """
# Imports # ======= # These are listed in the order prescribed by `PEP 8 # <http://www.python.org/dev/peps/pep-0008/#imports>`_. # # Standard library # ---------------- import datetime import logging from math import ceil from decimal import Decimal, ROUND_HALF_UP # Third-party imports # ------------------- from psycopg2 import IntegrityError from gluon import current # Local imports # ------------- from outcome_request import OutcomeRequest logger = logging.getLogger(current.settings.logger) logger.setLevel(current.settings.log_level) def _profile(start, msg): delta = datetime.datetime.now() - start logger.debug("{}: {}.{}".format(msg, delta.seconds, delta.microseconds)) D1 = Decimal("1") def _score_from_pct_correct(pct_correct, points, autograde): # ALL_AUTOGRADE_OPTIONS = ['all_or_nothing', 'pct_correct', 'interact'] if points is None: points = 0 if autograde == "interact" or autograde == "visited": return points elif autograde == "pct_correct": # prorate credit based on percentage correct # 2.x result return int(((pct_correct * points)/100.0)) return int(Decimal((pct_correct * points) / 100.0).quantize(D1, ROUND_HALF_UP)) elif autograde == "all_or_nothing" or autograde == "unittest": # 'unittest' is legacy, now deprecated # have to get *all* tests to pass in order to get any credit if pct_correct == 100: return points else: return 0 def _score_one_code_run(row, points, autograde): # row is one row from useinfo table # second element of act is the percentage of tests that passed if autograde == "interact": return _score_one_interaction(row, points, autograde) try: (ignore, pct, ignore, passed, ignore, failed) = row.act.split(":") pct_correct = 100 * float(passed) / (int(failed) + int(passed)) except (ZeroDivisionError, ValueError): pct_correct = 0 # can still get credit if autograde is 'interact' or 'visited'; but no autograded value return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_mchoice(row, points, autograde): # row is from mchoice_answers ## It appears that the mchoice_answers is only storing a binary correct_or_not ## If that is updated to store a pct_correct, the next few lines can change if autograde == "pct_correct" and "percent" in row and row.percent is not None: pct_correct = int(round(row.percent * 100)) else: if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_interaction(row, points, autograde): # row is from useinfo if row: return points else: return 0 def _score_one_parsons(row, points, autograde): # row is from parsons_answers # Much like mchoice, parsons_answers currently stores a binary correct value # So much like in _score_one_mchoice, the next lines can be altered if a pct_correct value is added to parsons_answers if autograde == "pct_correct" and "percent" in row and row.percent is not None: pct_correct = int(round(row.percent * 100)) else: if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_fitb(row, points, autograde): # row is from fitb_answers if autograde == "pct_correct" and "percent" in row and row.percent is not None: pct_correct = int(round(row.percent * 100)) else: if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_clickablearea(row, points, autograde): # row is from clickablearea_answers if autograde == "pct_correct" and "percent" in row and row.percent is not None: pct_correct = int(round(row.percent * 100)) else: if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_dragndrop(row, points, autograde): # row is from dragndrop_answers if autograde == "pct_correct" and "percent" in row and row.percent is not None: pct_correct = int(round(row.percent * 100)) else: if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_codelens(row, points, autograde): # row is from codelens_answers if row.correct: pct_correct = 100 else: pct_correct = 0 return _score_from_pct_correct(pct_correct, points, autograde) def _score_one_lp(row, points, autograde): # row is from lp_answers. # If row.correct is None, score this as a 0. return _score_from_pct_correct(row.correct or 0, points, autograde) def _scorable_mchoice_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.mchoice_answers.course_name == course_name) & (db.mchoice_answers.sid == sid) & (db.mchoice_answers.div_id == question_name) ) if deadline: query = query & (db.mchoice_answers.timestamp < deadline) if practice_start_time: query = query & (db.mchoice_answers.timestamp >= practice_start_time) if now: query = query & (db.mchoice_answers.timestamp <= now) return db(query).select(orderby=db.mchoice_answers.timestamp) def _scorable_useinfos( course_name, sid, div_id, points, deadline, event_filter=None, question_type=None, practice_start_time=None, db=None, now=None, ): # look in useinfo, to see if visited (before deadline) # sid matches auth_user.username, not auth_user.id # if question type is page we must do better with the div_id query = (db.useinfo.course_id == course_name) & (db.useinfo.sid == sid) if question_type == "page": base_course = ( db(db.courses.course_name == course_name) .select(db.courses.base_course) .first() .base_course ) quest = ( db( (db.questions.name == div_id) & (db.questions.base_course == base_course) ) .select() .first() ) div_id = "{}/{}.html".format(quest.chapter, quest.subchapter) query = query & (db.useinfo.div_id.endswith(div_id)) else: query = query & (db.useinfo.div_id == div_id) if event_filter: query = query & (db.useinfo.event == event_filter) if deadline: query = query & (db.useinfo.timestamp < deadline) if practice_start_time: query = query & (db.useinfo.timestamp >= practice_start_time) if now: query = query & (db.useinfo.timestamp <= now) return db(query).select(db.useinfo.id, db.useinfo.act, orderby=db.useinfo.timestamp) def _scorable_parsons_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.parsons_answers.course_name == course_name) & (db.parsons_answers.sid == sid) & (db.parsons_answers.div_id == question_name) ) if deadline: query = query & (db.parsons_answers.timestamp < deadline) if practice_start_time: query = query & (db.parsons_answers.timestamp >= practice_start_time) if now: query = query & (db.parsons_answers.timestamp <= now) return db(query).select(orderby=db.parsons_answers.timestamp) def _scorable_fitb_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.fitb_answers.course_name == course_name) & (db.fitb_answers.sid == sid) & (db.fitb_answers.div_id == question_name) ) if deadline: query = query & (db.fitb_answers.timestamp < deadline) if practice_start_time: query = query & (db.fitb_answers.timestamp >= practice_start_time) if now: query = query & (db.fitb_answers.timestamp <= now) return db(query).select(orderby=db.fitb_answers.timestamp) def _scorable_clickablearea_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.clickablearea_answers.course_name == course_name) & (db.clickablearea_answers.sid == sid) & (db.clickablearea_answers.div_id == question_name) ) if deadline: query = query & (db.clickablearea_answers.timestamp < deadline) if practice_start_time: query = query & (db.clickablearea_answers.timestamp >= practice_start_time) if now: query = query & (db.clickablearea_answers.timestamp <= now) return db(query).select(orderby=db.clickablearea_answers.timestamp) def _scorable_dragndrop_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.dragndrop_answers.course_name == course_name) & (db.dragndrop_answers.sid == sid) & (db.dragndrop_answers.div_id == question_name) ) if deadline: query = query & (db.dragndrop_answers.timestamp < deadline) if practice_start_time: query = query & (db.dragndrop_answers.timestamp >= practice_start_time) if now: query = query & (db.dragndrop_answers.timestamp <= now) return db(query).select(orderby=db.dragndrop_answers.timestamp) def _scorable_codelens_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.codelens_answers.course_name == course_name) & (db.codelens_answers.sid == sid) & (db.codelens_answers.div_id == question_name) ) if deadline: query = query & (db.codelens_answers.timestamp < deadline) if practice_start_time: query = query & (db.codelens_answers.timestamp >= practice_start_time) if now: query = query & (db.codelens_answers.timestamp <= now) return db(query).select(orderby=db.codelens_answers.timestamp) def _scorable_lp_answers( course_name, sid, question_name, points, deadline, practice_start_time=None, db=None, now=None, ): query = ( (db.lp_answers.course_name == course_name) & (db.lp_answers.sid == sid) & (db.lp_answers.div_id == question_name) ) if deadline: query = query & (db.lp_answers.timestamp < deadline) if practice_start_time: query = query & (db.codelens_answers.timestamp >= practice_start_time) if now: query = query & (db.codelens_answers.timestamp <= now) return db(query).select(orderby=db.lp_answers.timestamp) def _autograde_one_q( course_name, sid, question_name, points, question_type, deadline=None, autograde=None, which_to_grade=None, save_score=True, practice_start_time=None, db=None, now=None, ): logger.debug( "autograding %s %s %s %s %s %s", course_name, question_name, sid, deadline, autograde, which_to_grade, ) if not autograde: logger.debug("autograde not set returning 0") return 0 # If previously manually graded and it is required to save the score, don't overwrite. existing = ( db( (db.question_grades.sid == sid) & (db.question_grades.course_name == course_name) & (db.question_grades.div_id == question_name) ) .select() .first() ) if save_score and existing and (existing.comment != "autograded"): logger.debug( "skipping; previously manually graded, comment = {}".format( existing.comment ) ) return 0 # For all question types, and values of which_to_grade, we have the same basic structure: # 1. Query the appropriate table to get rows representing student responses # 2. Apply a scoring function to the first, last, or all rows # 2a. if scoring 'best_answer', take the max score # Note that the scoring function will take the autograde parameter as an input, which might # affect how the score is determined. # If the question type is a selectquestion then we need to resolve the # question for this student first, and we can recursively call again # with the actual question. if question_type == "selectquestion": logger.debug("grading a selectquestion") actual_q = ( db( (db.selected_questions.selector_id == question_name) & (db.selected_questions.sid == sid) & (db.questions.name == db.selected_questions.selected_id) ) .select() .first() ) if actual_q: act_question_name = actual_q.selected_questions.selected_id act_points = actual_q.selected_questions.points act_question_type = actual_q.questions.question_type sel_id = actual_q.selected_questions.id score =
'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL', 'Space': 123, 'Type': 'FileSystem'|'AWSCloudWatch' }, ] }, Name='string', tags={ 'string': 'string' } ) **Response Syntax** :: { 'Arn': 'string', 'CreationTimestamp': 'string', 'Id': 'string', 'LastUpdatedTimestamp': 'string', 'LatestVersion': 'string', 'LatestVersionArn': 'string', 'Name': 'string' } **Response Structure** - *(dict) --* - **Arn** *(string) --* The ARN of the definition. - **CreationTimestamp** *(string) --* The time, in milliseconds since the epoch, when the definition was created. - **Id** *(string) --* The ID of the definition. - **LastUpdatedTimestamp** *(string) --* The time, in milliseconds since the epoch, when the definition was last updated. - **LatestVersion** *(string) --* The latest version of the definition. - **LatestVersionArn** *(string) --* The ARN of the latest version of the definition. - **Name** *(string) --* The name of the definition. :type AmznClientToken: string :param AmznClientToken: A client token used to correlate requests and responses. :type InitialVersion: dict :param InitialVersion: Information about the initial version of the logger definition. - **Loggers** *(list) --* A list of loggers. - *(dict) --* Information about a logger - **Component** *(string) --* The component that will be subject to logging. - **Id** *(string) --* A descriptive or arbitrary ID for the logger. This value must be unique within the logger definition version. Max length is 128 characters with pattern \'\'[a-zA-Z0-9:_-]+\'\'. - **Level** *(string) --* The level of the logs. - **Space** *(integer) --* The amount of file space, in KB, to use if the local file system is used for logging purposes. - **Type** *(string) --* The type of log output which will be used. :type Name: string :param Name: The name of the logger definition. :type tags: dict :param tags: Tag(s) to add to the new resource - *(string) --* - *(string) --* :rtype: dict :returns: """ pass def create_logger_definition_version(self, LoggerDefinitionId: str, AmznClientToken: str = None, Loggers: List = None) -> Dict: """ Creates a version of a logger definition that has already been defined. See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateLoggerDefinitionVersion>`_ **Request Syntax** :: response = client.create_logger_definition_version( AmznClientToken='string', LoggerDefinitionId='string', Loggers=[ { 'Component': 'GreengrassSystem'|'Lambda', 'Id': 'string', 'Level': 'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL', 'Space': 123, 'Type': 'FileSystem'|'AWSCloudWatch' }, ] ) **Response Syntax** :: { 'Arn': 'string', 'CreationTimestamp': 'string', 'Id': 'string', 'Version': 'string' } **Response Structure** - *(dict) --* - **Arn** *(string) --* The ARN of the version. - **CreationTimestamp** *(string) --* The time, in milliseconds since the epoch, when the version was created. - **Id** *(string) --* The ID of the version. - **Version** *(string) --* The unique ID of the version. :type AmznClientToken: string :param AmznClientToken: A client token used to correlate requests and responses. :type LoggerDefinitionId: string :param LoggerDefinitionId: **[REQUIRED]** The ID of the logger definition. :type Loggers: list :param Loggers: A list of loggers. - *(dict) --* Information about a logger - **Component** *(string) --* The component that will be subject to logging. - **Id** *(string) --* A descriptive or arbitrary ID for the logger. This value must be unique within the logger definition version. Max length is 128 characters with pattern \'\'[a-zA-Z0-9:_-]+\'\'. - **Level** *(string) --* The level of the logs. - **Space** *(integer) --* The amount of file space, in KB, to use if the local file system is used for logging purposes. - **Type** *(string) --* The type of log output which will be used. :rtype: dict :returns: """ pass def create_resource_definition(self, AmznClientToken: str = None, InitialVersion: Dict = None, Name: str = None, tags: Dict = None) -> Dict: """ Creates a resource definition which contains a list of resources to be used in a group. You can create an initial version of the definition by providing a list of resources now, or use ''CreateResourceDefinitionVersion'' later. See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateResourceDefinition>`_ **Request Syntax** :: response = client.create_resource_definition( AmznClientToken='string', InitialVersion={ 'Resources': [ { 'Id': 'string', 'Name': 'string', 'ResourceDataContainer': { 'LocalDeviceResourceData': { 'GroupOwnerSetting': { 'AutoAddGroupOwner': True|False, 'GroupOwner': 'string' }, 'SourcePath': 'string' }, 'LocalVolumeResourceData': { 'DestinationPath': 'string', 'GroupOwnerSetting': { 'AutoAddGroupOwner': True|False, 'GroupOwner': 'string' }, 'SourcePath': 'string' }, 'S3MachineLearningModelResourceData': { 'DestinationPath': 'string', 'S3Uri': 'string' }, 'SageMakerMachineLearningModelResourceData': { 'DestinationPath': 'string', 'SageMakerJobArn': 'string' }, 'SecretsManagerSecretResourceData': { 'ARN': 'string', 'AdditionalStagingLabelsToDownload': [ 'string', ] } } }, ] }, Name='string', tags={ 'string': 'string' } ) **Response Syntax** :: { 'Arn': 'string', 'CreationTimestamp': 'string', 'Id': 'string', 'LastUpdatedTimestamp': 'string', 'LatestVersion': 'string', 'LatestVersionArn': 'string', 'Name': 'string' } **Response Structure** - *(dict) --* - **Arn** *(string) --* The ARN of the definition. - **CreationTimestamp** *(string) --* The time, in milliseconds since the epoch, when the definition was created. - **Id** *(string) --* The ID of the definition. - **LastUpdatedTimestamp** *(string) --* The time, in milliseconds since the epoch, when the definition was last updated. - **LatestVersion** *(string) --* The latest version of the definition. - **LatestVersionArn** *(string) --* The ARN of the latest version of the definition. - **Name** *(string) --* The name of the definition. :type AmznClientToken: string :param AmznClientToken: A client token used to correlate requests and responses. :type InitialVersion: dict :param InitialVersion: Information about the initial version of the resource definition. - **Resources** *(list) --* A list of resources. - *(dict) --* Information about a resource. - **Id** *(string) --* The resource ID, used to refer to a resource in the Lambda function configuration. Max length is 128 characters with pattern \'\'[a-zA-Z0-9:_-]+\'\'. This must be unique within a Greengrass group. - **Name** *(string) --* The descriptive resource name, which is displayed on the AWS IoT Greengrass console. Max length 128 characters with pattern \'\'[a-zA-Z0-9:_-]+\'\'. This must be unique within a Greengrass group. - **ResourceDataContainer** *(dict) --* A container of data for all resource types. - **LocalDeviceResourceData** *(dict) --* Attributes that define the local device resource. - **GroupOwnerSetting** *(dict) --* Group/owner related settings for local resources. - **AutoAddGroupOwner** *(boolean) --* If true, AWS IoT Greengrass automatically adds the specified Linux OS group owner of the resource to the Lambda process privileges. Thus the Lambda process will have the file access permissions of the added Linux group. - **GroupOwner** *(string) --* The name of the Linux OS group whose privileges will be added to the Lambda process. This field is optional. - **SourcePath** *(string) --* The local absolute path of the device resource. The source path for a device resource can refer only to a character device or block device under \'\'/dev\'\'. - **LocalVolumeResourceData** *(dict) --* Attributes that define the local volume resource. - **DestinationPath** *(string) --* The absolute local path of the resource inside the Lambda environment. - **GroupOwnerSetting** *(dict) --* Allows you to configure additional group privileges for the Lambda process. This field is optional. - **AutoAddGroupOwner** *(boolean) --* If true, AWS IoT Greengrass automatically adds the specified Linux OS group owner of the resource to the Lambda process privileges. Thus the Lambda process will have the file access permissions of the added Linux group. - **GroupOwner** *(string) --* The name of the Linux OS group whose privileges will be added to the Lambda process. This field is optional. - **SourcePath** *(string) --* The local absolute path of the volume resource on the host. The source path for a volume resource type cannot start with \'\'/sys\'\'. - **S3MachineLearningModelResourceData** *(dict) --* Attributes that define an Amazon S3 machine learning resource. - **DestinationPath** *(string) --* The absolute local path of the resource inside the Lambda environment. - **S3Uri** *(string) --* The URI of the source model in an S3 bucket. The model package must be in tar.gz or .zip format. - **SageMakerMachineLearningModelResourceData** *(dict) --* Attributes that define an Amazon SageMaker machine learning resource. - **DestinationPath** *(string) --* The absolute local path of the resource inside the Lambda environment. - **SageMakerJobArn** *(string) --* The ARN of the Amazon SageMaker training job that represents the source model. - **SecretsManagerSecretResourceData** *(dict) --* Attributes that define a secret resource, which references a secret from AWS
# coding=utf-8 # Author: <NAME> <<EMAIL>> # # License: BSD 3 clause import warnings import numpy as np from deslib.base import BaseDS from deslib.util.aggregation import majority_voting_rule from deslib.util.diversity import Q_statistic, ratio_errors, \ negative_double_fault, compute_pairwise_diversity from sklearn import metrics from sklearn.base import ClusterMixin from sklearn.cluster import KMeans class DESClustering(BaseDS): """Dynamic ensemble selection-Clustering (DES-Clustering). This method selects an ensemble of classifiers taking into account the accuracy and diversity of the base classifiers. The K-means algorithm is used to define the region of competence. For each cluster, the N most accurate classifiers are first selected. Then, the J more diverse classifiers from the N most accurate classifiers are selected to compose the ensemble. Parameters ---------- pool_classifiers : list of classifiers (Default = None) The generated_pool of classifiers trained for the corresponding classification problem. Each base classifiers should support the method "predict". If None, then the pool of classifiers is a bagging classifier. clustering : sklearn.cluster (Default = None) The clustering model used to estimate the region of competence. If None, a KMeans with K = 5 is used. pct_accuracy : float (Default = 0.5) Percentage of base classifiers selected based on accuracy pct_diversity : float (Default = 0.33) Percentage of base classifiers selected based on diversity more_diverse : Boolean (Default = True) Whether we select the most or the least diverse classifiers to add to the pre-selected ensemble metric_diversity : String (Default = 'df') Metric used to estimate the diversity of the base classifiers. Can be either the double fault (df), Q-statistics (Q), or error correlation. metric_performance : String (Default = 'accuracy_score') Metric used to estimate the performance of a base classifier on a cluster. Can be either any metric from sklearn.metrics. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. DSEL_perc : float (Default = 0.5) Percentage of the input data used to fit DSEL. Note: This parameter is only used if the pool of classifier is None or unfitted. n_jobs : int, default=-1 The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. Doesn’t affect fit method. References ---------- <NAME>., <NAME>., <NAME>., & <NAME>. "Using accuracy and more_diverse to select classifiers to build ensembles." International Joint Conference on Neural Networks (IJCNN)., 2006. <NAME>., <NAME>, and <NAME>. "Dynamic selection of classifiers—a comprehensive review." Pattern Recognition 47.11 (2014): 3665-3680. <NAME>, <NAME>, and <NAME>, “Dynamic classifier selection: Recent advances and perspectives,” Information Fusion, vol. 41, pp. 195 – 216, 2018. """ def __init__(self, pool_classifiers=None, clustering=None, with_IH=False, safe_k=None, IH_rate=0.30, pct_accuracy=0.5, pct_diversity=0.33, more_diverse=True, metric_diversity='DF', metric_performance='accuracy_score', n_clusters=5, random_state=None, DSEL_perc=0.5, n_jobs=-1): super(DESClustering, self).__init__(pool_classifiers=pool_classifiers, with_IH=with_IH, safe_k=safe_k, IH_rate=IH_rate, random_state=random_state, DSEL_perc=DSEL_perc, n_jobs=n_jobs) self.metric_diversity = metric_diversity self.metric_performance = metric_performance self.clustering = clustering self.pct_accuracy = pct_accuracy self.pct_diversity = pct_diversity self.more_diverse = more_diverse self.n_clusters = n_clusters def fit(self, X, y): """ Train the DS model by setting the Clustering algorithm and pre-processing the information required to apply the DS methods. First the data is divided into K clusters. Then, for each cluster, the N most accurate classifiers are first selected. Then, the J more diverse classifiers from the N most accurate classifiers are selected to compose the ensemble of the corresponding cluster. An ensemble of classifiers is assigned to each of the K clusters. Parameters ---------- X : array of shape (n_samples, n_features) Data used to fit the model. y : array of shape (n_samples) class labels of each example in X. Returns ------- self """ super(DESClustering, self).fit(X, y) self.N_ = int(self.n_classifiers_ * self.pct_accuracy) self.J_ = int(np.ceil(self.n_classifiers_ * self.pct_diversity)) self._check_parameters() self.metric_classifier_ = getattr(metrics, self.metric_performance) if self.clustering is None: if self.n_samples_ >= self.n_clusters: self.clustering_ = KMeans(n_clusters=self.n_clusters, random_state=self.random_state, n_jobs=self.n_jobs) else: warnings.warn("n_clusters is bigger than DSEL size. " "Using All DSEL examples as cluster centroids.", category=RuntimeWarning) self.clustering_ = KMeans(n_clusters=self.n_samples_, random_state=self.random_state) self.clustering_.fit(self.DSEL_data_) else: self.clustering_ = self.clustering.fit(self.DSEL_data_) # set the diversity metric used self._set_diversity_func() # Since the clusters are fixed, we can pre-compute the accuracy and # diversity of each cluster as well as the # selected classifiers # (indices) for each one. These pre-computed information will be kept # on those three variables: self.performance_cluster_ = np.zeros( (self.clustering_.n_clusters, self.n_classifiers_)) self.diversity_cluster_ = np.zeros( (self.clustering_.n_clusters, self.n_classifiers_)) self.indices_ = np.zeros((self.clustering_.n_clusters, self.J_), dtype=int) self._preprocess_clusters() return self def _preprocess_clusters(self): """Preprocess the competence as well as the average diversity of each base classifier for each specific cluster. This process makes the test routines faster, since the ensemble of classifiers of each cluster is already predefined. The class attributes Accuracy_cluster_ and diversity_cluster_ stores the accuracy and diversity information respectively of each base classifier for each cluster. The attribute indices_ stores the pre-selected base classifiers for each cluster. """ labels = self.clustering_.predict(self.DSEL_data_) for cluster_index in range(self.clustering_.n_clusters): # Get the indices_ of the samples in the corresponding cluster. sample_indices = np.where(labels == cluster_index)[0] # Compute performance metric of each classifier in this cluster score_classifier = self.get_scores_(sample_indices) self.performance_cluster_[cluster_index, :] = score_classifier # Get the N_ most accurate classifiers in the cluster performance_indices = np.argsort(score_classifier)[::-1][0:self.N_] # Get the target labels for the samples in the corresponding # cluster for the diversity calculation. targets = self.DSEL_target_[sample_indices] self.diversity_cluster_[cluster_index, :] = \ compute_pairwise_diversity(targets, self.BKS_DSEL_[sample_indices, :], self.diversity_func_) diversity_of_selected = self.diversity_cluster_[ cluster_index, performance_indices] if self.more_diverse: diversity_indices = np.argsort(diversity_of_selected)[::-1][ 0:self.J_] else: diversity_indices = np.argsort(diversity_of_selected)[ 0:self.J_] self.indices_[cluster_index, :] = performance_indices[ diversity_indices] def estimate_competence(self, query, predictions=None): """Get the competence estimates of each base classifier :math:`c_{i}` for the classification of the query sample. In this case, the competences were already pre-calculated for each cluster. So this method computes the nearest cluster and get the pre-calculated competences of the base classifiers for the corresponding cluster. Parameters ---------- query : array of shape (n_samples, n_features) The query sample. predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifiers for all test examples. Returns ------- competences : array = [n_samples, n_classifiers] The competence level estimated for each base classifier. """ cluster_index = self.clustering_.predict(query) competences = self.performance_cluster_[cluster_index][:] return competences def select(self, query): """Select an ensemble with the most accurate and most diverse classifier for the classification of the query. The ensemble for each cluster was already pre-calculated in the fit method. So, this method calculates the closest cluster, and returns the ensemble associated to this cluster. Parameters ---------- query : array of shape (n_samples, n_features) The test examples. Returns ------- selected_classifiers : array of shape = [n_samples, self.k] Indices of the selected base classifier for each test example. """ cluster_index = self.clustering_.predict(query) selected_classifiers = self.indices_[cluster_index, :] return selected_classifiers def classify_with_ds(self, query, predictions, probabilities=None, neighbors=None, distances=None, DFP_mask=None): """Predicts the label of the corresponding query sample. Parameters ---------- query : array of shape = [n_features] The test sample. predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifiers for all test examples. probabilities : array of shape (n_samples, n_classifiers, n_classes) Probabilities estimates of each base classifier for all test examples. neighbors : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors according for each test sample. distances : array of shape (n_samples, n_neighbors) Distances of the k nearest neighbors according for each test sample. DFP_mask : array of shape (n_samples, n_classifiers) Mask containing 1 for the selected base classifier and 0 otherwise. Returns ------- predicted_label : array of shape (n_samples) Predicted class label for each test example. """ if query.ndim < 2: query = query.reshape(1, -1) if predictions.ndim < 2: predictions = predictions.reshape(1, -1) if query.shape[0] != predictions.shape[0]: raise ValueError( 'The arrays query and predictions must have the same number' ' of samples. query.shape is {}' 'and predictions.shape is {}'.format(query.shape, predictions.shape)) selected_classifiers = self.select(query) votes = predictions[ np.arange(predictions.shape[0])[:, None], selected_classifiers] predicted_label = majority_voting_rule(votes) return predicted_label def predict_proba_with_ds(self, query, predictions, probabilities, neighbors=None, distances=None, DFP_mask=None): """Predicts the label of the corresponding query sample. Parameters ---------- query : array of
= self.create_dataloader(dataset_path) self.val_loader = None self.loss = loss_dict[args.loss].to(self.device) self.criterion = nn.CrossEntropyLoss() self.init_lr_decayer() self.print_info(args) self.save_model() self.pretrained_weight = None self.best_loss = 1e+20 def create_dataloader(self, dataset_path): train_on = self.args.train_on train_dataset = SyntheticDepthDataset(dataset_path, setname='train') test_dataset = SyntheticDepthDataset(dataset_path, setname='val') # Select the desired number of images from the training set if train_on != 'full': import random training_idxs = np.array(random.sample(range(0, len(train_dataset)), int(train_on))) train_dataset.training_case = train_dataset.training_case[training_idxs] test_dataset.training_case = test_dataset.training_case[:3] train_data_loader = DataLoader(train_dataset, shuffle=True, batch_size=self.args.batch_size, num_workers=4) test_data_loader = DataLoader(test_dataset, batch_size=self.args.batch_size, num_workers=4) print('\n- Found {} images in "{}" folder.'.format(train_data_loader.dataset.__len__(), 'train')) print('\n- Found {} images in "{}" folder.'.format(test_data_loader.dataset.__len__(), 'val')) return train_data_loader, test_data_loader def init_output_folder(self): folder_path = self.exp_dir / f"output_{date_now}_{time_now}" if not os.path.exists(str(folder_path)): os.mkdir(str(folder_path)) return folder_path def init_network(self, network): if self.args.resume: print(f'------------------ Resume a training work ----------------------- ') assert os.path.isfile(self.args.resume), f"No checkpoint found at:{self.args.resume}" checkpoint = torch.load(self.args.resume) self.start_epoch = checkpoint['epoch'] + 1 # resume epoch model = checkpoint['model'].to(self.device) # resume model self.optimizer = checkpoint['optimizer'] # resume optimizer # self.optimizer = SGD(self.parameters, lr=self.args.lr, momentum=self.args.momentum, weight_decay=0) # self.args = checkpoint['args'] self.parameters = filter(lambda p: p.requires_grad, model.parameters()) self.losses[:, :checkpoint['epoch']] = checkpoint['losses'] self.angle_losses[:, :checkpoint['epoch']] = checkpoint['angle_losses'] print(f"- checkout {checkpoint['epoch']} was loaded successfully!") return model else: print(f"------------ start a new training work -----------------") # init model model = network.to(self.device) self.parameters = filter(lambda p: p.requires_grad, model.parameters()) # init optimizer if self.args.optimizer.lower() == 'sgd': self.optimizer = SGD(self.parameters, lr=self.args.lr, momentum=self.args.momentum, weight_decay=0) elif self.args.optimizer.lower() == 'adam': self.optimizer = Adam(self.parameters, lr=self.args.lr, weight_decay=0, amsgrad=True) else: raise ValueError if self.exp_name == "degares": # load weight from pretrained resng model print(f'load model {config.resng_model}') pretrained_model = torch.load(config.resng_model) resng = pretrained_model['model'] self.missing_keys = model.load_state_dict(resng.state_dict(), strict=False) # load optimizer # self.optimizer = pretrained_model['optimizer'] # Print model's state_dict print("ResNg's state_dict:") for param_tensor in resng.state_dict(): print(param_tensor, "\t", resng.state_dict()[param_tensor].size()) print("DeGaRes's state_dict:") for param_tensor in model.state_dict(): print(param_tensor, "\t", model.state_dict()[param_tensor].size()) return model def init_lr_decayer(self): milestones = [int(x) for x in self.args.lr_scheduler.split(",")] self.lr_decayer = lr_scheduler.MultiStepLR(self.optimizer, milestones=milestones, gamma=self.args.lr_decay_factor) def print_info(self, args): print(f'\n------------------- Starting experiment {self.exp_name} ------------------ \n') print(f'- Model "{self.model.__name__}" was loaded successfully!') def save_checkpoint(self, is_best, epoch): checkpoint_filename = os.path.join(self.output_folder, 'checkpoint-' + str(epoch) + '.pth.tar') state = {'args': self.args, 'epoch': epoch, 'model': self.model, 'optimizer': self.optimizer, 'angle_losses': self.angle_losses[:, :epoch], 'losses': self.losses[:, :epoch], } torch.save(state, checkpoint_filename) if is_best: best_filename = os.path.join(self.output_folder, 'model_best.pth.tar') shutil.copyfile(checkpoint_filename, best_filename) if epoch > 0: prev_checkpoint_filename = os.path.join(self.output_folder, 'checkpoint-' + str(epoch - 1) + '.pth.tar') if os.path.exists(prev_checkpoint_filename): os.remove(prev_checkpoint_filename) def save_model(self): with open(str(Path(self.output_folder) / "param.json"), 'w') as f: json.dump(vars(self.args), f) with open(str(Path(self.output_folder) / "model.txt"), 'w') as f: f.write(str(self.model)) # ---------------------------------------------- Epoch ------------------------------------------------------------------ def train_epoch(nn_model, epoch): nn_model.args.epoch = epoch print( f"-{datetime.datetime.now().strftime('%H:%M:%S')} Epoch [{epoch}] lr={nn_model.optimizer.param_groups[0]['lr']:.1e}") # ------------ switch to train mode ------------------- nn_model.model.train() loss_total = torch.tensor([0.0]) angle_loss_avg = torch.tensor([0.0]) angle_loss_avg_light = torch.tensor([0.0]) angle_loss_sharp_total = torch.tensor([0.0]) for i, (input, target, train_idx) in enumerate(nn_model.train_loader): # put input and target to device input, target = input.to(nn_model.device), target.to(nn_model.device) # Wait for all kernels to finish torch.cuda.synchronize() # Clear the gradients nn_model.optimizer.zero_grad() # Forward pass out = nn_model.model(input) # Compute the loss loss = nn_model.loss(out, target, nn_model.args) # Backward pass loss.backward() # Update the parameters nn_model.optimizer.step() # gpu_time = time.time() - start loss_total += loss.detach().to('cpu') if not nn_model.args.fast_train: if nn_model.args.angle_loss: angle_loss_avg = mu.eval_angle_tensor(out[:, :3, :, :], target[:, :3, :, :]) # angle_loss_avg_light = mu.eval_albedo_tensor(out[:, 3, :, :], target[:, 3, :, :]) # angle_loss_total += mu.output_radians_loss(out[:, :3, :, :], target[:, :3, :, :]).to('cpu').detach().numpy() # visualisation if i == 0: # print statistics np.set_printoptions(precision=5) torch.set_printoptions(sci_mode=True, precision=3) input, out, target, train_idx = input.to("cpu"), out.to("cpu"), target.to("cpu"), train_idx.to('cpu') loss_0th = loss / int(nn_model.args.batch_size) print(f"\t loss: {loss_0th:.2e}\t axis: {epoch % 3}") # evaluation if epoch % nn_model.args.print_freq == nn_model.args.print_freq - 1: for j, (input, target, test_idx) in enumerate(nn_model.test_loader): with torch.no_grad(): # put input and target to device input, target = input.to(nn_model.device), target.to(nn_model.device) # Wait for all kernels to finish torch.cuda.synchronize() # Forward pass out = nn_model.model(input) input, out, target, test_idx = input.to("cpu"), out.to("cpu"), target.to("cpu"), test_idx.to( 'cpu') draw_output(nn_model.args.exp, input, out, target=target, exp_path=nn_model.output_folder, epoch=epoch, i=j, train_idx=test_idx, prefix=f"eval_epoch_{epoch}_{test_idx}_") # save loss loss_avg = loss_total / len(nn_model.train_loader.dataset) nn_model.losses[epoch % 3, epoch] = loss_avg if not nn_model.args.fast_train: if nn_model.args.angle_loss: angle_loss_avg = angle_loss_avg.to("cpu") angle_loss_avg_light = angle_loss_avg_light.to("cpu") nn_model.angle_losses[0, epoch] = angle_loss_avg nn_model.angle_losses_light[0, epoch] = angle_loss_avg_light if nn_model.args.exp == "degares": angle_loss_sharp_avg = angle_loss_sharp_total / len(nn_model.train_loader.dataset) nn_model.angle_sharp_losses[0, epoch] = angle_loss_sharp_avg # indicate for best model saving if nn_model.best_loss > loss_avg: nn_model.best_loss = loss_avg print(f'best loss updated to {float(loss_avg):.8e}') is_best = True else: is_best = False # draw line chart if epoch % 10 == 9: draw_line_chart(np.array([nn_model.losses[0]]), nn_model.output_folder, log_y=True, label=0, epoch=epoch, start_epoch=nn_model.start_epoch) draw_line_chart(np.array([nn_model.losses[1]]), nn_model.output_folder, log_y=True, label=1, epoch=epoch, start_epoch=nn_model.start_epoch) draw_line_chart(np.array([nn_model.losses[2]]), nn_model.output_folder, log_y=True, label=2, epoch=epoch, start_epoch=nn_model.start_epoch, cla_leg=True, title="Loss") if nn_model.args.angle_loss: draw_line_chart(np.array([nn_model.angle_losses[0]]), nn_model.output_folder, log_y=True, label="normal", epoch=epoch, start_epoch=nn_model.start_epoch, loss_type="angle") draw_line_chart(np.array([nn_model.angle_losses_light[0]]), nn_model.output_folder, log_y=True, label="albedo", epoch=epoch, start_epoch=nn_model.start_epoch, loss_type="angle", cla_leg=True) return is_best def train_fugrc(nn_model, epoch, loss_network): nn_model.args.epoch = epoch print( f"-{datetime.datetime.now().strftime('%H:%M:%S')} Epoch [{epoch}] lr={nn_model.optimizer.param_groups[0]['lr']:.1e}") # ------------ switch to train mode ------------------- nn_model.model.train() loss_logs = {'content_loss': [], 'style_loss': [], 'tv_loss': [], 'total_loss': []} # loss network # loss_network = None for i, (input, target, train_idx) in enumerate(nn_model.train_loader): # put input and target to device input, target = input[:, :3, :, :].to(nn_model.device), target[:, :3, :, :].to(nn_model.device) # Wait for all kernels to finish torch.cuda.synchronize() # Clear the gradients nn_model.optimizer.zero_grad() # Forward pass out = nn_model.model(input) if nn_model.args.loss == "perceptual_loss": target_content_features = extract_features(loss_network, input, nn_model.args.content_layers) target_style_features = extract_features(loss_network, target, nn_model.args.style_layers) output_content_features = extract_features(loss_network, out, nn_model.args.content_layers) output_style_features = extract_features(loss_network, out, nn_model.args.style_layers) # Compute the loss content_loss = calc_Content_Loss(output_content_features, target_content_features) style_loss = calc_Gram_Loss(output_style_features, target_style_features) tv_loss = calc_TV_Loss(out) loss = content_loss * nn_model.args.content_weight + style_loss * nn_model.args.style_weight + tv_loss * nn_model.args.tv_weight loss_logs['content_loss'].append(float(content_loss)) loss_logs['style_loss'].append(float(style_loss)) loss_logs['tv_loss'].append(tv_loss.item()) loss_logs['total_loss'].append(loss.item()) else: loss = nn_model.loss(out, target, nn_model.args) loss_logs['total_loss'].append(float(loss)) # print(f"loss: {loss}") # Backward pass loss.backward() # Update the parameters nn_model.optimizer.step() # print statistics np.set_printoptions(precision=5) torch.set_printoptions(sci_mode=True, precision=3) # evaluation if epoch % nn_model.args.print_freq == nn_model.args.print_freq - 1: for j, (input, target, test_idx) in enumerate(nn_model.test_loader): with torch.no_grad(): # put input and target to device input, target = input.to(nn_model.device), target.to(nn_model.device) # Wait for all kernels to finish torch.cuda.synchronize() # Forward pass out = nn_model.model(input) input, out, target, test_idx = input.to("cpu"), out.to("cpu"), target.to("cpu"), test_idx.to( 'cpu') draw_output(nn_model.args.exp, input, out, target=target, exp_path=nn_model.output_folder, epoch=epoch, i=j, train_idx=test_idx, prefix=f"eval_epoch_{epoch}_{test_idx}_") # save loss nn_model.losses[0, epoch] = (np.sum(loss_logs['total_loss']) / len(nn_model.train_loader.dataset)) nn_model.losses[1, epoch] = (np.sum(loss_logs['content_loss']) / len(nn_model.train_loader.dataset)) nn_model.losses[2, epoch] = (np.sum(loss_logs['style_loss']) / len(nn_model.train_loader.dataset)) # indicate for best model saving if nn_model.best_loss > nn_model.losses[0, epoch]: nn_model.best_loss = nn_model.losses[0, epoch] print(f'best loss updated to {nn_model.losses[0, epoch]}.') is_best = True else: is_best = False # draw line chart if epoch % 10 == 9: draw_line_chart(np.array([nn_model.losses[0]]), nn_model.output_folder, log_y=True, label=0, epoch=epoch, start_epoch=nn_model.start_epoch) draw_line_chart(np.array([nn_model.losses[0]]), nn_model.output_folder, log_y=True, label=0, epoch=epoch, start_epoch=nn_model.start_epoch) draw_line_chart(np.array([nn_model.losses[0]]), nn_model.output_folder, log_y=True, label=0, epoch=epoch, start_epoch=nn_model.start_epoch, cla_leg=True, title="Loss") return is_best # ---------------------------------------------- visualisation ------------------------------------------- def draw_line_chart(data_1, path, title=None, x_label=None, y_label=None, show=False, log_y=False, label=None, epoch=None, cla_leg=False, start_epoch=0, loss_type="mse"): if data_1.shape[1] <= 1: return x = np.arange(epoch - start_epoch) y = data_1[0, start_epoch:epoch] x = x[y.nonzero()] y = y[y.nonzero()] plt.plot(x, y, label=label) if title is not None: plt.title(title) if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel(y_label) if log_y: plt.yscale('log') plt.legend() plt.grid(True) if not os.path.exists(str(path)): os.mkdir(path) if loss_type == "mse": plt.savefig(str(Path(path) / f"line_{title}_{x_label}_{y_label}_{date_now}_{time_now}.png")) elif loss_type == "angle": plt.savefig(str(Path(path) / f"line_{title}_{x_label}_{y_label}_{date_now}_{time_now}_angle.png")) else: raise ValueError("loss type is not supported.") if show: plt.show() if cla_leg: plt.cla() def draw_output(exp_name, x0, xout, target, exp_path, epoch, i, train_idx, prefix): target_normal = target[0, :].permute(1, 2, 0)[:, :, :3].detach().numpy() # xout_light = xout[0, :].permute(1, 2, 0)[:, :, 3:6].detach().numpy() # xout_scaleProd = xout[0, :].permute(1, 2, 0)[:, :, 6].detach().numpy() # xout_light = xout[0, :].permute(1, 2, 0)[:, :, 3:6].detach().numpy() target_img = target[0, :].permute(1, 2, 0)[:, :, 4].detach().numpy() target_light = target[0, :].permute(1, 2, 0)[:, :, 5:8].detach().numpy() xout_normal = xout[0, :].permute(1, 2, 0)[:, :, :3].detach().numpy() if exp_name == "ag": xout_light = xout[0, :].permute(1, 2, 0)[:, :, 3:6].detach().numpy() xout_scaleProd = xout[0, :].permute(1, 2, 0)[:, :, 6].detach().numpy() # if xout.size() != (512, 512, 3): # if cout is not None: # cout = xout[0, :].permute(1, 2, 0)[:, :, 3:6] # x1 = xout[0, :].permute(1, 2, 0)[:, :, 6:9] # else: # x1 = None output_list = [] # input normal input = x0[:1, :3, :, :].permute(2, 3, 1, 0).squeeze(-1).detach().numpy() x0_normalized_8bit = mu.normalize2_32bit(input) mu.addText(x0_normalized_8bit, "Input(Vertex)") mu.addText(x0_normalized_8bit,
""" Trie based Entity Matcher, for Exact matching of Normalized text. Ref: https://github.com/google/pygtrie """ import dataclasses from datetime import datetime import os from pathlib import Path from typing import Dict, Iterable, List, NamedTuple, Optional, Sequence, Set, Tuple import pygtrie import numpy as np from ontomatch.utils.misc import get_set_element from .nttmatcher import NameMatch, EntityMatcher from .tokenizer import BasicRevMappedTokenizer, Token, NormalizationType # ----------------------------------------------------------------------------- # Classes # ----------------------------------------------------------------------------- class NameEntry(NamedTuple): """ Trie maps each normalized-name to a Set[NameEntry] """ entity_id: str name_type: str name_tier: int name_index: int # / class OriginalName(NamedTuple): entity_id: str name: str name_type: str # / @dataclasses.dataclass(frozen=True) class NameMatchImpl(NameMatch): # Used in sorting matches name_tier: int # Index into token-seq on which matches are computed start_idx: int # Length of matching key, in nbr tokens. So match is for token-seq[start_idx : start_idx + key_length] key_length: int @staticmethod def from_name_entry(name_entry: NameEntry, start_idx: int, key_length: int, char_start: int, char_end: int): return NameMatchImpl(entity_id=name_entry.entity_id, name_type=name_entry.name_type, name_tier=name_entry.name_tier, name_index=name_entry.name_index, start_idx=start_idx, key_length=key_length, char_start=char_start, char_end=char_end ) # / class TrieMatchHelper: """ Exact matcher on Normalized Names, functioning as a Mapping: Key: Sequence[str] = a normalized tokenized name Value: Set[NameEntry] """ ROUND_NBR_DECIMALS = 3 def __init__(self, name: str, min_name_length: int = 1, stop_names: List[List[str]] = None): """ :param name: Name of this `TrieMatchHelper` :param min_name_length: Single-token names with length less than this are rejected :param stop_names: List of tokenized-and-normalized names that are considered invalid names (and skipped) """ self.name = name self.min_name_length = min_name_length # Convert List to Tuple for use in Set self.stop_names = set(tuple(nm) for nm in stop_names) if stop_names else set() # Each entry is List[normalized-token] self.normalized_names: List[List[str]] = [] # Used to retrieve the original Entity Names that all map to the same normalized-name. # original_names[i] = Set of OriginalName's, from `self.add_name()`, # that normalized to `self.normalized_names[i]` self.original_names: List[Set[OriginalName]] = [] # List[str] => Set[NameEntry] self.trie = pygtrie.Trie() return def add_name(self, entity_id: str, original_name: str, normalized_name: List[str], name_type: str, name_tier: int): """ Add a name for entity `entity_id`. :param entity_id: Unique id for this entity :param original_name: The original name being added :param normalized_name: The normalized name, corresponding to the `original_name`, being added :param name_type: One of the Name-Types as specified in `EntityMatcher.name_type_params` :param name_tier: Specifies the priority tier for matching this name The `normalized_name` is rejected if: - It is a single token, and its length < `self.min_name_length` - It matches one of the stop-names :returns: -1 if rejected, Else: Index (>= 0) at which this name is added. This index corresponds to the `NameMatch.name_index` in a match, and can be used in the following methods to retrieve the names: `self.get_original_names()`, `self.get_normalized_name()`, `self.get_names()` """ entity_id = entity_id.strip() original_name = original_name.strip() if not entity_id or not original_name: return -1 if len(normalized_name) == 1: if len(normalized_name[0]) < self.min_name_length: return -1 elif tuple(normalized_name) in self.stop_names: return -1 kvalue = self.trie.get(normalized_name) if kvalue is None: kvalue = set() self.trie[normalized_name] = kvalue if kvalue: name_index = get_set_element(kvalue).name_index self.original_names[name_index].add(OriginalName(entity_id, original_name, name_type)) else: name_index = len(self.normalized_names) self.normalized_names.append(normalized_name) self.original_names.append({OriginalName(entity_id, original_name, name_type)}) kvalue.add(NameEntry(entity_id, name_type, name_tier, name_index)) return name_index def nbr_keys(self): return len(self.original_names) def get_all_entity_ids(self, name_type: Optional[str] = None) -> Set[str]: return set([orig_name_.entity_id for orig_names in self.original_names for orig_name_ in orig_names if name_type is None or orig_name_.name_type == name_type]) def get_original_names(self, name_index: int) -> Set[OriginalName]: return self.original_names[name_index] def get_normalized_name(self, name_index: int) -> str: return " ".join(self.normalized_names[name_index]) def get_names(self, name_indices: Iterable[int]) -> Tuple[Set[OriginalName], Set[str]]: if name_indices is None: name_indices = [] orig_names, norm_names = set(), set() for name_index in name_indices: orig_names |= self.get_original_names(name_index) norm_names.add(self.get_normalized_name(name_index)) return orig_names, norm_names def get_full_matches(self, mention_tkns: List[Token]) -> Set[NameMatchImpl]: mention = [t.text for t in mention_tkns] name_entries = self.trie.get(mention, set()) m_char_start = mention_tkns[0].char_start m_char_end = mention_tkns[-1].char_end return set([NameMatchImpl.from_name_entry(ne, 0, len(mention), m_char_start, m_char_end) for ne in name_entries]) def get_all_sub_matches(self, mention_tkns: List[Token]) -> Set[NameMatchImpl]: """ Match all sub-sequences of `tokens`. """ tokens = [t.text for t in mention_tkns] name_matches = set() for s in range(len(tokens)): for key, name_ent_set in self.trie.prefixes(tokens[s:]): m_char_start = mention_tkns[s].char_start m_char_end = mention_tkns[s + len(key) - 1].char_end name_matches.update(NameMatchImpl.from_name_entry(ne, s, len(key), m_char_start, m_char_end) for ne in name_ent_set) return name_matches def get_prefix_matches(self, mention_tkns: List[Token]) -> Set[NameMatchImpl]: """ Matches to all prefixes of `tokens`. """ tokens = [t.text for t in mention_tkns] name_matches = set() s = 0 for key, name_ent_set in self.trie.prefixes(tokens): m_char_start = mention_tkns[s].char_start m_char_end = mention_tkns[s + len(key) - 1].char_end name_matches.update(NameMatchImpl.from_name_entry(ne, s, len(key), m_char_start, m_char_end) for ne in name_ent_set) return name_matches @staticmethod def sorted_matches(name_matches: Set[NameMatchImpl]) -> List[NameMatchImpl]: """ Sort on: (name-tier [ascending], key_length [descending], start_token_index [asc.], entity_id [asc.]), ... where: key_length = Nbr. normalized tokens that matched (i.e. prefer longer matches) entity_id used in case multiple entities have the same normalized name """ if not name_matches: return [] # For indexing at the end name_matches = list(name_matches) # Assemble for Compound Sort ... include enough keys to make sort deterministic names_in_order = ["tier", "key_length", "start_idx", "entity_id"] match_scores = np.core.records.fromrecords([(nm.name_tier, -nm.key_length, nm.start_idx, nm.entity_id) for nm in name_matches], names=names_in_order) # Use "mergesort" for stable sort sorted_idxs = np.argsort(match_scores, kind="mergesort", order=names_in_order) return [name_matches[i] for i in sorted_idxs] # / class TrieMatcher(EntityMatcher): EXAMPLE_PARAMS = { # Required. Specifies sub-class of EntityMatcher to create. "class": "TrieMatcher", # Give it a meaningful name "name": "Default Matcher", # Brief description "descr": "Matcher with default parameters", # Identifies where the entities and their names are from "lexicon_id": "EDAM Imaging sub-Ontology", # Parameters used to instantiate `BasicRevMappedTokenizer`. Default is `None`. # (see class `ontomatch.text.tokenizer.BasicRevMappedTokenizer` for default parameters) "tokenizer": { "char_standardization": "UNIDECODE" }, # Any single-token Entity Names whose length is less than this value will be ignored. # Default is 2. "min_name_length": 2, # Entity names that match any of these (after corresponding normalization) are ignored. # Default is no stop-names. # Example: # Based on the "name_types" below, an entry of "Ms" will result in # - "primary", "synonym" and "partial" names that are normalized to "ms" being ignored # - "acronym" name "Ms" will be ignored, but not "MS" or "ms". "stop_names": ["as", "The"], # How to match the different types of names: # NameType [str] => [Dict] # {"tier": [int > 0] Match tier, # "normalization": [str] A name of one of the members of `tokenizer.NormalizationType` # } "name_types": { # An entry for "primary" is required, but the value can be customized. # This NameType is used for each entity's Primary-Name. "primary": {"tier": 1, "normalization": "LOWER"}, # Other NameTypes ... "acronym": {"tier": 2, "normalization": "STANDARD"}, "synonym": {"tier": 3, "normalization": "LOWER"}, "partial": {"tier": 4, "normalization": "LOWER"}, } } def __init__(self, *args, **kwargs): """ Args: Same as for `EntityMatcher`, plus: Additional Parameters for TrieMatcher: ------------------------------------- tokenizer: Dict[str, ...] These are the parameters used to instantiate `BasicRevMappedTokenizer`. Default is `None`, meaning the defaults for class `ontomatch.text.tokenizer.BasicRevMappedTokenizer`. """ super().__init__(*args, **kwargs) # --- Local fields self.tknzr = BasicRevMappedTokenizer(self.params.get("tokenizer")) # --- Fields populated by build / load # Separate match-helper for each style of normalization self.match_helpers: Dict[NormalizationType, TrieMatchHelper] = \ {norm_type: TrieMatchHelper(norm_type.value, min_name_length=self.min_name_length, stop_names=[self.tknzr.normalized_tokens(name_, normalization_type=norm_type) for name_ in self.stop_names]) for norm_type in NormalizationType } return def matches_loaded_obj(self, loaded_obj: "TrieMatcher") -> bool: return super().matches_loaded_obj(loaded_obj) def add_entity(self, entity_id: str, primary_name: str, synonyms: Sequence[str], acronyms: Sequence[str], partial_names: Sequence[str] = None): """ Convenience method, using the name-types as defined in `EXAMPLE_PARAMS` """ # Remove primary_name from synonyms if using same normalization primary_norm_type = self.name_type_params[self.NAME_TYPE_PRIMARY]["normalization"] if "synonym" in self.name_type_params \ and self.name_type_params["synonym"]["normalization"] == primary_norm_type: normlzd_primary = self.tknzr.normalize(primary_name, normalization_type=primary_norm_type) synonyms = [syn for syn in synonyms if self.tknzr.normalize(syn, normalization_type=primary_norm_type) != normlzd_primary] self.add_entity_with_names(entity_id, primary_name, dict(synonym=synonyms, acronym=acronyms, partial=partial_names)) return def _add_names_for_entity(self, entity_id: str, name_type: str, names: Sequence[str]): tkn_norm_type, name_tier, match_helper = self._get_params_and_match_helper(name_type) syn_idxs = set() for name_ in names: idx = match_helper.add_name(entity_id, name_, self.tknzr.normalized_tokens(name_, normalization_type=tkn_norm_type), name_type, name_tier) if idx >= 0: syn_idxs.add(idx) self.entity_info[entity_id].name_indices[name_type].update(syn_idxs) return def _get_params_and_match_helper(self, name_type: str): try: name_type_params = self.name_type_params[name_type] except KeyError: raise KeyError(f"name_type = '{name_type}' not defined for this {self.__class__.__name__} instance") # noinspection PyTypeChecker tkn_norm_type: NormalizationType = name_type_params["normalization"] name_tier = name_type_params["tier"] match_helper = self.match_helpers[tkn_norm_type] return tkn_norm_type, name_tier, match_helper def compile(self): # Nothing to do self.is_compiled = True return def compile_and_save(self): assert self.cache_file is not None, "`cache_file` path not provided!" print(' Data will be
<reponame>Konstantin-Bogdanoski/VI from Python_neinformirano_prebaruvanje_final import * # Check if the white Rook is in a valid position (not in the line of fire of all the black Rooks) def validityOfWhite(gun, A): #print("TESTING WHITE VALIDITY") # print(gun) location = gun #print(location[0] != A[4][0] and location[0] != A[5][0] and location[0] != A[6][0] and location[0] != A[7][0] and # location[1] != A[4][1] and location[1] != A[5][1] and location[1] != A[6][1] and location[1] != A[7][1] and # location[0] < 6 and location[0] > 0 and location[1] > 0 and location[1] < 8) return (location[0] != A[4][0] and location[0] != A[5][0] and location[0] != A[6][0] and location[0] != A[7][0] and location[1] != A[4][1] and location[1] != A[5][1] and location[1] != A[6][1] and location[1] != A[7][1] and location[0] < 6 and location[0] > 0 and location[1] > 0 and location[1] < 8) # Check if the black Rook is in a valid position (not in the line of fire of all the white Rooks) def validityOfBlack(gun, A): #print("TESTING BLACK VALIDITY") # print(gun) location = gun #print(location[0] != A[0][0] and location[0] != A[1][0] and location[0] != A[2][0] and location[0] != A[3][0] and # location[1] != A[0][1] and location[1] != A[1][1] and location[1] != A[2][1] and location[1] != A[3][1] and # location[0] < 6 and location[0] > 0 and location[1] > 0 and location[1] < 8) return (location[0] != A[0][0] and location[0] != A[1][0] and location[0] != A[2][0] and location[0] != A[3][0] and location[1] != A[0][1] and location[1] != A[1][1] and location[1] != A[2][1] and location[1] != A[3][1] and location[0] < 6 and location[0] > 0 and location[1] > 0 and location[1] < 8) # Check if the white rooks are not on top of each other def validityWhiteOnWhite(A): #print("TESTING WHITEonWHITE") #print(A[0][0] != A[1][0] and A[0][0] != A[2][0] and A[0][0] != A[3][0] and # A[1][0] != A[2][0] and A[1][0] != A[3][0] and # A[2][0] != A[3][0] and # A[0][1] != A[1][1] and A[0][1] != A[2][1] and A[0][1] != A[3][1] and # A[1][1] != A[2][1] and A[1][1] != A[3][1] and # A[2][1] != A[3][1]) return (A[0][0] != A[1][0] and A[0][0] != A[2][0] and A[0][0] != A[3][0] and A[1][0] != A[2][0] and A[1][0] != A[3][0] and A[2][0] != A[3][0] and A[0][1] != A[1][1] and A[0][1] != A[2][1] and A[0][1] != A[3][1] and A[1][1] != A[2][1] and A[1][1] != A[3][1] and A[2][1] != A[3][1]) # Check if the black rooks are not on top of each other def validityBlackOnBlack(A): #print("TESTING BLACKonBLACK") #print(A[0][0] != A[1][0] and A[0][0] != A[2][0] and A[0][0] != A[3][0] and # A[1][0] != A[2][0] and A[1][0] != A[3][0] and # A[2][0] != A[3][0] and # A[0][1] != A[1][1] and A[0][1] != A[2][1] and A[0][1] != A[3][1] and # A[1][1] != A[2][1] and A[1][1] != A[3][1] and # A[2][1] != A[3][1]) return (A[4][0] != A[5][0] and A[4][0] != A[6][0] and A[4][0] != A[7][0] and A[5][0] != A[6][0] and A[5][0] != A[7][0] and A[6][0] != A[7][0] and A[4][1] != A[5][1] and A[4][1] != A[6][1] and A[4][1] != A[7][1] and A[5][1] != A[6][1] and A[5][1] != A[7][1] and A[6][1] != A[7][1]) class Rooks(Problem): def __init__(self, initial): self.initial = initial def goal_test(self, state): return ((state[0] == (5,8) or state[0] == (5,7) or state[0] == (5,6) or state[0] == (5,5)) and (state[1] == (5, 8) or state[1] == (5, 7) or state[1] == (5, 6) or state[1] == (5, 5)) and (state[2] == (5, 8) or state[2] == (5, 7) or state[2] == (5, 6) or state[2] == (5, 5)) and (state[3] == (5, 8) or state[3] == (5, 7) or state[3] == (5, 6) or state[3] == (5, 5)) and (state[4] == (1, 1) or state[4] == (1, 2) or state[4] == (1, 3) or state[4] == (1, 4)) and (state[5] == (1, 1) or state[5] == (1, 2) or state[5] == (1, 3) or state[5] == (1, 4)) and (state[6] == (1, 1) or state[6] == (1, 2) or state[6] == (1, 3) or state[6] == (1, 4)) and (state[7] == (1, 1) or state[7] == (1, 2) or state[7] == (1, 3) or state[7] == (1, 4))) def actions(self, state): return self.successor(state).keys() def result(self, state, action): possible = self.successor(state) return possible[action] def successor(self, state): successors = dict() WhiteRook1 = state[0] WhiteRook2 = state[1] WhiteRook3 = state[2] WhiteRook4 = state[3] BlackRook1 = state[4] BlackRook2 = state[5] BlackRook3 = state[6] BlackRook4 = state[7] # # # # WHITE ROOK 1 # # # # WhiteRook1 UP newWhiteRook1 = WhiteRook1 moves=0 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while(not(validityOfWhite(newWhiteRook1, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook1 = (newWhiteRook1[0], newWhiteRook1[1] - 1) moves+=1 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook1 = (newWhiteRook1[0], newWhiteRook1[1] + 1) stateNew = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook1 - UP: ' + str(moves)] = stateNew # WhiteRook1 DOWN newWhiteRook1 = WhiteRook1 moves = 0 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook1, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook1 = (newWhiteRook1[0], newWhiteRook1[1] + 1) moves += 1 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook1 = (newWhiteRook1[0], newWhiteRook1[1] - 1) stateNew = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook1 - DOWN: ' + str(moves)] = stateNew # WhiteRook1 LEFT newWhiteRook1 = WhiteRook1 moves = 0 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook1, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook1 = (newWhiteRook1[0] - 1, newWhiteRook1[1]) moves += 1 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook1 = (newWhiteRook1[0] + 1, newWhiteRook1[1]) stateNew = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook1 - LEFT: ' + str(moves)] = stateNew # WhiteRook1 RIGHT newWhiteRook1 = WhiteRook1 moves = 0 tempState = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook1, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook1 = (newWhiteRook1[0] + 1, newWhiteRook1[1]) moves += 1 tempState = ( newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook1 = (newWhiteRook1[0] - 1, newWhiteRook1[1]) stateNew = (newWhiteRook1, WhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook1 - RIGHT: ' + str(moves)] = stateNew # # # # # WHITE ROOK 2 # # # # WhiteRook2 UP newWhiteRook2 = WhiteRook2 moves = 0 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook2, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook2 = (newWhiteRook2[0], newWhiteRook2[1] - 1) moves += 1 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook2 = (newWhiteRook2[0], newWhiteRook2[1] + 1) stateNew = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook2 - UP: ' + str(moves)] = stateNew # WhiteRook2 DOWN newWhiteRook2 = WhiteRook2 moves = 0 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook2, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook2 = (newWhiteRook2[0], newWhiteRook2[1] + 1) moves += 1 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook2 = (newWhiteRook2[0], newWhiteRook2[1] - 1) stateNew = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook2 - DOWN: ' + str(moves)] = stateNew # WhiteRook2 LEFT newWhiteRook2 = WhiteRook2 moves = 0 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook2, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook2 = (newWhiteRook2[0] - 1, newWhiteRook2[1]) moves += 1 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook2 = (newWhiteRook2[0] + 1, newWhiteRook2[1]) stateNew = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook2 - LEFT: ' + str(moves)] = stateNew # WhiteRook2 RIGHT newWhiteRook2 = WhiteRook2 moves = 0 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) while (not(validityOfWhite(newWhiteRook2, tempState)) and validityWhiteOnWhite(tempState) and validityBlackOnBlack(tempState)): newWhiteRook2 = (newWhiteRook2[0] + 1, newWhiteRook2[1]) moves += 1 tempState = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) newWhiteRook2 = (newWhiteRook2[0] - 1, newWhiteRook2[1]) stateNew = (WhiteRook1, newWhiteRook2, WhiteRook3, WhiteRook4, BlackRook1, BlackRook2, BlackRook3, BlackRook4) successors['WhiteRook2 - RIGHT: ' + str(moves)] = stateNew # # # # # WHITE ROOK 3 # # #
#! /usr/env/python """ This module attempts to "component-ify" GT's Fastscape stream power erosion. Created DEJH, March 2014. """ from __future__ import print_function import numpy import warnings from landlab import ModelParameterDictionary, Component from landlab.core.model_parameter_dictionary import MissingKeyError, \ ParameterValueError from landlab.utils.decorators import use_file_name_or_kwds from landlab.field.scalar_data_fields import FieldError from scipy.optimize import newton, fsolve UNDEFINED_INDEX = -1 class FastscapeEroder(Component): ''' This class uses the Braun-Willett Fastscape approach to calculate the amount of erosion at each node in a grid, following a stream power framework. This should allow it to be stable against larger timesteps than an explicit stream power scheme. Stream power erosion is implemented as:: E = K * (rainfall_intensity*A)**m * S**n - threshold_sp, if K * A**m * S**n > threshold_sp, and:: E = 0, if K * A**m * S**n <= threshold_sp. This module assumes you have already run :func:`landlab.components.flow_routing.route_flow_dn.FlowRouter.route_flow` in the same timestep. It looks for 'flow__upstream_node_order', 'flow__link_to_receiver_node', 'drainage_area', 'flow__receiver_node', and 'topographic__elevation' at the nodes in the grid. 'drainage_area' should be in area upstream, not volume (i.e., set runoff_rate=1.0 when calling FlowRouter.route_flow). The primary method of this class is :func:`run_one_step`. Construction:: FastscapeEroder(grid, K_sp=None, m_sp=0.5, n_sp=1., threshold_sp=0., rainfall_intensity=1.) Parameters ---------- grid : ModelGrid A grid. K_sp : float, array, or field name K in the stream power equation (units vary with other parameters). m_sp : float, optional m in the stream power equation (power on drainage area). n_sp : float, optional, ~ 0.5<n_sp<4. n in the stream power equation (power on slope). Performance will be VERY degraded if n < 1. threshold_sp : float, array, or field name The threshold stream power. rainfall_intensity : float; optional Modifying factor on drainage area to convert it to a true water volume flux in (m/time). i.e., E = K * (r_i*A)**m * S**n. For a time varying rainfall intensity, pass rainfall_intensity_if_used to `run_one_step`. For a spatially variable rainfall, use the StreamPowerEroder component. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> from landlab import CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY >>> from landlab.components import FlowRouter >>> mg = RasterModelGrid((5, 5), 10.) >>> z = np.array([7., 7., 7., 7., 7., ... 7., 5., 3.2, 6., 7., ... 7., 2., 3., 5., 7., ... 7., 1., 1.9, 4., 7., ... 7., 0., 7., 7., 7.]) >>> z = mg.add_field('node', 'topographic__elevation', z) >>> fr = FlowRouter(mg) >>> sp = FastscapeEroder(mg, K_sp=1.) >>> fr.run_one_step() >>> sp.run_one_step(dt=1.) >>> z # doctest: +NORMALIZE_WHITESPACE array([ 7. , 7. , 7. , 7. , 7. , 7. , 2.92996598, 2.02996598, 4.01498299, 7. , 7. , 0.85993197, 1.87743897, 3.28268321, 7. , 7. , 0.28989795, 0.85403051, 2.42701526, 7. , 7. , 0. , 7. , 7. , 7. ]) >>> mg2 = RasterModelGrid((3, 7), 1.) >>> z = np.array(mg2.node_x**2.) >>> z = mg2.add_field('node', 'topographic__elevation', z) >>> mg2.status_at_node[mg2.nodes_at_left_edge] = FIXED_VALUE_BOUNDARY >>> mg2.status_at_node[mg2.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg2.status_at_node[mg2.nodes_at_bottom_edge] = CLOSED_BOUNDARY >>> mg2.status_at_node[mg2.nodes_at_right_edge] = CLOSED_BOUNDARY >>> fr2 = FlowRouter(mg2) >>> sp2 = FastscapeEroder(mg2, K_sp=0.1, m_sp=0., n_sp=2., ... threshold_sp=2.) >>> fr2.run_one_step() >>> sp2.run_one_step(dt=10.) >>> z.reshape((3, 7))[1, :] # doctest: +NORMALIZE_WHITESPACE array([ 0. , 1. , 4. , 8.52493781, 13.29039716, 18.44367965, 36. ]) >>> mg3 = RasterModelGrid((3, 7), 1.) >>> z = np.array(mg3.node_x**2.) >>> z = mg3.add_field('node', 'topographic__elevation', z) >>> mg3.status_at_node[mg3.nodes_at_left_edge] = FIXED_VALUE_BOUNDARY >>> mg3.status_at_node[mg3.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg3.status_at_node[mg3.nodes_at_bottom_edge] = CLOSED_BOUNDARY >>> mg3.status_at_node[mg3.nodes_at_right_edge] = CLOSED_BOUNDARY >>> fr3 = FlowRouter(mg3) >>> K_field = mg3.ones('node') # K can be a field >>> sp3 = FastscapeEroder(mg3, K_sp=K_field, m_sp=1., n_sp=0.6, ... threshold_sp=mg3.node_x, ... rainfall_intensity=2.) >>> fr3.run_one_step() >>> sp3.run_one_step(1.) >>> z.reshape((3, 7))[1, :] # doctest: +NORMALIZE_WHITESPACE array([ 0. , 0.0647484 , 0.58634455, 2.67253503, 8.49212152, 20.92606987, 36. ]) >>> previous_z = z.copy() >>> sp3.run_one_step(1., rainfall_intensity_if_used=0.) >>> np.allclose(z, previous_z) True ''' _name = 'FastscapeEroder' _input_var_names = ( 'topographic__elevation', 'drainage_area', 'flow__link_to_receiver_node', 'flow__upstream_node_order', 'flow__receiver_node', ) _output_var_names = ( 'topographic__elevation', ) _var_units = { 'topographic__elevation': 'm', 'drainage_area': 'm**2', 'flow__link_to_receiver_node': '-', 'flow__upstream_node_order': '-', 'flow__receiver_node': '-', } _var_mapping = { 'topographic__elevation': 'node', 'drainage_area': 'node', 'flow__link_to_receiver_node': 'node', 'flow__upstream_node_order': 'node', 'flow__receiver_node': 'node', } _var_doc = { 'topographic__elevation': 'Land surface topographic elevation', 'drainage_area': "Upstream accumulated surface area contributing to the node's " "discharge", 'flow__link_to_receiver_node': 'ID of link downstream of each node, which carries the discharge', 'flow__upstream_node_order': 'Node array containing downstream-to-upstream ordered list of ' 'node IDs', 'flow__receiver_node': 'Node array of receivers (node that receives flow from current ' 'node)', } @use_file_name_or_kwds def __init__(self, grid, K_sp=None, m_sp=0.5, n_sp=1., threshold_sp=0., rainfall_intensity=1., **kwds): """ Initialize the Fastscape stream power component. Note: a timestep, dt, can no longer be supplied to this component through the input file. It must instead be passed directly to the run method. Parameters ---------- grid : ModelGrid A grid. K_sp : float, array, or field name K in the stream power equation (units vary with other parameters). m_sp : float, optional m in the stream power equation (power on drainage area). n_sp : float, optional n in the stream power equation (power on slope). rainfall intensity : float, array, or field name; optional Modifying factor on drainage area to convert it to a true water volume flux in (m/time). i.e., E = K * (r_i*A)**m * S**n """ self._grid = grid self.K = K_sp # overwritten below in special cases self.m = float(m_sp) self.n = float(n_sp) if type(threshold_sp) in (float, int): self.thresholds = float(threshold_sp) else: if type(threshold_sp) is str: self.thresholds = self.grid.at_node[threshold_sp] else: self.thresholds = threshold_sp assert self.thresholds.size == self.grid.number_of_nodes # make storage variables self.A_to_the_m = grid.zeros(at='node') self.alpha = grid.empty(at='node') self.alpha_by_flow_link_lengthtothenless1 = numpy.empty_like( self.alpha) try: self.grid._diagonal_links_at_node # calc number of diagonal links except AttributeError: pass # was not a raster if self.K is None: raise ValueError('K_sp must be set as a float, node array, or ' + 'field name. It was None.') # now handle the inputs that could be float, array or field name: # some support here for old-style inputs if type(K_sp) is str: if K_sp == 'array': self.K = None else: self.K = self._grid.at_node[K_sp] elif type(K_sp) in (float, int): # a float self.K = float(K_sp) elif len(K_sp) == self.grid.number_of_nodes: self.K = numpy.array(K_sp) else: raise TypeError('Supplied type of K_sp ' + 'was not recognised, or array was ' + 'not nnodes long!') if type(rainfall_intensity) is str: raise ValueError('This component can no longer handle ' + 'spatially variable rainfall. Use ' + 'StreamPowerEroder.') if rainfall_intensity == 'array': self._r_i = None else: self._r_i = self._grid.at_node[rainfall_intensity] elif type(rainfall_intensity) in (float, int): # a float self._r_i = float(rainfall_intensity) elif len(rainfall_intensity) == self.grid.number_of_nodes: raise ValueError('This component can no longer handle ' + 'spatially variable rainfall. Use ' + 'StreamPowerEroder.') self._r_i = numpy.array(rainfall_intensity) else: raise TypeError('Supplied type of rainfall_' + 'intensity was not recognised!') # We now forbid changing of the field name if 'value_field' in kwds.keys(): raise ValueError('This component can no longer support variable' + 'field names. Use "topographic__elevation".') def erode(self, grid_in, dt=None, K_if_used=None, flooded_nodes=None, rainfall_intensity_if_used=None): """ This method implements the stream power erosion, following the Braun- Willett (2013) implicit Fastscape algorithm. This should allow it to be stable against larger timesteps than an explicit stream power scheme. This driving method for this component is now superceded by the new, standardized wrapper :func:`run_one_step`, but is retained for back compatibility. Set 'K_if_used' as a field name or nnodes-long array if you set K_sp as 'array' during initialization. It returns the grid, in which it will have modified the value of *value_field*, as specified in component initialization. Parameters ---------- grid_in : a grid This is a dummy argument maintained for component back- compatibility. It is superceded by the copy of the grid passed during initialization. dt : float Time-step size. If you are calling the deprecated function :func:`gear_timestep`, that method will supercede any value supplied here. K_if_used : array (optional) Set this to an array if you set K_sp to 'array' in your input file. flooded_nodes : ndarray of int (optional) IDs of nodes that are flooded and should have no erosion. If not provided but flow has still been routed across depressions, erosion may still occur beneath the apparent water level (though
print("Error: ONTAP Rest API Error: ", err) try: if print_output: print("Deleting volume '" + svm+':'+volume_name + "'.") # Delete volume volume.delete(poll=True, poll_timeout=120) if print_output: print("Volume deleted successfully.") except NetAppRestError as err: if print_output: if "You must delete the SnapMirror relationships before" in str(err): print("Error: volume is snapmirror destination. add --delete-mirror to delete snapmirror relationship before deleting the volume") elif "the source endpoint of one or more SnapMirror relationships" in str(err): print("Error: volume is snapmirror source. add --delete-mirror to release snapmirror relationship before deleting the volume") else: print("Error: ONTAP Rest API Error: ", err) raise APIConnectionError(err) else: raise ConnectionTypeError() def list_cloud_sync_relationships(print_output: bool = False) -> list(): # Step 1: Obtain access token and account ID for accessing Cloud Sync API # Retrieve refresh token try: refreshToken = _retrieve_cloud_central_refresh_token(print_output=print_output) except InvalidConfigError: raise # Obtain access token and account ID try: accessToken, accountId = _get_cloud_sync_access_parameters(refreshToken=refreshToken, print_output=print_output) except APIConnectionError: raise # Step 2: Retrieve list of relationships # Define parameters for API call url = "https://cloudsync.netapp.com/api/relationships-v2" headers = { "Accept": "application/json", "x-account-id": accountId, "Authorization": "Bearer " + accessToken } # Call API to retrieve list of relationships response = requests.get(url = url, headers = headers) # Check for API response status code of 200; if not 200, raise error if response.status_code != 200: errorMessage = "Error calling Cloud Sync API to retrieve list of relationships." if print_output: print("Error:", errorMessage) _print_api_response(response) raise APIConnectionError(errorMessage, response) # Constrict list of relationships relationships = json.loads(response.text) relationshipsList = list() for relationship in relationships: relationshipDetails = dict() relationshipDetails["id"] = relationship["id"] relationshipDetails["source"] = relationship["source"] relationshipDetails["target"] = relationship["target"] relationshipsList.append(relationshipDetails) # Print list of relationships if print_output: print(yaml.dump(relationshipsList)) return relationshipsList def list_snap_mirror_relationships(print_output: bool = False, cluster_name: str = None) -> list(): # Retrieve config details from config file try: config = _retrieve_config(print_output=print_output) except InvalidConfigError: raise try: connectionType = config["connectionType"] except: if print_output: _print_invalid_config_error() raise InvalidConfigError() if cluster_name: config["hostname"] = cluster_name if connectionType == "ONTAP": # Instantiate connection to ONTAP cluster try: _instantiate_connection(config=config, connectionType=connectionType, print_output=print_output) except InvalidConfigError: raise try: # Retrieve all relationships for which destination is on current cluster destinationRelationships = NetAppSnapmirrorRelationship.get_collection() # Do not retrieve relationships for which source is on current cluster # Note: Uncomment below line to retrieve all relationships for which source is on current cluster, then add sourceRelationships to for loop # sourceRelationships = NetAppSnapmirrorRelationship.get_collection(list_destinations_only=True) # Construct list of relationships relationshipsList = list() for relationship in destinationRelationships: # Retrieve relationship details try: relationship.get() except NetAppRestError as err: relationship.get(list_destinations_only=True) # Set cluster value if hasattr(relationship.source, "cluster"): sourceCluster = relationship.source.cluster.name else: sourceCluster = "user's cluster" if hasattr(relationship.destination, "cluster"): destinationCluster = relationship.destination.cluster.name else: destinationCluster = "user's cluster" # Set transfer state value if hasattr(relationship, "transfer"): transferState = relationship.transfer.state else: transferState = None # Set healthy value if hasattr(relationship, "healthy"): healthy = relationship.healthy else: healthy = "unknown" # Construct dict containing relationship details relationshipDict = { "UUID": relationship.uuid, "Type": relationship.policy.type, "Healthy": healthy, "Current Transfer Status": transferState, "Source Cluster": sourceCluster, "Source SVM": relationship.source.svm.name, "Source Volume": relationship.source.path.split(":")[1], "Dest Cluster": destinationCluster, "Dest SVM": relationship.destination.svm.name, "Dest Volume": relationship.destination.path.split(":")[1] } # Append dict to list of relationships relationshipsList.append(relationshipDict) except NetAppRestError as err: if print_output: print("Error: ONTAP Rest API Error: ", err) raise APIConnectionError(err) # Print list of relationships if print_output: # Convert relationships array to Pandas DataFrame relationshipsDF = pd.DataFrame.from_dict(relationshipsList, dtype="string") print(tabulate(relationshipsDF, showindex=False, headers=relationshipsDF.columns)) return relationshipsList else: raise ConnectionTypeError() def list_snapshots(volume_name: str, cluster_name: str = None, svm_name: str = None, print_output: bool = False) -> list(): # Retrieve config details from config file try: config = _retrieve_config(print_output=print_output) except InvalidConfigError: raise try: connectionType = config["connectionType"] except: if print_output: _print_invalid_config_error() raise InvalidConfigError() if cluster_name: config["hostname"] = cluster_name if connectionType == "ONTAP": # Instantiate connection to ONTAP cluster try: _instantiate_connection(config=config, connectionType=connectionType, print_output=print_output) except InvalidConfigError: raise # Retrieve svm from config file try: svm = config["svm"] if svm_name: svm = svm_name except: if print_output: _print_invalid_config_error() raise InvalidConfigError() # Retrieve snapshots try: # Retrieve volume volume = NetAppVolume.find(name=volume_name, svm=svm) if not volume: if print_output: print("Error: Invalid volume name.") raise InvalidVolumeParameterError("name") # Construct list of snapshots snapshotsList = list() for snapshot in NetAppSnapshot.get_collection(volume.uuid): # Retrieve snapshot snapshot.get() # Construct dict of snapshot details snapshotDict = {"Snapshot Name": snapshot.name, "Create Time": snapshot.create_time} # Append dict to list of snapshots snapshotsList.append(snapshotDict) except NetAppRestError as err: if print_output: print("Error: ONTAP Rest API Error: ", err) raise APIConnectionError(err) # Print list of snapshots if print_output: # Convert snapshots array to Pandas DataFrame snapshotsDF = pd.DataFrame.from_dict(snapshotsList, dtype="string") print(tabulate(snapshotsDF, showindex=False, headers=snapshotsDF.columns)) return snapshotsList else: raise ConnectionTypeError() def list_volumes(check_local_mounts: bool = False, include_space_usage_details: bool = False, print_output: bool = False, cluster_name: str = None, svm_name: str = None) -> list(): # Retrieve config details from config file try: config = _retrieve_config(print_output=print_output) except InvalidConfigError: raise try: connectionType = config["connectionType"] except: if print_output : _print_invalid_config_error() raise InvalidConfigError() if cluster_name: config["hostname"] = cluster_name if connectionType == "ONTAP": # Instantiate connection to ONTAP cluster try: _instantiate_connection(config=config, connectionType=connectionType, print_output=print_output) except InvalidConfigError: raise try: svmname=config["svm"] if svm_name: svmname = svm_name # Retrieve all volumes for SVM volumes = NetAppVolume.get_collection(svm=svmname) # Retrieve local mounts if desired if check_local_mounts : mounts = subprocess.check_output(['mount']).decode() # Construct list of volumes; do not include SVM root volume volumesList = list() for volume in volumes: baseVolumeFields = "nas.path,size,style,clone,flexcache_endpoint_type" try : volumeFields = baseVolumeFields if include_space_usage_details : volumeFields += ",space,constituents" volume.get(fields=volumeFields) except NetAppRestError as err : volumeFields = baseVolumeFields if include_space_usage_details : volumeFields += ",space" volume.get(fields=volumeFields) # Retrieve volume export path; handle case where volume is not exported if hasattr(volume, "nas"): volumeExportPath = volume.nas.path else: volumeExportPath = None # Include all vols except for SVM root vol if volumeExportPath != "/": # Determine volume type type = volume.style # Construct NFS mount target if not volumeExportPath : nfsMountTarget = None else : nfsMountTarget = config["dataLif"]+":"+volume.nas.path if svmname != config["svm"]: nfsMountTarget = svmname+":"+volume.nas.path # Construct clone source clone = "no" cloneParentSvm = "" cloneParentVolume = "" cloneParentSnapshot = "" try: cloneParentSvm = volume.clone.parent_svm.name cloneParentVolume = volume.clone.parent_volume.name cloneParentSnapshot = volume.clone.parent_snapshot.name clone = "yes" except: pass # Determine if FlexCache if volume.flexcache_endpoint_type == "cache": flexcache = "yes" else: flexcache = "no" # Convert size in bytes to "pretty" size (size in KB, MB, GB, or TB) prettySize = _convert_bytes_to_pretty_size(size_in_bytes=volume.size) if include_space_usage_details : try : snapshotReserve = str(volume.space.snapshot.reserve_percent) + "%" logicalCapacity = float(volume.space.size) * (1 - float(volume.space.snapshot.reserve_percent)/100) prettyLogicalCapacity = _convert_bytes_to_pretty_size(size_in_bytes=logicalCapacity) logicalUsage = float(volume.space.used) prettyLogicalUsage = _convert_bytes_to_pretty_size(size_in_bytes=logicalUsage) except : snapshotReserve = "Unknown" prettyLogicalCapacity = "Unknown" prettyLogicalUsage = "Unknown" try : if type == "flexgroup" : totalFootprint: float = 0.0 for constituentVolume in volume.constituents : totalFootprint += float(constituentVolume["space"]["total_footprint"]) else : totalFootprint = float(volume.space.footprint) + float(volume.space.metadata) prettyFootprint = _convert_bytes_to_pretty_size(size_in_bytes=totalFootprint) except : prettyFootprint = "Unknown" # Construct dict containing volume details; optionally include local mountpoint volumeDict = { "Volume Name": volume.name, "Size": prettySize } if include_space_usage_details : volumeDict["Snap Reserve"] = snapshotReserve volumeDict["Capacity"] = prettyLogicalCapacity volumeDict["Usage"] = prettyLogicalUsage volumeDict["Footprint"] = prettyFootprint volumeDict["Type"] = volume.style volumeDict["NFS Mount Target"] = nfsMountTarget if check_local_mounts: localMountpoint = "" for mount in mounts.split("\n") : mountDetails = mount.split(" ") if mountDetails[0] == nfsMountTarget : localMountpoint = mountDetails[2] volumeDict["Local Mountpoint"] = localMountpoint volumeDict["FlexCache"] = flexcache volumeDict["Clone"] = clone volumeDict["Source SVM"] = cloneParentSvm volumeDict["Source Volume"] = cloneParentVolume volumeDict["Source Snapshot"] = cloneParentSnapshot # Append dict to list of volumes volumesList.append(volumeDict) except NetAppRestError as err: if print_output : print("Error: ONTAP Rest API Error: ", err) raise APIConnectionError(err) # Print list of volumes if print_output: # Convert volumes array to Pandas DataFrame volumesDF = pd.DataFrame.from_dict(volumesList, dtype="string") print(tabulate(volumesDF, showindex=False, headers=volumesDF.columns)) return volumesList else: raise ConnectionTypeError() def mount_volume(volume_name: str, mountpoint: str, cluster_name: str = None, svm_name: str = None, lif_name: str = None, readonly: bool = False, print_output: bool = False): nfsMountTarget = None svm = None try: config = _retrieve_config(print_output=print_output) except InvalidConfigError: raise try: svm = config["svm"] if svm_name: svm = svm_name except: if print_output: _print_invalid_config_error() raise InvalidConfigError() if cluster_name: config["hostname"] = cluster_name # Retrieve list of volumes
= getSet(modeChar) if action == '-': Set.discard(value) elif action == '+': Set.add(value) else: if action == '+': self.setMode(modeChar, value) else: assert action == '-' self.unsetMode(modeChar) def __getstate__(self): return [getattr(self, name) for name in self.__slots__] def __setstate__(self, t): for (name, value) in zip(self.__slots__, t): setattr(self, name, value) def __eq__(self, other): ret = True for name in self.__slots__: ret = ret and getattr(self, name) == getattr(other, name) return ret class IrcState(IrcCommandDispatcher): """Maintains state of the Irc connection. Should also become smarter. """ __metaclass__ = log.MetaFirewall __firewalled__ = {'addMsg': None} def __init__(self, history=None, supported=None, nicksToHostmasks=None, channels=None): if history is None: history = RingBuffer(conf.supybot.protocols.irc.maxHistoryLength()) if supported is None: supported = utils.InsensitivePreservingDict() if nicksToHostmasks is None: nicksToHostmasks = ircutils.IrcDict() if channels is None: channels = ircutils.IrcDict() self.supported = supported self.history = history self.channels = channels self.nicksToHostmasks = nicksToHostmasks def reset(self): """Resets the state to normal, unconnected state.""" self.history.reset() self.channels.clear() self.supported.clear() self.nicksToHostmasks.clear() self.history.resize(conf.supybot.protocols.irc.maxHistoryLength()) def __reduce__(self): return (self.__class__, (self.history, self.supported, self.nicksToHostmasks, self.channels)) def __eq__(self, other): return self.history == other.history and \ self.channels == other.channels and \ self.supported == other.supported and \ self.nicksToHostmasks == other.nicksToHostmasks def __ne__(self, other): return not self == other def copy(self): ret = self.__class__() ret.history = copy.deepcopy(self.history) ret.nicksToHostmasks = copy.deepcopy(self.nicksToHostmasks) ret.channels = copy.deepcopy(self.channels) return ret def addMsg(self, irc, msg): """Updates the state based on the irc object and the message.""" self.history.append(msg) if ircutils.isUserHostmask(msg.prefix) and not msg.command == 'NICK': self.nicksToHostmasks[msg.nick] = msg.prefix method = self.dispatchCommand(msg.command) if method is not None: method(irc, msg) def getTopic(self, channel): """Returns the topic for a given channel.""" return self.channels[channel].topic def nickToHostmask(self, nick): """Returns the hostmask for a given nick.""" return self.nicksToHostmasks[nick] _005converters = utils.InsensitivePreservingDict({ 'modes': int, 'keylen': int, 'nicklen': int, 'userlen': int, 'hostlen': int, 'kicklen': int, 'awaylen': int, 'silence': int, 'topiclen': int, 'channellen': int, 'maxtargets': int, 'maxnicklen': int, 'maxchannels': int, 'watch': int, # DynastyNet, EnterTheGame }) def _prefixParser(s): if ')' in s: (left, right) = s.split(')') assert left[0] == '(', 'Odd PREFIX in 005: %s' % s left = left[1:] assert len(left) == len(right), 'Odd PREFIX in 005: %s' % s return dict(zip(left, right)) else: return dict(zip('ovh', s)) _005converters['prefix'] = _prefixParser del _prefixParser def _maxlistParser(s): modes = '' limits = [] pairs = s.split(',') for pair in pairs: (mode, limit) = pair.split(':', 1) modes += mode limits += (int(limit),) * len(mode) return dict(zip(modes, limits)) _005converters['maxlist'] = _maxlistParser del _maxlistParser def _maxbansParser(s): # IRCd using a MAXLIST style string (IRCNet) if ':' in s: modes = '' limits = [] pairs = s.split(',') for pair in pairs: (mode, limit) = pair.split(':', 1) modes += mode limits += (int(limit),) * len(mode) d = dict(zip(modes, limits)) assert 'b' in d return d['b'] else: return int(s) _005converters['maxbans'] = _maxbansParser del _maxbansParser def do005(self, irc, msg): for arg in msg.args[1:-1]: # 0 is nick, -1 is "are supported" if '=' in arg: (name, value) = arg.split('=', 1) converter = self._005converters.get(name, lambda x: x) try: self.supported[name] = converter(value) except Exception, e: log.exception('Uncaught exception in 005 converter:') log.error('Name: %s, Converter: %s', name, converter) else: self.supported[arg] = None def do352(self, irc, msg): # WHO reply. (nick, user, host) = (msg.args[5], msg.args[2], msg.args[3]) hostmask = '%s!%s@%s' % (nick, user, host) self.nicksToHostmasks[nick] = hostmask def do353(self, irc, msg): # NAMES reply. (_, type, channel, names) = msg.args if channel not in self.channels: self.channels[channel] = ChannelState() c = self.channels[channel] for name in names.split(): c.addUser(name) if type == '@': c.modes['s'] = None def doJoin(self, irc, msg): for channel in msg.args[0].split(','): if channel in self.channels: self.channels[channel].addUser(msg.nick) elif msg.nick: # It must be us. chan = ChannelState() chan.addUser(msg.nick) self.channels[channel] = chan # I don't know why this assert was here. #assert msg.nick == irc.nick, msg def doMode(self, irc, msg): channel = msg.args[0] if ircutils.isChannel(channel): # There can be user modes, as well. try: chan = self.channels[channel] except KeyError: chan = ChannelState() self.channels[channel] = chan chan.doMode(msg) def do324(self, irc, msg): channel = msg.args[1] chan = self.channels[channel] for (mode, value) in ircutils.separateModes(msg.args[2:]): modeChar = mode[1] if mode[0] == '+' and mode[1] not in 'ovh': chan.setMode(modeChar, value) elif mode[0] == '-' and mode[1] not in 'ovh': chan.unsetMode(modeChar) def do329(self, irc, msg): # This is the last part of an empty mode. channel = msg.args[1] chan = self.channels[channel] chan.created = int(msg.args[2]) def doPart(self, irc, msg): for channel in msg.args[0].split(','): try: chan = self.channels[channel] except KeyError: continue if ircutils.strEqual(msg.nick, irc.nick): del self.channels[channel] else: chan.removeUser(msg.nick) def doKick(self, irc, msg): (channel, users) = msg.args[:2] chan = self.channels[channel] for user in users.split(','): if ircutils.strEqual(user, irc.nick): del self.channels[channel] return else: chan.removeUser(user) def doQuit(self, irc, msg): for channel in self.channels.itervalues(): channel.removeUser(msg.nick) if msg.nick in self.nicksToHostmasks: # If we're quitting, it may not be. del self.nicksToHostmasks[msg.nick] def doTopic(self, irc, msg): if len(msg.args) == 1: return # Empty TOPIC for information. Does not affect state. try: chan = self.channels[msg.args[0]] chan.topic = msg.args[1] except KeyError: pass # We don't have to be in a channel to send a TOPIC. def do332(self, irc, msg): chan = self.channels[msg.args[1]] chan.topic = msg.args[2] def doNick(self, irc, msg): newNick = msg.args[0] oldNick = msg.nick try: if msg.user and msg.host: # Nick messages being handed out from the bot itself won't # have the necessary prefix to make a hostmask. newHostmask = ircutils.joinHostmask(newNick,msg.user,msg.host) self.nicksToHostmasks[newNick] = newHostmask del self.nicksToHostmasks[oldNick] except KeyError: pass for channel in self.channels.itervalues(): channel.replaceUser(oldNick, newNick) ### # The basic class for handling a connection to an IRC server. Accepts # callbacks of the IrcCallback interface. Public attributes include 'driver', # 'queue', and 'state', in addition to the standard nick/user/ident attributes. ### _callbacks = [] class Irc(IrcCommandDispatcher): """The base class for an IRC connection. Handles PING commands already. """ __metaclass__ = log.MetaFirewall __firewalled__ = {'die': None, 'feedMsg': None, 'takeMsg': None,} _nickSetters = set(['001', '002', '003', '004', '250', '251', '252', '254', '255', '265', '266', '372', '375', '376', '333', '353', '332', '366', '005']) # We specifically want these callbacks to be common between all Ircs, # that's why we don't do the normal None default with a check. def __init__(self, network, callbacks=_callbacks): self.zombie = False world.ircs.append(self) self.network = network self.callbacks = callbacks self.state = IrcState() self.queue = IrcMsgQueue() self.fastqueue = smallqueue() self.driver = None # The driver should set this later. self._setNonResettingVariables() self._queueConnectMessages() self.startedSync = ircutils.IrcDict() def isChannel(self, s): """Helper function to check whether a given string is a channel on the network this Irc object is connected to.""" kw = {} if 'chantypes' in self.state.supported: kw['chantypes'] = self.state.supported['chantypes'] if 'channellen' in self.state.supported: kw['channellen'] = self.state.supported['channellen'] return ircutils.isChannel(s, **kw) def isNick(self, s): kw = {} if 'nicklen' in self.state.supported: kw['nicklen'] = self.state.supported['nicklen'] return ircutils.isNick(s, **kw) # This *isn't* threadsafe! def addCallback(self, callback): """Adds a callback to the callbacks list.""" assert not self.getCallback(callback.name()) self.callbacks.append(callback) # This is the new list we're building, which will be tsorted. cbs = [] # The vertices are self.callbacks itself. Now we make the edges. edges = set() for cb in self.callbacks: (before, after) = cb.callPrecedence(self) assert cb not in after, 'cb was in its own after.' assert cb not in before, 'cb was in its own before.' for otherCb in before: edges.add((otherCb, cb)) for otherCb in after: edges.add((cb, otherCb)) def getFirsts(): firsts = set(self.callbacks) - set(cbs) for (before, after) in edges: firsts.discard(after) return firsts firsts = getFirsts() while firsts: # Then we add these to our list of cbs, and remove all edges that # originate with these cbs. for cb in firsts: cbs.append(cb) edgesToRemove = [] for edge in edges: if edge[0] is cb: edgesToRemove.append(edge) for edge in edgesToRemove: edges.remove(edge) firsts = getFirsts() assert len(cbs) == len(self.callbacks), \ 'cbs: %s, self.callbacks: %s' % (cbs, self.callbacks) self.callbacks[:] = cbs def getCallback(self, name): """Gets a given callback by name.""" name = name.lower() for callback in self.callbacks: if callback.name().lower() == name: return callback else: return None def removeCallback(self, name): """Removes a callback from the callback list.""" name = name.lower() def nameMatches(cb): return cb.name().lower() == name (bad, good) = utils.iter.partition(nameMatches, self.callbacks) self.callbacks[:] = good return bad def queueMsg(self, msg): """Queues
<reponame>sjklipp/autochem_1219 """ test automol.graph """ import numpy import automol from automol import graph C8H13O_CGR = ( {0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None), 3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None), 6: ('C', 1, None), 7: ('C', 1, None), 8: ('O', 0, None)}, {frozenset({1, 4}): (1, None), frozenset({4, 6}): (1, None), frozenset({0, 3}): (1, None), frozenset({2, 6}): (1, None), frozenset({6, 7}): (1, None), frozenset({8, 7}): (1, None), frozenset({3, 5}): (1, None), frozenset({5, 7}): (1, None)}) C8H13O_RGR = ( {0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None), 3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None), 6: ('C', 1, None), 7: ('C', 1, None), 8: ('O', 0, None)}, {frozenset({1, 4}): (2, None), frozenset({4, 6}): (1, None), frozenset({0, 3}): (1, None), frozenset({2, 6}): (1, None), frozenset({6, 7}): (1, None), frozenset({8, 7}): (1, None), frozenset({3, 5}): (2, None), frozenset({5, 7}): (1, None)}) C8H13O_SGR = ( {0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None), 3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None), 6: ('C', 1, False), 7: ('C', 1, False), 8: ('O', 0, None)}, {frozenset({1, 4}): (1, None), frozenset({4, 6}): (1, None), frozenset({0, 3}): (1, None), frozenset({2, 6}): (1, None), frozenset({6, 7}): (1, None), frozenset({8, 7}): (1, None), frozenset({3, 5}): (1, False), frozenset({5, 7}): (1, None)}) C3H3_CGR = ( {0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None)}, {frozenset({0, 1}): (1, None), frozenset({1, 2}): (1, None), frozenset({2, 0}): (1, None)}) C3H3_RGRS = ( ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None)}, {frozenset({0, 1}): (1, None), frozenset({1, 2}): (1, None), frozenset({2, 0}): (1, None)}), ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None)}, {frozenset({0, 1}): (1, None), frozenset({1, 2}): (2, None), frozenset({2, 0}): (1, None)}), ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None)}, {frozenset({0, 1}): (1, None), frozenset({1, 2}): (1, None), frozenset({2, 0}): (2, None)}), ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None)}, {frozenset({0, 1}): (2, None), frozenset({1, 2}): (1, None), frozenset({2, 0}): (1, None)}), ) C2_CGR = ({0: ('C', 0, None), 1: ('C', 0, None)}, {frozenset({0, 1}): (1, None)}) C2_RGRS = ( ({0: ('C', 0, None), 1: ('C', 0, None)}, {frozenset({0, 1}): (1, None)}), ({0: ('C', 0, None), 1: ('C', 0, None)}, {frozenset({0, 1}): (2, None)}), ({0: ('C', 0, None), 1: ('C', 0, None)}, {frozenset({0, 1}): (3, None)}), ) CH2FH2H_CGR_IMP = ( {0: ('F', 0, None), 1: ('C', 2, None), 2: ('H', 1, None), 3: ('H', 0, None)}, {frozenset({0, 1}): (1, None)}) CH2FH2H_CGR_EXP = ( {0: ('F', 0, None), 1: ('C', 0, None), 2: ('H', 0, None), 3: ('H', 0, None), 4: ('H', 0, None), 5: ('H', 0, None), 6: ('H', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None), frozenset({2, 6}): (1, None)}) C2H2CL2F2_CGR = ( {0: ('C', 1, None), 1: ('C', 1, None), 2: ('F', 0, None), 3: ('Cl', 0, None), 4: ('F', 0, None), 5: ('Cl', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None)}) C2H2CL2F2_SGRS = ( ({0: ('C', 1, False), 1: ('C', 1, False), 2: ('F', 0, None), 3: ('Cl', 0, None), 4: ('F', 0, None), 5: ('Cl', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None)}), ({0: ('C', 1, False), 1: ('C', 1, True), 2: ('F', 0, None), 3: ('Cl', 0, None), 4: ('F', 0, None), 5: ('Cl', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None)}), ({0: ('C', 1, True), 1: ('C', 1, False), 2: ('F', 0, None), 3: ('Cl', 0, None), 4: ('F', 0, None), 5: ('Cl', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None)}), ({0: ('C', 1, True), 1: ('C', 1, True), 2: ('F', 0, None), 3: ('Cl', 0, None), 4: ('F', 0, None), 5: ('Cl', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({1, 4}): (1, None), frozenset({1, 5}): (1, None)}) ) C3H3CL2F3_CGR = ( {0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 1, None), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}) C3H3CL2F3_SGRS = ( ({0: ('C', 1, None), 1: ('C', 1, False), 2: ('C', 1, False), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ({0: ('C', 1, None), 1: ('C', 1, True), 2: ('C', 1, True), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ({0: ('C', 1, False), 1: ('C', 1, False), 2: ('C', 1, True), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ({0: ('C', 1, False), 1: ('C', 1, True), 2: ('C', 1, False), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ({0: ('C', 1, True), 1: ('C', 1, False), 2: ('C', 1, True), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ({0: ('C', 1, True), 1: ('C', 1, True), 2: ('C', 1, False), 3: ('Cl', 0, None), 4: ('Cl', 0, None), 5: ('F', 0, None), 6: ('F', 0, None), 7: ('F', 0, None)}, {frozenset({0, 1}): (1, None), frozenset({0, 2}): (1, None), frozenset({0, 5}): (1, None), frozenset({2, 4}): (1, None), frozenset({1, 3}): (1, None), frozenset({1, 6}): (1, None), frozenset({2, 7}): (1, None)}), ) C3H5N3_CGR = ( {0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 0, None), 3: ('N', 1, None), 4: ('N', 1, None), 5: ('N', 1, None)}, {frozenset({1, 4}): (1, None), frozenset({1, 2}): (1, None), frozenset({0, 3}): (1, None), frozenset({0, 2}): (1, None), frozenset({2, 5}): (1, None)}) C3H5N3_SGRS = ( ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 0, None), 3: ('N', 1, None), 4: ('N', 1, None), 5: ('N', 1, None)}, {frozenset({1, 4}): (1, False), frozenset({1, 2}): (1, None), frozenset({0, 3}): (1, False), frozenset({0, 2}): (1, None), frozenset({2, 5}): (1, None)}), ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 0, None), 3: ('N', 1, None), 4: ('N', 1, None), 5: ('N', 1, None)}, {frozenset({1, 4}): (1, True), frozenset({1, 2}): (1, None), frozenset({0, 3}): (1, False), frozenset({0, 2}): (1, None), frozenset({2, 5}): (1, False)}), ({0: ('C', 1, None), 1: ('C', 1, None), 2: ('C', 0, None), 3: ('N', 1, None), 4: ('N', 1, None), 5: ('N', 1, None)}, {frozenset({1, 4}): (1, True), frozenset({1, 2}): (1, None), frozenset({0, 3}): (1,
to the value in SSIDEAPMethod using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDEAPMethod must be specified if op_SSIDEAPMethod is specified. :type val_c_SSIDEAPMethod: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_SSIDEAPRequiredInd: The operator to apply to the field SSIDEAPRequiredInd. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. SSIDEAPRequiredInd: A flag indicates whether a extensible authentication protocol is required or not. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_SSIDEAPRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_SSIDEAPRequiredInd: If op_SSIDEAPRequiredInd is specified, the field named in this input will be compared to the value in SSIDEAPRequiredInd using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_SSIDEAPRequiredInd must be specified if op_SSIDEAPRequiredInd is specified. :type val_f_SSIDEAPRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_SSIDEAPRequiredInd: If op_SSIDEAPRequiredInd is specified, this value will be compared to the value in SSIDEAPRequiredInd using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDEAPRequiredInd must be specified if op_SSIDEAPRequiredInd is specified. :type val_c_SSIDEAPRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_SSIDIndex: The operator to apply to the field SSIDIndex. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. SSIDIndex: The SSID index of the local interface for this Wireless SSID. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_SSIDIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_SSIDIndex: If op_SSIDIndex is specified, the field named in this input will be compared to the value in SSIDIndex using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_SSIDIndex must be specified if op_SSIDIndex is specified. :type val_f_SSIDIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_SSIDIndex: If op_SSIDIndex is specified, this value will be compared to the value in SSIDIndex using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDIndex must be specified if op_SSIDIndex is specified. :type val_c_SSIDIndex: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_SSIDMACAuthMethod: The operator to apply to the field SSIDMACAuthMethod. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. SSIDMACAuthMethod: The Media Access Controller(MAC) authentication method in the Wireless SSID. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_SSIDMACAuthMethod: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_SSIDMACAuthMethod: If op_SSIDMACAuthMethod is specified, the field named in this input will be compared to the value in SSIDMACAuthMethod using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_SSIDMACAuthMethod must be specified if op_SSIDMACAuthMethod is specified. :type val_f_SSIDMACAuthMethod: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_SSIDMACAuthMethod: If op_SSIDMACAuthMethod is specified, this value will be compared to the value in SSIDMACAuthMethod using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDMACAuthMethod must be specified if op_SSIDMACAuthMethod is specified. :type val_c_SSIDMACAuthMethod: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_SSIDMACAuthRequiredInd: The operator to apply to the field SSIDMACAuthRequiredInd. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. SSIDMACAuthRequiredInd: A flag indicates the SSID Media Access Controller(MAC) is required the authentication or not. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_SSIDMACAuthRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_SSIDMACAuthRequiredInd: If op_SSIDMACAuthRequiredInd is specified, the field named in this input will be compared to the value in SSIDMACAuthRequiredInd using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_SSIDMACAuthRequiredInd must be specified if op_SSIDMACAuthRequiredInd is specified. :type val_f_SSIDMACAuthRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_SSIDMACAuthRequiredInd: If op_SSIDMACAuthRequiredInd is specified, this value will be compared to the value in SSIDMACAuthRequiredInd using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDMACAuthRequiredInd must be specified if op_SSIDMACAuthRequiredInd is specified. :type val_c_SSIDMACAuthRequiredInd: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_VlanID: The operator to apply to the field VlanID. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. VlanID: The internal NetMRI identifier of the VLAN. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_VlanID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_VlanID: If op_VlanID is specified, the field named in this input will be compared to the value in VlanID using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_VlanID must be specified if op_VlanID is specified. :type val_f_VlanID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_VlanID: If op_VlanID is specified, this value will be compared to the value in VlanID using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_VlanID must be specified if op_VlanID is specified. :type val_c_VlanID: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_ifWirelessSSIDAuthChangedCols: The operator to apply to the field ifWirelessSSIDAuthChangedCols. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. ifWirelessSSIDAuthChangedCols: The fields that changed between this revision of the record and the previous revision. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_ifWirelessSSIDAuthChangedCols: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param
# Import the needed libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import datetime # For linear regression function from sklearn.ensemble import GradientBoostingRegressor from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error # For clustering function from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures import boto3 from io import StringIO import warnings warnings.filterwarnings("ignore") BUCKETNAME = 'covid-v1-part-3-data-bucket' def report_date(lag=1): ''' returns a string representing the date for the report we are running lag is an int, representing how many days in the past to run the report, the default lag is 1 days ''' today=str(datetime.datetime.now())[:8] date = int(str(datetime.datetime.now())[8:10]) if date > lag: day = date - lag zero = str(0) if day < 10: return f'{today}{zero}{day}' return f'{today}{day}' # If the date is the first of the month, take the report # for the last day of the prior month month = str(int(today[5:7]) - 1) year = today[:4] thirty_one = ['01', '03', '05', '07', '08', '10', '12'] thirty = ['04', '06', '09', '11'] if month in thirty_one: day = '31' elif month in thirty: day = '30' else: day = '28' return f'{year}-{month}-{day}' def jhu_date(date): ''' returns a string representing the date for the report we are running date is a string representing the date found by report_date() ''' year = date[:4] month = date[5:7] day = date[8:10] zero = 0 #if int(day) < 10: # return f'{month}-{zero}{day}-{year}' return f'{month}-{day}-{year}' def daily_snapshot(datapath, covpath, date, bucket=BUCKETNAME): ''' sends the daily snapshot of the covid totals incorporated in to the static data set to a data folder to be used by the models datapath is a string, the relative path through the s3 bucket covpath is a string, the relative or absolute path the the daily updated covid-19 data from the Johns Hopkins github repo date is a string representing the report date bucket is a string, the name of the s3 bucket for storage in aws ''' # set filename for the daily data cov_date = jhu_date(date) filename = f'{covpath}/{cov_date}.csv' print(f'searching {covpath} for {cov_date}.csv') try: # create new dataframe with the covid data covid = pd.read_csv(filename) print(f'SUCCESS, creating "covid" dataframe using {filename}') except: print(f'Exception: {filename} not found. Check your file location or try to run prior day\'s report') # strip down the covid data to cases and deaths covid = covid[covid['Country_Region']=='US'] covid['county_state'] = covid['Admin2'] + ' County, ' + covid['Province_State'] covid.set_index('county_state', inplace=True) covid.rename(columns=({ 'Confirmed': 'confirmed_cases', 'Deaths': 'deaths' }), inplace=True) covid=covid[['confirmed_cases', 'deaths']] # pull in prior collective data set filename = 'cov_soc_eco.csv' ### DELETE THIS PRINT STATEMENT UPON COMPLETION### print(f'searching {datapath} for {filename}') # create new dataframe with the covid data full = pd.read_csv(f's3://{bucket}/{datapath}/{filename}') print(f'SUCCESS, creating dataframe using {filename}') # set the index in the dataframe to 'county_state' full['county_state'] = full['county'] + ", " + full['state'] full.set_index('county_state', inplace=True) ### This part will vary ********************** # set the index in the covid dataframe for consistency # print the cases and deaths numbers from the old data_set print("Think about changing this to be yesterday's numbers:") print('cases total on prior data set: ', full['confirmed_cases'].sum()) print('deaths total on prior data set: ', full['deaths'].sum()) # open the dataframe confirmed cases and deaths columns for replacement full.drop(columns=['confirmed_cases', 'deaths'], inplace=True) # merge the dataframes full = full.merge(covid, how='left', left_on=full.index, right_on=covid.index) full['county_state'] = full['key_0'] full.drop(columns='key_0', inplace=True) full.set_index('county_state', inplace=True) # print the cases and deaths numbers from the new data_set print("Think about changing this to be today's numbers:") print('cases total on new data set: ', full['confirmed_cases'].sum()) print('deaths total on new data set: ', full['deaths'].sum()) # overwrite the covid-per-capita columns full['cases_per_100k'] = (full['confirmed_cases'] / full['Population']) * 100_000 full['deaths_per_100k']= (full['deaths'] / full['Population']) * 100_000 # export the new dataframe to csv csv_buffer = StringIO() full.to_csv(csv_buffer) s3_resource = boto3.resource('s3') s3_resource.Object(bucket, f'{datapath}/updated_snapshot.csv' ).put(Body=csv_buffer.getvalue()) print('SUCCESS, sending file updated_snapshot.csv to data folder') print('\nDaily Snapshot run, commence Machine Learning models\n') def show_rmse(model_1, model_2): ''' returns 1 for error, 0 for complete prints the Root Mean Squared error of one or two models ''' try: print('Root Mean Squared Error of the LR: ',(mean_squared_error(y_test, model_1.predict(X_test)))**(1/2)) print('Root Mean Squared Error of the GB: ',(mean_squared_error(y_test, model_2.predict(X_test)))**(1/2)) return 0 except: print('An exception occurred') return 1 def i_regress(dataframe, features, target, test_size=0.2, n_estimators=100): ''' returns two models, a LinearRegression() and GradientBoostingRegressor(), in that order, and also prints out the r2 scores of each dataframe is the dataframe being used for the testing features is a list of numeric data target is a string, the column name from the dataframe of the target test_size is a float between 0.0 and 1.0 exclusive used in the train_test_split() function n_estimators is an int used in the GradientBoostingRegressor() ''' # import librarires if exporting this function to a useful library lr = LinearRegression() gb = GradientBoostingRegressor(n_estimators=n_estimators) X = dataframe[features] y = dataframe[target] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42) lr.fit(X_train, y_train) gb.fit(X_train, y_train) print(f'Models successfully built: Target = "{target}"') print('*'*30) print('Training Scores: ') print('LinearRegression : ', lr.score(X_train, y_train)) print('GradientBoostingRegressor: ', gb.score(X_train, y_train)) print('*'*30) print('Testing Scores: ') print('LinearRegression : ', lr.score(X_test, y_test)) print('GradientBoostingRegressor: ', gb.score(X_test, y_test)) print('*'*30) show_rmse(lr, gb) print('\n') return lr, gb def run_regression_models(datapath, filename, date, model=False, bucket=BUCKETNAME): ''' Runs Linear Regression models and sends a new 85_col.csv to data storage datapath is a string, the relative or absolute path to the data storage filename is the name of the daily snapshot file date is a string representing the report date bucket is a string representing the s3 bucket name ''' # call the pandas read_csv() function to create a dataframe covid_df = pd.read_csv(f's3://{bucket}/{datapath}/{filename}') covid_df.set_index('county_state', inplace=True) # use one-hot-encoding to split up the states covid_df = pd.get_dummies(columns=['state_abr'], data=covid_df, prefix="", prefix_sep="") # create a features list cols = dict(covid_df.dtypes) features = [] for col in cols: if "object" not in str(cols[col]): features.append(col) # export this dataset for use in the KMeans model: csv_buffer = StringIO() covid_df[features].to_csv(csv_buffer) s3_resource = boto3.resource('s3') s3_resource.Object(bucket, f'{datapath}/85_cols.csv').put(Body=csv_buffer.getvalue()) #commenting out this next bit as changing to an s3 StringIO upload #covid_df[features].to_csv(datapath+'85_cols.csv') # Remove the target columns from the features list features.remove('deaths') features.remove('confirmed_cases') features.remove('deaths_per_100k') features.remove('cases_per_100k') targets_list = ['deaths', 'confirmed_cases', 'deaths_per_100k', 'cases_per_100k'] # If the model input is envoked, run models: if model: # call the i_regress() function to run the models themselves lr_1, gb_1 = i_regress(covid_df, features, target='deaths', test_size=.3, n_estimators=500) lr_2, gb_2 = i_regress(covid_df, features, target='confirmed_cases', test_size=.2, n_estimators=200) lr_3, gb_3 = i_regress(covid_df, features, target='deaths_per_100k', test_size=.4, n_estimators=500) lr_4, gb_4 = i_regress(covid_df, features, target='cases_per_100k', test_size=.35, n_estimators=500) ## Begin re-working the dataframe for exporting to Tableau Dashboard # Receate a features list containing only the numerical features cols = dict(covid_df.dtypes) features = [] for col in cols: if "object" not in str(cols[col]) and col not in targets_list: features.append(col) # Create a list of the state columns and seperate them from the features list states = [] for feat in features: if len(feat)==2 and 'Q' not in feat: states.append(feat) for state in states: features.remove(state) # create a locations list locations = ['latitude', 'longitude', 'fips'] for loc in locations: features.remove(loc) print('For re-assessment, wittling down to ', len(features), ' features') # If the model input is envoked, run models: if model: # Run the models again and look for movement print('\nRe-running the models using new features\n') lr_5, gb_5 = i_regress(covid_df, features, target='deaths', test_size=.3, n_estimators=500) lr_6, gb_6 = i_regress(covid_df, features, target='confirmed_cases', test_size=.2, n_estimators=200) lr_7, gb_7 = i_regress(covid_df, features, target='deaths_per_100k', test_size=.4, n_estimators=500) lr_8, gb_8 = i_regress(covid_df, features, target='cases_per_100k', test_size=.35, n_estimators=500) print('\nIn next iteration, this is a good place for a printout of the') print(' results of the modeling. Show a graph demonstrating changes\n') strongest = ['deaths_per_100k', 'cases_per_100k', 'pct_white', 'pct_black', 'percapita_income', 'median_household_income', 'median_family_income'] plt.figure(figsize=(18, 12)) #sns.set(font_scale=3) # font size 2 sns.heatmap(covid_df[strongest].corr(), cmap='coolwarm', annot=True ); plt.title('Heatmap of strongest correlations in Model', fontsize=24) def prep_final_data(datapath, dashboard_datapath, archive_path, filename, date, bucket=BUCKETNAME): ''' sends final data set to storage datapath is a string, the relative or absolute path to the data storage dashboard_datapath is a string, the path to where dashboard file is stored
shared_depth = min(self.config["shared_depth"], self.config["ffnn_depth"]) for i in range(shared_depth): hidden_weights = tf.get_variable("shared_hidden_weights_{}".format(i), [util.shape(flattened_pair_emb, 1), self.config["ffnn_size"]]) hidden_bias = tf.get_variable("shared_hidden_bias_{}".format(i), [self.config["ffnn_size"]]) flattened_pair_emb = tf.nn.relu(tf.nn.xw_plus_b(flattened_pair_emb, hidden_weights, hidden_bias)) flattened_pair_emb = tf.nn.dropout(flattened_pair_emb, self.dropout) pair_emb = tf.reshape(flattened_pair_emb, [k, c, self.config["ffnn_size"]]) ante_score_list = [] pairwise_label_list = [] dummy_scores = tf.zeros([k, 1]) # [k, 1] ante_score_list.append(dummy_scores) with tf.variable_scope("slow_bridging_scores"): slow_bridging_scores = util.ffnn(pair_emb, self.config["ffnn_depth"] - shared_depth, self.config["ffnn_size"], 1, self.dropout) # [k, c, 1] slow_bridging_scores = tf.squeeze(slow_bridging_scores, 2) # [k, c] top_bridging_scores = slow_bridging_scores + top_fast_antecedent_scores ante_score_list.append(top_bridging_scores) bridging_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_bridging_ante_cids, 1)) # [k, c] non_dummy_bridging_indicator = tf.expand_dims(top_span_bridging_ante_cids > 0, 1) # [k, 1] bridging_pairwise_labels = tf.logical_and(bridging_cluster_indicator, non_dummy_bridging_indicator) # [k, c] pairwise_label_list.append(bridging_pairwise_labels) if self.config["train_with_coref"]: with tf.variable_scope("slow_coreference_scores"): slow_coref_scores = util.ffnn(pair_emb, self.config["ffnn_depth"] - shared_depth, self.config["ffnn_size"], 1, self.dropout) # [k, c, 1] slow_coref_scores = tf.squeeze(slow_coref_scores, 2) # [k, c] top_coref_scores = slow_coref_scores + top_fast_antecedent_scores ante_score_list.append(top_coref_scores) coref_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_cluster_ids, 1)) # [k,c] non_dummy_coref_indicator = tf.expand_dims(top_span_cluster_ids > 0, 1) # [k,1] coref_pairwise_labels = tf.logical_and(coref_cluster_indicator, non_dummy_coref_indicator) # [k,c] pairwise_label_list.append(coref_pairwise_labels) top_antecedent_scores = tf.concat(ante_score_list, 1) # [k, c + 1] or [k, 2*c+1] pairwise_labels = tf.concat(pairwise_label_list, 1) # [k,c] or [k,2*c] top_antecedent_scores = tf.boolean_mask(top_antecedent_scores, top_us_mask) pairwise_labels = tf.boolean_mask(pairwise_labels, top_us_mask) dummy_labels = tf.logical_not(tf.reduce_any(pairwise_labels, 1, keepdims=True)) # [k, 1] pairwise_labels = tf.concat([dummy_labels, pairwise_labels], 1) # [k, c + 1] or [k,2*c+1] loss = self.softmax_loss(top_antecedent_scores, pairwise_labels) loss = tf.reduce_sum(loss) if self.config["use_gold_bridging_anaphora"]: bridging_mask = tf.equal(top_is_status, 2) # bridging top_span_starts = tf.boolean_mask(top_span_starts, bridging_mask) top_span_ends = tf.boolean_mask(top_span_ends, bridging_mask) top_antecedents = tf.boolean_mask(top_antecedents, bridging_mask) top_antecedent_scores_output = tf.boolean_mask(top_bridging_scores, bridging_mask) elif self.config["remove_coref_anaphora"]: bridging_mask = tf.not_equal(top_is_status, 1) # DO top_span_starts = tf.boolean_mask(top_span_starts, bridging_mask) top_span_ends = tf.boolean_mask(top_span_ends, bridging_mask) top_antecedents = tf.boolean_mask(top_antecedents, bridging_mask) top_antecedent_scores_output = tf.boolean_mask(tf.concat([dummy_scores, top_bridging_scores], 1), bridging_mask) else: top_antecedent_scores_output = top_antecedent_scores return [top_span_starts, top_span_ends, top_span_cluster_ids, top_antecedents, top_antecedent_scores_output], loss def get_span_emb(self, head_emb, context_outputs, span_starts, span_ends): span_emb_list = [] span_start_emb = tf.gather(context_outputs, span_starts) # [k, emb] span_emb_list.append(span_start_emb) span_end_emb = tf.gather(context_outputs, span_ends) # [k, emb] span_emb_list.append(span_end_emb) span_width = tf.minimum(1 + span_ends - span_starts, self.config["max_span_width"]) # [k] if self.config["use_features"]: span_width_index = span_width - 1 # [k] span_width_emb = tf.gather( tf.get_variable("span_width_embeddings", [self.config["max_span_width"], self.config["feature_size"]]), span_width_index) # [k, emb] span_width_emb = tf.nn.dropout(span_width_emb, self.dropout) span_emb_list.append(span_width_emb) if self.config["model_heads"]: span_indices = tf.expand_dims(tf.range(self.config["max_span_width"]), 0) + tf.expand_dims(span_starts, 1) # [k, max_span_width] span_indices = tf.minimum(util.shape(context_outputs, 0) - 1, span_indices) # [k, max_span_width] span_text_emb = tf.gather(head_emb, span_indices) # [k, max_span_width, emb] with tf.variable_scope("head_scores"): self.head_scores = util.projection(context_outputs, 1) # [num_words, 1] span_head_scores = tf.gather(self.head_scores, span_indices) # [k, max_span_width, 1] span_mask = tf.expand_dims(tf.sequence_mask(span_width, self.config["max_span_width"], dtype=tf.float32), 2) # [k, max_span_width, 1] span_head_scores += tf.log(span_mask) # [k, max_span_width, 1] span_attention = tf.nn.softmax(span_head_scores, 1) # [k, max_span_width, 1] span_head_emb = tf.reduce_sum(span_attention * span_text_emb, 1) # [k, emb] span_emb_list.append(span_head_emb) span_emb = tf.concat(span_emb_list, 1) # [k, emb] return span_emb # [k, emb] def softmax_loss(self, antecedent_scores, antecedent_labels): gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [k, max_ant + 1] marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [k] log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [k] return log_norm - marginalized_gold_scores # [k] def bucket_distance(self, distances): """ Places the given values (designed for distances) into 10 semi-logscale buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+]. """ logspace_idx = tf.to_int32(tf.floor(tf.log(tf.to_float(distances)) / math.log(2))) + 3 use_identity = tf.to_int32(distances <= 4) combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx return tf.clip_by_value(combined_idx, 0, 9) def get_pair_embeddings(self, top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb): k = util.shape(top_span_emb, 0) c = util.shape(top_antecedents, 1) feature_emb_list = [] if self.config["use_metadata"]: top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c] same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c] speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb] feature_emb_list.append(speaker_pair_emb) tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb] feature_emb_list.append(tiled_genre_emb) if self.config["use_features"]: antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c] antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c] feature_emb_list.append(antecedent_distance_emb) feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb] feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb] target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb] similarity_emb = top_antecedent_emb * target_emb # [k, c, emb] target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb] pair_emb = tf.concat([target_emb, top_antecedent_emb, similarity_emb, feature_emb], 2) # [k, c, emb] return pair_emb def flatten_emb_by_sentence(self, emb, text_len_mask): num_sentences = tf.shape(emb)[0] max_sentence_length = tf.shape(emb)[1] emb_rank = len(emb.get_shape()) if emb_rank == 2: flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length]) elif emb_rank == 3: flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)]) else: raise ValueError("Unsupported rank: {}".format(emb_rank)) return tf.boolean_mask(flattened_emb, tf.reshape(text_len_mask, [num_sentences * max_sentence_length])) def lstm_contextualize(self, text_emb, text_len, text_len_mask): num_sentences = tf.shape(text_emb)[0] current_inputs = text_emb # [num_sentences, max_sentence_length, emb] for layer in range(self.config["contextualization_layers"]): with tf.variable_scope("layer_{}".format(layer)): with tf.variable_scope("fw_cell"): cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout) with tf.variable_scope("bw_cell"): cell_bw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout) state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1])) state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1])) (fw_outputs, bw_outputs), _ = tf.nn.bidirectional_dynamic_rnn( cell_fw=cell_fw, cell_bw=cell_bw, inputs=current_inputs, sequence_length=text_len, initial_state_fw=state_fw, initial_state_bw=state_bw) text_outputs = tf.concat([fw_outputs, bw_outputs], 2) # [num_sentences, max_sentence_length, emb] text_outputs = tf.nn.dropout(text_outputs, self.lstm_dropout) if layer > 0: highway_gates = tf.sigmoid( util.projection(text_outputs, util.shape(text_outputs, 2))) # [num_sentences, max_sentence_length, emb] text_outputs = highway_gates * text_outputs + (1 - highway_gates) * current_inputs current_inputs = text_outputs return self.flatten_emb_by_sentence(text_outputs, text_len_mask) def get_predicted_bridging_pairs(self, predictions): top_span_starts, top_span_ends, top_span_cluster_ids, top_antecedents, top_antecedent_scores = predictions pred_bridging_pairs = set() pred_bridging_anaphora = set() c = np.shape(top_antecedents)[1] # c pred_ante_indices = np.argmax(top_antecedent_scores, axis=1) - ( 0 if self.config["use_gold_bridging_anaphora"] else 1) for i, index in enumerate(pred_ante_indices): if self.config["use_gold_bridging_anaphora"] or (index < c and index >= 0): pred_bridging_pairs.add((top_span_starts[i], top_span_ends[i], top_span_cluster_ids[top_antecedents[i, index]])) pred_bridging_anaphora.add((top_span_starts[i], top_span_ends[i])) return pred_bridging_pairs, pred_bridging_anaphora def get_gold_bridging_pairs(self, gold_starts, gold_ends, cluster_ids, bridgings,pred_bridging_pairs): bridging_map = {} mention2cid = {(s, e): cid for s, e, cid in zip(gold_starts, gold_ends, cluster_ids)} gold_bridging_pairs = set() gold_bridging_anaphora = set() for p in bridgings: ana = (p[0][0], p[0][1]) ant_cid = mention2cid[(p[1][0], p[1][1])] if not ana in bridging_map: bridging_map[ana] = set() bridging_map[ana].add(ant_cid) for ana in bridging_map: gold_bridging_anaphora.add(ana) s, e = ana ant_cid = list(bridging_map[ana]) if len(ant_cid) > 1: cid = ant_cid[0] for c in ant_cid: if (s, e, c) in pred_bridging_pairs: # we follow hou et al to count bridgings with multi-antecedent as correct # as long as any gold bridging ant is recovered (only for BASHI) (only 15 multi-ant) # The impact on results are very small e.g. 0 ~ 0.2 cid = c gold_bridging_pairs.add((s, e, cid)) else: gold_bridging_pairs.add((s, e, ant_cid[0])) return gold_bridging_pairs, gold_bridging_anaphora def load_eval_data(self, eval_fold=-1, num_fold=-1): if self.eval_data is None: def load_line(line): example = json.loads(line) return self.tensorize_example(example, is_training=False), example if num_fold > 1: #cross validation with open(self.config["train_path"]) as f: self.eval_data = [load_line(l) for i, l in enumerate(f.readlines()) if i % num_fold == eval_fold] else: with open(self.config["eval_path"]) as f: self.eval_data = [load_line(l) for l in f.readlines()] print("Loaded {} eval examples.".format(len(self.eval_data))) def evaluate(self, session, eval_fold=-1, num_fold=-1, is_final_test=False): self.load_eval_data(eval_fold, num_fold) if "eval_on_test_part_only" in self.config and self.config["eval_on_test_part_only"]: eval_on_test_part_only = True print("Evaluate on the test part only!!!!") else: eval_on_test_part_only = False if num_fold > 1 and is_final_test: print("Evaluating %d/%d fold." % (eval_fold+1, num_fold)) tp, fn, fp = 0, 0, 0 tpa, fna, fpa = 0, 0, 0 for example_num, (tensorized_example, example) in enumerate(self.eval_data): _, _, _, _, _, _, _, _, gold_starts, gold_ends, cluster_ids, bridging_ante_cids, _, _, = tensorized_example feed_dict = {i: t for i, t in zip(self.input_tensors, tensorized_example)} predictions = session.run(self.predictions, feed_dict=feed_dict) pred_bridging_pairs, pred_bridging_anaphora = self.get_predicted_bridging_pairs(predictions) if self.config["has_multi_bridging_ant"]: #we follow hou et al to count birdings with multi-antecedent as correct # as long as any gold bridging ant is recovered (only for BASHI) gold_bridging_pairs, gold_bridging_anaphora = self.get_gold_bridging_pairs(gold_starts, gold_ends, cluster_ids, example["bridging_pairs"], pred_bridging_pairs) else: gold_bridging_pairs = set( [(s, e, cid) for s, e, cid in zip(gold_starts, gold_ends, bridging_ante_cids) if cid > 0]) gold_bridging_anaphora = set( [(s, e) for s, e, cid in zip(gold_starts, gold_ends, bridging_ante_cids) if cid > 0]) add2eval = True if eval_on_test_part_only and not example["doc_key"].endswith('_test'): add2eval = False if add2eval: tp += len(gold_bridging_pairs & pred_bridging_pairs) fn += len(gold_bridging_pairs - pred_bridging_pairs) fp += len(pred_bridging_pairs - gold_bridging_pairs) tpa += len(gold_bridging_anaphora & pred_bridging_anaphora) fna += len(gold_bridging_anaphora - pred_bridging_anaphora) fpa += len(pred_bridging_anaphora - gold_bridging_anaphora) if example_num % 10 == 0: print("Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data))) bridging_recall = 0.0 if tp == 0 else float(tp) / (tp + fn) bridging_precision = 0.0 if tp == 0 else float(tp)
'pdbSolventFile' attribute def getPdbSolventFile(self): return self._pdbSolventFile def setPdbSolventFile(self, pdbSolventFile): if pdbSolventFile is None: self._pdbSolventFile = None elif pdbSolventFile.__class__.__name__ == "XSDataFile": self._pdbSolventFile = pdbSolventFile else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyBModellingv1_0.setPdbSolventFile argument is not XSDataFile but %s" % pdbSolventFile.__class__.__name__ ) raise BaseException(strMessage) def delPdbSolventFile(self): self._pdbSolventFile = None pdbSolventFile = property( getPdbSolventFile, setPdbSolventFile, delPdbSolventFile, "Property for pdbSolventFile", ) # Methods and properties for the 'chiRfactorPlot' attribute def getChiRfactorPlot(self): return self._chiRfactorPlot def setChiRfactorPlot(self, chiRfactorPlot): if chiRfactorPlot is None: self._chiRfactorPlot = None elif chiRfactorPlot.__class__.__name__ == "XSDataFile": self._chiRfactorPlot = chiRfactorPlot else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyBModellingv1_0.setChiRfactorPlot argument is not XSDataFile but %s" % chiRfactorPlot.__class__.__name__ ) raise BaseException(strMessage) def delChiRfactorPlot(self): self._chiRfactorPlot = None chiRfactorPlot = property( getChiRfactorPlot, setChiRfactorPlot, delChiRfactorPlot, "Property for chiRfactorPlot", ) # Methods and properties for the 'nsdPlot' attribute def getNsdPlot(self): return self._nsdPlot def setNsdPlot(self, nsdPlot): if nsdPlot is None: self._nsdPlot = None elif nsdPlot.__class__.__name__ == "XSDataFile": self._nsdPlot = nsdPlot else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyBModellingv1_0.setNsdPlot argument is not XSDataFile but %s" % nsdPlot.__class__.__name__ ) raise BaseException(strMessage) def delNsdPlot(self): self._nsdPlot = None nsdPlot = property(getNsdPlot, setNsdPlot, delNsdPlot, "Property for nsdPlot") def export(self, outfile, level, name_="XSDataInputBioSaxsISPyBModellingv1_0"): showIndent(outfile, level) outfile.write(unicode("<%s>\n" % name_)) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write(unicode("</%s>\n" % name_)) def exportChildren( self, outfile, level, name_="XSDataInputBioSaxsISPyBModellingv1_0" ): XSDataInput.exportChildren(self, outfile, level, name_) if self._sample is not None: self.sample.export(outfile, level, name_="sample") else: warnEmptyAttribute("sample", "XSDataBioSaxsSample") for dammifModels_ in self.getDammifModels(): dammifModels_.export(outfile, level, name_="dammifModels") if self._damaverModel is not None: self.damaverModel.export(outfile, level, name_="damaverModel") if self._damfiltModel is not None: self.damfiltModel.export(outfile, level, name_="damfiltModel") if self._damstartModel is not None: self.damstartModel.export(outfile, level, name_="damstartModel") if self._damminModel is not None: self.damminModel.export(outfile, level, name_="damminModel") if self._fitFile is not None: self.fitFile.export(outfile, level, name_="fitFile") if self._logFile is not None: self.logFile.export(outfile, level, name_="logFile") if self._pdbMoleculeFile is not None: self.pdbMoleculeFile.export(outfile, level, name_="pdbMoleculeFile") if self._pdbSolventFile is not None: self.pdbSolventFile.export(outfile, level, name_="pdbSolventFile") if self._chiRfactorPlot is not None: self.chiRfactorPlot.export(outfile, level, name_="chiRfactorPlot") if self._nsdPlot is not None: self.nsdPlot.export(outfile, level, name_="nsdPlot") def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "sample": obj_ = XSDataBioSaxsSample() obj_.build(child_) self.setSample(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "dammifModels": obj_ = XSDataSaxsModel() obj_.build(child_) self.dammifModels.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "damaverModel": obj_ = XSDataSaxsModel() obj_.build(child_) self.setDamaverModel(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "damfiltModel": obj_ = XSDataSaxsModel() obj_.build(child_) self.setDamfiltModel(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "damstartModel": obj_ = XSDataSaxsModel() obj_.build(child_) self.setDamstartModel(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "damminModel": obj_ = XSDataSaxsModel() obj_.build(child_) self.setDamminModel(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "fitFile": obj_ = XSDataFile() obj_.build(child_) self.setFitFile(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "logFile": obj_ = XSDataFile() obj_.build(child_) self.setLogFile(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "pdbMoleculeFile": obj_ = XSDataFile() obj_.build(child_) self.setPdbMoleculeFile(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "pdbSolventFile": obj_ = XSDataFile() obj_.build(child_) self.setPdbSolventFile(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "chiRfactorPlot": obj_ = XSDataFile() obj_.build(child_) self.setChiRfactorPlot(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "nsdPlot": obj_ = XSDataFile() obj_.build(child_) self.setNsdPlot(obj_) XSDataInput.buildChildren(self, child_, nodeName_) # Method for marshalling an object def marshal(self): oStreamString = StringIO() oStreamString.write(unicode('<?xml version="1.0" ?>\n')) self.export(oStreamString, 0, name_="XSDataInputBioSaxsISPyBModellingv1_0") oStringXML = oStreamString.getvalue() oStreamString.close() return oStringXML # Only to export the entire XML tree to a file stream on disk def exportToFile(self, _outfileName): outfile = open(_outfileName, "w") outfile.write(unicode('<?xml version="1.0" ?>\n')) self.export(outfile, 0, name_="XSDataInputBioSaxsISPyBModellingv1_0") outfile.close() # Deprecated method, replaced by exportToFile def outputFile(self, _outfileName): print( "WARNING: Method outputFile in class XSDataInputBioSaxsISPyBModellingv1_0 is deprecated, please use instead exportToFile!" ) self.exportToFile(_outfileName) # Method for making a copy in a new instance def copy(self): return XSDataInputBioSaxsISPyBModellingv1_0.parseString(self.marshal()) # Static method for parsing a string def parseString(_inString): doc = minidom.parseString(_inString) rootNode = doc.documentElement rootObj = XSDataInputBioSaxsISPyBModellingv1_0() rootObj.build(rootNode) # Check that all minOccurs are obeyed by marshalling the created object oStreamString = StringIO() rootObj.export(oStreamString, 0, name_="XSDataInputBioSaxsISPyBModellingv1_0") oStreamString.close() return rootObj parseString = staticmethod(parseString) # Static method for parsing a file def parseFile(_inFilePath): doc = minidom.parse(_inFilePath) rootNode = doc.documentElement rootObj = XSDataInputBioSaxsISPyBModellingv1_0() rootObj.build(rootNode) return rootObj parseFile = staticmethod(parseFile) # end class XSDataInputBioSaxsISPyBModellingv1_0 class XSDataInputBioSaxsISPyB_HPLCv1_0(XSDataInput): """Input class for populating ISPyB""" def __init__( self, configuration=None, hplcPlot=None, jsonFile=None, hdf5File=None, sample=None, ): XSDataInput.__init__(self, configuration) if sample is None: self._sample = None elif sample.__class__.__name__ == "XSDataBioSaxsSample": self._sample = sample else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0 constructor argument 'sample' is not XSDataBioSaxsSample but %s" % self._sample.__class__.__name__ ) raise BaseException(strMessage) if hdf5File is None: self._hdf5File = None elif hdf5File.__class__.__name__ == "XSDataFile": self._hdf5File = hdf5File else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0 constructor argument 'hdf5File' is not XSDataFile but %s" % self._hdf5File.__class__.__name__ ) raise BaseException(strMessage) if jsonFile is None: self._jsonFile = None elif jsonFile.__class__.__name__ == "XSDataFile": self._jsonFile = jsonFile else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0 constructor argument 'jsonFile' is not XSDataFile but %s" % self._jsonFile.__class__.__name__ ) raise BaseException(strMessage) if hplcPlot is None: self._hplcPlot = None elif hplcPlot.__class__.__name__ == "XSDataFile": self._hplcPlot = hplcPlot else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0 constructor argument 'hplcPlot' is not XSDataFile but %s" % self._hplcPlot.__class__.__name__ ) raise BaseException(strMessage) # Methods and properties for the 'sample' attribute def getSample(self): return self._sample def setSample(self, sample): if sample is None: self._sample = None elif sample.__class__.__name__ == "XSDataBioSaxsSample": self._sample = sample else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0.setSample argument is not XSDataBioSaxsSample but %s" % sample.__class__.__name__ ) raise BaseException(strMessage) def delSample(self): self._sample = None sample = property(getSample, setSample, delSample, "Property for sample") # Methods and properties for the 'hdf5File' attribute def getHdf5File(self): return self._hdf5File def setHdf5File(self, hdf5File): if hdf5File is None: self._hdf5File = None elif hdf5File.__class__.__name__ == "XSDataFile": self._hdf5File = hdf5File else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0.setHdf5File argument is not XSDataFile but %s" % hdf5File.__class__.__name__ ) raise BaseException(strMessage) def delHdf5File(self): self._hdf5File = None hdf5File = property(getHdf5File, setHdf5File, delHdf5File, "Property for hdf5File") # Methods and properties for the 'jsonFile' attribute def getJsonFile(self): return self._jsonFile def setJsonFile(self, jsonFile): if jsonFile is None: self._jsonFile = None elif jsonFile.__class__.__name__ == "XSDataFile": self._jsonFile = jsonFile else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0.setJsonFile argument is not XSDataFile but %s" % jsonFile.__class__.__name__ ) raise BaseException(strMessage) def delJsonFile(self): self._jsonFile = None jsonFile = property(getJsonFile, setJsonFile, delJsonFile, "Property for jsonFile") # Methods and properties for the 'hplcPlot' attribute def getHplcPlot(self): return self._hplcPlot def setHplcPlot(self, hplcPlot): if hplcPlot is None: self._hplcPlot = None elif hplcPlot.__class__.__name__ == "XSDataFile": self._hplcPlot = hplcPlot else: strMessage = ( "ERROR! XSDataInputBioSaxsISPyB_HPLCv1_0.setHplcPlot argument is not XSDataFile but %s" % hplcPlot.__class__.__name__ ) raise BaseException(strMessage) def delHplcPlot(self): self._hplcPlot = None hplcPlot = property(getHplcPlot, setHplcPlot, delHplcPlot, "Property for hplcPlot") def export(self, outfile, level, name_="XSDataInputBioSaxsISPyB_HPLCv1_0"): showIndent(outfile, level) outfile.write(unicode("<%s>\n" % name_)) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write(unicode("</%s>\n" % name_)) def exportChildren(self, outfile, level, name_="XSDataInputBioSaxsISPyB_HPLCv1_0"): XSDataInput.exportChildren(self, outfile, level, name_) if self._sample is not None: self.sample.export(outfile, level, name_="sample") else: warnEmptyAttribute("sample", "XSDataBioSaxsSample") if self._hdf5File is not None: self.hdf5File.export(outfile, level, name_="hdf5File") if self._jsonFile is not None: self.jsonFile.export(outfile, level, name_="jsonFile") if self._hplcPlot is not None: self.hplcPlot.export(outfile, level, name_="hplcPlot") def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "sample": obj_ = XSDataBioSaxsSample() obj_.build(child_) self.setSample(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "hdf5File": obj_ = XSDataFile() obj_.build(child_) self.setHdf5File(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "jsonFile": obj_ = XSDataFile() obj_.build(child_) self.setJsonFile(obj_) elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "hplcPlot": obj_ = XSDataFile() obj_.build(child_) self.setHplcPlot(obj_) XSDataInput.buildChildren(self, child_, nodeName_) # Method for marshalling an object def marshal(self): oStreamString = StringIO() oStreamString.write(unicode('<?xml version="1.0" ?>\n')) self.export(oStreamString, 0, name_="XSDataInputBioSaxsISPyB_HPLCv1_0") oStringXML = oStreamString.getvalue() oStreamString.close() return oStringXML # Only to export the entire XML tree to a file stream on disk def exportToFile(self, _outfileName): outfile = open(_outfileName, "w") outfile.write(unicode('<?xml version="1.0" ?>\n')) self.export(outfile, 0, name_="XSDataInputBioSaxsISPyB_HPLCv1_0") outfile.close() # Deprecated method, replaced by exportToFile def outputFile(self, _outfileName): print( "WARNING: Method outputFile in class XSDataInputBioSaxsISPyB_HPLCv1_0 is deprecated, please use instead exportToFile!" ) self.exportToFile(_outfileName) # Method for making a copy in a new instance def copy(self): return XSDataInputBioSaxsISPyB_HPLCv1_0.parseString(self.marshal()) # Static method for parsing a string def parseString(_inString): doc = minidom.parseString(_inString) rootNode = doc.documentElement rootObj = XSDataInputBioSaxsISPyB_HPLCv1_0() rootObj.build(rootNode) # Check that all minOccurs are obeyed by marshalling the created object oStreamString =
b in a.t: if isinstance(b, Var): b = "individual" r.append(b) a.t = tuple(r) return if isinstance(a.t, Var): a.t = "individual" return return # third step of type inference: # check the types are correct def type_check(wanted, a): if wanted != typeof(a): raise ValueError(f"{wanted} != typeof({a})") if isinstance(a, tuple): o = a[0] # predefined function if isinstance(o, str): # quantifiers require body boolean if o in ("exists", "forall"): for x in a[1]: if x.t == "bool": raise ValueError(a) type_check("bool", a[2]) return # all arguments boolean if o in ("and", "or", "eqv", "not"): for i in range(1, len(a)): type_check("bool", a[i]) return # all arguments int if o in ("div-e", "div-f", "div-t", "rem-e", "rem-f", "rem-t"): for i in range(1, len(a)): type_check("int", a[i]) return # all arguments of the same type actual = typeof(a[1]) for i in range(2, len(a)): type_check(actual, a[i]) # = if o == "=": return # numbers if actual not in ("int", "rat", "real"): raise ValueError(a) # rational or real if o == "div" and actual == "int": raise ValueError(a) return return if isinstance(a, Fn): if isinstance(a.t, tuple): for b in a.t[1:]: if b == "bool": raise ValueError(a) return if isinstance(a, Var): if a.t == "bool": raise ValueError(a) return ######################################## logic formula_name_i = 0 def reset_formula_names(): global formula_name_i formula_name_i = 0 class Formula: def __init__(self, name, term, inference=None, *parents): self.set_name(name) self.__term = term self.inference = inference self.parents = parents def proof(self): visited = set() r = [] def rec(F): if F in visited: return visited.add(F) for G in F.parents: rec(G) r.append(F) rec(self) return r def set_name(self, name): global formula_name_i if name is None: name = formula_name_i formula_name_i += 1 elif isinstance(name, int): formula_name_i = max(formula_name_i, name + 1) self.name = name def status(self): # input data or definition is logical data if not self.parents: return "lda" # negated conjecture is counterequivalent if self.inference == "negate": return "ceq" # if a formula introduces new symbols, then it is only equisatisfiable # this happens during subformula renaming in CNF conversion if len(self.parents) == 1 and not fns(self.term()).issubset( fns(self.parents[0].term()) ): return "esa" # formula is a theorem of parents # could also be equivalent; don't currently bother distinguishing that case return "thm" def term(self): return self.__term class Clause(Formula): def __init__(self, name, neg, pos, inference=None, *parents): for a in neg: check_tuples(a) for a in pos: check_tuples(a) self.set_name(name) self.neg = tuple(neg) self.pos = tuple(pos) self.inference = inference self.parents = parents def __lt__(self, other): return self.size() < other.size() def rename_vars(self): m = {} neg = [rename_vars(a, m) for a in self.neg] pos = [rename_vars(a, m) for a in self.pos] return Clause("*RENAMED*", neg, pos, "rename_vars", self) def simplify(self): # simplify terms neg = map(simplify, self.neg) pos = map(simplify, self.pos) # eliminate redundancy neg = filter(lambda a: a != True, neg) pos = filter(lambda a: a != False, pos) # reify iterators neg = tuple(neg) pos = tuple(pos) # check for tautology if False in neg or True in pos: neg, pos = (), (True,) else: for a in neg: if a in pos: neg, pos = (), (True,) # did anything change? if (neg, pos) == (self.neg, self.pos): return self # derived clause return Clause(None, neg, pos, "simplify", self) def size(self): return term_size(self.neg + self.pos) def term(self): r = tuple([("not", a) for a in self.neg]) + self.pos if not r: return False if len(r) == 1: return r[0] return ("or",) + r class Problem: def __init__(self): self.formulas = [] self.clauses = [] ######################################## Dimacs def read_dimacs(filename): global header neg = [] pos = [] for s in open(filename): if s[0] in ("c", "\n"): if header: prn(s[:-1]) if not hasattr(problem, "expected"): if "UNSAT" in s: problem.expected = "Unsatisfiable" elif "SAT" in s: problem.expected = "Satisfiable" continue header = False if s[0] == "p": continue for word in s.split(): atoms = pos if word[0] == "-": atoms = neg word = word[1:] if word == "0": problem.clauses.append(Clause(None, neg, pos)) neg = [] pos = [] continue int(word) a = fn(word) a.t = "bool" atoms.append(a) if neg or pos: problem.clauses.append(Clause(None, neg, pos)) ######################################## TPTP defined_types = { "$o": "bool", "$i": "individual", "$int": "int", "$rat": "rat", "$real": "real", } defined_fns = { "$ceiling": "ceil", "$difference": "-", "$floor": "floor", "$is_int": "int?", "$is_rat": "rat?", "$less": "<", "$lesseq": "<=", "$product": "*", "$quotient": "/", "$quotient_e": "div-e", "$quotient_f": "div-f", "$quotient_t": "div-t", "$remainder_e": "rem-e", "$remainder_f": "rem-f", "$remainder_t": "rem-t", "$round": "round", "$sum": "+", "$to_int": "to-int", "$to_rat": "to-rat", "$to_real": "to-real", "$truncate": "trunc", "$uminus": "unary-", } # parser class Inappropriate(Exception): def __init__(self): super().__init__("Inappropriate") def read_tptp(filename, select=True): global header fname = os.path.basename(filename) text = open(filename).read() if text and text[-1] != "\n": text += "\n" # tokenizer ti = 0 tok = "" def err(msg): line = 1 for i in range(ti): if text[i] == "\n": line += 1 raise ValueError(f"{filename}:{line}: {repr(tok)}: {msg}") def lex(): nonlocal ti nonlocal tok while ti < len(text): c = text[ti] # space if c.isspace(): ti += 1 continue # line comment if c in ("%", "#"): i = ti while text[ti] != "\n": ti += 1 if header: prn(text[i:ti]) if text[ti : ti + 2] == "\n\n": prn() if not hasattr(problem, "expected"): m = re.match(r"%\s*Status\s*:\s*(\w+)", text[i:ti]) if m: problem.expected = m[1] continue # block comment if text[ti : ti + 2] == "/*": ti += 2 while text[ti : ti + 2] != "*/": ti += 1 ti += 2 continue # word if c.isalpha() or c == "$": i = ti ti += 1 while text[ti].isalnum() or text[ti] == "_": ti += 1 tok = text[i:ti] return # quote if c in ("'", '"'): i = ti ti += 1 while text[ti] != c: if text[ti] == "\\": ti += 1 ti += 1 ti += 1 tok = text[i:ti] return # number if c.isdigit() or (c == "-" and text[ti + 1].isdigit()): # integer part i = ti ti += 1 while text[ti].isalnum(): ti += 1 # rational if text[ti] == "/": ti += 1 while text[ti].isdigit(): ti += 1 # real else: if text[ti] == ".": ti += 1 while text[ti].isalnum(): ti += 1 if text[ti - 1] in ("e", "E") and text[ti] in ("+", "-"): ti += 1 while text[ti].isdigit(): ti += 1 tok = text[i:ti] return # punctuation if text[ti : ti + 3] in ("<=>", "<~>"): tok = text[ti : ti + 3] ti += 3 return if text[ti : ti + 2] in ("!=", "=>", "<=", "~&", "~|"): tok = text[ti : ti + 2] ti += 2 return tok = c ti += 1 return # end of file tok = None def eat(o): if tok == o: lex() return True def expect(o): if tok != o: err(f"expected '{o}'") lex() # terms def read_name(): o = tok # word if o[0].islower(): lex() return o # single quoted, equivalent to word if o[0] == "'": lex() return o[1:-1] # number if o[0].isdigit() or o[0] == "-": lex() return int(o) err("expected name") def atomic_type(): o = tok if o in defined_types: lex() return defined_types[o] if tok == "$tType": raise Inappropriate() return mktype(read_name()) def compound_type(): if eat("("): params = [atomic_type()] while eat("*"): params.append(atomic_type()) expect(")") expect(">") return (atomic_type(),) + tuple(params) t = atomic_type() if eat(">"): return atomic_type(), t return t free = {} def args(bound, n=-1): expect("(") r = [] if tok != ")": r.append(atomic_term(bound)) while tok == ",": lex() r.append(atomic_term(bound)) if n > 0 and len(r) != n: err(f"expected {n} args") expect(")") return tuple(r) def atomic_term(bound): o = tok # defined function if o[0] == "$": # constant if eat("$false"): return False if eat("$true"): return True # syntax sugar if eat("$greater"): s = args(bound, 2) return "<", s[1], s[0] if eat("$greatereq"): s = args(bound, 2) return "<=", s[1], s[0] if eat("$distinct"): s = args() inequalities = ["and"] for i in range(len(s)): for j in range(len(s)): if i != j: inequalities.append(("not", ("=", s[i], s[j]))) return tuple(inequalities) # predefined function if o in defined_fns: a = defined_fns[o] lex() arities = { "*": 2,