input
stringlengths
2.65k
237k
output
stringclasses
1 value
<reponame>KVSlab/vascularManipulationToolkit<filename>morphman/common/vmtk_wrapper.py ## Copyright (c) <NAME>, <NAME>. All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notices for more information. from os import path from vmtk import vtkvmtk, vmtkscripts # Global array names from morphman.common.vtk_wrapper import read_polydata, write_polydata radiusArrayName = 'MaximumInscribedSphereRadius' surfaceNormalsArrayName = 'SurfaceNormalArray' parallelTransportNormalsArrayName = 'ParallelTransportNormals' groupIDsArrayName = "GroupIds" abscissasArrayName = 'Abscissas' blankingArrayName = 'Blanking' branchClippingArrayName = 'BranchClippingArray' def vmtk_smooth_centerline(centerlines, num_iter, smooth_factor): """ Wrapper for vmtkCenterlineSmoothing. Smooth centerlines with a moving average filter. Args: centerlines (vtkPolyDat): Centerline to be smoothed. num_iter (int): Number of smoothing iterations. smooth_factor (float): Smoothing factor Returns: vtkPolyData: Smoothed version of input centerline """ centerline_smoothing = vmtkscripts.vmtkCenterlineSmoothing() centerline_smoothing.Centerlines = centerlines centerline_smoothing.SetNumberOfSmoothingIterations = num_iter centerline_smoothing.SetSmoothingFactor = smooth_factor centerline_smoothing.Execute() centerlines_smoothed = centerline_smoothing.Centerlines return centerlines_smoothed def vmtk_compute_centerlines(end_point, inlet, method, outlet, pole_ids, resampling_step, surface, voronoi, flip_normals=False, cap_displacement=None, delaunay_tolerance=None, simplify_voronoi=False): """ Wrapper for vmtkCenterlines. compute centerlines from a branching tubular surface. Seed points can be interactively selected on the surface, or specified as the barycenters of the open boundaries of the surface. Args: end_point (int): Toggle append open profile barycenters to centerlines surface (vktPolyData): Surface model voronoi (vtkPolyData): Voronoi diagram based on previous centerlines (Optional) inlet (ndarray): List of source point coordinates method (str): Seed point selection method outlet (ndarray): List of target point coordinates pole_ids (ndarray): Pole ID list of Voronoi diagram (Optional) resampling_step (float): Resampling step flip_normals (float): Flip normals after outward normal computation cap_displacement (float): Displacement of the center points of caps at open profiles along their normals delaunay_tolerance (float): Tolerance for evaluating coincident points during Delaunay tessellation simplify_voronoi (bool): Toggle simplification of Voronoi diagram Returns: """ centerlines = vmtkscripts.vmtkCenterlines() centerlines.Surface = surface centerlines.SeedSelectorName = method centerlines.AppendEndPoints = end_point centerlines.Resampling = 1 centerlines.ResamplingStepLength = resampling_step centerlines.SourcePoints = inlet centerlines.TargetPoints = outlet if voronoi is not None and pole_ids is not None: centerlines.VoronoiDiagram = voronoi centerlines.PoleIds = pole_ids if flip_normals: centerlines.FlipNormals = 1 if cap_displacement is not None: centerlines.CapDisplacement = cap_displacement if delaunay_tolerance is not None: centerlines.DelaunayTolerance = delaunay_tolerance if simplify_voronoi: centerlines.SimplifyVoronoi = 1 centerlines.Execute() centerlines_output = centerlines.Centerlines return centerlines, centerlines_output def vmtk_compute_centerline_sections(surface, centerlines): """ Wrapper for vmtk centerline sections. Args: surface (vtkPolyData): Surface to meassure area. centerlines (vtkPolyData): centerline to measure along. Returns: line (vtkPolyData): centerline with the attributes centerline_sections_area (vtkPolyData): sections along the centerline """ centerline_sections = vtkvmtk.vtkvmtkPolyDataCenterlineSections() centerline_sections.SetInputData(surface) centerline_sections.SetCenterlines(centerlines) centerline_sections.SetCenterlineSectionAreaArrayName('CenterlineSectionArea') centerline_sections.SetCenterlineSectionMinSizeArrayName('CenterlineSectionMinSize') centerline_sections.SetCenterlineSectionMaxSizeArrayName('CenterlineSectionMaxSize') centerline_sections.SetCenterlineSectionShapeArrayName('CenterlineSectionShape') centerline_sections.SetCenterlineSectionClosedArrayName('CenterlineSectionClosed') centerline_sections.Update() centerlines_sections_area = centerline_sections.GetOutput() line = centerline_sections.GetCenterlines() return line, centerlines_sections_area def vmtk_compute_geometric_features(centerlines, smooth, outputsmoothed=False, factor=1.0, iterations=100): """Wrapper for vmtk centerline geometry. Args: centerlines (vtkPolyData): Line to compute centerline geometry from. smooth (bool): Turn on and off smoothing before computing the geometric features. outputsmoothed (bool): Turn on and off the smoothed centerline. factor (float): Smoothing factor. iterations (int): Number of iterations. Returns: line (vtkPolyData): Line with geometry. """ geometry = vmtkscripts.vmtkCenterlineGeometry() geometry.Centerlines = centerlines if smooth: geometry.LineSmoothing = 1 geometry.OutputSmoothedLines = outputsmoothed geometry.SmoothingFactor = factor geometry.NumberOfSmoothingIterations = iterations geometry.FernetTangentArrayName = "FernetTangent" geometry.FernetNormalArrayName = "FernetNormal" geometry.FrenetBinormalArrayName = "FernetBiNormal" geometry.CurvatureArrayName = "Curvature" geometry.TorsionArrayName = "Torsion" geometry.TortuosityArrayName = "Tortuosity" geometry.Execute() return geometry.Centerlines def vmtk_compute_centerline_attributes(centerlines): """ Wrapper for centerline attributes. Args: centerlines (vtkPolyData): Line to investigate. Returns: line (vtkPolyData): Line with centerline atributes. """ attributes = vmtkscripts.vmtkCenterlineAttributes() attributes.Centerlines = centerlines attributes.NormalsArrayName = parallelTransportNormalsArrayName attributes.AbscissaArrayName = abscissasArrayName attributes.Execute() centerlines = attributes.Centerlines return centerlines def vmtk_resample_centerline(centerlines, length): """Wrapper for vmtkcenterlineresampling Args: centerlines (vtkPolyData): line to resample. length (float): resampling step. Returns: line (vtkPolyData): Resampled line. """ resampler = vmtkscripts.vmtkCenterlineResampling() resampler.Centerlines = centerlines resampler.Length = length resampler.Execute() resampled_centerline = resampler.Centerlines return resampled_centerline def vmtk_cap_polydata(surface, boundary_ids=None, displacement=0.0, in_plane_displacement=0.0): """Wrapper for vmtkCapPolyData. Close holes in a surface model. Args: in_plane_displacement (float): Displacement of boundary baricenters, at section plane relative to the radius displacement (float): Displacement of boundary baricenters along boundary normals relative to the radius. boundary_ids (ndarray): Set ids of the boundaries to cap. surface (vtkPolyData): Surface to be capped. Returns: surface (vtkPolyData): Capped surface. """ surface_capper = vtkvmtk.vtkvmtkCapPolyData() surface_capper.SetInputData(surface) surface_capper.SetDisplacement(displacement) surface_capper.SetInPlaneDisplacement(in_plane_displacement) if boundary_ids is not None: surface_capper.SetBoundaryIds(boundary_ids) surface_capper.Update() return surface_capper.GetOutput() def vmtk_smooth_surface(surface, method, iterations=800, passband=1.0, relaxation=0.01, normalize_coordinates=True, smooth_boundary=True): """Wrapper for a vmtksurfacesmoothing. Args: smooth_boundary (bool): Toggle allow change of position of boundary points normalize_coordinates (bool): Normalization of coordinates prior to filtering, minimize spurious translation effects (Taubin only) surface (vtkPolyData): Input surface to be smoothed. method (str): Smoothing method. iterations (int): Number of iterations. passband (float): The passband for Taubin smoothing. relaxation (float): The relaxation for laplace smoothing. Returns: surface (vtkPolyData): The smoothed surface. """ smoother = vmtkscripts.vmtkSurfaceSmoothing() smoother.Surface = surface smoother.NumberOfIterations = iterations if method == "laplace": smoother.RelaxationFactor = relaxation elif method == "taubin": smoother.PassBand = passband if not normalize_coordinates: smoother.NormalizeCoordinates = 0 if not smooth_boundary: smoother.BoundarySmoothing = 0 smoother.Method = method smoother.Execute() surface = smoother.Surface return surface def vmtk_compute_voronoi_diagram(surface, filename, simplify_voronoi=False, cap_displacement=None, flip_normals=False, check_non_manifold=False, delaunay_tolerance=0.001, subresolution_factor=1.0): """ Wrapper for vmtkDelanayVoronoi. Creates a surface model's coresponding voronoi diagram. Args: subresolution_factor (float): Factor for removal of subresolution tetrahedra flip_normals (bool): Flip normals after outward normal computation. cap_displacement (float): Displacement of the center points of caps at open profiles along their normals simplify_voronoi (bool): Use alternative algorith for compute Voronoi diagram, reducing quality, improving speed check_non_manifold (bool): Check the surface for non-manifold edges delaunay_tolerance (float): Tolerance for evaluating coincident points during Delaunay tessellation surface (vtkPolyData): Surface model filename (str): Path where voronoi diagram is stored Returns: new_voronoi (vtkPolyData): Voronoi diagram """ if path.isfile(filename): return read_polydata(filename) voronoi = vmtkscripts.vmtkDelaunayVoronoi() voronoi.Surface = surface voronoi.RemoveSubresolutionTetrahedra = 1 voronoi.DelaunayTolerance = delaunay_tolerance voronoi.SubresolutionFactor = subresolution_factor if simplify_voronoi: voronoi.SimplifyVoronoi = 1 if cap_displacement is not None: voronoi.CapDisplacement = cap_displacement if flip_normals: voronoi.FlipNormals = 1 if check_non_manifold: voronoi.CheckNonManifold = 1 voronoi.Execute() new_voronoi = voronoi.VoronoiDiagram write_polydata(new_voronoi, filename) return new_voronoi def vmtk_polyball_modeller(voronoi_diagram, poly_ball_size): """ Wrapper for vtkvmtkPolyBallModeller. Create an image where a polyball or polyball line are evaluated as a function. Args: voronoi_diagram (vtkPolyData): Input Voronoi diagram representing surface model poly_ball_size (list): Resolution of output Returns: vtkvmtkPolyBallModeller: Image where polyballs have been evaluated over a Voronoi diagram """ modeller = vtkvmtk.vtkvmtkPolyBallModeller() modeller.SetInputData(voronoi_diagram) modeller.SetRadiusArrayName(radiusArrayName) modeller.UsePolyBallLineOff() modeller.SetSampleDimensions(poly_ball_size) modeller.Update() return modeller def vmtk_surface_connectivity(surface, method="largest", clean_output=True, closest_point=None): """ Wrapper for vmtkSurfaceConnectivity. Extract the largest connected region, the closest point-connected region or the scalar-connected region from a surface Args: surface (vtkPolyData): Surface model method (str): Connectivity method, either 'largest' or 'closest' clean_output (bool): Clean the unused points in the output closest_point (ndarray): Coordinates of the closest point Returns: vmtkSurfaceConnectivity: Filter for extracting largest connected region """ connector = vmtkscripts.vmtkSurfaceConnectivity() connector.Surface = surface connector.Method = method if clean_output: connector.CleanOutput = 1 if closest_point is not None: connector.ClosestPoint = closest_point connector.Execute() return connector def vmtk_branch_clipper(centerlines, surface, clip_value=0.0, inside_out=False, use_radius_information=True, interactive=False): """ Wrapper for vmtkBranchClipper. Divide a surface in relation to its split and grouped centerlines. Args: centerlines (vtkPolyData): Input centerlines surface (vtkPolyData): Input surface model clip_value (float): inside_out (bool): Get the inverse of the branch clipper output. use_radius_information (bool): To use MISR info for clipping branches. interactive (bool): Use interactive mode, requires user input. Returns: vmtkBranchClipper: Branch clipper used to divide a surface into regions. """ clipper = vmtkscripts.vmtkBranchClipper() clipper.Surface = surface clipper.Centerlines = centerlines clipper.ClipValue = clip_value clipper.RadiusArrayName = radiusArrayName clipper.GroupIdsArrayName = groupIDsArrayName clipper.BlankingArrayName = blankingArrayName if inside_out: clipper.InsideOut = 1 if not use_radius_information: clipper.UseRadiusInformation = 0 if interactive: clipper.Interactive = 1 clipper.Execute() return clipper def vmtk_endpoint_extractor(centerlines, number_of_end_point_spheres, number_of_gap_spheres=1): """ Wrapper for vmtkEndpointExtractor. Find the endpoints of a split and grouped centerline Args: centerlines (vtkPolyData): Input centerlines. number_of_end_point_spheres (float): Number of spheres to skip at endpoint number_of_gap_spheres (float): Number of spheres to skip per gap. Returns: vmtkEndpointExtractor: Endpoint extractor based on centerline """ extractor = vmtkscripts.vmtkEndpointExtractor() extractor.Centerlines = centerlines extractor.RadiusArrayName = radiusArrayName extractor.GroupIdsArrayName = groupIDsArrayName extractor.BlankingArrayName = branchClippingArrayName extractor.NumberOfEndPointSpheres = number_of_end_point_spheres extractor.NumberOfGapSpheres = number_of_gap_spheres extractor.Execute() return extractor def vmtk_compute_surface_normals(surface, auto_orient_normals=True, orient_normals=True, compute_cell_normals=False, flip_normals=False): """ Wrapper for vmtkSurfaceNormals. Computes the normals of the input surface. Args: surface (vtkPolyData): Input surface model auto_orient_normals (bool): Try to auto orient normals outwards orient_normals (bool): Try to orient normals so that neighboring points have similar orientations
## # File: DictMethodChemRefHelper.py # Author: <NAME> # Date: 16-Jul-2019 # Version: 0.001 Initial version # ## """ Helper class implements external method references supporting chemical reference data definitions in the RCSB dictionary extension. """ __docformat__ = "google en" __author__ = "<NAME>" __email__ = "<EMAIL>" __license__ = "Apache 2.0" import logging # from collections import Counter, OrderedDict from mmcif.api.DataCategory import DataCategory logger = logging.getLogger(__name__) class DictMethodChemRefHelper(object): """Helper class implements external method references supporting chemical reference data definitions in the RCSB dictionary extension. """ def __init__(self, **kwargs): """ Args: resourceProvider: (obj) instance of DictMethodResourceProvider() """ # self._raiseExceptions = kwargs.get("raiseExceptions", False) # rP = kwargs.get("resourceProvider") # dapw = rP.getResource("DictionaryAPIProviderWrapper instance") if rP else None # self.__dApi = dapw.getApiByName("pdbx_core") if dapw else None self.__dApi = kwargs.get("dictionaryApi", None) self.__ccP = rP.getResource("ChemCompProvider instance") if rP else None logger.debug("Dictionary method helper init") def echo(self, msg): logger.info(msg) def addChemCompRelated(self, dataContainer, catName, **kwargs): """Add category rcsb_chem_comp_related. Args: dataContainer (object): mmif.api.DataContainer object instance catName (str): Category name Returns: bool: True for success or False otherwise For example, loop_ _rcsb_chem_comp_related.comp_id _rcsb_chem_comp_related.ordinal _rcsb_chem_comp_related.resource_name _rcsb_chem_comp_related.resource_accession_code _rcsb_chem_comp_related.related_mapping_method ATP 1 DrugBank DB00171 'assigned by resource' """ try: logger.debug("Starting with %r %r", dataContainer.getName(), catName) if not (dataContainer.exists("chem_comp_atom") and dataContainer.exists("chem_comp_bond")): return False rP = kwargs.get("resourceProvider") # ------- new ccId = self.__getChemCompId(dataContainer) dbId, atcIdL, mappingType, dbVersion = self.__getDrugBankMapping(dataContainer, rP) logger.debug("Using DrugBank version %r", dbVersion) # ------------ ----------------------- ----------------------- ----------------------- ----------- if dbId: # if dataContainer.exists("rcsb_chem_comp_container_identifiers"): tObj = dataContainer.getObj("rcsb_chem_comp_container_identifiers") if not tObj.hasAttribute("drugbank_id"): tObj.appendAttribute("drugbank_id") tObj.setValue(dbId, "drugbank_id", 0) if atcIdL: if not tObj.hasAttribute("atc_codes"): tObj.appendAttribute("atc_codes") tObj.setValue(",".join(atcIdL), "atc_codes", 0) # if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) rL = wObj.selectIndices("DrugBank", "resource_name") ok = False if rL: ok = wObj.removeRows(rL) if not ok: logger.debug("Error removing rows in %r %r", catName, rL) # --- iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue("DrugBank", "resource_name", iRow) wObj.setValue(dbId, "resource_accession_code", iRow) wObj.setValue(mappingType, "related_mapping_method", iRow) # # ------------ ----------------------- ----------------------- ----------------------- ----------- ccmProvider = rP.getResource("ChemCompModelProvider instance") if rP else None if ccmProvider: csdMapD = ccmProvider.getMapping() # if csdMapD and ccId in csdMapD: if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) logger.debug("Using CSD model mapping length %d", len(csdMapD)) dbId = csdMapD[ccId][0]["db_code"] rL = wObj.selectIndices("CCDC/CSD", "resource_name") if rL: ok = wObj.removeRows(rL) if not ok: logger.debug("Error removing rows in %r %r", catName, rL) iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue("CCDC/CSD", "resource_name", iRow) wObj.setValue(dbId, "resource_accession_code", iRow) wObj.setValue("assigned by PDB", "related_mapping_method", iRow) # residProvider = rP.getResource("ResidProvider instance") if rP else None if residProvider: residMapD = residProvider.getMapping() # if residMapD and ccId in residMapD: if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) rL = wObj.selectIndices("RESID", "resource_name") if rL: ok = wObj.removeRows(rL) if not ok: logger.debug("Error removing rows in %r %r", catName, rL) logger.debug("Using RESID model mapping length %d", len(residMapD)) for rD in residMapD[ccId]: dbId = rD["residCode"] iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue("RESID", "resource_name", iRow) wObj.setValue(dbId, "resource_accession_code", iRow) wObj.setValue("matching by RESID resource", "related_mapping_method", iRow) # pubchemProvider = rP.getResource("PubChemProvider instance") if rP else None pharosProvider = rP.getResource("PharosProvider instance") if rP else None if pubchemProvider and pharosProvider: pubchemMapD = pubchemProvider.getIdentifiers() if pubchemMapD and ccId in pubchemMapD: pharosChemblD = pharosProvider.getIdentifiers() if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) for rName in ["ChEBI", "ChEMBL", "CAS", "PubChem"]: rL = wObj.selectIndices(rName, "resource_name") if rL: ok = wObj.removeRows(rL) if not ok: logger.debug("Error removing rows in %r %r", catName, rL) # logger.debug("Using PubChem mapping length %d", len(pubchemMapD)) xD = {} for rD in pubchemMapD[ccId]: for tName, tObj in rD.items(): if tName == "pcId": xD.setdefault("PubChem", set()).add(tObj) elif tName in ["CAS", "ChEBI"]: for tId in tObj: xD.setdefault(tName, set()).add(tId) elif tName in ["ChEMBL"]: for tId in tObj: xD.setdefault(tName, set()).add(tId) if pharosChemblD and tId in pharosChemblD: logger.debug("Mapping ccId %r to Pharos %r", ccId, tId) xD.setdefault("Pharos", set()).add(tId) # for rName, rIdS in xD.items(): if rName in ["PubChem", "Pharos"]: aMethod = "matching InChIKey in PubChem" elif rName in ["CAS", "ChEMBL", "ChEBI"]: aMethod = "assigned by PubChem resource" elif rName in ["Pharos"]: aMethod = "matching ChEMBL ID in Pharos" for rId in rIdS: iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue(rName, "resource_name", iRow) wObj.setValue(rId, "resource_accession_code", iRow) wObj.setValue(aMethod, "related_mapping_method", iRow) return True except Exception as e: logger.exception("For %s failing with %s", catName, str(e)) return False def __getChemCompId(self, dataContainer): if not dataContainer.exists("chem_comp"): return None ccObj = dataContainer.getObj("chem_comp") if not ccObj.hasAttribute("pdbx_release_status"): return None return ccObj.getValueOrDefault("id", 0, None) def __getDrugBankMapping(self, dataContainer, resourceProvider): """Return the DrugBank mapping for the chemical definition in the input dataContainer. Args: dataContainer (obj): instance of a DataContainer() object resourceProvider (obj): instance of a ResourceProvider() object Returns: mType, DrugBankId, actL (str,str, list): mapping type and DrugBank accession code, list of ATC assignments """ try: dbId = None atcL = [] mappingType = None dbProvider = resourceProvider.getResource("DrugBankProvider instance") if resourceProvider else None dbD = dbProvider.getMapping() dbVersion = dbProvider.getVersion() if dbD: ccId = self.__getChemCompId(dataContainer) # dbMapD = dbD["id_map"] inKeyD = dbD["inchikey_map"] atcD = dbD["db_atc_map"] logger.debug("DrugBank correspondence length is %d", len(dbMapD)) logger.debug("atcD length is %d", len(atcD)) logger.debug("inKeyD length is %d", len(inKeyD)) # if dataContainer.exists("rcsb_chem_comp_descriptor"): ccIObj = dataContainer.getObj("rcsb_chem_comp_descriptor") if ccIObj.hasAttribute("InChIKey"): inky = ccIObj.getValue("InChIKey", 0) logger.debug("inKeyD length is %d testing %r", len(inKeyD), inky) if inky in inKeyD: logger.debug("Matching inchikey for %s", ccId) dbId = inKeyD[inky][0]["drugbank_id"] mappingType = "matching InChIKey in DrugBank" # if not dbId and dbMapD and dataContainer.getName() in dbMapD: dbId = dbMapD[ccId]["drugbank_id"] mappingType = "assigned by DrugBank resource" logger.debug("Matching db assignment for %s", ccId) if atcD and dbId in atcD: atcL = atcD[dbId] except Exception as e: logger.exception("Failing with %s", str(e)) return dbId, atcL, mappingType, dbVersion def addChemCompAnnotation(self, dataContainer, catName, **kwargs): """Generate the rcsb_chem_annotation category - Args: dataContainer ([type]): [description] catName ([type]): [description] Returns: [type]: [description] loop_ _rcsb_chem_comp_annotation.ordinal _rcsb_chem_comp_annotation.entry_id _rcsb_chem_comp_annotation.entity_id # _rcsb_chem_comp_annotation.annotation_id _rcsb_chem_comp_annotation.type _rcsb_chem_comp_annotation.name _rcsb_chem_comp_annotation.description # _rcsb_chem_comp_annotation.annotation_lineage_id _rcsb_chem_comp_annotation.annotation_lineage_name _rcsb_chem_comp_annotation.annotation_lineage_depth # _rcsb_chem_comp_annotation.provenance_source _rcsb_chem_comp_annotation.assignment_version # ... loop_ _pdbx_chem_comp_feature.comp_id _pdbx_chem_comp_feature.type _pdbx_chem_comp_feature.value _pdbx_chem_comp_feature.source _pdbx_chem_comp_feature.support NAG 'CARBOHYDRATE ISOMER' D PDB ? NAG 'CARBOHYDRATE RING' pyranose PDB ? NAG 'CARBOHYDRATE ANOMER' beta PDB ? """ try: if not (dataContainer.exists("chem_comp_atom") and dataContainer.exists("chem_comp_bond")): return False # logger.debug("Starting with %r %r", dataContainer.getName(), catName) rP = kwargs.get("resourceProvider") ccId = self.__getChemCompId(dataContainer) # ---- if dataContainer.exists("pdbx_chem_comp_feature"): fObj = dataContainer.getObj("pdbx_chem_comp_feature") if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) # modDate = None if dataContainer.exists("chem_comp"): cObj = dataContainer.getObj("chem_comp") if cObj.hasAttribute("pdbx_modified_date"): modDate = cObj.getValue("pdbx_modified_date", 0) else: logger.info("%r missing modified_date", ccId) # fD = {} for ii in range(fObj.getRowCount()): pSource = fObj.getValue("source", ii) pCode = "PDB Reference Data" if pSource.upper() == "PDB" else None if not pCode: continue fType = fObj.getValue("type", ii) if fType.upper() not in ["CARBOHYDRATE ISOMER", "CARBOHYDRATE RING", "CARBOHYDRATE ANOMER", "CARBOHYDRATE PRIMARY CARBONYL GROUP"]: continue fType = fType.title() fValue = fObj.getValue("value", ii) if (fType, fValue, pCode) in fD: continue fD[(fType, fValue, pCode)] = True # iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue(fType, "type", iRow) wObj.setValue("%s_%d" % (ccId, ii + 1), "annotation_id", iRow) wObj.setValue(fValue, "name", iRow) wObj.setValue(pCode, "provenance_source", iRow) av = modDate if modDate else "1.0" wObj.setValue(av, "assignment_version", iRow) # # ---- dbId, atcIdL, mappingType, dbVersion = self.__getDrugBankMapping(dataContainer, rP) atcP = rP.getResource("AtcProvider instance") if rP else None if atcIdL and atcP: # if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) # ----- wObj = dataContainer.getObj(catName) # for atcId in atcIdL: if not atcP.getAtcName(atcId): continue iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue("ATC", "type", iRow) wObj.setValue(atcId, "annotation_id", iRow) wObj.setValue(atcP.getAtcName(atcId), "name", iRow) # wObj.setValue("ATC " + mappingType, "description", iRow) # --- wObj.setValue(";".join(atcP.getNameLineage(atcId)), "annotation_lineage_name", iRow) idLinL = atcP.getIdLineage(atcId) wObj.setValue(";".join(idLinL), "annotation_lineage_id", iRow) wObj.setValue(";".join([str(jj) for jj in range(0, len(idLinL) + 1)]), "annotation_lineage_depth", iRow) # wObj.setValue("DrugBank", "provenance_source", iRow) wObj.setValue(dbVersion, "assignment_version", iRow) logger.debug("dbId %r atcId %r lineage %r", dbId, atcId, idLinL) # ----- rsProvider = rP.getResource("ResidProvider instance") if rP else None residD = rsProvider.getMapping() # if residD and (ccId in residD): if not dataContainer.exists(catName): dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName))) wObj = dataContainer.getObj(catName) # ----- residVersion = rsProvider.getVersion() jj = 1 for rD in residD[ccId]: if "modRes" not in rD: continue for modRes in rD["modRes"]: iRow = wObj.getRowCount() wObj.setValue(ccId, "comp_id", iRow) wObj.setValue(iRow + 1, "ordinal", iRow) wObj.setValue("Modification Type", "type", iRow) wObj.setValue("modres_%d" % jj, "annotation_id", iRow) wObj.setValue(modRes, "name", iRow) wObj.setValue("RESID", "provenance_source", iRow) wObj.setValue(residVersion, "assignment_version", iRow)
chat_id = update.message.chat_id message = general_burned_eth_message() context.bot.send_message(chat_id=chat_id, text=message, disable_web_page_preview=True, parse_mode='html') context.bot.send_message(chat_id=announcement_channel_id, text=message, disable_web_page_preview=True, parse_mode='html') def general_burned_eth_message(): price_usd_eth, burn_rate_1_h, burn_rate_24_h, total_burn = general_end_functions.get_burned_eth_data() burn_rate_1_h_usd = burn_rate_1_h * price_usd_eth burn_rate_24_h_usd = burn_rate_24_h * price_usd_eth total_burned_usd = int(total_burn * price_usd_eth) message = "<b>Burn rate:</b><code>" + \ "\n1H : " + util.pretty_number(burn_rate_1_h) + 'ETH/min = ' + util.pretty_number( burn_rate_1_h_usd) + "$/min" + \ "\n24H: " + util.pretty_number(burn_rate_24_h) + 'ETH/min = ' + util.pretty_number( burn_rate_24_h_usd) + "$/min" + \ "\n</code><b>Total burned:</b><code> " + \ "\n" + util.pretty_number(total_burn) + 'ETH = ' + util.pretty_number(total_burned_usd) + '$</code>' return message def get_time_to(update: Update, context: CallbackContext): __log_channel(update.message.chat, "timeto") chat_id = update.message.chat_id query_received = update.message.text[7:] if query_received in ["jackpot", " jackpot"]: query_received = "7 pm CST" elif query_received.lower() in ["christmas", " christmas"]: logging.info("requesting timeto christmas") query_received = "25 december" higher, time_to = time_util.get_time_diff(query_received) word = ' is ' if higher else ' was ' message = str(query_received) + word + str(time_to) + " from now." context.bot.send_message(chat_id=chat_id, text=message, disable_web_page_preview=True) # TODO: fix stuff with default token not being fully used def get_latest_actions(update: Update, context: CallbackContext): __log_channel(update.message.chat, "last_actions") chat_id = update.message.chat_id query_received = update.message.text.split(' ') if len(query_received) == 1: default_token = __get_default_token_channel(chat_id) if default_token is not None: latest_actions_pretty = general_end_functions.get_last_actions_token_in_eth_pair(token_ticker=default_token[0], uni_wrapper=uni_wrapper, graphql_client_uni=graphql_client_uni, converter=converter ) util.create_and_send_vote(default_token[0], "actions", update.message.from_user.name, zerorpc_client_data_aggregator) context.bot.send_message(chat_id=chat_id, text=latest_actions_pretty, disable_web_page_preview=True, parse_mode='html') context.bot.send_message(chat_id=announcement_channel_id, text=latest_actions_pretty, disable_web_page_preview=True, parse_mode='html') else: context.bot.send_message(chat_id=chat_id, text=rejection_no_default_ticker_message) else: default_token = __get_default_token_channel(chat_id) if default_token is not None: ticker, addr = default_token[0], default_token[1] else: ticker, addr = None, None token, options = queries_parser.analyze_query_last_actions(update.message.text, ticker) if token is not None: latest_actions_pretty = general_end_functions.get_last_actions_token_in_eth_pair(token_ticker=token, uni_wrapper=uni_wrapper, graphql_client_uni=graphql_client_uni, converter=converter, contract=None, options=options) util.create_and_send_vote(token, "actions", update.message.from_user.name, zerorpc_client_data_aggregator) context.bot.send_message(chat_id=chat_id, text=latest_actions_pretty, disable_web_page_preview=True, parse_mode='html') context.bot.send_message(chat_id=announcement_channel_id, text=latest_actions_pretty, disable_web_page_preview=True, parse_mode='html') else: context.bot.send_message(chat_id=chat_id, text=rejection_no_default_ticker_message) def get_trending(update: Update, context: CallbackContext): __log_channel(update.message.chat, "trending") chat_id = update.message.chat_id res = zerorpc_client_data_aggregator.view_trending() context.bot.send_message(chat_id=chat_id, text=res) context.bot.send_message(chat_id=announcement_channel_id, text=res) def get_gas_spent(update: Update, context: CallbackContext): __log_channel(update.message.chat, "gas_spent") chat_id = update.message.chat_id query_received = update.message.text.split(' ') if len(query_received) >= 2: addr, options = queries_parser.analyze_query_gas_spent(update.message.text) res = general_end_functions.get_gas_spent(addr, options) context.bot.send_message(chat_id=chat_id, text=res) else: context.bot.send_message(chat_id=chat_id, text="Please use the format /gas_spent address (ex: /gas_spent 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8)") # ADMIN STUFF def set_faq(update: Update, context: CallbackContext): __log_channel(update.message.chat, "set_faq") chat_id = update.message.chat_id query_received = update.message.text[8:] if __is_user_admin(context, update): if query_received != "": faq = query_received res = zerorpc_client_data_aggregator.set_faq(chat_id, faq) message_info = res + '\n' + message_faq_additional context.bot.send_message(chat_id=chat_id, text=message_info, parse_mode='html', disable_web_page_preview=True) else: context.bot.send_message(chat_id=chat_id, text="Please use the format /set_faq FAQ") else: context.bot.send_message(chat_id=chat_id, text="Only an admin can do that you silly.") def get_the_faq(update: Update, context: CallbackContext): __log_channel(update.message.chat, "faq") chat_id = update.message.chat_id res = __get_faq_channel(chat_id) if res == "null" or res is None: res = message_faq_empty try: context.bot.send_message(chat_id=chat_id, text=res, parse_mode='html', disable_web_page_preview=True) except BadRequest: header = "Looks like some html tags are not properly set. Here's the raw faq: \n" context.bot.send_message(chat_id=chat_id, text=header + res, disable_web_page_preview=True) def __get_faq_channel(channel_id: int): res = zerorpc_client_data_aggregator.get_faq(channel_id) return res def set_default_token(update: Update, context: CallbackContext): __log_channel(update.message.chat, "set_default_token") chat_id = update.message.chat_id query_received = update.message.text.split(' ') if __is_user_admin(context, update): if len(query_received) == 2: ticker = query_received[1].upper() token_addr = requests_util.get_token_contract_address(ticker) logging.info("setting default channel " + str(chat_id) + " with address " + str(token_addr)) res = zerorpc_client_data_aggregator.set_default_token(chat_id, ticker, token_addr) context.bot.send_message(chat_id=chat_id, text=res) elif len(query_received) == 3: ticker = query_received[1].upper() token_addr = query_received[2].lower() logging.info("setting default channel " + str(chat_id) + " with address " + str(token_addr)) res = zerorpc_client_data_aggregator.set_default_token(chat_id, ticker, token_addr) context.bot.send_message(chat_id=chat_id, text=res) else: context.bot.send_message(chat_id=chat_id, text="Please use the format /set_default_token TICKER (address)") else: context.bot.send_message(chat_id=chat_id, text="Only an admin can do that you silly.") def get_default_token(update: Update, context: CallbackContext): __log_channel(update.message.chat, "default_token") chat_id = update.message.chat_id ticker, addr = __get_default_token_channel(chat_id) context.bot.send_message(chat_id=chat_id, text="ticker: " + str(ticker) + " - addr: " + str(addr)) def __get_default_token_channel(channel_id: int): res = zerorpc_client_data_aggregator.get_default_token(channel_id) if res is not None: logging.debug("Default token channel " + str(channel_id) + " is " + str(res[0]) + " - " + str(res[1])) else: logging.debug("Default token channel " + str(channel_id) + " is None") return res def set_function(update: Update, context: CallbackContext): channel_type = update.message.chat.type __log_channel(update.message.chat, "set_function") chat_id = update.message.chat_id query_received = update.message.text.split(' ') if __is_user_admin(context, update) or channel_type == "private": if len(query_received) == 2: arg = query_received[1] if arg.lower() == "meme": res = not _is_meme_authorized_on_channel(chat_id) _update_meme_status_on_channel(chat_id, res) if res: context.bot.send_message(chat_id=chat_id, text="Memes are now activated. You can now:\nAdd some with /add_meme\nView one random with /get_meme\nRemove one with /delete_meme (only for admins).") else: context.bot.send_message(chat_id=chat_id, text="Memes are now de-activated. You can always go back with /set_function meme (only for admins)") else: context.bot.send_message(chat_id=chat_id, text="Wrongly formatted query") else: context.bot.send_message(chat_id=chat_id, text="This function is only available to admins or in private chat") def set_monitor(update: Update, context: CallbackContext): channel_type = update.message.chat.type __log_channel(update.message.chat, "set_monitor") chat_id = update.message.chat_id query_received = update.message.text.split(' ') if __is_user_admin(context, update) or channel_type == "private": if len(query_received) == 2: ticker = query_received[1].upper() token_addr = requests_util.get_token_contract_address(ticker) message = "setting watcher for token actions (buys > 10eth) with address " + str( token_addr) + ". If it is not the correct address, please define it explicitly with /set_default_token TICKER ADDRESS" zerorpc_client_data_aggregator.add_monitor(chat_id, token_addr, "buy") context.bot.send_message(chat_id=chat_id, text=message) elif len(query_received) == 3: ticker = query_received[1].upper() token_addr = query_received[2].lower() message = "setting watcher for token actions (buys > 10eth) with address " + str( token_addr) + ". If it is not the correct address, please define it explicitly with /set_default_token TICKER ADDRESS" zerorpc_client_data_aggregator.add_monitor(chat_id, token_addr, "buy") context.bot.send_message(chat_id=chat_id, text=message) else: context.bot.send_message(chat_id=chat_id, text="Only admins can do that you silly") def __is_user_admin(context, update): user = context.bot.get_chat_member(update.effective_chat.id, update.message.from_user.id) status = user.status username = user.user.username return status == 'administrator' or status == 'creator' or username == 'rotted_ben' def get_chart_supply(update: Update, context: CallbackContext): __log_channel(update.message.chat, "chart_supply") chat_id = update.message.chat_id query_received = update.message.text.split(' ') default_ticker_channel = __get_default_token_channel(chat_id) ok = True if len(query_received) == 1 and (default_ticker_channel is None or default_ticker_channel == "null"): ok = False if default_ticker_channel is None or default_ticker_channel == "": default_ticker_channel = "" else: default_ticker_channel = default_ticker_channel[0] if ok: time_type, k_hours, k_days, tokens = commands_util.check_query(query_received, default_ticker_channel) if isinstance(tokens, list): tokens = tokens[0] ticker_supply_file_path = supply_file_path.replace("$TICKER", tokens.upper()) ticker_supply_chart_path = supply_chart_path.replace("$TICKER", tokens.upper()) current_token_nbr = general_end_functions.send_supply_single_pyplot(ticker_supply_file_path, k_days, k_hours, tokens, ticker_supply_chart_path) current_token_str = util.number_to_beautiful(current_token_nbr) msg_time = " " + str(k_days) + " day(s) " if k_days > 0 else " last " + str(k_hours) + " hour(s) " caption = "Supply of the last " + msg_time + ".\nCurrent supply: \n<b>" + tokens + ":</b> <pre>" + current_token_str + "</pre>" context.bot.send_photo(chat_id=chat_id, photo=open(ticker_supply_chart_path, 'rb'), caption=caption, parse_mode="html") def _is_meme_authorized_on_channel(channel_id: int) -> bool: return zerorpc_client_data_aggregator.get_meme_channel_value(channel_id) def _update_meme_status_on_channel(channel_id: int, status: bool): return zerorpc_client_data_aggregator.update_meme_channel_value(channel_id, status) @cached(cache=TTLCache(maxsize=1024, ttl=120)) def _is_coin_being_watched(ticker: str): return zerorpc_client_data_aggregator.is_coin_being_watched(ticker.upper()) def text_if_coin_being_watched(ticker: str, small=False): if _is_coin_being_watched(ticker): logging.info(ticker + " is being watched") if small: return "➡ @TheFomoBot_" + ticker.upper() + "_actions ⬅" else: return "Live $" + ticker.upper() + " actions ➡ @TheFomoBot_" + ticker.upper() + "_actions ⬅" else: return None def __log_channel(chat, method): now = datetime.now().strftime('%Y-%m-%d, %H') # today = datetime.today().strftime('%Y-%m-%d') chat_id = chat.id channel_type = chat.type chat_name = chat.title logging.info("chat_id = " + str(chat_id) + " - type = " + str(channel_type) + " - chat_name = " + str( chat_name) + " - method " + method) zerorpc_client_data_aggregator.log_action(chat_id, channel_type, str(chat_name), now, method) # casting chat name to str in case it's None def __send_message_to_announcement_channel_if_needed(username: str, method: str, token: str, message: str, context: CallbackContext) -> None: if not __did_user_vote_too_much(username, method, token): context.bot.send_message(chat_id=announcement_channel_id, text=message, parse_mode='html', disable_web_page_preview=True) def __did_user_vote_too_much(username, method, token) -> bool: hashed_uname = util.get_hashed_uname(username) return zerorpc_client_data_aggregator.did_user_vote_too_much(hashed_uname, method, token.upper()) def callback_minute(context: CallbackContext): if IS_TEST_ENV: return channels_to_check = zerorpc_client_data_aggregator.get_all_monitors() logging.info("checking monitors") now = round(time.time()) last_min = now - (60 * 5) - 20 new_list = {} if channels_to_check is not None: for c in channels_to_check: if c[1].lower() in new_list: new_list[c[1].lower()] = new_list.get(c[1].lower()) + [c[0]] else: new_list[c[1].lower()] = [c[0]] for coin, value in new_list.items(): # pprint.pprint(channel_mon) # channel = channel_mon[0] # coin = channel_mon[1] # monitor_type = channel_mon[2] options = ["buy", "whale"] pair = web3_calls.does_pair_token_eth_exist(coin, uni_wrapper) latest_actions_pretty = requests_util.pretty_print_monitor_last_actions(last_min, coin, pair.lower(), graphql_client_uni, uni_wrapper, converter, options) if latest_actions_pretty is not None: maybe_bottom_text = text_if_coin_being_watched(coin) if maybe_bottom_text is not None and maybe_bottom_text != "": follow_up_message = "\n" + maybe_bottom_text else: follow_up_message = "" logging.debug("follow up message: " + follow_up_message) message = latest_actions_pretty + follow_up_message for channel in value: logging.info("sent latest actions to channel: " + str(channel)) try: context.bot.send_message(chat_id=channel, text=message, disable_web_page_preview=True, parse_mode='html') except ChatMigrated as err: logging.info("CHANNEL ID CHANGED: ", err) def translate_text(update:
# -*- coding:utf-8 -*- # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110- 1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> # ---------------------------------------------------------- # Author: <NAME> (s-leger) # # ---------------------------------------------------------- bl_info = { 'name': 'PolyLib', 'description': 'Polygons detection from unordered splines', 'author': 's-leger', 'license': 'GPL', 'deps': 'shapely', 'version': (1, 1), 'blender': (2, 7, 8), 'location': 'View3D > Tools > Polygons', 'warning': '', 'wiki_url': 'https://github.com/s-leger/blenderPolygons/wiki', 'tracker_url': 'https://github.com/s-leger/blenderPolygons/issues', 'link': 'https://github.com/s-leger/blenderPolygons', 'support': 'COMMUNITY', 'category': '3D View' } import sys import time import bpy import bgl import numpy as np from math import cos, sin, pi, atan2 import bmesh # let shapely import raise ImportError when missing import shapely.ops import shapely.prepared from shapely.geometry import Point as ShapelyPoint from shapely.geometry import Polygon as ShapelyPolygon try: import shapely.speedups if shapely.speedups.available: shapely.speedups.enable() except: pass from .bitarray import BitArray from .pyqtree import _QuadTree from mathutils import Vector, Matrix from mathutils.geometry import intersect_line_plane, interpolate_bezier from bpy_extras import view3d_utils from bpy.types import Operator, PropertyGroup from bpy.props import StringProperty, FloatProperty, PointerProperty, EnumProperty, IntProperty, BoolProperty from bpy.app.handlers import persistent from .materialutils import MaterialUtils from .archipack_gl import ( FeedbackPanel, GlCursorFence, GlCursorArea, GlLine, GlPolyline ) # module globals vars dict vars_dict = { # spacial tree for segments and points 'seg_tree': None, 'point_tree': None, # keep track of shapely geometry selection sets 'select_polygons': None, 'select_lines': None, 'select_points': None } # module constants # precision 1e-4 = 0.1mm EPSILON = 1.0e-4 # Qtree params MAX_ITEMS = 10 MAX_DEPTH = 20 class CoordSys(object): """ reference coordsys world : matrix from local to world invert: matrix from world to local width, height: bonding region size """ def __init__(self, objs): x = [] y = [] if len(objs) > 0: if hasattr(objs[0], 'bound_box'): for obj in objs: pos = obj.location x.append(obj.bound_box[0][0] + pos.x) x.append(obj.bound_box[6][0] + pos.x) y.append(obj.bound_box[0][1] + pos.y) y.append(obj.bound_box[6][1] + pos.y) elif hasattr(objs[0], 'bounds'): for geom in objs: x0, y0, x1, y1 = geom.bounds x.append(x0) x.append(x1) y.append(y0) y.append(y1) else: raise Exception("CoordSys require at least one object with bounds or bound_box property to initialize") else: raise Exception("CoordSys require at least one object to initialize bounds") x0 = min(x) y0 = min(y) x1 = max(x) y1 = max(y) width, height = x1 - x0, y1 - y0 midx, midy = x0 + width / 2.0, y0 + height / 2.0 # reference coordsys bounding box center self.world = Matrix([ [1, 0, 0, midx], [0, 1, 0, midy], [0, 0, 1, 0], [0, 0, 0, 1], ]) self.invert = self.world.inverted() self.width = width self.height = height class Prolongement(): """ intersection of two segments outside segment (projection) c0 = extremite sur le segment courant c1 = intersection point on oposite segment id = oposite segment id t = param t on oposite segment d = distance from ends to segment insert = do we need to insert the point on other segment use id, c1 and t to insert segment slices """ def __init__(self, c0, c1, id, t, d): self.length = c0.distance(c1) self.c0 = c0 self.c1 = c1 self.id = id self.t = t self.d = d class Point(): def __init__(self, co, precision=EPSILON): self.users = 0 self.co = tuple(co) x, y, z = co self.shapeIds = [] self.bounds = (x - precision, y - precision, x + precision, y + precision) @property def geom(self): return ShapelyPoint(self.co) def vect(self, point): """ vector from this point to another """ return np.subtract(point.co, self.co) def distance(self, point): """ euclidian distance between points """ return np.linalg.norm(self.vect(point)) def add_user(self): self.users += 1 class Segment(): def __init__(self, c0, c1, extend=EPSILON): self.c0 = c0 self.c1 = c1 self._splits = [] self.available = True # ensure uniqueness when merge self.opposite = False # this seg has an opposite self.original = False # source of opposite x0, y0, z0 = c0.co x1, y1, z1 = c1.co self.bounds = (min(x0, x1) - extend, min(y0, y1) - extend, max(x0, x1) + extend, max(y0, y1) + extend) @property def splits(self): return sorted(self._splits) @property def vect(self): """ vector c0-c1""" return np.subtract(self.c1.co, self.c0.co) @property def vect_2d(self): v = self.vect v[2] = 0 return v def lerp(self, t): return np.add(self.c0.co, np.multiply(t, self.vect)) def _point_sur_segment(self, point): """ _point_sur_segment point: Point t: param t de l'intersection sur le segment courant d: distance laterale perpendiculaire """ vect = self.vect dp = point.vect(self.c0) dl = np.linalg.norm(vect) d = np.linalg.norm(np.cross(vect, dp)) / dl t = -np.divide(np.dot(dp, vect), np.multiply(dl, dl)) if d < EPSILON: if t > 0 and t < 1: self._append_splits((t, point)) def is_end(self, point): return point == self.c0 or point == self.c1 def min_intersect_dist(self, t, point): """ distance intersection extremite la plus proche t: param t de l'intersection sur le segment courant point: Point d'intersection return d: distance """ if t > 0.5: return self.c1.distance(point) else: return self.c0.distance(point) def intersect(self, segment): """ point_sur_segment return p: point d'intersection u: param t de l'intersection sur le segment courant v: param t de l'intersection sur le segment segment """ v2d = self.vect_2d c2 = np.cross(segment.vect_2d, (0, 0, 1)) d = np.dot(v2d, c2) if d == 0: # segments paralleles segment._point_sur_segment(self.c0) segment._point_sur_segment(self.c1) self._point_sur_segment(segment.c0) self._point_sur_segment(segment.c1) return False, 0, 0, 0 c1 = np.cross(v2d, (0, 0, 1)) v3 = self.c0.vect(segment.c0) v3[2] = 0.0 u = np.dot(c2, v3) / d v = np.dot(c1, v3) / d co = self.lerp(u) return True, co, u, v def _append_splits(self, split): """ append a unique split point """ if split not in self._splits: self._splits.append(split) def slice(self, d, t, point): if d > EPSILON: if t > 0.5: if point != self.c1: self._append_splits((t, point)) else: if point != self.c0: self._append_splits((t, point)) def add_user(self): self.c0.add_user() self.c1.add_user() def consume(self): self.available = False class Shape(): """ Ensure uniqueness and fix precision issues by design implicit closed with last point require point_tree and seg_tree """ def __init__(self, points=[]): """ @vertex: list of coords """ self.available = True # Ensure uniqueness of shape when merging self._segs = [] # Shape segments self.shapeId = [] # Id of shape in shapes to keep a track of shape parts when merging self._create_segments(points) def _create_segments(self, points): global vars_dict if vars_dict['seg_tree'] is None: raise RuntimeError('Shape._create_segments() require spacial index ') # skip null segments with unique points test self._segs = list(vars_dict['seg_tree'].newSegment(points[v], points[v + 1]) for v in range(len(points) - 1) if points[v] != points[v + 1]) @property def coords(self): coords = list(seg.c0.co for seg in self._segs) coords.append(self.c1.co) return coords @property def points(self): points = list(seg.c0 for seg in self._segs) points.append(self.c1) return points @property def c0(self): if not self.valid: raise RuntimeError('Shape does not contains any segments') return self._segs[0].c0 @property def c1(self): if not self.valid: raise RuntimeError('Shape does not contains any segments') return self._segs[-1].c1 @property def nbsegs(self): return len(self._segs) @property def valid(self): return self.nbsegs > 0 @property def closed(self): return self.valid and bool(self.c0 == self.c1) def merge(self, shape): """ merge this shape with specified shape shapes must share at least one vertex """ if not self.valid or not shape.valid: raise RuntimeError('Trying to merge invalid shape') if self.c1 == shape.c1 or self.c0 == shape.c0: shape._reverse() if self.c1 == shape.c0: self._segs += shape._segs elif shape.c1 == self.c0: self._segs = shape._segs + self._segs else: # should never happen raise RuntimeError("Shape merge failed {} {} {} {}".format( id(self), id(shape), self.shapeId, shape.shapeId)) def _reverse(self): """ reverse vertex order """ points = self.points[::-1] self._create_segments(points) def slice(self, shapes): """ slice shape into smaller parts at intersections """ if not self.valid: raise RuntimeError('Cant slice invalid shape') points = [] for seg in self._segs: if seg.available and not seg.original: seg.consume() points.append(seg.c0) if seg.c1.users > 2:
+ 0.20000000000j, '10110010': -0.60000000000 + 0.33333333333j, '10110011': -0.60000000000 + 0.46666666667j, '10110100': -0.60000000000 + 0.60000000000j, '10110101': -0.60000000000 + 0.73333333333j, '10110110': -0.60000000000 + 0.86666666667j, '10110111': -0.60000000000 + 1.00000000000j, '10111000': -0.60000000000 - 1.00000000000j, '10111001': -0.60000000000 - 0.86666666667j, '10111010': -0.60000000000 - 0.73333333333j, '10111011': -0.60000000000 - 0.60000000000j, '10111100': -0.60000000000 - 0.46666666667j, '10111101': -0.60000000000 - 0.33333333333j, '10111110': -0.60000000000 - 0.20000000000j, '10111111': -0.60000000000 - 0.06666666667j, '11000000': -0.46666666667 + 0.06666666667j, '11000001': -0.46666666667 + 0.20000000000j, '11000010': -0.46666666667 + 0.33333333333j, '11000011': -0.46666666667 + 0.46666666667j, '11000100': -0.46666666667 + 0.60000000000j, '11000101': -0.46666666667 + 0.73333333333j, '11000110': -0.46666666667 + 0.86666666667j, '11000111': -0.46666666667 + 1.00000000000j, '11001000': -0.46666666667 - 1.00000000000j, '11001001': -0.46666666667 - 0.86666666667j, '11001010': -0.46666666667 - 0.73333333333j, '11001011': -0.46666666667 - 0.60000000000j, '11001100': -0.46666666667 - 0.46666666667j, '11001101': -0.46666666667 - 0.33333333333j, '11001110': -0.46666666667 - 0.20000000000j, '11001111': -0.46666666667 - 0.06666666667j, '11010000': -0.33333333333 + 0.06666666667j, '11010001': -0.33333333333 + 0.20000000000j, '11010010': -0.33333333333 + 0.33333333333j, '11010011': -0.33333333333 + 0.46666666667j, '11010100': -0.33333333333 + 0.60000000000j, '11010101': -0.33333333333 + 0.73333333333j, '11010110': -0.33333333333 + 0.86666666667j, '11010111': -0.33333333333 + 1.00000000000j, '11011000': -0.33333333333 - 1.00000000000j, '11011001': -0.33333333333 - 0.86666666667j, '11011010': -0.33333333333 - 0.73333333333j, '11011011': -0.33333333333 - 0.60000000000j, '11011100': -0.33333333333 - 0.46666666667j, '11011101': -0.33333333333 - 0.33333333333j, '11011110': -0.33333333333 - 0.20000000000j, '11011111': -0.33333333333 - 0.06666666667j, '11100000': -0.20000000000 + 0.06666666667j, '11100001': -0.20000000000 + 0.20000000000j, '11100010': -0.20000000000 + 0.33333333333j, '11100011': -0.20000000000 + 0.46666666667j, '11100100': -0.20000000000 + 0.60000000000j, '11100101': -0.20000000000 + 0.73333333333j, '11100110': -0.20000000000 + 0.86666666667j, '11100111': -0.20000000000 + 1.00000000000j, '11101000': -0.20000000000 - 1.00000000000j, '11101001': -0.20000000000 - 0.86666666667j, '11101010': -0.20000000000 - 0.73333333333j, '11101011': -0.20000000000 - 0.60000000000j, '11101100': -0.20000000000 - 0.46666666667j, '11101101': -0.20000000000 - 0.33333333333j, '11101110': -0.20000000000 - 0.20000000000j, '11101111': -0.20000000000 - 0.06666666667j, '11110000': -0.06666666667 + 0.06666666667j, '11110001': -0.06666666667 + 0.20000000000j, '11110010': -0.06666666667 + 0.33333333333j, '11110011': -0.06666666667 + 0.46666666667j, '11110100': -0.06666666667 + 0.60000000000j, '11110101': -0.06666666667 + 0.73333333333j, '11110110': -0.06666666667 + 0.86666666667j, '11110111': -0.06666666667 + 1.00000000000j, '11111000': -0.06666666667 - 1.00000000000j, '11111001': -0.06666666667 - 0.86666666667j, '11111010': -0.06666666667 - 0.73333333333j, '11111011': -0.06666666667 - 0.60000000000j, '11111100': -0.06666666667 - 0.46666666667j, '11111101': -0.06666666667 - 0.33333333333j, '11111110': -0.06666666667 - 0.20000000000j, '11111111': -0.06666666667 - 0.06666666667j} try: return np.array([qamMap[p] for p in pattern]) except KeyError: raise ValueError('Invalid 256 QAM symbol.') def digmod_prbs_generator(fs=100e6, modType='qpsk', symRate=10e6, prbsOrder=9, filt=rrc_filter, alpha=0.35, wfmFormat='iq', zeroLast=False): """DEPRECATED. THIS IS A PASS-THROUGH FUNCTION ONLY""" warnings.warn('pyarbtools.wfmBuilder.digmod_prbs_generator() is deprecated. Use pyarbtools.wfmBuilder.digmod_generator() instead.') if filt == rrc_filter: filt = 'rootraisedcosine' elif filt == rc_filter: filt = 'raisedcosine' numSymbols = int(2 ** prbsOrder - 1) return digmod_generator(fs=fs, symRate=symRate, modType=modType, numSymbols=numSymbols, filt=filt, alpha=alpha, zeroLast=zeroLast, wfmFormat=wfmFormat) def digmod_generator(fs=10, symRate=1, modType='bpsk', numSymbols=1000, filt='raisedcosine', alpha=0.35, wfmFormat='iq', zeroLast=False, plot=False): """ Generates a digitally modulated signal at baseband with a given modulation type, number of symbols, and filter type/alpha using random data. WARNING: Reading through this function is not for the faint of heart. There are a lot of details in here that you don't think about unless you're interacting with hardware. Args: fs (float): Sample rate used to create the waveform in samples/sec. symRate (float): Symbol rate in symbols/sec. modType (str): Type of modulation. ('bpsk', 'qpsk', 'psk8', 'psk16', 'qam16', 'qam32', 'qam64', 'qam128', 'qam256') numSymbols (int): Number of symbols to put in the waveform. filt (str): Pulse shaping filter type. ('raisedcosine' or 'rootraisedcosine') alpha (float): Pulse shaping filter excess bandwidth specification. Also known as roll-off factor, alpha, or beta. wfmFormat (str): Determines type of waveform. Currently only 'iq' format is supported. zeroLast (bool): Force the last sample point to 0. plot (bool): Enable or disable plotting of final waveform in time domain and constellation domain. Returns: (NumPy array): Array containing the complex values of the waveform. TODO Add an argument that allows user to specify symbol data. """ if symRate >= fs: raise error.WfmBuilderError('symRate violates Nyquist. Reduce symbol rate or increase sample rate.') if wfmFormat.lower() != 'iq': raise error.WfmBuilderError('Digital modulation currently supports IQ waveform format only.') if not isinstance(numSymbols, int) or numSymbols < 1: raise error.WfmBuilderError('"numSymbols" must be a positive integer value.') if not isinstance(zeroLast, bool): raise error.WfmBuilderError('"zeroLast" must be a boolean.') if not isinstance(plot, bool): raise error.WfmBuilderError('"plot" must be a boolean') # Use 20 samples per symbol for creating and pulse shaping the signal prior to final resampling intermediateOsFactor = 20 # Calculate oversampling factors for resampling finalOsFactor = fs / (symRate * intermediateOsFactor) # Python's built-in fractions module makes this easy fracOs = Fraction(finalOsFactor).limit_denominator(1000) finalOsNum = fracOs.numerator finalOsDenom = fracOs.denominator # print(f'Oversampling factor: {finalOsNum} / {finalOsDenom}') if finalOsNum > 200 and finalOsDenom > 200: print(f'Oversampling factor: {finalOsNum} / {finalOsDenom}') warn(f'Poor choice of sample rate/symbol rate. Resulting waveform will be large and slightly distorted. Choose sample rate so that it is an integer multiple of symbol rate.') # If necessary, adjust the number of symbols to ensure an integer number of samples after final resampling numSamples = numSymbols * finalOsNum / finalOsDenom # print(f'Initial numSymbols: {numSymbols}') if not numSamples.is_integer(): numSymbols = np.lcm(numSymbols, finalOsDenom) # print(f'Adjusted numSymbols: {numSymbols}') # Define bits per symbol and modulator function based on modType if modType.lower() == 'bpsk': bitsPerSym = 1 modulator = bpsk_modulator elif modType.lower() == 'qpsk': bitsPerSym = 2 modulator = qpsk_modulator elif modType.lower() == 'psk8': bitsPerSym = 3 modulator = psk8_modulator elif modType.lower() == 'psk16': bitsPerSym = 4 modulator = psk16_modulator elif modType.lower() == 'apsk16': bitsPerSym = 4 modulator = apsk16_modulator elif modType.lower() == 'apsk32': bitsPerSym = 5 modulator = apsk32_modulator elif modType.lower() == 'apsk64': bitsPerSym = 6 modulator = apsk64_modulator elif modType.lower() == 'qam16': bitsPerSym = 4 modulator = qam16_modulator elif modType.lower() == 'qam32': bitsPerSym = 5 modulator = qam32_modulator elif modType.lower() == 'qam64': bitsPerSym = 6 modulator = qam64_modulator elif modType.lower() == 'qam128': bitsPerSym = 7 modulator = qam128_modulator elif modType.lower() == 'qam256': bitsPerSym = 8 modulator = qam256_modulator else: raise ValueError('Invalid modType chosen.') # Create random bit pattern bits = np.random.randint(0, 2, bitsPerSym * numSymbols) # tempBits = bits # repeats = 1 # while len(bits) % bitsPerSym: # bits = np.tile(tempBits, repeats) # repeats += 1 # Group the bits into symbol values and then map the symbols to locations in the complex plane. modulatedValues = modulator(bits) # Zero-pad symbols to satisfy oversampling factor and provide impulse-like response for better pulse shaping performance. rawSymbols = np.zeros(len(modulatedValues) * intermediateOsFactor, dtype=np.complex) rawSymbols[::intermediateOsFactor] = modulatedValues # Create pulse shaping filter # The number of taps required must be a multiple of the oversampling factor taps = 4 * intermediateOsFactor if filt.lower() == 'rootraisedcosine': psFilter = rrc_filter(alpha, taps, intermediateOsFactor) elif filt.lower() == 'raisedcosine': psFilter = rc_filter(alpha, taps, intermediateOsFactor) else: raise error.WfmBuilderError('Invalid pulse shaping filter chosen. Use \'raisedcosine\' or \'rootraisedcosine\'') """There are several considerations here.""" # At the beginning and the end of convolution, the two arrays don't # fully overlap, which results in invalid data. We don't want to # keep that data, so we're prepending the end of the signal onto # the beginning and append the beginning onto the end to provide # "runway" for the convolution. We will be throwing this prepended # and appended data away at the end of the signal creation process. # # In order to eliminate wraparound issues, we need to ensure that # the prepended and appended segments will be an integer number of # samples AFTER final resampling. The extra segments must also # be at least as long as the pulse shaping filter so that we have # enough runway to get all the invalid samples out before getting # into the meat of the waveform. # Determine wraparound location wrapLocation = finalOsDenom # Make sure it's at least as long as the pulse shaping filter while wrapLocation < taps: wrapLocation *= 2 # Prepend and append rawSymbols = np.concatenate([rawSymbols[-wrapLocation:], rawSymbols, rawSymbols[:wrapLocation]]) # Apply pulse shaping filter to symbols via convolution filteredSymbols = np.convolve(rawSymbols, psFilter, mode='same') # Perform the final resampling AND filter out images using a single SciPy function iq = sig.resample_poly(filteredSymbols, finalOsNum, finalOsDenom, window=('kaiser', 11)) # Calculate location of final prepended and appended segments finalWrapLocation = wrapLocation * finalOsNum / finalOsDenom if finalWrapLocation.is_integer(): finalWrapLocation = int(finalWrapLocation) else: raise error.WfmBuilderError('Signal does not
# -*- coding: utf-8 -*- import math import numpy as np import numpy.random as npr import cv2 # from matplotlib.colors import rgb_to_hsv # from matplotlib.colors import hsv_to_rgb from configure import cfg import utils.blob # from caffe.io import resize_image def GenerateBatchSamples(roi, img_shape): sampled_bboxes = [] for i in range(len(cfg.TRAIN.batch_sampler)): sampled_bboxes_this = GenerateSamples(roi, cfg.TRAIN.batch_sampler[i], img_shape) sampled_bboxes.extend(sampled_bboxes_this) return sampled_bboxes def GenerateSamples(roi, batch_sampler, img_shape): found = 0 sampled_bboxes = [] for i in range(batch_sampler.max_trials): if found > batch_sampler.max_sample: return sampled_bboxes # Generate sampled_bbox in the normalized space [0, 1]. sampled_bbox = SampleBBox(batch_sampler.sampler, img_shape) if SatisfySampleConstraint(sampled_bbox, roi, batch_sampler.sample_constraint): found = found + 1 sampled_bboxes.append(sampled_bbox) return sampled_bboxes def SampleBBox(sampler, img_shape): # Get random scale. assert sampler.max_scale >= sampler.min_scale assert sampler.min_scale > 0.0 assert sampler.max_scale <= 1.0 scale = npr.uniform(sampler.min_scale, sampler.max_scale) # Get random aspect ratio. assert sampler.max_aspect_ratio >= sampler.min_aspect_ratio assert sampler.min_aspect_ratio > 0.0 assert sampler.max_aspect_ratio < 10000 aspect_ratio = npr.uniform(sampler.min_aspect_ratio, sampler.max_aspect_ratio) aspect_ratio = max(aspect_ratio, 1.0 * math.pow(scale, 2.0)) aspect_ratio = min(aspect_ratio, 1.0 / math.pow(scale, 2.0)) # Figure out bbox dimension. bbox_width = scale * math.sqrt(aspect_ratio) bbox_height = scale / math.sqrt(aspect_ratio) # Figure out top left coordinates. h_off = npr.uniform(0.0, 1.0 - bbox_height) w_off = npr.uniform(0.0, 1.0 - bbox_width) #--------------------------------------- bbox_height = bbox_height * img_shape[0] bbox_width = bbox_width * img_shape[1] h_off = h_off * img_shape[0] w_off = w_off * img_shape[1] assert bbox_width > 0 assert bbox_height > 0 sampled_bbox = np.array( [w_off, h_off, w_off + bbox_width, h_off + bbox_height], dtype=np.uint16) sampled_bbox[0] = min(max(sampled_bbox[0], 0), img_shape[1] - 1) sampled_bbox[1] = min(max(sampled_bbox[1], 0), img_shape[0] - 1) sampled_bbox[2] = min( max(sampled_bbox[2], sampled_bbox[0]), img_shape[1] - 1) sampled_bbox[3] = min( max(sampled_bbox[3], sampled_bbox[1]), img_shape[0] - 1) assert sampled_bbox[0] <= sampled_bbox[2] assert sampled_bbox[1] <= sampled_bbox[3] return sampled_bbox def SatisfySampleConstraint(sampled_bbox, roi, sample_constraint): # Check constraints. found = False roi_num = roi.shape[0] for i in range(roi_num): this_roi = roi[i, :] jaccard_overlap = JaccardOverlap(sampled_bbox, this_roi) if jaccard_overlap < sample_constraint.min_jaccard_overlap: continue if jaccard_overlap > sample_constraint.max_jaccard_overlap: continue return True return False def JaccardOverlap(bbox1, bbox2): intersect_bbox = IntersectBBox(bbox1, bbox2) intersect_width = intersect_bbox[2] - intersect_bbox[0] + 1 intersect_height = intersect_bbox[3] - intersect_bbox[1] + 1 if intersect_width > 0 and intersect_height > 0: intersect_size = intersect_width * intersect_height bbox1_size = BBoxSize(bbox1) bbox2_size = BBoxSize(bbox2) return 1.0 * intersect_size / ( bbox1_size + bbox2_size - intersect_size) else: return 0.0 def IntersectBBox(bbox1, bbox2): if bbox2[0] > bbox1[2] or bbox2[2] < bbox1[0] or bbox2[1] > bbox1[3] or bbox2[3] < bbox1[1]: # Return [0, 0, 0, 0] if there is no intersection. # intersect_bbox=[0.0,0.0,0.0,0.0] intersect_bbox = [-1.0, -1.0, -1.0, -1.0] else: intersect_bbox = [ max(bbox1[0], bbox2[0]), max(bbox1[1], bbox2[1]), min(bbox1[2], bbox2[2]), min(bbox1[3], bbox2[3]) ] return intersect_bbox def BBoxSize(bbox): if (bbox[2] < bbox[0] or bbox[3] < bbox[1]): # If bbox is invalid (e.g. xmax < xmin or ymax < ymin), return 0. return 0.0 else: width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] return (width + 1) * (height + 1) def Crop(img, crop_bbox): img_shape = img.shape # x1 = 1.0 * crop_bbox[0] * img_shape[1] # y1 = 1.0 * crop_bbox[1] * img_shape[0] # x2 = 1.0 * crop_bbox[2] * img_shape[1] # y2 = 1.0 * crop_bbox[3] * img_shape[0] x1 = crop_bbox[0] y1 = crop_bbox[1] x2 = crop_bbox[2] y2 = crop_bbox[3] assert x1 >= 0, x1 assert y1 >= 0, y1 assert x2 <= img_shape[1], '{} vs {}'.format(x2, img_shape[1]) assert y2 <= img_shape[0], '{} vs {}'.format(y2, img_shape[0]) crop_img = img[y1:y2 + 1, x1:x2 + 1, :] return crop_img def MeetEmitConstraint(src_bbox, bbox): x_center = 1.0 * (bbox[0] + bbox[2]) / 2 y_center = 1.0 * (bbox[1] + bbox[3]) / 2 if x_center >= src_bbox[0] and x_center <= src_bbox[2] and y_center >= src_bbox[1] and y_center <= src_bbox[3]: return True else: return False def ApplyCrop(img): if cfg.TRAIN.CROP <= 0: img_height = img.shape[0] img_width = img.shape[1] return img, np.array( (0, 0, img_width - 1, img_height - 1), dtype=np.uint16) img_shape = np.array(img.shape) crop_dims = img_shape[:2] * cfg.TRAIN.CROP # crop_dims = img_shape[:2] * 0.9 r0 = npr.random() r1 = npr.random() s = img_shape[:2] - crop_dims s[0] *= r0 s[1] *= r1 # im_crop = np.array([s[0], # s[1], # s[0] + crop_dims[0] - 1, # s[1] + crop_dims[1] - 1], # dtype=np.uint16) crop_bbox = np.array( [s[1], s[0], s[1] + crop_dims[1] - 1, s[0] + crop_dims[0] - 1], dtype=np.uint16) crop_img = img[crop_bbox[1]:crop_bbox[3] + 1, crop_bbox[0]: crop_bbox[2] + 1, :] return crop_img, crop_bbox def ApplyExpand(img): img_shape = img.shape prob = npr.random() if prob > cfg.TRAIN.expand_prob: return img, np.array( (0, 0, img_shape[1], img_shape[0]), dtype=np.uint16) if abs(cfg.TRAIN.max_expand_ratio - 1.) < 1e-2: return img, np.array( (0, 0, img_shape[1], img_shape[0]), dtype=np.uint16) expand_ratio = npr.uniform(1, cfg.TRAIN.max_expand_ratio) expand_img, expand_bbox = ExpandImage(img, expand_ratio) return expand_img, expand_bbox def ExpandImage(img, expand_ratio): img_height = img.shape[0] img_width = img.shape[1] img_channels = img.shape[2] # Get the bbox dimension. height = int(img_height * expand_ratio) width = int(img_width * expand_ratio) h_off = npr.uniform(0, height - img_height) w_off = npr.uniform(0, width - img_width) h_off = int(h_off) w_off = int(w_off) expand_bbox = [] # expand_bbox.append(1.0 * (-w_off) / img_width) # expand_bbox.append(1.0 * (-h_off) / img_height) # expand_bbox.append(1.0 * (width - w_off) / img_width) # expand_bbox.append(1.0 * (height - h_off) / img_height) expand_bbox.append(-w_off) expand_bbox.append(-h_off) expand_bbox.append(width - w_off - 1) expand_bbox.append(height - h_off - 1) expand_bbox = np.array(expand_bbox) expand_img = np.tile(cfg.PIXEL_MEANS, (height, width, 1)).astype(img.dtype) expand_img[h_off:h_off + img_height, w_off:w_off + img_width, :] = img return expand_img, expand_bbox def ApplyDistort_old(in_img): hsv = cv2.cvtColor(in_img, cv2.COLOR_BGR2HSV) s0 = npr.random() * (cfg.TRAIN.SATURATION - 1) + 1 s1 = npr.random() * (cfg.TRAIN.EXPOSURE - 1) + 1 # s0 = npr.random() * (1.5 - 1) + 1 # s1 = npr.random() * (1.5 - 1) + 1 s0 = s0 if npr.random() > 0.5 else 1.0 / s0 s1 = s1 if npr.random() > 0.5 else 1.0 / s1 hsv = np.array(hsv, dtype=np.float32) hsv[:, :, 1] = np.minimum(s0 * hsv[:, :, 1], 255) hsv[:, :, 2] = np.minimum(s1 * hsv[:, :, 2], 255) hsv = np.array(hsv, dtype=np.uint8) out_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return out_img def ApplyDistort(in_img): prob = npr.random() if prob > 0.5: # Do random brightness distortion. out_img = RandomBrightness(in_img, cfg.TRAIN.brightness_prob, cfg.TRAIN.brightness_delta) # cv2.imshow('0 RandomBrightness',out_img.astype(np.uint8)) # Do random contrast distortion. out_img = RandomContrast(out_img, cfg.TRAIN.contrast_prob, cfg.TRAIN.contrast_lower, cfg.TRAIN.contrast_upper) # cv2.imshow('1 RandomContrast',out_img.astype(np.uint8)) # Do random saturation distortion. out_img = RandomSaturation(out_img, cfg.TRAIN.saturation_prob, cfg.TRAIN.saturation_lower, cfg.TRAIN.saturation_upper) # cv2.imshow('2 RandomSaturation',out_img.astype(np.uint8)) # Do random exposure distortion. out_img = RandomExposure(out_img, cfg.TRAIN.exposure_prob, cfg.TRAIN.exposure_lower, cfg.TRAIN.exposure_upper) # cv2.imshow('3 RandomExposure',out_img.astype(np.uint8)) # Do random hue distortion. out_img = RandomHue(out_img, cfg.TRAIN.hue_prob, cfg.TRAIN.hue_delta) # cv2.imshow('4 RandomHue',out_img.astype(np.uint8)) # Do random reordering of the channels. out_img = RandomOrderChannels(out_img, cfg.TRAIN.random_order_prob) # cv2.imshow('5 RandomOrderChannels',out_img.astype(np.uint8)) else: # Do random brightness distortion. out_img = RandomBrightness(in_img, cfg.TRAIN.brightness_prob, cfg.TRAIN.brightness_delta) # cv2.imshow('0 RandomBrightness',out_img.astype(np.uint8)) # Do random saturation distortion. out_img = RandomSaturation(out_img, cfg.TRAIN.saturation_prob, cfg.TRAIN.saturation_lower, cfg.TRAIN.saturation_upper) # cv2.imshow('1 RandomSaturation',out_img.astype(np.uint8)) # Do random exposure distortion. out_img = RandomExposure(out_img, cfg.TRAIN.exposure_prob, cfg.TRAIN.exposure_lower, cfg.TRAIN.exposure_upper) # cv2.imshow('2 RandomExposure',out_img.astype(np.uint8)) # Do random hue distortion. out_img = RandomHue(out_img, cfg.TRAIN.hue_prob, cfg.TRAIN.hue_delta) # cv2.imshow('3 RandomHue',out_img.astype(np.uint8)) # Do random contrast distortion. out_img = RandomContrast(out_img, cfg.TRAIN.contrast_prob, cfg.TRAIN.contrast_lower, cfg.TRAIN.contrast_upper) # cv2.imshow('4 RandomContrast',out_img.astype(np.uint8)) # Do random reordering of the channels. out_img = RandomOrderChannels(out_img, cfg.TRAIN.random_order_prob) # cv2.imshow('5 RandomOrderChannels',out_img.astype(np.uint8)) return out_img def convertTo(in_img, alpha, beta): out_img = in_img.astype(np.float32) out_img = out_img * alpha + beta out_img = np.clip(out_img, 0, 255) out_img = out_img.astype(in_img.dtype) return out_img # def bgr_to_hsv(bgr): # b, g, r = cv2.split(bgr) # rgb = cv2.merge((r, g, b)) # hsv = rgb_to_hsv(rgb) # return hsv # def hsv_to_bgr(hsv): # rgb = hsv_to_rgb(hsv) # r, g, b = cv2.split(rgb) # bgr = cv2.merge((b, g, r)) # return bgr def RandomBrightness(in_img, brightness_prob, brightness_delta): prob = npr.random() if prob < brightness_prob: assert brightness_delta > 0, "brightness_delta must be non-negative." delta = npr.uniform(-brightness_delta, brightness_delta) out_img = AdjustBrightness(in_img, delta) else: out_img = in_img return out_img def AdjustBrightness(in_img, delta): if abs(delta) > 0: # out_img = cv2.convertTo(in_img, 1, 1, delta) out_img = convertTo(in_img, 1, delta) else: out_img = in_img return out_img def RandomContrast(in_img, contrast_prob, lower, upper): prob = npr.random() if prob < contrast_prob: assert upper >= lower, 'contrast upper must be >= lower.' assert lower >= 0, 'contrast lower must be non-negative.' delta = npr.uniform(lower, upper) out_img = AdjustContrast(in_img, delta) else: out_img = in_img return out_img def AdjustContrast(in_img, delta): if abs(delta - 1.0) > 1e-3: #
27198, 27199 ), "AL22bMnthCl" : ( 27199, 27200 ), "AL23bMnthCl" : ( 27200, 27201 ), "AL24bMnthCl" : ( 27201, 27202 ), "AL25MnthCl" : ( 27202, 27203 ), "AL29bMnthCl" : ( 27203, 27204 ), "AL26a1MnthCl" : ( 27204, 27205 ), "AL26a2MnthCl" : ( 27205, 27206 ), "AL26a3MnthCl" : ( 27206, 27207 ), "AL27cMnthCl" : ( 27207, 27208 ), "AL28bMnthCl" : ( 27208, 27209 ), "AL31bMnthCl" : ( 27209, 27210 ), "AL32MnthCl" : ( 27210, 27211 ), "AL33aMnthCl" : ( 27211, 27212 ), "AL37dMnthCl" : ( 27212, 27213 ), "AL38MnthCl" : ( 27213, 27214 ), "AL39MnthCl" : ( 27214, 27215 ), "AL37iMnthCl" : ( 27215, 27216 ), "AL38cMnthCl" : ( 27216, 27217 ), "AL39cMnthCl" : ( 27217, 27218 ), "AL19MnthCl" : ( 27218, 27219 ), "AL43" : ( 27219, 27222 ), "AL43A" : ( 27222, 27224 ), "AL43FromMnth_" : ( 27224, 27226 ), "AL43FromYr_" : ( 27226, 27230 ), "AL43ToMnth_" : ( 27230, 27232 ), "AL43ToYR_" : ( 27232, 27236 ), "AL43FromMnth_2" : ( 27236, 27238 ), "AL43FromYr_2" : ( 27238, 27242 ), "AL43ToMnth_2" : ( 27242, 27244 ), "AL43ToYR_2" : ( 27244, 27248 ), "AL43FromMnth_3" : ( 27248, 27250 ), "AL43FromYr_3" : ( 27250, 27254 ), "AL43ToMnth_3" : ( 27254, 27256 ), "AL43ToYR_3" : ( 27256, 27260 ), "AL43FromMnth_4" : ( 27260, 27262 ), "AL43FromYr_4" : ( 27262, 27266 ), "AL43ToMnth_4" : ( 27266, 27268 ), "AL43ToYR_4" : ( 27268, 27272 ), "AL43FromMnth_5" : ( 27272, 27274 ), "AL43FromYr_5" : ( 27274, 27278 ), "AL43ToMnth_5" : ( 27278, 27280 ), "AL43ToYR_5" : ( 27280, 27284 ), "AL44" : ( 27284, 27285 ), "AL44a1" : ( 27285, 27286 ), "AL44a2" : ( 27286, 27287 ), "AL44a3" : ( 27287, 27288 ), "AL44a4" : ( 27288, 27289 ), "AL44a5" : ( 27289, 27290 ), "AL44a6" : ( 27290, 27291 ), "AL44a6_specify" : ( 27291, 27371 ), "AL44AgeOns" : ( 27371, 27373 ), "AL44Ons" : ( 27373, 27374 ), "AL44AgeRec" : ( 27374, 27376 ), "AL44Rec" : ( 27376, 27377 ), "AL44c" : ( 27377, 27378 ), "AL45" : ( 27378, 27379 ), "AL45a1" : ( 27379, 27380 ), "AL45a2" : ( 27380, 27381 ), "AL45a3" : ( 27381, 27382 ), "AL45a4" : ( 27382, 27383 ), "AL45a5" : ( 27383, 27384 ), "AL45a6" : ( 27384, 27385 ), "AL45a6_Specify" : ( 27385, 27610 ), "AL45bAgeOns" : ( 27610, 27612 ), "AL45bOns" : ( 27612, 27613 ), "AL45bAgeRec" : ( 27613, 27615 ), "AL45bRec" : ( 27615, 27616 ), "AL45c" : ( 27616, 27617 ), "AL45d" : ( 27617, 27618 ), "AL45dAgeOns" : ( 27618, 27620 ), "AL45dOns" : ( 27620, 27621 ), "AL45dAgeRec" : ( 27621, 27623 ), "AL45dRec" : ( 27623, 27624 ), "IND_ID2" : ( 27624, 27633 ), "MJ1" : ( 27633, 27634 ), "MJ1a" : ( 27634, 27638 ), "MJ1a1" : ( 27638, 27639 ), "MJ1a2" : ( 27639, 27640 ), "MJ1b" : ( 27640, 27641 ), "MJ2AgeOns" : ( 27641, 27643 ), "MJ2Ons" : ( 27643, 27644 ), "MJ2AgeRec" : ( 27644, 27646 ), "MJ2Rec" : ( 27646, 27647 ), "MJ2A" : ( 27647, 27648 ), "MJ2C" : ( 27648, 27651 ), "MJ2c1" : ( 27651, 27652 ), "MJ2d" : ( 27652, 27653 ), "MJ3_num" : ( 27653, 27656 ), "MJ3_unit" : ( 27656, 27657 ), "MJ3AgeOns" : ( 27657, 27659 ), "MJ3Ons" : ( 27659, 27660 ), "MJ3AgeRec" : ( 27660, 27662 ), "MJ3Rec" : ( 27662, 27663 ), "MJ3b" : ( 27663, 27665 ), "MJ3c_NUM" : ( 27665, 27668 ), "MJ3c_UNIT" : ( 27668, 27669 ), "MJ3d" : ( 27669, 27672 ), "MJ3e" : ( 27672, 27676 ), "MJ4" : ( 27676, 27677 ), "MJ4AgeOns" : ( 27677, 27679 ), "MJ4Ons" : ( 27679, 27680 ), "MJ4AgeRec" : ( 27680, 27682 ), "MJ4Rec" : ( 27682, 27683 ), "MJ5" : ( 27683, 27684 ), "MJ6_1" : ( 27684, 27685 ), "MJ6_2" : ( 27685, 27686 ), "MJ6_3" : ( 27686, 27687 ), "MJ6_4" : ( 27687, 27688 ), "MJ6_5" : ( 27688, 27689 ), "MJ6a1" : ( 27689, 27690 ), "MJ6a2" : ( 27690, 27691 ), "MJ6a3" : ( 27691, 27692 ), "MJ6a4" : ( 27692, 27693 ), "MJ6a5" : ( 27693, 27694 ), "MJ6b" : ( 27694, 27695 ), "MJ7" : ( 27695, 27696 ), "MJ7A" : ( 27696, 27697 ), "MJ7B" : ( 27697, 27698 ), "MJ8" : ( 27698, 27699 ), "MJ9" : ( 27699, 27700 ), "MJ10_1" : ( 27700, 27701 ), "MJ10_2" : ( 27701, 27702 ), "MJ10_3" : ( 27702, 27703 ), "MJ10_4" : ( 27703, 27704 ), "MJ10_5" : ( 27704, 27705 ), "MJ10_6" : ( 27705, 27706 ), "MJ10_7" : ( 27706, 27707 ), "MJ10dQsx" : ( 27707, 27708 ), "MJ10dQsx2" : ( 27708, 27709 ), "MJ10dQsx3" : ( 27709, 27710 ), "MJ10dQsx4" : ( 27710, 27711 ), "MJ10dQsx5" : ( 27711, 27712 ), "MJ10dQsx6" : ( 27712, 27713 ), "MJ10dQsx7" : ( 27713, 27714 ), "MJ10d_1" : ( 27714, 27715 ), "MJ10d_2" : ( 27715, 27716 ), "MJ10d_3" : ( 27716, 27717 ), "MJ10d_4" : ( 27717, 27718 ), "MJ10d_5" : ( 27718, 27719 ), "MJ10d_6" : ( 27719, 27720 ), "MJ10d_7" : ( 27720, 27721 ), "MJ10a" : ( 27721, 27722 ), "MJ10b" : ( 27722, 27723 ), "MJ10c" : ( 27723, 27724 ), "MJ10e" : ( 27724, 27727 ), "MJ10f" : ( 27727, 27730 ), "MJ10g" : ( 27730, 27731 ), "MJ11" : ( 27731, 27732 ), "MJ11a" : ( 27732, 27733 ), "MJ11a1" : ( 27733, 27734 ), "MJ11b" : ( 27734, 27735 ), "MJ11c" : ( 27735, 27736 ), "MJ11c1" : ( 27736, 27737 ), "MJ12" : ( 27737, 27738 ), "MJ12a" : ( 27738, 27739 ), "MJ12b" : ( 27739, 27740 ), "MJ13" : ( 27740, 27741 ), "MJ13a" : ( 27741, 27742 ), "MJ13a1" : ( 27742, 27743 ), "MJ14" : ( 27743, 27744 ), "MJ14a" : ( 27744, 27745 ), "MJ16" : ( 27745, 27746 ), "MJ16AgeOns" : ( 27746, 27748 ), "MJ16Ons" : ( 27748, 27749 ), "MJ16AgeRec" : ( 27749, 27751 ), "MJ16Rec" : ( 27751, 27752 ), "MJ17" : ( 27752, 27753 ), "MJ17a" : ( 27753, 27754 ), "MJ18" : ( 27754, 27755 ), "MJ18Another" : ( 27755, 27756 ), "MJ18_Specify" : ( 27756, 27836 ), "MJ18_Code" : ( 27836, 27855 ), "MJ18Another2" : ( 27855, 27856 ), "MJ18_Specify2" : ( 27856, 27936 ), "MJ18_Code2" : ( 27936, 27955 ), "MJ18Another3" : ( 27955, 27956 ), "MJ18_Specify3" : ( 27956, 28036 ), "MJ18_Code3" : ( 28036, 28055 ), "MJ18Another4" : ( 28055, 28056 ), "MJ18_Specify4" : ( 28056, 28136 ), "MJ18_Code4" : ( 28136, 28155 ), "MJ19AgeOns" : ( 28155, 28157 ), "MJ19Ons" : ( 28157, 28158 ), "MJ19AgeRec" : ( 28158, 28160 ), "MJ19Rec" : ( 28160, 28161 ), "MJ19Qsx" : ( 28161, 28162 ), "MJ19Qsx2" : ( 28162, 28163 ), "MJ19Qsx3" : ( 28163, 28164 ), "MJ19Qsx4" : ( 28164, 28165 ), "MJ19Qsx5" : ( 28165, 28166 ), "MJ19Qsx6" : ( 28166, 28167 ), "MJ19Qsx7" : ( 28167, 28168 ), "MJ19Qsx8" : ( 28168, 28169 ), "MJ19Qsx9" : ( 28169, 28170 ), "MJ19Qsx10" : ( 28170, 28171 ), "MJ19Qsx11" : ( 28171, 28172 ), "MJ19Qsx12" : ( 28172, 28173 ), "MJ19Qsx13" : ( 28173, 28174 ), "MJ19Qsx14" : ( 28174, 28175 ), "MJ19Qsx15" : ( 28175, 28176 ), "MJ19Qsx16" : ( 28176, 28177 ), "MJ19Qsx17" : ( 28177, 28178 ), "MJ19Qsx18" : ( 28178, 28179 ), "MJ19dQsx" : ( 28179, 28180 ), "MJ19dQsx2" : ( 28180, 28181 ), "MJ19dQsx3" : ( 28181, 28182 ), "MJ19dQsx4" : ( 28182, 28183 ), "MJ19dQsx5" : ( 28183, 28184 ), "MJ19dQsx6" : ( 28184, 28185 ), "MJ19dQsx7" : ( 28185, 28186 ), "MJ19dQsx8" : ( 28186, 28187 ), "MJ19dQsx9" : ( 28187, 28188 ), "MJ19dQsx10" : ( 28188, 28189
<reponame>R3SWebDevelopment/MineSweeper from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.postgres.fields import ArrayField, JSONField from django.utils.translation import ugettext as _ from django.urls import reverse import random import json import datetime import numpy as np DEFAULT_CELLS = 10 MIN_CELLS = 10 MAX_CELLS = 30 DEFAULT_MINES = 10 MIN_MINES = 10 MAX_MINES = 30 GAME_STARTED = 1 GAME_PAUSED = 2 GAME_LOST = 3 GAME_WON = 4 GAME_STATUS = ( (GAME_STARTED, _('Started')), (GAME_PAUSED, _('Paused')), (GAME_LOST, _('Lost')), (GAME_WON, _('Won')), ) class Game(models.Model): rows = models.IntegerField(null=False, default=DEFAULT_CELLS, validators=[ MaxValueValidator(MAX_CELLS), MinValueValidator(MIN_CELLS) ]) columns = models.IntegerField(null=False, default=DEFAULT_CELLS, validators=[ MaxValueValidator(MAX_CELLS), MinValueValidator(MIN_CELLS) ]) mines_count = models.IntegerField(null=False, default=DEFAULT_MINES, validators=[ MaxValueValidator(MAX_MINES), MinValueValidator(MIN_MINES) ]) mines_left = models.IntegerField(null=False, default=0) mines = ArrayField(ArrayField((models.IntegerField())), null=True) revelead_cells = ArrayField(ArrayField((models.IntegerField())), null=True) marked_cells = ArrayField(ArrayField((models.IntegerField())), null=True) cells = ArrayField(ArrayField(models.TextField(null=False)), null=True) players = models.ManyToManyField(User, related_name="games") turn = models.ForeignKey(User, related_name="current_move", null=True, default=None) queue = ArrayField(models.IntegerField(), null=False, default=[]) status = models.IntegerField(null=False, default=GAME_STARTED, choices=GAME_STATUS) seconds = models.IntegerField(null=False, default=0) started_timestamp = models.DateTimeField(null=False, auto_now_add=True) last_turn = models.ForeignKey(User, related_name="last_move", null=True, default=None) result = models.CharField(max_length=250, null=True, default="") def __str__(self): return "Game" def swap_turn(self): """ Cicle the turn of the players """ if len(self.queue) > 1: self.queue = self.queue[1:] + self.queue[:1] self.turn = self.players.filter(pk=self.queue[0]).first() self.save() @property def cells_data(self): """ Returns dictionary with the game status """ data = {} for x in range(0, self.columns): for y in range(0, self.rows): cell = self.cell(x, y) if cell.get('is_reveal', False): # The cell is reveal if cell.get('has_boom', False): # The cell has a boom value = 'B' elif cell.get('count', 0) == 0: # The cell does not has adjacents value = '_' else: # The cell does has adjacents value = '{}'.format(cell.get('count', 0)) else: if cell.get('is_marked', False): # The cell has been marked value = '?' else: value = '*' data.update({ "{}_{}".format(x, y): value }) return data @property def marks_left(self): return self.mines_count - self.marked_cells_count @property def marked_cells_count(self): return len(self.marked_cells) if self.marked_cells is not None else 0 @property def reveled_cells_count(self): return len(self.revelead_cells) if self.revelead_cells is not None else 0 @property def cells_count(self): return self.rows * self.columns @property def are_mines_marked(self): """ Return True if all the mine cells has been marked and the only cells none revealed are the one with mines """ cells_count = self.cells_count if (cells_count - self.reveled_cells_count) == self.mines_count and self.marks_left == 0: return True return False @classmethod def create(cls, user, rows=None, columns=None, mines=None): """ Creates a new instance of the game if any of the parameters (rows, columns or mines) are null, the class randomly assign a value within the max and min values """ rows = random.randint(MIN_MINES, MAX_MINES) if rows is None else rows columns = random.randint(MIN_MINES, MAX_MINES) if columns is None else columns mines = random.randint(MIN_MINES, MAX_MINES) if mines is None else mines game = cls.objects.create(turn=user, rows=rows, columns=columns, mines_count=mines) game.players.add(user) game.queue = [user.pk] game.save() game.build_cells() return game def is_your_turn(self, user): """ Checks if the user has the turn """ return self.turn == user def cell_has_boom(self, x, y): """ Checks if the cell on x and y coordinates there is a boom """ return [x, y] in self.mines @property def get_seconds(self): """ Get the seconds of the game """ seconds = self.seconds if self.status in [GAME_STARTED]: delta = datetime.datetime.now() - self.started_timestamp.replace(tzinfo=None) seconds += delta.seconds return seconds def cell(self, x, y): """ Returns the data of the cell """ if x >= self.columns: raise ValueError(_('Out of range column')) if y >= self.rows: raise ValueError(_('Out of range row')) cell = self.cells[x][y] return json.loads(cell) def set_cell(self, x, y, data, save=True): """ Set the data on a cell """ if x >= self.columns: raise ValueError(_('Out of range column')) if y >= self.rows: raise ValueError(_('Out of range row')) self.cells[x][y] = json.dumps(data) if save: self.save() def check_board_status(self, user): """ Checks if the game is over """ if self.status in [GAME_STARTED]: if self.are_mines_marked: self.finish(user, won=True) def build_cells(self): """ Builds the cells for the game using the rows, columns and mines parameters """ def get_adjacent(x, y, mines): adjacents = [] if x == 0 and y == 0: adjacents = [(0, 1), (1, 0), (1, 1)] elif x == 0 and y == self.rows - 1: adjacents = [(0, self.rows - 2), (1, self.columns - 1), (1, self.rows - 2)] elif x == self.columns - 1 and y == 0: adjacents = [(self.columns - 2, 0), (self.columns - 2, 1), (self.columns - 1, 1)] elif x == self.columns - 1 and y == self.rows - 1: adjacents = [(self.columns - 2, self.rows - 2), (self.columns - 2, self.rows - 1), (self.columns - 1, self.rows - 2)] elif y == 0: adjacents = [(x - 1, 0), (x - 1, 1), (x, 1), (x + 1, 0), (x + 1, 1)] elif y == self.rows - 1: adjacents = [(x - 1, self.rows - 1), (x - 1, self.rows - 2), (x, self.rows - 2), (x + 1, self.rows - 1), (x + 1, self.rows - 2)] elif x == 0: adjacents = [(x, y - 1), (x + 1, y - 1), (x + 1, y), (x + 1, y + 1), (x, y + 1)] elif x == self.columns - 1: adjacents = [(x, y - 1), (x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y + 1)] else: adjacents = [(x - 1, y - 1), (x, y - 1), (x + 1, y - 1), (x - 1, y), (x + 1, y), (x + 1, y + 1), (x, y + 1), (x + 1, y + 1)] return adjacents def get_adjacents_count(adjacents, mines): count = 0 for position in adjacents: if position in mines: count += 1 return count mines = [] for _ in range(0, self.mines_count): x = random.randint(0, self.columns - 1) y = random.randint(0, self.rows - 1) while (x, y) in mines: # Verify that the position of the boom is not already defined x = random.randint(0, self.columns - 1) y = random.randint(0, self.rows - 1) mines.append((x, y)) cells = [] for x in range(0, self.columns): rows = [] for y in range(0, self.rows): adjacents = get_adjacent(x, y, mines) rows.append(json.dumps({ "is_marked": False, "is_reveal": False, "has_boom": None, "count": get_adjacents_count(adjacents, mines), "adjacents": adjacents, })) cells.append(rows) self.cells = cells self.revelead_cells = [] self.marked_cells = [] self.mines = [list(p) for p in mines] self.save() def finish(self, user, boom=False, won=False, x=0, y=0): """ Define the outcome of the game """ if boom: self.result = "User: {} revealed a Mine at cell ({}, {})".format(user.email, x + 1, y + 1) self.status = GAME_LOST delta = datetime.datetime.now() - self.started_timestamp.replace(tzinfo=None) self.seconds += delta.seconds self.save() elif won: self.result = "User: {} has won".format(user.email) self.status = GAME_WON delta = datetime.datetime.now() - self.started_timestamp.replace(tzinfo=None) self.seconds += delta.seconds self.save() def join(self, user): """ Adds the user to the list of users playing the game """ self.players.add(user) if user.pk not in self.queue: self.queue.append(user.pk) self.save() def leave(self, user): """ Removes the user from the list of users playing the game """ self.players.remove(user) if user.pk in self.queue: self.queue.remove(user.pk) self.save() def mark_cell(self, user, x, y): """ Marks the given cell on x and y to be a possible cell with boom """ if self.status not in [GAME_STARTED]: raise Exception(_('The game is not started')) cell = self.cell(x, y) if cell.get('is_reveal', False): raise Exception(_('This cell is already revealed')) if cell.get('is_marked', False): raise Exception(_('This cell is already marked')) if not self.is_your_turn(user): raise Exception(_('Is not your turn to play')) cell.update({ "is_marked": True }) if [x, y] not in self.marked_cells: self.marked_cells.append([x, y]) self.set_cell(x, y, cell) self.swap_turn() def unmark_cell(self, user, x, y): """ Unmarks the given cell on x and y to be a possible cell with boom """ if self.status not in [GAME_STARTED]: raise Exception(_('The game is not started')) cell = self.cell(x, y) if not cell.get('is_marked', False): raise Exception(_('This cell is not marked')) if not self.is_your_turn(user): raise Exception(_('Is not your turn to play')) cell.update({ "is_marked": False }) if [x, y] in self.marked_cells: self.marked_cells.remove([x, y]) self.set_cell(x, y, cell) self.swap_turn() def reveal_cell(self, user, x, y, save=True): """ Reveal the given cell on x
operands.dst elif instruction.fp_update is not Instruction.FpUpdate.REGULAR: raise NotImplementedError('Invalid fp_update value') # Update ap. if instruction.ap_update is Instruction.ApUpdate.ADD: if operands.res is None: raise NotImplementedError('Res.UNCONSTRAINED cannot be used with ApUpdate.ADD') self.run_context.ap += operands.res % self.prime elif instruction.ap_update is Instruction.ApUpdate.ADD1: self.run_context.ap += 1 elif instruction.ap_update is Instruction.ApUpdate.ADD2: self.run_context.ap += 2 elif instruction.ap_update is not Instruction.ApUpdate.REGULAR: raise NotImplementedError('Invalid ap_update value') self.run_context.ap = self.run_context.ap % self.prime # Update pc. # The pc update should be done last so that we will have the correct pc in case of an # exception during one of the updates above. if instruction.pc_update is Instruction.PcUpdate.REGULAR: self.run_context.pc += instruction.size elif instruction.pc_update is Instruction.PcUpdate.JUMP: if operands.res is None: raise NotImplementedError('Res.UNCONSTRAINED cannot be used with PcUpdate.JUMP') self.run_context.pc = operands.res elif instruction.pc_update is Instruction.PcUpdate.JUMP_REL: if operands.res is None: raise NotImplementedError('Res.UNCONSTRAINED cannot be used with PcUpdate.JUMP_REL') if not isinstance(operands.res, int): raise PureValueError('jmp rel', operands.res) self.run_context.pc += operands.res elif instruction.pc_update is Instruction.PcUpdate.JNZ: if self.is_zero(operands.dst): self.run_context.pc += instruction.size else: self.run_context.pc += operands.op1 else: raise NotImplementedError('Invalid pc_update value') self.run_context.pc = self.run_context.pc % self.prime def deduce_op0( self, instruction: Instruction, dst: Optional[MaybeRelocatable], op1: Optional[MaybeRelocatable]) -> \ Tuple[Optional[MaybeRelocatable], Optional[MaybeRelocatable]]: if instruction.opcode is Instruction.Opcode.CALL: return self.run_context.pc + instruction.size, None elif instruction.opcode is Instruction.Opcode.ASSERT_EQ: if (instruction.res is Instruction.Res.ADD) and (dst is not None) and \ (op1 is not None): return (dst - op1) % self.prime, dst # type: ignore elif (instruction.res is Instruction.Res.MUL) and isinstance(dst, int) and \ isinstance(op1, int) and op1 != 0: return div_mod(dst, op1, self.prime), dst return None, None def deduce_op1( self, instruction: Instruction, dst: Optional[MaybeRelocatable], op0: Optional[MaybeRelocatable]) -> \ Tuple[Optional[MaybeRelocatable], Optional[MaybeRelocatable]]: if instruction.opcode is Instruction.Opcode.ASSERT_EQ: if (instruction.res is Instruction.Res.OP1) and (dst is not None): return dst, dst elif (instruction.res is Instruction.Res.ADD) and (dst is not None) and \ (op0 is not None): return (dst - op0) % self.prime, dst # type: ignore elif (instruction.res is Instruction.Res.MUL) and isinstance(dst, int) and \ isinstance(op0, int) and op0 != 0: return div_mod(dst, op0, self.prime), dst return None, None def compute_res( self, instruction: Instruction, op0: MaybeRelocatable, op1: MaybeRelocatable, op0_addr: MaybeRelocatable) -> Optional[MaybeRelocatable]: if instruction.res is Instruction.Res.OP1: return op1 elif instruction.res is Instruction.Res.ADD: return (op0 + op1) % self.prime elif instruction.res is Instruction.Res.MUL: if isinstance(op0, RelocatableValue) or isinstance(op1, RelocatableValue): raise PureValueError('*', op0, op1) return (op0 * op1) % self.prime elif instruction.res is Instruction.Res.UNCONSTRAINED: # In this case res should be the inverse of dst. # For efficiency, we do not compute it here. return None else: raise NotImplementedError('Invalid res value') def compute_operands(self, instruction: Instruction) -> \ Tuple[Operands, List[int], List[MaybeRelocatable]]: """ Computes the values of the operands. Deduces dst if needed. Returns: operands - an Operands instance with the values of the operands. mem_addresses - the memory addresses for the 3 memory units used (dst, op0, op1). mem_values - the corresponding memory values. """ # Try to fetch dst, op0, op1. # op0 throughout this function represents the value at op0_addr. # If op0 is set, this implies that we are going to set memory at op0_addr to that value. # Same for op1, dst. dst_addr = self.run_context.compute_dst_addr(instruction) dst: Optional[MaybeRelocatable] = self.validated_memory.get(dst_addr) op0_addr = self.run_context.compute_op0_addr(instruction) op0: Optional[MaybeRelocatable] = self.validated_memory.get(op0_addr) op1_addr = self.run_context.compute_op1_addr(instruction, op0=op0) op1: Optional[MaybeRelocatable] = self.validated_memory.get(op1_addr) # res throughout this function represents the computation on op0,op1 # as defined in decode.py. # If it is set, this implies that compute_res(...) will return this value. # If it is set without invoking compute_res(), this is an optimization, but should not # yield a different result. # In particular, res may be different than dst, even in ASSERT_EQ. In this case, # The ASSERT_EQ validation will fail in opcode_assertions(). res: Optional[MaybeRelocatable] = None # Auto deduction rules. # Note: This may fail to deduce if 2 auto deduction rules are needed to be used in # a different order. if op0 is None: op0 = self.deduce_memory_cell(op0_addr) if op1 is None: op1 = self.deduce_memory_cell(op1_addr) should_update_dst = dst is None should_update_op0 = op0 is None should_update_op1 = op1 is None # Deduce op0 if needed. if op0 is None: op0, deduced_res = self.deduce_op0(instruction, dst, op1) if res is None: res = deduced_res # Deduce op1 if needed. if op1 is None: op1, deduced_res = self.deduce_op1(instruction, dst, op0) if res is None: res = deduced_res # Force pulling op0, op1 from memory for soundness test # and to get an informative error message if they were not computed. if op0 is None: op0 = self.validated_memory[op0_addr] if op1 is None: op1 = self.validated_memory[op1_addr] # Compute res if needed. if res is None: res = self.compute_res(instruction, op0, op1, op0_addr) # Deduce dst. if dst is None: if instruction.opcode is Instruction.Opcode.ASSERT_EQ and res is not None: dst = res elif instruction.opcode is Instruction.Opcode.CALL: dst = self.run_context.fp # Force pulling dst from memory for soundness. if dst is None: dst = self.validated_memory[dst_addr] # Write updated values. if should_update_dst: self.validated_memory[dst_addr] = dst if should_update_op0: self.validated_memory[op0_addr] = op0 if should_update_op1: self.validated_memory[op1_addr] = op1 return Operands( dst=dst, op0=op0, op1=op1, res=res), [dst_addr, op0_addr, op1_addr], [dst, op0, op1] def is_zero(self, value): """ Returns True if value is zero (used for jnz instructions). This function can be overridden by subclasses. """ if not isinstance(value, int): raise PureValueError('jmp != 0', value) return value == 0 def is_integer_value(self, value): """ Returns True if value is integer rather than relocatable. This function can be overridden by subclasses. """ return isinstance(value, int) @staticmethod @lru_cache(None) def decode_instruction(encoded_inst: int, imm: Optional[int] = None): return decode_instruction(encoded_inst, imm) def decode_current_instruction(self): try: instruction_encoding, imm = self.run_context.get_instruction_encoding() except Exception as exc: raise self.as_vm_exception(exc) from None instruction = self.decode_instruction(instruction_encoding, imm) return instruction, instruction_encoding def opcode_assertions(self, instruction: Instruction, operands: Operands): if instruction.opcode is Instruction.Opcode.ASSERT_EQ: if operands.res is None: raise NotImplementedError( 'Res.UNCONSTRAINED cannot be used with Opcode.ASSERT_EQ') if operands.dst != operands.res and not self.check_eq(operands.dst, operands.res): raise Exception( f'An ASSERT_EQ instruction failed: {operands.dst} != {operands.res}') elif instruction.opcode is Instruction.Opcode.CALL: next_pc = self.run_context.pc + instruction.size if operands.op0 != next_pc and not self.check_eq(operands.op0, next_pc): raise Exception( 'Call failed to write return-pc (inconsistent op0): ' + f'{operands.op0} != {next_pc}. Did you forget to increment ap?') fp = self.run_context.fp if operands.dst != fp and not self.check_eq(operands.dst, fp): raise Exception( 'Call failed to write return-fp (inconsistent dst): ' + f'{operands.dst} != {fp}. Did you forget to increment ap?') elif instruction.opcode in [Instruction.Opcode.RET, Instruction.Opcode.NOP]: # Nothing to check. pass else: raise NotImplementedError(f'Unsupported opcode {instruction.opcode}') def step(self): self.skip_instruction_execution = False # Execute hints. hint = self.hints.get(self.run_context.pc) if hint is not None: exec_locals = self.exec_scopes[-1] exec_locals['memory'] = memory = self.validated_memory exec_locals['ap'] = ap = self.run_context.ap exec_locals['fp'] = fp = self.run_context.fp exec_locals['pc'] = pc = self.run_context.pc exec_locals['current_step'] = self.current_step exec_locals['ids'] = hint.consts(pc, ap, fp, memory) exec_locals['vm_load_program'] = self.load_program exec_locals['vm_enter_scope'] = self.enter_scope exec_locals['vm_exit_scope'] = self.exit_scope exec_locals.update(self.static_locals) self.exec_hint(hint.compiled, exec_locals) # Clear ids (which will be rewritten by the next hint anyway) to make the VM instance # smaller and faster to copy. del exec_locals['ids'] del exec_locals['memory'] if self.skip_instruction_execution: return # Decode. instruction, instruction_encoding = self.decode_current_instruction() self.run_instruction(instruction, instruction_encoding) def compile_hint(self, source, filename): """ Compiles the given python source code. This function can be overridden by subclasses. """ return compile(source, filename, mode='exec') def exec_hint(self, code, globals_): """ Executes the given code with the given globals. This function can be overridden by subclasses. """ try: exec(code, globals_) except Exception: hint_exception = HintException(self, *sys.exc_info()) raise self.as_vm_exception( hint_exception, notes=[hint_exception.exception_str], hint=True) from None def run_instruction(self, instruction, instruction_encoding): try: # Compute operands. operands, operands_mem_addresses, operands_mem_values = self.compute_operands( instruction) except Exception as exc: raise self.as_vm_exception(exc) from None try: # Opcode assertions. self.opcode_assertions(instruction, operands) except Exception as exc: raise self.as_vm_exception(exc) from None # Write to trace. self.trace.append(TraceEntry( pc=self.run_context.pc, ap=self.run_context.ap, fp=self.run_context.fp, )) try: # Update registers. self.update_registers(instruction, operands) except Exception as exc: raise self.as_vm_exception(exc) from None self.current_step += 1 def check_eq(self, val0, val1): """ Called when an instruction encounters an assertion that two values should be equal. This function can be overridden by subclasses. """ return val0 == val1 @property def last_pc(self): """
used") gp.add_argument("--stepa", type=float, default=0.05, help="a step") gp.add_argument("--stepc", type=float, default=0.05, help="c step") # Phonopy # ------------------------------- gp = subparser.add_argument_group(title="phonopy") gp.add_argument("-n", "--supercell-n", type=int, nargs="+", default=[1, 1,1], help="supercell option for phonopy, like '2 2 2'") # -------------------------------------------------------------------------- # VASP # -------------------------------------------------------------------------- subparser = subparsers.add_parser("vasp", help="using vasp as calculator") # run params # ----------------------------------------------------------------- gp = subparser.add_argument_group(title="overall running control", description="control the task running parameters") gp.add_argument("-d", "--directory", type=str, default="matflow-running", help="directory to generate all the files, do not specify the current directory") gp.add_argument("-r", "--runtype", type=int, default=0, choices=[0, 1, 2, 3, 4, 5, 6, 7, 8], help="choices of runtype. 0->static_run; 1->optimization; 2->cubic-cell; 3->hexagonal-cell; 4->tetragonal-cell; 5->neb; 6->vasp-phonon; 7->phonopy; 8->surf pes") # calypso input.dat template gp = subparser.add_argument_group(title="template", description="read in Calypso input.dat template") gp.add_argument("--input-dat", type=str, default=None, help="specify Calypso input.dat template to set parameters") # run option gp.add_argument("--runopt", type=str, default="gen", choices=["gen", "run", "genrun"], help="Generate or run or both at the same time.") gp.add_argument("--auto", type=int, default=3, choices=[0, 1, 2, 3], help="auto:0 nothing, 1: copying files to server, 2: copying and executing, 3: pymatflow run inserver with direct submit, in order use auto=1, 2, you must make sure there is a working ~/.pymatflow/server_[pbs|llhpc].conf") gp.add_argument("--mpi", type=str, default="", help="MPI command, used in single node running, namely --auto 0 --runopt genrun") gp.add_argument("--server", type=str, default="pbs", choices=["pbs", "llhpc", "lsf_sz"], help="type of remote server, can be pbs or llhpc or lsf_sz") gp.add_argument("--jobname", type=str, default="matflow-running", help="jobname on the pbs server") gp.add_argument("--nodes", type=int, default=1, help="Nodes used in server") gp.add_argument("--ppn", type=int, default=32, help="ppn of the server") gp.add_argument("--queue", type=str, default=None, help="the queue to submit to job, default is not set") # llhpc gp.add_argument("--partition", type=str, default="free", help="choose partition to submit job, now only apply for llhpc") gp.add_argument("--ntask", type=int, default=24, help="choose task number, now only apply for llhpc") gp.add_argument("--stdout", type=str, default="slurm.out", help="set standard out, now only apply for llhpc") gp.add_argument("--stderr", type=str, default="slurm.err", help="set standard err, now only apply for llhpc") # potential file gp = subparser.add_argument_group(title="pseudopotential") gp.add_argument("--pot", type=str, default="./", help="specify the path to the POTCAR, default is ./. if you pass 'auto' to it, matflow will build the POTCAR foryou(need simple configuration, see manual)") gp.add_argument("--pot-type", type=str, default="PAW_PBE", choices=["PAW_PBE", "PAW_LDA", "PAW_PW91", "paw_pbe", "paw_lda", "paw_pw91"], help="choose type of POT for POTCAR") # -------------------------------------------------------- # INCAR PARAMETERS # -------------------------------------------------------- # incar->start parameters gp = subparser.add_argument_group(title="incar->start parameters", description="start parameters to be set in INCAR") gp.add_argument("--nwrite", type=int, nargs="+", default=None, help=" This flag determines how much will be written to the file OUTCAR (verbosity flag)") gp.add_argument("--prec", type=str, nargs="+", default=None, choices=["Normal", "Accurate", "A", "N"], help="PREC, default value: Normal") gp.add_argument("--ncore", type=int, nargs="+", default=None, help="NCORE determines the number of compute cores that work on an individual orbital ") # incar->electrons gp = subparser.add_argument_group(title="incar->electron", description="electrons calculation related parameters") gp.add_argument("--encut", type=int, nargs="+", default=None, help="ENCUT, default value: 300 eV") gp.add_argument("--ediff", type=float, nargs="+", default=None, help="EDIFF, default value: 1.0e-4") gp.add_argument("--nelm", type=int, nargs="+", default=None, help="NELM sets the maximum number of electronic SC (selfconsistency) steps which may be performed") gp.add_argument("--nfree", type=int, nargs="+", default=None, help="NFREE specifies the number of remembered steps in the history of ionic convergence runs, or the number of ionic displacements in frozen phonon calculations") gp.add_argument("--kpoints-mp", type=int, nargs="+", default=[1, 1, 1, 0, 0, 0], help="set kpoints like -k 1 1 1 0 0 0") gp.add_argument("--kspacing", type=float, nargs="+", default=None, help="determines the number of k-points if the KPOINTS file is not present. default is 0.5") #gp.add_argument("--kpoints-mp-scf", type=int, nargs="+", # default=[1, 1, 1, 0, 0, 0], # help="set kpoints like -k 1 1 1 0 0 0") #gp.add_argument("--kpoints-mp-nscf", type=int, nargs="+", # default=[3, 3, 3, 0, 0, 0], # help="set kpoints like -k 1 1 1 0 0 0") gp.add_argument("--kpath-manual", type=str, nargs="+", default=None, help="set kpoints for band structure calculation manually") gp.add_argument("--kpath-file", type=str, nargs="+", default="kpath.txt", help="set kpoints for band structure calculation manually from file") gp.add_argument("--kpath-intersections", type=int, nargs="+", default=15, help="intersection of the line mode kpoint for band calculation") gp.add_argument("--ismear", type=int, nargs="+", default=None, help="smearing type(methfessel-paxton(>0), gaussian(0), fermi-dirac(-1), tetra(-4), tetra-bloch-dorrected(-5)), default: 0") gp.add_argument("--sigma", type=float, nargs="+", default=None, help="determines the width of the smearing in eV.") gp.add_argument("--ivdw", type=int, nargs="+", default=None, choices=[0, 11, 12, 21, 202, 4], help="IVDW = 0(no correction), 1(dft-d2), 11(dft-d3 Grimme), 12(dft-d3 Becke-Jonson), default: None which means 0, no correction") # ----------------------------------------------------------------- gp.add_argument("--lorbit", type=int, nargs="+", default=None, choices=[0, 1, 2, 5, 10, 11, 12], help="together with an appropriate RWIGS, determines whether the PROCAR or PROOUT files are written") # optics related gp.add_argument("--loptics", type=str, nargs="+", default=None, choices=["TRUE", "FALSE"], help="calculates the frequency dependent dielectric matrix after the electronic ground state has been determined.") gp.add_argument("--cshift", type=float, nargs="+", default=None, help="CSHIFT sets the (small) complex shift η in the Kramers-Kronig transformation") gp.add_argument("--nedos", type=int, nargs="+", default=None, help="NEDOS specifies number of gridpoints on which the DOS is evaluated") # magnetic related gp.add_argument("--ispin", type=int, nargs="+", default=None, choices=[1, 2], help="specifies spin polarization: 1->no spin polarized, 2->spin polarized(collinear). combine SIPIN with MAGMOM to study collinear magnetism.") gp.add_argument("--magmom", type=float, nargs="+", default=None, help="Specifies the initial magnetic moment for each atom, if and only if ICHARG=2, or if ICHARG=1 and the CHGCAR file contains no magnetisation density.") gp.add_argument("--lnoncollinear", type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE."], help="specifies whether fully non-collinear magnetic calculations are performed") gp.add_argument("--lsorbit", type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE."], help="specifies whether spin-orbit coupling is taken into account.") gp.add_argument("--saxis", type=float, nargs="+", default=None, help="SAXIS specifies the quantisation axis for noncollinear spins") gp.add_argument("--lmaxmix", type=int, nargs="+", default=None, help="LMAXMIX controls up to which l-quantum number the one-center PAW charge densities are passed through the charge density mixer and written to the CHGCAR file.") # hybrid functional gp = subparser.add_argument_group(title="incar->Exchange correlation") gp.add_argument("--lhfcalc", type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE."], help=" specifies whether Hartree-Fock/DFT hybrid functional type calculations are performed") gp.add_argument("--hfscreen", type=float, nargs="+", default=None, choices=[0.3, 0.2], help=" specifies the range-separation parameter in range separated hybrid functionals: HSE03->0.3, HSE06->0.2, must also set LHFCALC=.TRUE.") gp.add_argument("--aexx", type=float, nargs="+", default=None, help="AEXX specifies the fraction of exact exchange in a Hartree-Fock/DFT hybrid functional type calculation") gp.add_argument("--lsubrot", type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE."], help="This flag can be set for hybrid functionals (HF-type calculations).") gp.add_argument("--nsw", type=int, nargs="+", default=None, help="NSW sets the maximum number of ionic steps") gp.add_argument("--ediffg", type=float, nargs="+", default=None, help="EDIFFG, default value: 10*EDIFF") gp = subparser.add_argument_group(title="incar->ions", description="setting ions related parameters") gp.add_argument("--ibrion", type=int, nargs="+", default=None, choices=[-1, 0, 1, 2, 3, 5, 6, 7, 8, 44], help="IBRION = refer to https://cms.mpi.univie.ac.at/wiki/index.php/IBRION for how to set the algorithm of optimization you need!") gp.add_argument("--isif", type=int, nargs="+", default=None, choices=[0, 1, 2, 3, 4, 5, 6, 7], help="ISIF = 0-7: refer to https://cms.mpi.univie.ac.at/wiki/index.php/ISIF for how to set the type of Geometri Optimization you need!") gp.add_argument("--potim", type=float, nargs="+", default=None, help="step width scaling (ionic relaxations), default: None = 0.015 in phonon calculation") gp.add_argument("--selective-dynamics", type=str, nargs="+", default="False", choices=["True", "False", "T", "F"], help="whether use selective dyanmics") # incar-miscellaneous gp = subparser.add_argument_group(title="incar-miscellaneous", description="miscellaneous input parameters") gp.add_argument("--algo", type=str, nargs="+", default=None, choices=["N", "D", "V", "F"], #"Exact", "G0W0", "GW0", "GW"], help=" a convenient option to specify the electronic minimisation algorithm (as of VASP.4.5) and/or to select the type of GW calculations") gp.add_argument("--ialgo", type=int, nargs="+", default=None, choices=[5, 6, 7, 8, 38, 44, 46, 48], help="IALGO selects the algorithm used to optimize the orbitals.Mind: We strongly urge the users to select the algorithms via ALGO. Algorithms other than those available via ALGO are subject to instabilities.") gp.add_argument("--addgrid", type=str, nargs="+", default=None, choices=[".TRUE.", ".FALSE.", "T", "F"], help="ADDGRID determines whether an additional support grid is used for the evaluation of the augmentation charges.") gp.add_argument("--isym", type=int, nargs="+", default=None, choices=[-1, 0, 1, 2, 3], help=" ISYM determines the way VASP treats symmetry.") gp.add_argument('--lreal', type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE.", "O", "On", "A", "Auto"], help="LREAL determines whether the projection operators are evaluated in real-space or in reciprocal space.") gp.add_argument("--pstress", type=float, nargs="+", default=None, help="controls whether Pulay corrections are added to the stress tensor or not.") # properties parameters gp.add_argument("--lelf", type=str, nargs="+", default=None, choices=["T", "F", ".TRUE.", ".FALSE."], help="LELF determines whether to create an ELFCAR file or not.") # write PARAMETERS gp = subparser.add_argument_group(title="incar->write parameters", description="set writing parameters") gp.add_argument("--lwave", type=str, nargs="+", default=None, choices=['T', 'F', ".TRUE.", '.FALSE.'], help="LWAVE determines whether the wavefunctions are written
import os import shutil from pathlib import Path import pytest from mock import patch from ruamel.yaml import YAML from demisto_sdk.commands.common.constants import ( CLASSIFIERS_DIR, CONNECTIONS_DIR, CONTENT_ENTITIES_DIRS, DASHBOARDS_DIR, DELETED_JSON_FIELDS_BY_DEMISTO, DELETED_YML_FIELDS_BY_DEMISTO, GENERIC_DEFINITIONS_DIR, GENERIC_FIELDS_DIR, GENERIC_MODULES_DIR, GENERIC_TYPES_DIR, INCIDENT_FIELDS_DIR, INCIDENT_TYPES_DIR, INDICATOR_FIELDS_DIR, INDICATOR_TYPES_DIR, INTEGRATIONS_DIR, JOBS_DIR, LAYOUTS_DIR, LISTS_DIR, PLAYBOOKS_DIR, PRE_PROCESS_RULES_DIR, REPORTS_DIR, SCRIPTS_DIR, TEST_PLAYBOOKS_DIR, WIDGETS_DIR) from demisto_sdk.commands.common.tools import (get_child_files, get_json, get_yaml) from demisto_sdk.commands.download.downloader import Downloader def ordered(obj): if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj class Environment: """ Environment is class designed to spin up a virtual, temporary content repo and build all objects related to the Downloader (such as pack content & custom content) """ def __init__(self, tmp_path): self.CONTENT_BASE_PATH = None self.CUSTOM_CONTENT_BASE_PATH = None self.PACK_INSTANCE_PATH = None self.INTEGRATION_INSTANCE_PATH = None self.SCRIPT_INSTANCE_PATH = None self.PLAYBOOK_INSTANCE_PATH = None self.LAYOUT_INSTANCE_PATH = None self.PRE_PROCESS_RULES_INSTANCE_PATH = None self.LISTS_INSTANCE_PATH = None self.CUSTOM_CONTENT_SCRIPT_PATH = None self.CUSTOM_CONTENT_INTEGRATION_PATH = None self.CUSTOM_CONTENT_LAYOUT_PATH = None self.CUSTOM_CONTENT_PLAYBOOK_PATH = None self.CUSTOM_CONTENT_JS_INTEGRATION_PATH = None self.INTEGRATION_PACK_OBJECT = None self.SCRIPT_PACK_OBJECT = None self.PLAYBOOK_PACK_OBJECT = None self.LAYOUT_PACK_OBJECT = None self.LISTS_PACK_OBJECT = None self.JOBS_PACK_OBJECT = None self.JOBS_INSTANCE_PATH = None self.PACK_CONTENT = None self.INTEGRATION_CUSTOM_CONTENT_OBJECT = None self.SCRIPT_CUSTOM_CONTENT_OBJECT = None self.PLAYBOOK_CUSTOM_CONTENT_OBJECT = None self.LAYOUT_CUSTOM_CONTENT_OBJECT = None self.FAKE_CUSTOM_CONTENT_OBJECT = None self.JS_INTEGRATION_CUSTOM_CONTENT_OBJECT = None self.CUSTOM_CONTENT = None self.tmp_path = Path(tmp_path) self.setup() def setup(self): tests_path = self.tmp_path / 'tests' tests_env_path = tests_path / 'tests_env' tests_data_path = tests_path / 'tests_data' shutil.copytree(src='demisto_sdk/commands/download/tests/tests_env', dst=str(tests_env_path)) shutil.copytree(src='demisto_sdk/commands/download/tests/tests_data', dst=str(tests_data_path)) self.CONTENT_BASE_PATH = f'{tests_path}/tests_env/content' self.CUSTOM_CONTENT_BASE_PATH = f'{tests_path}/tests_data/custom_content' self.PACK_INSTANCE_PATH = f'{self.CONTENT_BASE_PATH}/Packs/TestPack' self.INTEGRATION_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Integrations/TestIntegration' self.SCRIPT_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Scripts/TestScript' self.PLAYBOOK_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Playbooks/playbook-DummyPlaybook.yml' self.LAYOUT_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Layouts/layout-details-TestLayout.json' self.PRE_PROCESS_RULES_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/PreProcessRules/preprocessrule-dummy.json' self.LISTS_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Lists/list-dummy.json' self.JOBS_INSTANCE_PATH = f'{self.PACK_INSTANCE_PATH}/Jobs/job-sample.json' self.CUSTOM_CONTENT_SCRIPT_PATH = f'{self.CUSTOM_CONTENT_BASE_PATH}/automation-TestScript.yml' self.CUSTOM_CONTENT_INTEGRATION_PATH = f'{self.CUSTOM_CONTENT_BASE_PATH}/integration-Test_Integration.yml' self.CUSTOM_CONTENT_LAYOUT_PATH = f'{self.CUSTOM_CONTENT_BASE_PATH}/layout-details-TestLayout.json' self.CUSTOM_CONTENT_PLAYBOOK_PATH = f'{self.CUSTOM_CONTENT_BASE_PATH}/playbook-DummyPlaybook.yml' self.CUSTOM_CONTENT_JS_INTEGRATION_PATH = f'{self.CUSTOM_CONTENT_BASE_PATH}/integration-DummyJSIntegration.yml' self.INTEGRATION_PACK_OBJECT = {'Test Integration': [ {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/TestIntegration.py', 'file_ending': 'py'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/TestIntegration_testt.py', 'file_ending': 'py'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/TestIntegration.yml', 'file_ending': 'yml'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/TestIntegration_image.png', 'file_ending': 'png'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/CHANGELOG.md', 'file_ending': 'md'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/TestIntegration_description.md', 'file_ending': 'md'}, {'name': 'Test Integration', 'id': 'Test Integration', 'path': f'{self.INTEGRATION_INSTANCE_PATH}/README.md', 'file_ending': 'md'} ]} self.SCRIPT_PACK_OBJECT = {'TestScript': [ {'name': 'TestScript', 'id': 'TestScript', 'path': f'{self.SCRIPT_INSTANCE_PATH}/TestScript.py', 'file_ending': 'py'}, {'name': 'TestScript', 'id': 'TestScript', 'path': f'{self.SCRIPT_INSTANCE_PATH}/TestScript.yml', 'file_ending': 'yml'}, {'name': 'TestScript', 'id': 'TestScript', 'path': f'{self.SCRIPT_INSTANCE_PATH}/CHANGELOG.md', 'file_ending': 'md'}, {'name': 'TestScript', 'id': 'TestScript', 'path': f'{self.SCRIPT_INSTANCE_PATH}/README.md', 'file_ending': 'md'} ]} self.PLAYBOOK_PACK_OBJECT = {'DummyPlaybook': [ {'name': 'DummyPlaybook', 'id': 'DummyPlaybook', 'path': self.PLAYBOOK_INSTANCE_PATH, 'file_ending': 'yml'} ]} self.LAYOUT_PACK_OBJECT = {'Hello World Alert': [ {'name': 'Hello World Alert', 'id': 'Hello World Alert', 'path': self.LAYOUT_INSTANCE_PATH, 'file_ending': 'json'} ]} self.PRE_PROCESS_RULES_PACK_OBJECT = {'DummyPreProcessRule': [ {'name': 'DummyPreProcessRule', 'id': 'DummyPreProcessRule', 'path': self.PRE_PROCESS_RULES_INSTANCE_PATH, 'file_ending': 'json'} ]} self.LISTS_PACK_OBJECT = {'DummyList': [ {'name': 'DummyList', 'id': 'DummyList', 'path': self.LISTS_INSTANCE_PATH, 'file_ending': 'json'} ]} self.JOBS_PACK_OBJECT = {'DummyJob': [ {'name': 'DummyJob', 'id': 'DummyJob', 'path': self.JOBS_INSTANCE_PATH, 'file_ending': 'json'} ]} self.PACK_CONTENT = { INTEGRATIONS_DIR: [self.INTEGRATION_PACK_OBJECT], SCRIPTS_DIR: [self.SCRIPT_PACK_OBJECT], PLAYBOOKS_DIR: [self.PLAYBOOK_PACK_OBJECT], LAYOUTS_DIR: [self.LAYOUT_PACK_OBJECT], PRE_PROCESS_RULES_DIR: [], LISTS_DIR: [], JOBS_DIR: [], TEST_PLAYBOOKS_DIR: [], REPORTS_DIR: [], DASHBOARDS_DIR: [], WIDGETS_DIR: [], INCIDENT_FIELDS_DIR: [], INDICATOR_FIELDS_DIR: [], INCIDENT_TYPES_DIR: [], CLASSIFIERS_DIR: [], CONNECTIONS_DIR: [], INDICATOR_TYPES_DIR: [], GENERIC_TYPES_DIR: [], GENERIC_FIELDS_DIR: [], GENERIC_MODULES_DIR: [], GENERIC_DEFINITIONS_DIR: [] } self.INTEGRATION_CUSTOM_CONTENT_OBJECT = {'id': 'Test Integration', 'name': 'Test Integration', 'path': self.CUSTOM_CONTENT_INTEGRATION_PATH, 'entity': 'Integrations', 'type': 'integration', 'file_ending': 'yml', 'code_lang': 'python'} self.SCRIPT_CUSTOM_CONTENT_OBJECT = {'id': 'TestScript', 'name': 'TestScript', 'path': self.CUSTOM_CONTENT_SCRIPT_PATH, 'entity': 'Scripts', 'type': 'script', 'file_ending': 'yml', 'code_lang': 'python'} self.PLAYBOOK_CUSTOM_CONTENT_OBJECT = {'id': 'DummyPlaybook', 'name': 'DummyPlaybook', 'path': self.CUSTOM_CONTENT_PLAYBOOK_PATH, 'entity': 'Playbooks', 'type': 'playbook', 'file_ending': 'yml'} self.LAYOUT_CUSTOM_CONTENT_OBJECT = {'id': 'Hello World Alert', 'name': 'Hello World Alert', 'path': self.CUSTOM_CONTENT_LAYOUT_PATH, 'entity': 'Layouts', 'type': 'layout', 'file_ending': 'json'} self.FAKE_CUSTOM_CONTENT_OBJECT = {'id': 'DEMISTO', 'name': 'DEMISTO', 'path': f'{self.CUSTOM_CONTENT_BASE_PATH}/DEMISTO.json', 'entity': 'Layouts', 'type': 'layout', 'file_ending': 'json'} self.JS_INTEGRATION_CUSTOM_CONTENT_OBJECT = {'id': 'SumoLogic', 'name': 'SumoLogic', 'path': self.CUSTOM_CONTENT_JS_INTEGRATION_PATH, 'entity': 'Integrations', 'type': 'integration', 'file_ending': 'yml', 'code_lang': 'javascript'} self.CUSTOM_CONTENT = [ self.INTEGRATION_CUSTOM_CONTENT_OBJECT, self.SCRIPT_CUSTOM_CONTENT_OBJECT, self.PLAYBOOK_CUSTOM_CONTENT_OBJECT, self.LAYOUT_CUSTOM_CONTENT_OBJECT, self.JS_INTEGRATION_CUSTOM_CONTENT_OBJECT ] class TestHelperMethods: @pytest.mark.parametrize('code_lang, file_type, file_name, err_msg, output', [ ('javascript', 'integration', 'file name', 'Downloading an integration written in JavaScript is not supported.', False), ('javascript', 'script', 'file name', 'Downloading a script written in JavaScript is not supported.', False), ('python', 'integration', 'file name', '', True), ]) def test_verify_code_lang(self, code_lang, file_type, file_name, err_msg, output): with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') downloader.files_not_downloaded = [] assert downloader.verify_code_lang(code_lang, file_type, file_name) is output if not output: assert [file_name, err_msg] in downloader.files_not_downloaded @pytest.mark.parametrize('data, file_type, entity', [ ({'name': 'test-pb'}, 'playbook', TEST_PLAYBOOKS_DIR), ({}, 'integration', INTEGRATIONS_DIR) ]) def test_file_type_to_entity(self, data, file_type, entity): with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') assert downloader.file_type_to_entity(data, file_type) == entity def test_get_custom_content_objects(self, tmp_path): env = Environment(tmp_path) with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') downloader.custom_content_temp_dir = env.CUSTOM_CONTENT_BASE_PATH custom_content_objects = downloader.get_custom_content_objects() assert ordered(custom_content_objects) == ordered(env.CUSTOM_CONTENT) @pytest.mark.parametrize('name, ending, detail, output', [ ('G S M', 'py', 'python', 'GSM.py'), ('G S M', 'yml', 'yaml', 'GSM.yml'), ('G S M', 'png', 'image', 'GSM_image.png'), ('G S M', 'md', 'description', 'GSM_description.md') ]) def test_get_searched_basename(self, name, ending, detail, output): downloader = Downloader(output='', input='', regex='') assert downloader.get_searched_basename(name, ending, detail) == output @pytest.mark.parametrize('ending, output', [ ('py', 'python'), ('md', 'description'), ('yml', 'yaml'), ('png', 'image'), ('', '') ]) def test_get_extracted_file_detail(self, ending, output): downloader = Downloader(output='', input='', regex='') assert downloader.get_extracted_file_detail(ending) == output @pytest.mark.parametrize('name, output', [('automation-demisto', 'script-demisto'), ('wow', 'wow'), ("playbook-demisto", "demisto")]) def test_update_file_prefix(self, name, output): downloader = Downloader(output='', input='', regex='') assert downloader.update_file_prefix(name) == output assert not downloader.update_file_prefix(name).startswith("playbook-") @pytest.mark.parametrize('name', ['GSM', 'G S M', 'G_S_M', 'G-S-M', 'G S_M', 'G_S-M']) def test_create_dir_name(self, name): downloader = Downloader(output='', input='', regex='') assert downloader.create_dir_name(name) == 'GSM' class TestFlagHandlers: @pytest.mark.parametrize('lf, a, o, i, r, res, err', [ (True, True, True, True, None, True, ''), (False, False, False, True, None, False, "Error: Missing option '-o' / '--output'."), (False, False, True, False, None, False, "Error: Missing option '-i' / '--input'."), (False, True, True, False, None, True, ''), (False, True, True, True, None, True, ''), (False, False, True, False, 'Some Regex', True, '') ]) def test_verify_flags(self, lf, a, o, i, r, res, err, capsys): with patch.object(Downloader, "__init__", lambda x, y, z: None): downloader = Downloader('', '') downloader.list_files = lf downloader.all_custom_content = a downloader.output_pack_path = o downloader.input_files = i downloader.regex = r answer = downloader.verify_flags() stdout, _ = capsys.readouterr() if err: assert err in stdout assert answer is res def test_handle_all_custom_content_flag(self, tmp_path): env = Environment(tmp_path) with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') downloader.custom_content_temp_dir = env.CUSTOM_CONTENT_BASE_PATH downloader.all_custom_content = True downloader.handle_all_custom_content_flag() custom_content_names = [cco['name'] for cco in env.CUSTOM_CONTENT] assert ordered(custom_content_names) == ordered(downloader.input_files) def test_handle_list_files_flag(self, capsys, tmp_path): env = Environment(tmp_path) with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') downloader.custom_content_temp_dir = env.CUSTOM_CONTENT_BASE_PATH downloader.list_files = True answer = downloader.handle_list_files_flag() stdout, _ = capsys.readouterr() list_files = [[cco['name'], cco['type']] for cco in env.CUSTOM_CONTENT] for file in list_files: assert file[0] in stdout assert file[1] in stdout assert answer def test_handle_list_files_flag_error(self, mocker, tmp_path): """ GIVEN a file contained in custom content of not supported type WHEN the user runs demisto-sdk download -lf THEN the handle_list_files_flag method should ignore the file """ env = Environment(tmp_path) mocker.patch('demisto_sdk.commands.download.downloader.get_dict_from_file', return_value=({}, 'json')) mocker.patch('demisto_sdk.commands.download.downloader.get_child_files', return_value=['path']) with patch.object(Downloader, "__init__", lambda a, b, c: None): downloader = Downloader('', '') downloader.custom_content_temp_dir = env.INTEGRATION_INSTANCE_PATH downloader.list_files = True assert downloader.handle_list_files_flag() class TestBuildPackContent: def test_build_pack_content(self, tmp_path): env = Environment(tmp_path) downloader = Downloader(output=env.PACK_INSTANCE_PATH, input='', regex='') downloader.build_pack_content() assert ordered(downloader.pack_content) == ordered(env.PACK_CONTENT) def test_build_pack_content_object(self, tmp_path): env = Environment(tmp_path) parameters = [ {'entity': INTEGRATIONS_DIR, 'path': env.INTEGRATION_INSTANCE_PATH, 'out': env.INTEGRATION_PACK_OBJECT}, {'entity': SCRIPTS_DIR, 'path': env.SCRIPT_INSTANCE_PATH, 'out': env.SCRIPT_PACK_OBJECT}, {'entity': PLAYBOOKS_DIR, 'path': env.PLAYBOOK_INSTANCE_PATH, 'out': env.PLAYBOOK_PACK_OBJECT}, {'entity': LAYOUTS_DIR, 'path': env.LAYOUT_INSTANCE_PATH, 'out': env.LAYOUT_PACK_OBJECT}, {'entity': LAYOUTS_DIR, 'path': 'demisto_sdk/commands/download/tests/downloader_test.py', 'out': {}}, {'entity': PRE_PROCESS_RULES_DIR, 'path': env.PRE_PROCESS_RULES_INSTANCE_PATH, 'out': []}, {'entity': LISTS_DIR, 'path': env.LISTS_INSTANCE_PATH, 'out': []}, {'entity': JOBS_DIR, 'path': env.JOBS_INSTANCE_PATH, 'out': []} ] downloader = Downloader(output='', input='', regex='') for param in parameters: pack_content_object = downloader.build_pack_content_object(param['entity'], param['path']) assert ordered(pack_content_object) == ordered(param['out']) def test_get_main_file_details(self, tmp_path): env = Environment(tmp_path) parameters = [ {'entity': INTEGRATIONS_DIR, 'path': env.INTEGRATION_INSTANCE_PATH, 'main_id': 'Test Integration', 'main_name': 'Test Integration'}, {'entity': LAYOUTS_DIR, 'path': env.LAYOUT_INSTANCE_PATH, 'main_id': 'Hello World Alert', 'main_name': 'Hello World Alert'}, {'entity': LAYOUTS_DIR, 'path': 'demisto_sdk/commands/download/tests/downloader_test.py', 'main_id': '', 'main_name': ''} ] downloader = Downloader(output='', input='', regex='') for param in parameters: op_id, op_name = downloader.get_main_file_details(param['entity'], os.path.abspath(param['path'])) assert op_id == param['main_id'] assert op_name == param['main_name'] class TestBuildCustomContent: def
& Video': '21 West Highland Avenue', 'Windows 7': None }, 'digitizer.organization.address.street2': { '#REF!': None, '21 West Highland Avenue': None, 'PA': None, 'Prism': None, 'Windows 7': None }, 'digitizer.organization.name': { '6.0.7': None, 'NYPL': 'New York Public Library' }, 'source.audioRecording.audioSamplingRate.measure': { 48.0: 48000.0, 44.1: 44100.0 }, 'source.audioRecording.audioSoundField': { '4-track': 'quadraphonic', 'momo': 'mono', ' ': None }, 'source.audioRecording.designatedEQ': { '44.1kHz / 16bits': None, 'nab': 'NAB', 'none': None, 'not specified': 'unknown', 'unspecified': 'unknown' }, 'source.audioRecording.designatedNoiseReduction': { 'no NR': None, 'None': None, 'none': None, 'not specified': 'unknown', 'DBX Type 1': 'DBX I', 'Type I': 'DBX I' }, 'source.audioRecording.designatedSpeed': { 'None': 'unknown', 'none': 'unknown', 'not specified': 'unknown' }, 'source.audioRecording.numberOfAudioTracks': { 0: None, 0.0: None, '4-track': 4.0, '/': None, ' ': None, 'color': 2.0, 'None': None, 'none': None }, 'source.audioRecording.trackConfiguration': { 'Mixed': 'mixed', 'N; A': 'unknown', 'Quarter-track': 'quarter-track' }, 'source.contentSpecifications.broadcastStandard': { 'NTSC ': 'NTSC' }, 'source.contentSpecifications.colorBW': { 'YUV': 'color', 'Color': 'color', 'b&w/color': 'color & b/w', 'b/w & color': 'color & b/w', 'color/b&w': 'color & b/w', 'color mono': 'color' }, 'source.object.format': { '1/4 in. reel to reel': 'quarter-inch open-reel audio', '1/4" open reel audio': 'quarter-inch open-reel audio', '1/4" open-reel audio': 'quarter-inch open-reel audio', '1/2" CV': 'half-inch open-reel video CV', '1/2" EIAJ': 'half-inch open-reel video EIAJ/AV', '1/2" open reel': 'half-inch open-reel video other', '1" Type C': 'one-inch open-reel video Type C', '3/4" U-matic': 'U-matic', 'Betacam sp': 'Betacam SP', 'BetaMax': 'Betamax', 'CD-DA': 'Audio CD, pressed', 'CD-R': 'Audio CD-R', 'compact cassette': 'Compact cassette', 'D2': 'D-2', 'DAT cassette': 'DAT', 'digital betacam': 'Digital Betacam', 'digital file': 'Digital file', 'DVCPRO': 'DVCPro', 'DVD': 'Video DVD', 'DVD-R': 'Video DVD-R', 'DVD+R': 'Video DVD+R', 'DVD+RW': 'Video DVD+RW', 'Edison VoiceWriter': 'disc, Edison Voicewriter', 'EIAJ 1/2" open-reel': 'half-inch open-reel video EIAJ/AV', 'EIAJ 1/2" r-r': 'half-inch open-reel video EIAJ/AV', 'Folder': 'Digital file', 'Instantaneous disc': 'disc, other', 'instantaneous disc, coated': 'disc, other', 'instantaneous disc, uncoated': 'disc, other', 'Laserdisc': 'Laser Disc', 'microcassette': 'Microcassette', 'minicassette': 'Minicassette', 'motion picture film': '16mm film [LEGACY]', 'Open-reel, 1/2" EIAJ': 'half-inch open-reel video EIAJ/AV', 'Open-reel - 1/2" EIAJ': 'half-inch open-reel video EIAJ/AV', 'Open-reel - 1/2" NONSTANDARD CV': 'half-inch open-reel video other', 'Open-reel - 1" Type C': 'one-inch open-reel video Type C', 'Open-reel - 2" Quad': 'two-inch open-reel video Quadruplex', 'replicated disc, uncoated': 'disc, other', 'SVHS': 'S-VHS', 'Umatic': 'U-matic' }, 'source.physicalDescription.backcoatMaterial': { 'none': 'no', 'yes for 206 stock': 'yes', 'Yes': 'yes', 'No': 'no' }, 'source.physicalDescription.baseMaterial': { 'Acetae': 'acetate', 'acetae & polyester': 'acetate and polyester', 'Acetate': 'acetate', 'acetate, polyester': 'acetate and polyester', 'Acetate/Polyester': 'acetate and polyester', 'acetate/polyester': 'acetate and polyester', 'black wax': 'wax, black', 'Metal': 'unknown metal', 'metal': 'unknown metal', 'Paper': 'paper', 'Plaster': 'plaster', 'Pokyester': 'polyester', 'Polyester': 'polyester', 'polyester and acetate': 'acetate and polyester', 'polyester [?]/acetate mixed': 'acetate and polyester', 'pvc': 'PVC', 'Steel': 'steel', 'Unidentified metal': 'unknown metal', 'unidentified metal': 'unknown metal', 'Wax, black': 'wax, black', 'Wax, brown': 'wax, brown' }, 'source.physicalDescription.dataCapacity.unit': { '[unknown]': None, }, 'source.physicalDescription.oxideMaterial': { 'Chromium': 'chromium dioxide', 'chromium ': 'chromium dioxide', 'chormium': 'chromium dioxide', 'chromium oxide': 'chromium dioxide', 'Ferric': 'ferric oxide', 'ferric ': 'ferric oxide', 'iron': 'ferric oxide', 'ferric oxide?': 'ferric oxide', 'ferric': 'ferric oxide', 'ferrric': 'ferric oxide', 'ferrid': 'ferric oxide', 'ferrci': 'ferric oxide', 'ferriec': 'ferric oxide', 'ferrica': 'ferric oxide', 'ferroc': 'ferric oxide', 'feriic': 'ferric oxide', 'ferricferric': 'ferric oxide', 'ferri': 'ferric oxide', 'Metal': 'metal oxide', 'metal': 'metal oxide', 'normal': None, }, 'source.physicalDescription.stockManufacturer': { '/': None, '???': None, '????': None, '[Edison ?]': 'Edison', '[unknown]': None, '3m': '3M', 'acoustiguide': 'Acoustiguide', 'adonai': 'Adonai', 'Amepx': 'Ampex', 'audio magneticx': 'Audio Magnetics', 'Audio Magnetic': 'Audio Magnetics', 'Audio Magnetics Corporation': 'Audio Magnetics', 'audiotape': 'Audiotape', 'Audiotape ': 'Audiotape', 'ATT': 'AT&T', 'ampex': 'Ampex', 'Cetron': 'Certron', 'Columbia Magnetics': 'Columbia', 'Comcast Cassette': None, 'Concertape': 'Concert', 'concertape': 'Concert', 'Dak Industries': 'DAK', 'denon': 'Denon', 'Delmar': 'Delmark', 'grand central': 'Grand Central', 'Irsh': 'Irish', 'JCV': 'JVC', 'JVC Dynarec HR': 'JVC', 'keystone': 'Keystone', 'Lnacer': 'Lancer', 'LNX60': None, 'national': 'National', 'None': None, 'not identified': None, 'Mazell': 'Maxell', 'originalFormatStockBrand': None, 'PANASONIC': 'Panasonic', 'pca': 'PCA', 'pd magnetics': 'PD Magnetics', 'Phillips': 'Philips', 'phillips': 'Philips', 'quantegy': 'Quantegy', 'Quantegy Broadcast': 'Quantegy', 'realistic': 'Realistic', 'Scotj': 'Scotch', 'Scotvh': 'Scotch', 'Sctoch': 'Scotch', 'Schotch': 'Scotch', 'seiko': 'Seiko', 'shamrock': 'Shamrock', 'soundcraft': 'Soundcraft', 'soundtape': 'Soundtape', 'supertape': 'Supertape', 'teac': 'TEAC', 'the learning tape': 'The Learning Tape', 'Tone Master': 'ToneMaster', 'Tonemaster': 'ToneMaster', 'triad': 'Triad', 'triton': 'Triton', 'Unidentified': None, 'united': 'United' }, 'source.physicalDescription.stockProductID': { 'na': None, 'none': None }, 'source.physicalDescription.tapeThickness.measure': { '1.0mil': 1.0, '1.0 mil': 1.0, '1.5 mil': 1.5, '1.500 (Mostly)': 1.5, '1.5[?]': 1.5, 'Unidentified': None, '[unknown]': None }, 'source.physicalDescription.tapeWidth.measure': { '1/8': 0.125, '1/4"': 0.25, 0.025: 0.25, '16mm': 16, '42008.0': '0.25' }, 'technical.audioBitDepth.measure': { '0.0': None, 23: None, '#REF!': None, 'mp4': None, 'Windows 7': None }, 'technical.audioBitRate.measure': { '0.0': None, 23: None, '#REF!': None }, 'technical.audioBitRate.mode': { '0.0': None, 23: None, '#REF!': None, 'Windows 7': None }, 'technical.audioCodecVersion': { 0.0: None }, 'technical.audioDataEncoding': { '00:00:00': None, 23: None, '6.0.7': None, '#REF!': None }, 'technical.audioSamplingRate.measure': { 0: None, 23: None, 48: 48000.0, 'Prism': None, 'MPEG-4': None }, 'technical.chromaSubsampling': { '04:02:02': '4:2:2', '4:02:02': '4:2:2', '04:02:00': '4:2:0' }, 'technical.durationHuman': { 23: None, '#REF!': None, 'SADiE': None }, 'technical.extension': { 0: None, 23: None, '#REF!': None, 'SADiE': None }, 'technical.fieldOrder': { '0.0': None }, 'technical.fileFormat': { 23: None, '#REF!': None, 'Final Cut Pro Project': 'Final Cut Pro Project File', 'Project File': 'Final Cut Pro Project File', 'Wave': 'BWF', 'Windows 7': None }, 'technical.filename': { 0: None, 23: None, '#REF!': None }, 'technical.fileSize.measure': { 'Prism': None, 23: None, '#REF!': None }, 'technical.numberOfAudioTracks': { 0.0: None, '#REF!': None, 'SADiE': None }, 'technical.videoCodecVersion': { 0.0: None } } """ Dict of dicts of regex replacements. Each first-level key is the name of the column the replacements apply to Second-level dictionary key-value pairs are used as find-replace Probably too comprehensive in its current state. Might speed up code to move all whole-string match-strings to STRING_REPLACE_DICT """ REGEX_REPLACE_DICT = { 'bibliographic.barcode': { r'^3343([^3]\d+)': r'33433\1', r'^3433(\\d+)': r'33433\1', r'^34433(\\d+)': r'33433\1', r'^33([^4]\\d+)': r'33433\1' }, 'digitizationProcess.analogDigitalConverter.manufacturer': { r'AJA.*': 'AJA', r'Antelope.*': 'Antelope Audio', r'Black.*': 'Blackmagic Design', r'FS\d': 'AJA', r'Lucid.*': 'Lucid', r'MAC OS X 10.6.8.*': None, r'(?i)Mytek.*': 'Mytek Digital', r'Prism.*': 'Prism Sound', r'Snell.*': 'Snell and Wilcox', }, 'digitizationProcess.analogDigitalConverter.model': { r'.*IOLA.*': 'Io LA', r'.*KLHi-Box.*': 'KLHi-Box', r'8(x|X)192\s?ADDA': '8X192 ADDA', r'(?i)ADA?[-8]{2}XR': 'ADA-8XR', r'(?i)Teranex2d422': 'Teranex2d422', r'AD.*9624': 'AD-9624' }, 'digitizationProcess.analogDigitalConverter.operatingLevel.measure': { r'^\s': '', r'dBFS': '', r'\.0$': '' }, 'digitizationProcess.captureSoftware.platform': { r'^(10.+|OS\s X)': 'Mac OS X', r'(?i)(Mac|Macintosh)\sOS\s?X': 'Mac OS X', r'Mac\sOS\s10': 'Mac OS X 10', r'Windows\s?XP': 'Windows XP' }, 'digitizationProcess.playbackDevice.phonoPreamp.1.eq': { r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.1.eqRolloff.measure': { r'\.0$': '' }, 'digitizationProcess.playbackDevice.phonoPreamp.1.eqTurnover..measure': { r'\.0$': '', r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.1.manufacturer': { r'(?i)Timestep': 'Time-Step' }, 'digitizationProcess.playbackDevice.phonoPreamp.1.model': { r'EQS\s?MK12': 'Souvenir EQS MK12' }, 'digitizationProcess.playbackDevice.phonoPreamp.2.eq': { r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.2.eqRolloff.measure': { r'\.0$': '' }, 'digitizationProcess.playbackDevice.phonoPreamp.2.eqTurnover.measure': { r'\.0$': '', r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.2.manufacturer': { r'OWL.*': 'OWL' }, 'digitizationProcess.playbackDevice.phonoPreamp.2.serialNumber': { r'\.0$': '' }, 'digitizationProcess.playbackDevice.phonoPreamp.3.eq': { r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.3.eqRolloff.measure': { r'\.0$': '' }, 'digitizationProcess.playbackDevice.phonoPreamp.3.eqTurnover.measure': { r'\.0$': '', r'(?i)flat': 'flat' }, 'digitizationProcess.playbackDevice.phonoPreamp.3.manufacturer': { r'OWL.*': 'OWL' }, 'digitizationProcess.playbackDevice.phonoPreamp.3.serialNumber': { r'\.0$': '' }, 'digitizationProcess.playbackDevice.eq': { r'.*Type\sI': 'Type I', r'IEC|CCIR': 'IEC/CCIR' }, 'digitizationProcess.playbackDevice.manufacturer': { r'(?i)TASCAM.*': 'TASCAM', r'(?i)ReVox': 'ReVox', r'(?i)Sony.*': 'Sony', r'(?i)Pana?sonic.*': 'Panasonic' }, 'digitizationProcess.playbackDevice.model': { r'(?i)122 ?MKIII': '122 MKIII', r'mk': 'MK' }, 'digitizationProcess.playbackDevice.phonoCartridge.model':{ r'\.0$': '' }, 'digitizationProcess.playbackDevice.phonoCartridge.stylusSize': { r'^(\d)$': r'\1.0' }, 'digitizationProcess.playbackDevice.tapeHeadType': { r'(?i)(-|\s)track$': '-track', r'(?i)full': 'full', r'^(?i)full$': 'full-track', r'(?i)half': 'half', r'(?i)quarter|1/4': 'quarter', r'(?i)two': 'two', r'(?i)3': 'three', r'(?i)four|4': 'four', r'(?i)mixed': 'mixed' }, 'digitizationProcess.timeBaseCorrector.manufacturer': { r'(?i)FOR\.?A': 'FOR.A' }, 'digitizer.organization.address.postalCode': { r'191\d\d$': '19118', r'\.0$': '' }, 'digitizer.organization.address.street1': { r'Ave\.?$': 'Avenue', r'St\.?$': 'Street', r'\d\d(\d|)\sW\.?\s': '21 West ' }, 'digitizer.organization.name': { r'.*(?i)George.*': 'George Blood Audio Video Film', r'.*(?i)MediaPreserve.*': 'The MediaPreserve' }, 'notes.notes': { r'\n\s?': '; ', r';([^\s])': r';\1' }, 'notes.otherNotes': { r'\n\s?': '; ', r';([^\s])': r';\1' }, 'source.audioRecording.audioSoundField': { r'(?i)stereo': 'stereo', r'(?i)mono.': 'mono', r'(?i)silent|none|no\saudio': 'none', r'(?i)binaural.*': 'binaural', r'(?i)unknown.*': 'unknown', r'(?i)dual(-|\s)mono': 'dual-mono', r'(?i)mono(/|\s)stereo.*': 'stereo/mono', r';\s': '/', r'(?i)Unmixed/': '', r'(?i)mixed': 'mixed', r'(\(|\[).*$': '' }, 'source.audioRecording.designatedEQ': { r'.*Type\sI': 'Type I', r'IEC|CCIR': 'IEC/CCIR', r'(?i)NAB': 'NAB' }, 'source.audioRecording.numberOfAudioTracks': { r'(?i)Ch\s?1[Ch,\.\s]+2': 'Ch1, Ch2', r'(?i).*(\d).*o.*': r'Ch\1 Only', r'^(?i)Ch\s?(\d)$': r'Ch\1 Only', r'(?i)none|0\.0': 'none' }, 'source.audioRecording.trackConfiguration': { r'(?i)(-|\s)track$': '-track', r'(?i)full': 'full', r'^(?i)full$': 'full-track', r'(?i)half': 'half', r'(?i)quarter|1/4': 'quarter', r'(?i)two|2|dual': 'two', r'(?i)3': 'three', r'(?i)four|4': 'four', r'\n\s|/': '; ', r'\s?(\(|\[|\?).*$': '' }, 'source.physicalDescription.baseMaterial': { r'\s?(\(|\[|\?).*$': '', r'^(?i)ac\w+$': 'acetate', r'^(?i)po\w+$': 'polyester' }, 'source.physicalDescription.diameter.measure': { r'\.0$': '', r'\sin\.':
# Author: <NAME> <<EMAIL>> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. import datetime import os import re import sickbeard import generic from sickbeard.common import XML_NSMAP from sickbeard import logger, exceptions, helpers from sickbeard import encodingKludge as ek from lib.tvdb_api import tvdb_api, tvdb_exceptions from sickbeard.exceptions import ex import xml.etree.cElementTree as etree class MediaBrowserMetadata(generic.GenericMetadata): """ Metadata generation class for Media Browser. All xml formatting and file naming information was contributed by users in the following ticket's comments: http://code.google.com/p/sickbeard/issues/detail?id=311 The following file structure is used: show_root/series.xml (show metadata) show_root/folder.jpg (poster) show_root/backdrop.jpg (fanart) show_root/Season 01/folder.jpg (season thumb) show_root/Season 01/show - 1x01 - episode.avi (* example of existing ep of course) show_root/Season 01/show - 1x01 - episode.xml (episode metadata) show_root/metadata/show - 1x01 - episode.jpg (episode thumb) """ def __init__(self, show_metadata=False, episode_metadata=False, poster=False, fanart=False, episode_thumbnails=False, season_thumbnails=False): generic.GenericMetadata.__init__(self, show_metadata, episode_metadata, poster, fanart, episode_thumbnails, season_thumbnails) self.fanart_name = "backdrop.jpg" self._show_file_name = 'series.xml' self._ep_nfo_extension = 'xml' self.name = 'MediaBrowser' self.eg_show_metadata = "series.xml" self.eg_episode_metadata = "Season##\\metadata\\<i>filename</i>.xml" self.eg_fanart = "backdrop.jpg" self.eg_poster = "folder.jpg" self.eg_episode_thumbnails = "Season##\\metadata\\<i>filename</i>.jpg" self.eg_season_thumbnails = "Season##\\folder.jpg" def get_episode_file_path(self, ep_obj): """ Returns a full show dir/metadata/episode.xml path for MediaBrowser episode metadata files ep_obj: a TVEpisode object to get the path for """ if ek.ek(os.path.isfile, ep_obj.location): xml_file_name = helpers.replaceExtension(ek.ek(os.path.basename, ep_obj.location), self._ep_nfo_extension) metadata_dir_name = ek.ek(os.path.join, ek.ek(os.path.dirname, ep_obj.location), 'metadata') xml_file_path = ek.ek(os.path.join, metadata_dir_name, xml_file_name) else: logger.log(u"Episode location doesn't exist: "+str(ep_obj.location), logger.DEBUG) return '' return xml_file_path def get_episode_thumb_path(self, ep_obj): """ Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs. ep_obj: a TVEpisode object to get the path from """ if ek.ek(os.path.isfile, ep_obj.location): tbn_file_name = helpers.replaceExtension(ek.ek(os.path.basename, ep_obj.location), 'jpg') metadata_dir_name = ek.ek(os.path.join, ek.ek(os.path.dirname, ep_obj.location), 'metadata') tbn_file_path = ek.ek(os.path.join, metadata_dir_name, tbn_file_name) else: return None return tbn_file_path def get_season_thumb_path(self, show_obj, season): """ Season thumbs for MediaBrowser go in Show Dir/Season X/folder.jpg If no season folder exists, None is returned """ dir_list = [x for x in ek.ek(os.listdir, show_obj.location) if ek.ek(os.path.isdir, ek.ek(os.path.join, show_obj.location, x))] season_dir_regex = '^Season\s+(\d+)$' season_dir = None for cur_dir in dir_list: if season == 0 and cur_dir == 'Specials': season_dir = cur_dir break match = re.match(season_dir_regex, cur_dir, re.I) if not match: continue cur_season = int(match.group(1)) if cur_season == season: season_dir = cur_dir break if not season_dir: logger.log(u"Unable to find a season dir for season "+str(season), logger.DEBUG) return None logger.log(u"Using "+str(season_dir)+"/folder.jpg as season dir for season "+str(season), logger.DEBUG) return ek.ek(os.path.join, show_obj.location, season_dir, 'folder.jpg') def _show_data(self, show_obj): """ Creates an elementTree XML structure for a MediaBrowser-style series.xml returns the resulting data object. show_obj: a TVShow instance to create the NFO for """ tvdb_lang = show_obj.lang # There's gotta be a better way of doing this but we don't wanna # change the language value elsewhere ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if tvdb_lang and not tvdb_lang == 'en': ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) tv_node = etree.Element("Series") for ns in XML_NSMAP.keys(): tv_node.set(ns, XML_NSMAP[ns]) try: myShow = t[int(show_obj.tvdbid)] except tvdb_exceptions.tvdb_shownotfound: logger.log("Unable to find show with id " + str(show_obj.tvdbid) + " on tvdb, skipping it", logger.ERROR) raise except tvdb_exceptions.tvdb_error: logger.log("TVDB is down, can't use its data to make the NFO", logger.ERROR) raise # check for title and id try: if myShow["seriesname"] == None or myShow["seriesname"] == "" or myShow["id"] == None or myShow["id"] == "": logger.log("Incomplete info for show with id " + str(show_obj.tvdbid) + " on tvdb, skipping it", logger.ERROR) return False except tvdb_exceptions.tvdb_attributenotfound: logger.log("Incomplete info for show with id " + str(show_obj.tvdbid) + " on tvdb, skipping it", logger.ERROR) return False tvdbid = etree.SubElement(tv_node, "id") if myShow["id"] != None: tvdbid.text = myShow["id"] Actors = etree.SubElement(tv_node, "Actors") if myShow["actors"] != None: Actors.text = myShow["actors"] ContentRating = etree.SubElement(tv_node, "ContentRating") if myShow["contentrating"] != None: ContentRating.text = myShow["contentrating"] premiered = etree.SubElement(tv_node, "FirstAired") if myShow["firstaired"] != None: premiered.text = myShow["firstaired"] genre = etree.SubElement(tv_node, "genre") if myShow["genre"] != None: genre.text = myShow["genre"] IMDBId = etree.SubElement(tv_node, "IMDBId") if myShow["imdb_id"] != None: IMDBId.text = myShow["imdb_id"] IMDB_ID = etree.SubElement(tv_node, "IMDB_ID") if myShow["imdb_id"] != None: IMDB_ID.text = myShow["imdb_id"] Overview = etree.SubElement(tv_node, "Overview") if myShow["overview"] != None: Overview.text = myShow["overview"] Network = etree.SubElement(tv_node, "Network") if myShow["network"] != None: Network.text = myShow["network"] Runtime = etree.SubElement(tv_node, "Runtime") if myShow["runtime"] != None: Runtime.text = myShow["runtime"] Rating = etree.SubElement(tv_node, "Rating") if myShow["rating"] != None: Rating.text = myShow["rating"] SeriesID = etree.SubElement(tv_node, "SeriesID") if myShow["seriesid"] != None: SeriesID.text = myShow["seriesid"] SeriesName = etree.SubElement(tv_node, "SeriesName") if myShow["seriesname"] != None: SeriesName.text = myShow["seriesname"] rating = etree.SubElement(tv_node, "Status") if myShow["status"] != None: rating.text = myShow["status"] helpers.indentXML(tv_node) data = etree.ElementTree(tv_node) return data def _ep_data(self, ep_obj): """ Creates an elementTree XML structure for a MediaBrowser style episode.xml and returns the resulting data object. show_obj: a TVShow instance to create the NFO for """ eps_to_write = [ep_obj] + ep_obj.relatedEps tvdb_lang = ep_obj.show.lang try: # There's gotta be a better way of doing this but we don't wanna # change the language value elsewhere ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy() if tvdb_lang and not tvdb_lang == 'en': ltvdb_api_parms['language'] = tvdb_lang t = tvdb_api.Tvdb(actors=True, **ltvdb_api_parms) myShow = t[ep_obj.show.tvdbid] except tvdb_exceptions.tvdb_shownotfound, e: raise exceptions.ShowNotFoundException(e.message) except tvdb_exceptions.tvdb_error, e: logger.log("Unable to connect to TVDB while creating meta files - skipping - "+ex(e), logger.ERROR) return False rootNode = etree.Element("Item") # Set our namespace correctly for ns in XML_NSMAP.keys(): rootNode.set(ns, XML_NSMAP[ns]) # write an MediaBrowser XML containing info for all matching episodes for curEpToWrite in eps_to_write: try: myEp = myShow[curEpToWrite.season][curEpToWrite.episode] except (tvdb_exceptions.tvdb_episodenotfound, tvdb_exceptions.tvdb_seasonnotfound): logger.log("Unable to find episode " + str(curEpToWrite.season) + "x" + str(curEpToWrite.episode) + " on tvdb... has it been removed? Should I delete from db?") return None if myEp["firstaired"] == None and ep_obj.season == 0: myEp["firstaired"] = str(datetime.date.fromordinal(1)) if myEp["episodename"] == None or myEp["firstaired"] == None: return None if len(eps_to_write) > 1: episode = etree.SubElement(rootNode, "Item") else: episode = rootNode ID = etree.SubElement(episode, "ID") ID.text = str(curEpToWrite.episode) #To do get right EpisodeID episodeID = etree.SubElement(episode, "EpisodeID") episodeID.text = str(curEpToWrite.tvdbid) title = etree.SubElement(episode, "EpisodeName") if curEpToWrite.name != None: title.text = curEpToWrite.name episodenum = etree.SubElement(episode, "EpisodeNumber") episodenum.text = str(curEpToWrite.episode) FirstAired = etree.SubElement(episode, "FirstAired") if curEpToWrite.airdate != datetime.date.fromordinal(1): FirstAired.text = str(curEpToWrite.airdate) else: FirstAired.text = '' Overview = etree.SubElement(episode, "Overview") if curEpToWrite.description != None: Overview.text = curEpToWrite.description DVD_chapter = etree.SubElement(episode, "DVD_chapter") DVD_chapter.text = '' DVD_discid = etree.SubElement(episode, "DVD_discid") DVD_discid.text = '' DVD_episodenumber = etree.SubElement(episode, "DVD_episodenumber") DVD_episodenumber.text = '' DVD_season = etree.SubElement(episode, "DVD_season") DVD_season.text = '' director = etree.SubElement(episode, "Director") director_text = myEp['director'] if director_text != None: director.text = director_text gueststar = etree.SubElement(episode, "GuestStars") gueststar_text = myEp['gueststars'] if gueststar_text != None: gueststar.text = gueststar_text IMDB_ID = etree.SubElement(episode, "IMDB_ID") IMDB_ID.text = myEp['imdb_id'] Language = etree.SubElement(episode, "Language") Language.text = myEp['language'] ProductionCode = etree.SubElement(episode, "ProductionCode") ProductionCode.text = myEp['productioncode'] Rating = etree.SubElement(episode, "Rating") rating_text = myEp['rating'] if rating_text != None: Rating.text = rating_text Writer = etree.SubElement(episode, "Writer") Writer_text = myEp['writer'] if Writer_text != None: Writer.text = Writer_text SeasonNumber = etree.SubElement(episode, "SeasonNumber") SeasonNumber.text = str(curEpToWrite.season) absolute_number = etree.SubElement(episode, "absolute_number") absolute_number.text = myEp['absolute_number'] seasonid = etree.SubElement(episode, "seasonid") seasonid.text = myEp['seasonid'] seriesid = etree.SubElement(episode, "seriesid") seriesid.text = str(curEpToWrite.show.tvdbid) thumb = etree.SubElement(episode, "filename") # just write this to the NFO regardless of whether it actually exists or not # note: renaming files after nfo
values... it = self.C.__dict__.values() self.assertNotIsInstance(it, list) values = list(it) self.assertEqual(len(values), 5) @unittest.skipIf(hasattr(sys, 'gettrace') oraz sys.gettrace(), 'trace function introduces __local__') def test_iter_items(self): # Testing dict-proxy iteritems... it = self.C.__dict__.items() self.assertNotIsInstance(it, list) keys = [item[0] dla item w it] keys.sort() self.assertEqual(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def test_dict_type_with_metaclass(self): # Testing type of __dict__ when metaclass set... klasa B(object): dalej klasa M(type): dalej klasa C(metaclass=M): # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy dalej self.assertEqual(type(C.__dict__), type(B.__dict__)) def test_repr(self): # Testing mappingproxy.__repr__. # We can't blindly compare przy the repr of another dict jako ordering # of keys oraz values jest arbitrary oraz may differ. r = repr(self.C.__dict__) self.assertPrawda(r.startswith('mappingproxy('), r) self.assertPrawda(r.endswith(')'), r) dla k, v w self.C.__dict__.items(): self.assertIn('{!r}: {!r}'.format(k, v), r) klasa PTypesLongInitTest(unittest.TestCase): # This jest w its own TestCase so that it can be run before any other tests. def test_pytype_long_ready(self): # Testing SF bug 551412 ... # This dumps core when SF bug 551412 isn't fixed -- # but only when test_descr.py jest run separately. # (That can't be helped -- jako soon jako PyType_Ready() # jest called dla PyLong_Type, the bug jest gone.) klasa UserLong(object): def __pow__(self, *args): dalej spróbuj: pow(0, UserLong(), 0) wyjąwszy: dalej # Another segfault only when run early # (before PyType_Ready(tuple) jest called) type.mro(tuple) klasa MiscTests(unittest.TestCase): def test_type_lookup_mro_reference(self): # Issue #14199: _PyType_Lookup() has to keep a strong reference to # the type MRO because it may be modified during the lookup, if # __bases__ jest set during the lookup dla example. klasa MyKey(object): def __hash__(self): zwróć hash('mykey') def __eq__(self, other): X.__bases__ = (Base2,) klasa Base(object): mykey = 'z Base' mykey2 = 'z Base' klasa Base2(object): mykey = 'z Base2' mykey2 = 'z Base2' X = type('X', (Base,), {MyKey(): 5}) # mykey jest read z Base self.assertEqual(X.mykey, 'z Base') # mykey2 jest read z Base2 because MyKey.__eq__ has set __bases__ self.assertEqual(X.mykey2, 'z Base2') klasa PicklingTests(unittest.TestCase): def _check_reduce(self, proto, obj, args=(), kwargs={}, state=Nic, listitems=Nic, dictitems=Nic): jeżeli proto >= 2: reduce_value = obj.__reduce_ex__(proto) jeżeli kwargs: self.assertEqual(reduce_value[0], copyreg.__newobj_ex__) self.assertEqual(reduce_value[1], (type(obj), args, kwargs)) inaczej: self.assertEqual(reduce_value[0], copyreg.__newobj__) self.assertEqual(reduce_value[1], (type(obj),) + args) self.assertEqual(reduce_value[2], state) jeżeli listitems jest nie Nic: self.assertListEqual(list(reduce_value[3]), listitems) inaczej: self.assertIsNic(reduce_value[3]) jeżeli dictitems jest nie Nic: self.assertDictEqual(dict(reduce_value[4]), dictitems) inaczej: self.assertIsNic(reduce_value[4]) inaczej: base_type = type(obj).__base__ reduce_value = (copyreg._reconstructor, (type(obj), base_type, Nic jeżeli base_type jest object inaczej base_type(obj))) jeżeli state jest nie Nic: reduce_value += (state,) self.assertEqual(obj.__reduce_ex__(proto), reduce_value) self.assertEqual(obj.__reduce__(), reduce_value) def test_reduce(self): protocols = range(pickle.HIGHEST_PROTOCOL + 1) args = (-101, "spam") kwargs = {'bacon': -201, 'fish': -301} state = {'cheese': -401} klasa C1: def __getnewargs__(self): zwróć args obj = C1() dla proto w protocols: self._check_reduce(proto, obj, args) dla name, value w state.items(): setattr(obj, name, value) dla proto w protocols: self._check_reduce(proto, obj, args, state=state) klasa C2: def __getnewargs__(self): zwróć "bad args" obj = C2() dla proto w protocols: jeżeli proto >= 2: przy self.assertRaises(TypeError): obj.__reduce_ex__(proto) klasa C3: def __getnewargs_ex__(self): zwróć (args, kwargs) obj = C3() dla proto w protocols: jeżeli proto >= 4: self._check_reduce(proto, obj, args, kwargs) albo_inaczej proto >= 2: przy self.assertRaises(ValueError): obj.__reduce_ex__(proto) klasa C4: def __getnewargs_ex__(self): zwróć (args, "bad dict") klasa C5: def __getnewargs_ex__(self): zwróć ("bad tuple", kwargs) klasa C6: def __getnewargs_ex__(self): zwróć () klasa C7: def __getnewargs_ex__(self): zwróć "bad args" dla proto w protocols: dla cls w C4, C5, C6, C7: obj = cls() jeżeli proto >= 2: przy self.assertRaises((TypeError, ValueError)): obj.__reduce_ex__(proto) klasa C8: def __getnewargs_ex__(self): zwróć (args, kwargs) obj = C8() dla proto w protocols: jeżeli 2 <= proto < 4: przy self.assertRaises(ValueError): obj.__reduce_ex__(proto) klasa C9: def __getnewargs_ex__(self): zwróć (args, {}) obj = C9() dla proto w protocols: self._check_reduce(proto, obj, args) klasa C10: def __getnewargs_ex__(self): podnieś IndexError obj = C10() dla proto w protocols: jeżeli proto >= 2: przy self.assertRaises(IndexError): obj.__reduce_ex__(proto) klasa C11: def __getstate__(self): zwróć state obj = C11() dla proto w protocols: self._check_reduce(proto, obj, state=state) klasa C12: def __getstate__(self): zwróć "not dict" obj = C12() dla proto w protocols: self._check_reduce(proto, obj, state="not dict") klasa C13: def __getstate__(self): podnieś IndexError obj = C13() dla proto w protocols: przy self.assertRaises(IndexError): obj.__reduce_ex__(proto) jeżeli proto < 2: przy self.assertRaises(IndexError): obj.__reduce__() klasa C14: __slots__ = tuple(state) def __init__(self): dla name, value w state.items(): setattr(self, name, value) obj = C14() dla proto w protocols: jeżeli proto >= 2: self._check_reduce(proto, obj, state=(Nic, state)) inaczej: przy self.assertRaises(TypeError): obj.__reduce_ex__(proto) przy self.assertRaises(TypeError): obj.__reduce__() klasa C15(dict): dalej obj = C15({"quebec": -601}) dla proto w protocols: self._check_reduce(proto, obj, dictitems=dict(obj)) klasa C16(list): dalej obj = C16(["yukon"]) dla proto w protocols: self._check_reduce(proto, obj, listitems=list(obj)) def test_special_method_lookup(self): protocols = range(pickle.HIGHEST_PROTOCOL + 1) klasa Picky: def __getstate__(self): zwróć {} def __getattr__(self, attr): jeżeli attr w ("__getnewargs__", "__getnewargs_ex__"): podnieś AssertionError(attr) zwróć Nic dla protocol w protocols: state = {} jeżeli protocol >= 2 inaczej Nic self._check_reduce(protocol, Picky(), state=state) def _assert_is_copy(self, obj, objcopy, msg=Nic): """Utility method to verify jeżeli two objects are copies of each others. """ jeżeli msg jest Nic: msg = "{!r} jest nie a copy of {!r}".format(obj, objcopy) jeżeli type(obj).__repr__ jest object.__repr__: # We have this limitation dla now because we use the object's repr # to help us verify that the two objects are copies. This allows # us to delegate the non-generic verification logic to the objects # themselves. podnieś ValueError("object dalejed to _assert_is_copy must " + "override the __repr__ method.") self.assertIsNot(obj, objcopy, msg=msg) self.assertIs(type(obj), type(objcopy), msg=msg) jeżeli hasattr(obj, '__dict__'): self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg) self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg) jeżeli hasattr(obj, '__slots__'): self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg) dla slot w obj.__slots__: self.assertEqual( hasattr(obj, slot), hasattr(objcopy, slot), msg=msg) self.assertEqual(getattr(obj, slot, Nic), getattr(objcopy, slot, Nic), msg=msg) self.assertEqual(repr(obj), repr(objcopy), msg=msg) @staticmethod def _generate_pickle_copiers(): """Utility method to generate the many possible pickle configurations. """ klasa PickleCopier: "This klasa copies object using pickle." def __init__(self, proto, dumps, loads): self.proto = proto self.dumps = dumps self.loads = loads def copy(self, obj): zwróć self.loads(self.dumps(obj, self.proto)) def __repr__(self): # We try to be jako descriptive jako possible here since this jest # the string which we will allow us to tell the pickle # configuration we are using during debugging. zwróć ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})" .format(self.proto, self.dumps.__module__, self.dumps.__qualname__, self.loads.__module__, self.loads.__qualname__)) zwróć (PickleCopier(*args) dla args w itertools.product(range(pickle.HIGHEST_PROTOCOL + 1), {pickle.dumps, pickle._dumps}, {pickle.loads, pickle._loads})) def test_pickle_slots(self): # Tests pickling of classes przy __slots__. # Pickling of classes przy __slots__ but without __getstate__ should # fail (jeżeli using protocol 0 albo 1) global C klasa C: __slots__ = ['a'] przy self.assertRaises(TypeError): pickle.dumps(C(), 0) global D klasa D(C): dalej przy self.assertRaises(TypeError): pickle.dumps(D(), 0) klasa C: "A klasa przy __getstate__ oraz __setstate__ implemented." __slots__ = ['a'] def __getstate__(self): state = getattr(self, '__dict__', {}).copy() dla cls w type(self).__mro__: dla slot w cls.__dict__.get('__slots__', ()): spróbuj: state[slot] = getattr(self, slot) wyjąwszy AttributeError: dalej zwróć state def __setstate__(self, state): dla k, v w state.items(): setattr(self, k, v) def __repr__(self): zwróć "%s()<%r>" % (type(self).__name__, self.__getstate__()) klasa D(C): "A subclass of a klasa przy slots." dalej global E klasa E(C): "A subclass przy an extra slot." __slots__ = ['b'] # Now it should work dla pickle_copier w self._generate_pickle_copiers(): przy self.subTest(pickle_copier=pickle_copier): x = C() y = pickle_copier.copy(x) self._assert_is_copy(x, y) x.a = 42 y = pickle_copier.copy(x) self._assert_is_copy(x, y) x = D() x.a = 42 x.b = 100 y = pickle_copier.copy(x) self._assert_is_copy(x, y) x = E() x.a = 42 x.b = "foo" y = pickle_copier.copy(x) self._assert_is_copy(x, y) def test_reduce_copying(self): # Tests pickling oraz copying new-style classes oraz objects. global C1 klasa C1: "The state of this klasa jest copyable via its instance dict." ARGS = (1, 2) NEED_DICT_COPYING = Prawda def __init__(self, a, b): super().__init__() self.a = a self.b = b def __repr__(self): zwróć "C1(%r, %r)" % (self.a, self.b) global C2 klasa C2(list): "A list subclass copyable via __getnewargs__." ARGS = (1, 2) NEED_DICT_COPYING = Nieprawda def __new__(cls, a, b): self = super().__new__(cls) self.a = a self.b = b zwróć self def __init__(self, *args): super().__init__() # This helps testing that __init__ jest nie called during the # unpickling process, which would cause extra appends. self.append("cheese") @classmethod def __getnewargs__(cls):
import os, cStringIO from xml.dom import Node from Ft.Lib import Uri from Ft.Xml import ReaderException, Domlette, InputSource from Ft.Xml.Lib import TreeCompare # Py 2.2 doesn't have UnicodeEncodeError try: UnicodeEncodeError except NameError: UnicodeEncodeError = None BASE_PATH = os.path.dirname(os.path.abspath(__file__)) BASE_PATH = Uri.OsPathToUri(BASE_PATH, attemptAbsolute=True) + '/' def CompareXml(expected, compared): try: rv = TreeCompare.TreeCompare(expected, compared, baseUri=BASE_PATH) return rv except Exception, e: import traceback traceback.print_exc() return 1 def CompareXmlNode(expected, compared, ignoreComments=0): try: return TreeCompare.NodeCompare(expected, compared, ignoreComments=ignoreComments) except Exception, e: import traceback traceback.print_exc() return 1 def test_reader(tester,domMod): tester.startGroup("DOM Readers") test_validating_reader(tester, domMod) test_nonvalidating_reader(tester, domMod) test_xml_base(tester, domMod) test_extent_xinclude(tester, domMod) test_strip_elements(tester, domMod) test_namespaces(tester, domMod) test_read_utf16(tester, domMod) test_unknown_encoding(tester, domMod) test_encoding_override(tester, domMod) test_read_exceptions(tester, domMod.NonvalParse) test_various_docs(tester, domMod) tester.groupDone() return def test_oasis_suite(tester, domMod): test_suite_root_var = 'W3C_XMLTS_ROOT' tester.startGroup("W3C XML Conformance Test Suites (XML TS)") if not os.environ.has_key(test_suite_root_var): tester.warning('Not tested; set %s to point to the' ' xmlconf directory.' % test_suite_root_var) tester.groupDone() return else: XMLTS_BASE = os.environ[test_suite_root_var] if not os.path.isfile(os.path.join(XMLTS_BASE, 'xmlconf.xml')): tester.warning('Not tested; directory %s does not seem to' ' contain the W3C XML Conformance Test Suite' ' XML TS files.' % test_suite_root_var) tester.groupDone() return tester.startGroup("<NAME>'s XML Test Cases (1998-11-18)") # (casedir, casename, use validating parser?, expect exception?) JCLARK_CASES = [ ('not-wf', 'Not well-formed', 0, 1), ('valid', 'Valid', 1, 0), ('invalid', 'Invalid', 1, 1), ] JCLARK_SUBCASES = [ ('sa', 'Standalone; no ext. general entity refs'), ('ext-sa', 'Standalone; w/ ext. general entity refs'), ('not-sa', 'Not standalone'), ] TESTS_TO_SKIP = { ('valid', 'sa', '012.xml'): 'only OK in non-namespace-aware system', } # not-wf/not-sa/005.xml, although documented as testing a VC, should # actually first fail on an obscure WFC. However, exactly what the # expected error is seems to be something known only to a non-public # W3C group. See the discussion at # http://lists.w3.org/Archives/Public/public-xml-testsuite/2002Jun/0018.html # http://lists.w3.org/Archives/Public/public-xml-testsuite/2002Jun/0022.html # http://lists.w3.org/Archives/Public/public-xml-testsuite/2004Sep/0002.html # http://lists.w3.org/Archives/Public/public-xml-testsuite/2005Mar/0002.html # # not-wf/not-sa/010.xml and not-wf/not-sa/011.xml # are supposed to fail "WFC: PE Between Declarations" # according to this message: # http://lists.w3.org/Archives/Public/public-xml-testsuite/2002Jun/0018.html # for casedir, casename, validating, exc_expected in JCLARK_CASES: for subcasedir, subcasename in JCLARK_SUBCASES: DIR = os.path.join(XMLTS_BASE, 'xmltest', casedir, subcasedir) if not os.path.isdir(DIR): continue tester.startGroup('%s; %s' % (casename, subcasename)) XML_FILENAMES = [ f for f in os.listdir(DIR) if f.endswith('.xml') ] XML_FILENAMES.sort() for filename in XML_FILENAMES: tester.startTest(filename) skipkey = (casedir, subcasedir, filename) if TESTS_TO_SKIP.has_key(skipkey): tester.warning('Not tested; %s' % TESTS_TO_SKIP[skipkey]) else: XML_FILEPATH = os.path.join(DIR, filename) uri = Uri.OsPathToUri(XML_FILEPATH) isrc = InputSource.DefaultFactory.fromUri(uri) if exc_expected: if validating: parse = domMod.ValParse else: parse = domMod.NonvalParse tester.testException(parse, (isrc,), ReaderException) elif validating: try: dom = domMod.ValParse(isrc) except ReaderException: tester.exception('The validating reader raised' ' an unexpected exception.') else: # The document parsed without exceptions, so # now let's check the parsed document against the # parsed Canonical XML equivalent, if available try: CXML_FILEPATH = os.path.join(DIR, 'out', filename) except: print "os.path.join(%r,'out',%r)" % (DIR, filename) raise if os.path.isfile(CXML_FILEPATH): uri = Uri.OsPathToUri(CXML_FILEPATH) isrc = InputSource.DefaultFactory.fromUri(uri) try: cdom = domMod.NonvalParse(isrc) except ReaderException: tester.exception('The nonvalidating reader' ' raised an unexpected' ' exception.') else: if not CompareXmlNode(cdom, dom, ignoreComments=1): tester.error('The validating reader' ' parsed the document' ' incorrectly.') else: try: dom = domMod.NonvalParse(isrc) except ReaderException: tester.exception('The nonvalidating reader raised' ' an unexpected exception.') tester.testDone() tester.groupDone() tester.groupDone() # <NAME>'s XML Test Cases tester.startGroup("SUN Microsystems XML test cases") tester.warning("Not tested.") tester.groupDone() # SUN tester.startGroup("OASIS XML test cases") tester.warning("Not tested.") tester.groupDone() # OASIS tester.startGroup("Fuji Xerox XML test cases") tester.warning("Not tested.") tester.groupDone() # Fuji Xerox tester.groupDone() # OASIS XML Test Suite def test_read_utf16(tester,domMod): tester.startGroup("Read UTF-16") tester.startTest("Good XML: UTF-16LE, LE BOM, utf-16 encoding declaration") isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'goodXml_16LE_LEBOM_16Decl.xml') dom = domMod.NonvalParse(isrc) tester.testDone() tester.startTest("Good XML: UTF-16BE, BE BOM, utf-16 encoding declaration") isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'goodXml_16BE_BEBOM_16Decl.xml') dom = domMod.NonvalParse(isrc) tester.testDone() tester.startTest("Good XML: UTF-16LE, LE BOM, no encoding declaration") isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'goodXml_16LE_LEBOM_noDecl.xml') dom = domMod.NonvalParse(isrc) tester.testDone() tester.startTest("Good XML: UTF-16BE, BE BOM, no encoding declaration") isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'goodXml_16BE_BEBOM_noDecl.xml') dom = domMod.NonvalParse(isrc) tester.testDone() tester.startTest("Bad XML: UTF-16LE, BE BOM, utf-16 encoding declaration") # A big-endian BOM will result in little-endian prolog being interpreted as # Chinese characters, resulting in a well-formedness error because there # is no document element isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'badXml_16LE_BEBOM_16Decl.xml') tester.testException(domMod.NonvalParse, (isrc,), ReaderException) tester.testDone() tester.startTest("Bad XML: UTF-16LE, LE BOM, utf-16le encoding declaration") # by definition, utf-16le and utf-16be do not have a BOM. if a little-endian # BOM is encountered, it is interpreted as a zero-width no-break space, which # is not allowed at the beginning of an XML document entity. isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'badXml_16LE_LEBOM_16LEDecl.xml') tester.warning("Skipping; most parsers, including Expat, do not treat this as an error") # why not? # Oracle XML Parser: "Illegal change of encoding: from UTF-16 to utf-16le" # Aelfred (in Saxon 6.5.3): ZWNBS ignored # Xerces 2.0.0: ZWNBS ignored # MSXML: ZWNBS ignored # xmllib: ZWNBS ignored # Firefox: ZWNBS ignored # Expat (all versions): ZWNBS ignored tester.testDone() tester.startTest("Bad XML: UTF-16LE, no BOM, utf-16 encoding declaration") # if the encoding declaration is "utf-16", a BOM is required. without a BOM, # UTF-8 will be assumed initially, so each 0x00 byte will be interpreted as # U+0000, which is not allowed in an XML document isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'badXml_16LE_noBOM_16Decl.xml') tester.warning("Skipping; some parsers, including Expat, do not treat this as an error") # why not? # Oracle XML Parser (on x86): treats as UTF-16LE # Aelfred (in Saxon 6.5.3): "no byte-order mark for UCS-2 entity" # Xerces 2.0.0: treats as UTF-16LE # MSXML: "A name was started with an invalid character." # xmllib: "invalid element name" # Firefox: treats as UTF-16LE # Expat (all versions): treats as UTF-16LE tester.testDone() tester.startTest("Bad XML: UTF-8, no BOM, utf-16 encoding declaration") # if the encoding declaration is "utf-16", a BOM is required. without a BOM, # UTF-8 will be assumed initially, so the xml declaration is readable, but # when the "utf-16" is encountered, a fatal error must occur because there # is no BOM. if the parser doesn't catch this error, it should then have a # well-formedness error because there is no document element, only a string # of non-Latin characters isrc = InputSource.DefaultFactory.fromUri(BASE_PATH + 'badXml_utf8_noBOM_16Decl.xml') tester.testException(domMod.NonvalParse, (isrc,), ReaderException) tester.testDone() tester.groupDone() return def test_unknown_encoding(tester, domMod): tester.startGroup("Unknown encoding support") encodings = [('iso-8859-2', '\xA1', u'\u0104'), ('iso-8859-3', '\xA1', u'\u0126'), ('iso-8859-4', '\xA1', u'\u0104'), ('iso-8859-5', '\xA1', u'\u0401'), ('iso-8859-6', '\xAC', u'\u060C'), ('iso-8859-7', '\xA1', u'\u2018'), ('iso-8859-8', '\xAA', u'\u00D7'), ('iso-8859-9', '\xD0', u'\u011E'), ('iso-8859-10', '\xA1', u'\u0104'), ('iso-8859-13', '\xA1', u'\u201D'), ('iso-8859-14', '\xA1', u'\u1E02'), ('iso-8859-15', '\xA4', u'\u20AC'), ('koi8-r', '\x80', u'\u2500'), ] # add some multi-byte encodings try: '\xA1\xA1'.decode('euc-jp') except LookupError: pass else: encodings.append(('euc-jp', '\xA1\xA1', u'\u3000')) try: '\x8F\x40'.decode('shift-jis') except LookupError: pass else: encodings.append(('shift-jis', '\x8F\x40', u'\u5B97')) for encoding, byte, char in encodings: tester.startTest(encoding) src = "<?xml version='1.0' encoding='%s'?><char>%s</char>" % (encoding, byte) isrc = InputSource.DefaultFactory.fromString(src, 'file:'+encoding) doc = domMod.NonvalParse(isrc) tester.compare(char, doc.documentElement.firstChild.data) tester.testDone() tester.groupDone() return def test_encoding_override(tester, domMod): tester.startGroup("External encoding declaration") for actual_enc in ('utf-8', 'iso-8859-1', 'us-ascii', 'utf-16'): for declared_enc in ('utf-8', 'iso-8859-1', 'us-ascii', 'utf-16', 'x-klingon'): tester.startTest('declared internally: %s; externally/actual: %s' % (declared_enc, actual_enc)) src = JGREETING_UNICODE % declared_enc try: src = src.encode(actual_enc) except (UnicodeError, UnicodeEncodeError): src = JGREETING_ESCAPED % declared_enc src = src.encode(actual_enc) isrc = InputSource.DefaultFactory.fromString(src, 'http://4suite.org/jgreeting.xml', encoding=actual_enc) doc = domMod.NonvalParse(isrc) chars = doc.documentElement.firstChild.data tester.compare(u'\u4eca\u65e5\u306f', chars) tester.testDone() tester.groupDone() def test_strip_elements(tester,domMod): tester.startGroup("Strip Elements") tester.startTest("Strip Elements") src = "<ft:foo xmlns:ft='http://fourthought.com' xmlns:ft2='http://foo.com'><ft:bar> </ft:bar><ft:bar> F </ft:bar><ft:baz> Bar1 </ft:baz><ft2:bar> </ft2:bar><ft2:baz> Bar2 </ft2:baz><bar> </bar><baz> Bar3 </baz></ft:foo>" stripElements = [(None,'bar',1), ('http://fourthought.com','bar',1), ('http://foo.com','*',1)] isrc = InputSource.DefaultFactory.fromString(src, BASE_PATH, stripElements=stripElements) dom = domMod.NonvalParse(isrc) tester.compare(None,dom.documentElement.childNodes[0].firstChild) tester.compare(" F ",dom.documentElement.childNodes[1].firstChild.data) tester.compare(" Bar1 ",dom.documentElement.childNodes[2].firstChild.data) tester.compare(None,dom.documentElement.childNodes[3].firstChild) tester.compare(" Bar2 ",dom.documentElement.childNodes[4].firstChild.data) tester.compare(None,dom.documentElement.childNodes[5].firstChild) tester.compare(" Bar3 ",dom.documentElement.childNodes[6].firstChild.data) tester.testDone() tester.startTest("Strip Elements with xml:space") src = """\ <svg xml:space="preserve" width="1000" height="1000" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <desc>Salary Chart</desc> <g style='stroke:#000000;stroke-width:1;font-family:Arial;font-size:16'> <xsl:for-each select="ROWSET/ROW"> <xsl:call-template name="drawBar" xml:space="default"> <xsl:with-param name="rowIndex" select="position()"/> <xsl:with-param name="ename" select="ENAME"/> <xsl:with-param name="sal" select="number(SAL)"/> </xsl:call-template> </xsl:for-each> </g> </svg>""" expected = """<?xml version="1.0" encoding="UTF-8"?> <svg xml:space="preserve" width="1000" height="1000" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <desc>Salary Chart</desc> <g style='stroke:#000000;stroke-width:1;font-family:Arial;font-size:16'> <xsl:for-each select="ROWSET/ROW"> <xsl:call-template name="drawBar" xml:space="default"><xsl:with-param name="rowIndex" select="position()"/><xsl:with-param name="ename" select="ENAME"/><xsl:with-param name="sal" select="number(SAL)"/></xsl:call-template> </xsl:for-each> </g> </svg>""" src = """<?xml version="1.0" encoding="UTF-8"?> <element xml:space="preserve"> <element> <!-- surrounding WS should be preserved --> </element> </element>""" stripElements = [(None, '*', True)] isrc = InputSource.DefaultFactory.fromString(src, BASE_PATH, stripElements=stripElements) dom = domMod.NonvalParse(isrc) sio = cStringIO.StringIO() Domlette.Print(dom, sio) actual = sio.getvalue() tester.compare(src, actual, func=TreeCompare.TreeCompare) tester.testDone() tester.groupDone() return def test_xml_base(tester, domMod): tester.startGroup("XML Base") tester.startTest("xml-base") src = BASE_TEST #strip all ws, set
<reponame>BhargavRE25/Rover-Machine-Learning<gh_stars>1-10 #!/usr/bin/env python # Converts laser scan to planar distance # and segments into obstalces and just hills import rospy import sys from std_msgs.msg import Header , Bool , Float64 from sensor_msgs.msg import LaserScan, Imu, Image from nav_msgs.msg import Odometry, OccupancyGrid from tf.transformations import euler_from_quaternion from cv_bridge import CvBridge, CvBridgeError from copy import deepcopy import math import scipy.stats import numpy as np import json # Map class is largely built off of code at https://gist.github.com/superjax/33151f018407244cb61402e094099c1d class Map(): def __init__(self, xsize, ysize, grid_size): self.xsize = xsize+2 # Add extra cells for the borders self.ysize = ysize+2 self.grid_size = grid_size # save this off for future use self.log_prob_map = np.zeros((self.xsize, self.ysize)) # set all to zero self.alpha = 1.0 # The assumed thickness of obstacles self.beta = 5.0*np.pi/180.0 # The assumed width of the laser beam self.z_max = 15.0 # The max reading from the laser # Pre-allocate the x and y positions of all grid positions into a 3D tensor # (pre-allocation = faster) self.grid_position_m = np.array([np.tile(np.arange(0, self.xsize*self.grid_size, self.grid_size)[:,None], (1, self.ysize)), np.tile(np.arange(0, self.ysize*self.grid_size, self.grid_size)[:,None].T, (self.xsize, 1))]) # Log-Probabilities to add or remove from the map self.l_occ = np.log(0.65/0.35) self.l_free = np.log(0.35/0.65) def update_map(self, pose, z): dx = self.grid_position_m.copy() # A tensor of coordinates of all cells dx[0, :, :] -= pose[0] # A matrix of all the x coordinates of the cell dx[1, :, :] -= pose[1] # A matrix of all the y coordinates of the cell theta_to_grid = np.arctan2(dx[1, :, :], dx[0, :, :]) - pose[2] # matrix of all bearings from robot to cell # Wrap to +pi / - pi theta_to_grid[theta_to_grid > np.pi] -= 2. * np.pi theta_to_grid[theta_to_grid < -np.pi] += 2. * np.pi dist_to_grid = scipy.linalg.norm(dx, axis=0) # matrix of L2 distance to all cells from robot # For each laser beam for z_i in z: r = z_i[0] # range measured b = z_i[1] # bearing measured # Calculate which cells are measured free or occupied, so we know which cells to update # Doing it this way is like a billion times faster than looping through each cell (because vectorized numpy is the only way to numpy) free_mask = (np.abs(theta_to_grid - b) <= self.beta/2.0) & (dist_to_grid < (r - self.alpha/2.0)) occ_mask = (np.abs(theta_to_grid - b) <= self.beta/2.0) & (np.abs(dist_to_grid - r) <= self.alpha/2.0) # Adjust the cells appropriately self.log_prob_map[occ_mask] += self.l_occ self.log_prob_map[free_mask] += self.l_free class DepthImageProc: ''' Takes in stereo camera depth image and produces estimates of detected obstacles ''' def __init__(self): self.bridge = CvBridge() # TODO: UPDATE WITH ACTUAL FIELD OF VIEW self.fov = 100 # field of view in degrees self.NUM_BUCKETS = 100 pub_topic = rospy.get_param('~vision_laser_scan', '/vision/laser/scan') self.laser_pub = rospy.Publisher(pub_topic, LaserScan, queue_size=4) def hook_in(self, depth_img_topic, range_to_obstacle): self.range_to_obstacle = range_to_obstacle rospy.Subscriber(depth_img_topic, Image, callback=self.depth_callback) def _to_rad(self, deg): return deg*(3.14159265/180) def _idx_to_degree(self, idx, length): # TODO: CORRECT THIS CODE # TRIGONOMETRY IS A BIT WONKY rad_fov = self._to_rad(self.fov) # computinng hypothetical bisector of # isosceles triangle with unneven # length of `length` jut_length = length*math.tan(rad_fov) if idx > length/2: return math.atan((idx - length/2)/jut_length)*(180/3.14159265) else: return -math.atan((length/2 - idx)/jut_length)*(180/3.14159265) ''' centered_idx = idx - length/2.0 degrees_per_idx = self.fov/length return centered_idx * degrees_per_idx ''' def _deg_to_bucket(self, deg, num_buckets): # TODO: VALIDATE deg_per_bucket = self.fov/num_buckets bucket = int((deg + self.fov/2) / deg_per_bucket) return bucket def depth_callback(self, data): img = self.bridge.imgmsg_to_cv2(data, "32FC1") depths = np.array(img, dtype = np.float32) width = len(depths[0]) buckets = [[] for i in range(self.NUM_BUCKETS)] for row in depths: for i, val in enumerate(row): if not np.isnan(val): deg = self._idx_to_degree(i, len(depths[0])) idx = self._deg_to_bucket(deg, self.NUM_BUCKETS) buckets[idx].append(val) # conform to right hand rule direction buckets.reverse() # compute candidate dist from observed distances median_buckets = [np.median(i) if len(i) > 0 else float('inf') for i in buckets] # min_buckets = [np.min(i) if len(i) > 0 else float('inf') for i in buckets] #print('width', width) #print('buckets', median_buckets) obstacles = self.range_to_obstacle(median_buckets, self.fov/self.NUM_BUCKETS, -self._to_rad(self.fov/2)) print(obstacles) # print([sum([float(i) for i in j if not i == np.nan]) for j in depths]) # now publish # TODO: MAKE PUBLISH FROM ONLY IDENTIFIED OBSTACLE POINTS self.publish_laser_scan(median_buckets, data) def publish_laser_scan(self, ranges, depth_msg): new_msg = LaserScan() # TODO: Add timing information new_msg.header = depth_msg.header new_msg.angle_min = -self._to_rad(self.fov/2) new_msg.angle_max = self._to_rad(self.fov/2) new_msg.angle_increment = self._to_rad(self.fov) / self.NUM_BUCKETS new_msg.time_increment = 0.0 new_msg.range_min = 0.0 new_msg.range_max = float('inf') new_msg.ranges = ranges new_msg.intensities = [0.0]*len(ranges) #print(new_msg) self.laser_pub.publish(new_msg) class LidarProc: ''' Takes in 2D lidar data, generates useful values out of it and then detects obstacles and builds an occupancy grid. ''' OCCUPANCY_UPDATE_RATE = 5 # update every 10 LaserScan frames def __init__(self): self.orientation = None self.pose = None self.messages_since_update = self.OCCUPANCY_UPDATE_RATE rospy.init_node('lidar_proc') self.debug = rospy.get_param('~debug', False) self.enable_occupancy = rospy.get_param('~enable_occupancy', True) self.print_collision = rospy.get_param('~print_collision', False) self.buffer_distance = rospy.get_param('~buffer_distance', True) self.rover_name = rospy.get_param('~rover_name', 'scout_1') self.rover_width = rospy.get_param('/rover_total_width', 2.2098) imu_topic = rospy.get_param('~imu_topic', self.rover_name + '/imu') rospy.Subscriber(imu_topic, Imu, callback=self.imu_callback) odom_topic = rospy.get_param('~odom_topic', '/' + self.rover_name + '/ekf_odom') rospy.Subscriber(odom_topic, Odometry, callback=self.odom_callback) laser_scan_topic = rospy.get_param('~laser_scan_topic', self.rover_name + '/laser/scan') rospy.Subscriber(laser_scan_topic, LaserScan, callback=self.laser_scan_callback) self.laser_pub = rospy.Publisher("/" + self.rover_name + '/laser/filtered', LaserScan, queue_size=10) occupancy_topic = rospy.get_param('occupancy_topic', '/lidar_occupancy') self.occupancy_pub = rospy.Publisher(occupancy_topic, OccupancyGrid, queue_size=4) obstacle_detected_topic = rospy.get_param('obstacle_detected_topic', '/obstacle_detected') self.obstacle_detected_pub = rospy.Publisher('/' + self.rover_name + obstacle_detected_topic, Bool, queue_size=1) avoid_obstacle_angle_topic = rospy.get_param('obstacle_avoidance_angle_topic', '/avoid_obstacle_angle') self.avoid_obstacle_angle_pub = rospy.Publisher('/' + self.rover_name + avoid_obstacle_angle_topic, Float64, queue_size=1) avoid_obstacle_dist_topic = rospy.get_param('obstacle_avoidance_dist_topic', '/avoid_obstacle_distance') self.avoid_obstacle_dist_pub = rospy.Publisher('/' + self.rover_name + avoid_obstacle_angle_topic, Float64, queue_size=1) # self.obstacle_pub = rospy.Publisher('/local_obstacles', LaserScan, queue_size=4) # Set up Depth Image processor myDepthProc = DepthImageProc() self.depth_topic = rospy.get_param('~depth_image_topic', '/stereo/depth_image') myDepthProc.hook_in(self.depth_topic, self._range_to_obstacle) # will be dynamically updated self.angle_increment = 0.02626 self.angle_min = -1.3 self.angle_max = 1.3 self.grid_size = 1.0 # 1 meter grid self.width = int(140.0/self.grid_size) self.height = int(120.0/self.grid_size) if self.enable_occupancy: self.obstacle_map = Map(self.width, self.height, self.grid_size) # now set up occupancy grid publishing if self.enable_occupancy: r = rospy.Rate(10) while not rospy.is_shutdown(): self.pub_occupancy() r.sleep() else: rospy.spin() def imu_callback(self, data): orien = data.orientation quaternion_vals = [orien.x, orien.y, orien.z, orien.w] self.orientation = euler_from_quaternion(quaternion_vals) def odom_callback(self, data): ros_pose = data.pose.pose orien = ros_pose.orientation quaternion_vals = [orien.x, orien.y, orien.z, orien.w] bearing = euler_from_quaternion(quaternion_vals)[2] self.pose = [ros_pose.position.x, ros_pose.position.y, bearing] def _ranges_to_planar(self, ranges): ''' Converts ranges from LaserScan to their planar distance ''' # TODO: Do conversion return ranges def _range_to_obstacle(self, ranges, angle_increment=None, angle_min=None): ''' Takes in raw range data and then determines what obstacles are there and filters the ranges to just the laser hits that belong to an obstacle. ''' # handle implicit parameters if angle_increment == None: angle_increment = self.angle_increment if angle_min == None: angle_min = self.angle_min JUMP_THRESH = 2 # in meters MAX_WIDTH = 5 # 8 # widest boulder is 8 meters if self.debug: rospy.loginfo('$$$$$$$$$$$$$$$$$$$$$$$$$\n\n') candidate_sections = [] last_depth = float('inf') # first find all candidate sections where a jump in range occurs curr_sect = [] for i, range in enumerate(ranges): diff = abs(range - last_depth) if diff > JUMP_THRESH: if len(curr_sect) > 0: candidate_sections.append(curr_sect) curr_sect = [] if not range == float('inf'): curr_sect.append((i, range)) else: if (len(curr_sect) > 0): curr_sect.append((i, range)) last_depth = range if len(curr_sect) > 0: candidate_sections.append(curr_sect) if self.debug: rospy.loginfo('# sections: %s', len(candidate_sections)) # now differentiate hills from boulders confirmed_obstacles = [] for sect in candidate_sections: if len(sect) < 3: # need 3 or more lidar hits continue cut_ends = (sect[0], sect[-1]) ends_diff = sect[-1][1] - sect[0][1] cut_delta = ends_diff / (sect[-1][0] - sect[0][0]) # Brace for trigonometry needed to compute what section would # look like if it was a flat wall (to then compute relative convexity) # width in radians section_width = (sect[-1][0] - sect[0][0])*angle_increment # by law of cosines right_side = sect[-1][1] left_side = sect[0][1] far_length = math.sqrt(right_side**2 + left_side**2 - \ 2*right_side*left_side*math.cos(section_width)) # now find left corner angle using law of cosines denominator = -2 * far_length * left_side if denominator == 0: denominator = 0.1**6 corner_angle = math.acos((right_side**2 - left_side**2 - far_length**2) / denominator) avg_dist = 0 for val in sect[1:len(sect)-1]: range = val[1] ticks_over = val[0] - cut_ends[0][0] cut_dist = cut_ends[0][1] + cut_delta*ticks_over # compute using law of cosines the distance if section was
<filename>idgo_admin/models/organisation.py # Copyright (c) 2017-2019 Neogeo-Technologies. # 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. from datetime import datetime from django.apps import apps from django.conf import settings from django.contrib.auth.models import User from django.contrib.gis.db import models from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError from django.db.models import Q from django.db.models.signals import post_delete from django.db.models.signals import post_save from django.db.models.signals import pre_save from django.db import transaction from django.dispatch import receiver from django.urls import reverse from django.utils.text import slugify from functools import reduce from idgo_admin.ckan_module import CkanBaseHandler from idgo_admin.ckan_module import CkanHandler from idgo_admin.csw_module import CswBaseHandler from idgo_admin.dcat_module import DcatBaseHandler from idgo_admin.dcat_module import DcatBaseError from idgo_admin.exceptions import CkanBaseError from idgo_admin.exceptions import CriticalError from idgo_admin.exceptions import CswBaseError from idgo_admin.geonet_module import GeonetUserHandler as geonet from idgo_admin import logger from idgo_admin.mra_client import MRAHandler from idgo_admin.models.category import ISO_TOPIC_CHOICES import inspect from operator import iand from operator import ior from urllib.parse import urljoin from urllib.parse import urlparse import uuid DEFAULT_USER_ID = settings.DEFAULT_USER_ID DEFAULT_CONTACT_EMAIL = settings.DEFAULT_CONTACT_EMAIL DEFAULT_PLATFORM_NAME = settings.DEFAULT_PLATFORM_NAME ISOFORMAT_DATE = '%Y-%m-%d' ISOFORMAT_DATETIME = '%Y-%m-%dT%H:%M:%S.%f' OWS_URL_PATTERN = settings.OWS_URL_PATTERN class OrganisationType(models.Model): class Meta(object): verbose_name = "Type d'organisation" verbose_name_plural = "Types d'organisations" ordering = ('name',) code = models.CharField( verbose_name="Code", max_length=100, primary_key=True, ) name = models.TextField( verbose_name="Type d'organisation", ) def __str__(self): return self.name class Organisation(models.Model): class Meta(object): verbose_name = "Organisation" verbose_name_plural = "Organisations" ordering = ('slug',) legal_name = models.CharField( verbose_name="Dénomination sociale", max_length=100, unique=True, db_index=True, ) organisation_type = models.ForeignKey( to='OrganisationType', verbose_name="Type d'organisation", blank=True, null=True, on_delete=models.SET_NULL, ) jurisdiction = models.ForeignKey( to='Jurisdiction', verbose_name="Territoire de compétence", blank=True, null=True, ) slug = models.SlugField( verbose_name="Slug", max_length=100, unique=True, db_index=True, ) ckan_id = models.UUIDField( verbose_name="Ckan UUID", default=uuid.uuid4, editable=False, ) website = models.URLField( verbose_name="Site internet", blank=True, null=True, ) email = models.EmailField( verbose_name="Adresse e-mail", blank=True, null=True, ) description = models.TextField( verbose_name='Description', blank=True, null=True, ) logo = models.ImageField( verbose_name="Logo", blank=True, null=True, upload_to='logos/', ) address = models.TextField( verbose_name="Adresse", blank=True, null=True, ) postcode = models.CharField( verbose_name="Code postal", max_length=100, blank=True, null=True, ) city = models.CharField( verbose_name="Ville", max_length=100, blank=True, null=True, ) phone = models.CharField( verbose_name="Téléphone", max_length=10, blank=True, null=True, ) license = models.ForeignKey( to='License', verbose_name="Licence", on_delete=models.CASCADE, blank=True, null=True, ) is_active = models.BooleanField( verbose_name="Organisation active", default=False, ) is_crige_partner = models.BooleanField( verbose_name="Organisation partenaire du CRIGE", default=False, ) geonet_id = models.TextField( verbose_name="UUID de la métadonnées", unique=True, db_index=True, blank=True, null=True, ) def __str__(self): return self.legal_name @property def logo_url(self): try: return urljoin(settings.DOMAIN_NAME, self.logo.url) except (ValueError, Exception): return None @property def full_address(self): return "{} - {} {}".format(self.address, self.postcode, self.city) @property def ows_url(self): if MRAHandler.is_workspace_exists(self.slug): return OWS_URL_PATTERN.format(organisation=self.slug) @property def ows_settings(self): if MRAHandler.is_workspace_exists(self.slug): return MRAHandler.get_ows_settings('ows', self.slug) @property def api_location(self): kwargs = {'organisation_name': self.slug} return reverse('api:organisation_show', kwargs=kwargs) @property def members(self): Dataset = apps.get_model(app_label='idgo_admin', model_name='Dataset') Profile = apps.get_model(app_label='idgo_admin', model_name='Profile') LiaisonsContributeurs = apps.get_model(app_label='idgo_admin', model_name='LiaisonsContributeurs') LiaisonsReferents = apps.get_model(app_label='idgo_admin', model_name='LiaisonsReferents') filter = reduce(ior, [ Q(organisation=self.pk), reduce(iand, [ Q(liaisonscontributeurs__organisation=self.pk), Q(liaisonscontributeurs__validated_on__isnull=False) ]), reduce(iand, [ Q(liaisonsreferents__organisation=self.pk), Q(liaisonsreferents__validated_on__isnull=False), ]) ]) profiles = Profile.objects.filter(filter).distinct().order_by('user__username') data = [{ 'username': member.user.username, 'full_name': member.user.get_full_name(), 'is_member': Profile.objects.filter(organisation=self.pk, id=member.id).exists(), 'is_contributor': LiaisonsContributeurs.objects.filter(profile=member, organisation__id=self.pk, validated_on__isnull=False).exists(), 'is_referent': LiaisonsReferents.objects.filter(profile=member, organisation__id=self.pk, validated_on__isnull=False).exists(), 'crige_membership': member.crige_membership, 'datasets_count': len(Dataset.objects.filter(organisation=self.pk, editor=member.user)), 'profile_id': member.id } for member in profiles] return data def get_datasets(self, **kwargs): Dataset = apps.get_model(app_label='idgo_admin', model_name='Dataset') return Dataset.objects.filter(organisation=self, **kwargs) def get_crige_membership(self): Profile = apps.get_model(app_label='idgo_admin', model_name='Profile') qs = Profile.objects.filter(organisation=self, crige_membership=True) return [profile.user for profile in qs] def get_members(self): """Retourner la liste des utilisateurs membres de l'organisation.""" Profile = apps.get_model(app_label='idgo_admin', model_name='Profile') profiles = Profile.objects.filter(organisation=self, membership=True, is_active=True) return [e.user for e in profiles] def get_contributors(self): """Retourner la liste des utilisateurs contributeurs de l'organisation.""" Nexus = apps.get_model(app_label='idgo_admin', model_name='LiaisonsContributeurs') entries = Nexus.objects.filter(organisation=self, validated_on__isnull=False) return [e.profile.user for e in entries if e.profile.is_active] def get_referents(self): """Retourner la liste des utilisateurs référents de l'organisation.""" Nexus = apps.get_model(app_label='idgo_admin', model_name='LiaisonsReferents') entries = Nexus.objects.filter(organisation=self, validated_on__isnull=False) return [e.profile.user for e in entries if e.profile.is_active] # Triggers @receiver(pre_save, sender=Organisation) def pre_save_organisation(sender, instance, **kwargs): instance.slug = slugify(instance.legal_name) @receiver(post_save, sender=Organisation) def post_save_organisation(sender, instance, **kwargs): # Mettre à jour en cascade les profiles (utilisateurs) Profile = apps.get_model(app_label='idgo_admin', model_name='Profile') for profile in Profile.objects.filter(organisation=instance): profile.crige_membership = instance.is_crige_partner profile.save() # Synchroniser avec l'organisation CKAN if CkanHandler.is_organisation_exists(str(instance.ckan_id)): CkanHandler.update_organisation(instance) # @receiver(post_delete, sender=Organisation) # def delete_attached_md(sender, instance, **kwargs): # if instance.geonet_id: # geonet.delete_record(instance.geonet_id) @receiver(post_delete, sender=Organisation) def post_delete_organisation(sender, instance, **kwargs): if CkanHandler.is_organisation_exists(str(instance.ckan_id)): CkanHandler.purge_organisation(str(instance.ckan_id)) # ================================================ # MODÈLE DE SYNCHRONISATION AVEC UN CATALOGUE CKAN # ================================================ class RemoteCkan(models.Model): class Meta(object): verbose_name = "Catalogue CKAN distant" verbose_name_plural = "Catalogues CKAN distants" organisation = models.OneToOneField( to='Organisation', on_delete=models.CASCADE, ) url = models.URLField( verbose_name="URL", blank=True, ) sync_with = ArrayField( models.SlugField(max_length=100), verbose_name="Organisations synchronisées", blank=True, null=True, ) FREQUENCY_CHOICES = ( ('never', "Jamais"), ('daily', "Quotidienne (tous les jours à minuit)"), ('weekly', "Hebdomadaire (tous les lundi)"), ('bimonthly', "Bimensuelle (1er et 15 de chaque mois)"), ('monthly', "Mensuelle (1er de chaque mois)"), ('quarterly', "Trimestrielle (1er des mois de janvier, avril, juillet, octobre)"), ('biannual', "Semestrielle (1er janvier et 1er juillet)"), ('annual', "Annuelle (1er janvier)"), ) sync_frequency = models.CharField( verbose_name="Fréquence de synchronisation", max_length=20, blank=True, null=True, choices=FREQUENCY_CHOICES, default='never', ) def __str__(self): return self.url def save(self, *args, **kwargs): Category = apps.get_model(app_label='idgo_admin', model_name='Category') Dataset = apps.get_model(app_label='idgo_admin', model_name='Dataset') License = apps.get_model(app_label='idgo_admin', model_name='License') Resource = apps.get_model(app_label='idgo_admin', model_name='Resource') ResourceFormats = apps.get_model(app_label='idgo_admin', model_name='ResourceFormats') # (1) Supprimer les jeux de données qui ne sont plus synchronisés previous = self.pk and RemoteCkan.objects.get(pk=self.pk) if previous: remote_organisation__in = [ x for x in (previous.sync_with or []) if x not in (self.sync_with or [])] filter = { 'remote_instance': previous, 'remote_organisation__in': remote_organisation__in, } # TODO: 'Dataset.harvested_ckan.filter(**filter).delete()' ne fonctionne pas for dataset in Dataset.harvested_ckan.filter(**filter): dataset.delete() else: # Dans le cas d'une création, on vérifie si l'URL CKAN est valide try: with CkanBaseHandler(self.url): pass except CkanBaseError as e: raise ValidationError(e.__str__(), code='url') # (2) Sauver l'instance super().save(*args, **kwargs) # (3) Créer/Mettre à jour les jeux de données synchronisés # On récupère dans le `stack` l'utilisateur effectuant l'opération editor = User.objects.get(pk=DEFAULT_USER_ID) for entry in inspect.stack(): try: editor = entry[0].f_locals['request'].user._wrapped except (KeyError, AttributeError): continue break # Puis on moissonne le catalogue if self.sync_with: try: ckan_ids = [] with transaction.atomic(): # TODO: Factoriser for value in self.sync_with: with CkanBaseHandler(self.url) as ckan: ckan_organisation = ckan.get_organisation( value, include_datasets=True, include_groups=True, include_tags=True) if not ckan_organisation.get('package_count', 0): continue for package in ckan_organisation.get('packages'): if not package['state'] == 'active' \ or not package['type'] == 'dataset': continue with CkanBaseHandler(self.url) as ckan: package = ckan.get_package(package['id']) ckan_id = uuid.UUID(package['id']) update_frequency = dict(Dataset.FREQUENCY_CHOICES).get( package.get('frequency'), 'unknown') update_frequency = package.get('frequency') if not(update_frequency and update_frequency in dict(Dataset.FREQUENCY_CHOICES).keys()): update_frequency = 'unknown' metadata_created = package.get('metadata_created', None) if metadata_created: metadata_created = datetime.strptime(metadata_created, ISOFORMAT_DATETIME) metadata_modified = package.get('metadata_modified', None) if metadata_modified: metadata_modified = datetime.strptime(metadata_modified, ISOFORMAT_DATETIME) try: mapping_licence = MappingLicence.objects.get( remote_ckan=self, slug=package.get('license_id')) except MappingLicence.DoesNotExist: try: license = License.objects.get(slug='other-at') except MappingLicence.DoesNotExist: license = None else: logger.warning("'{}' non trouvé".format(package.get('license_id'))) license = mapping_licence.licence slug = 'sync{}-{}'.format(str(uuid.uuid4())[:7].lower(), package.get('name'))[:100] kvp = { 'slug': slug, 'title': package.get('title'), 'description': package.get('notes'), 'date_creation': metadata_created and metadata_created.date(), 'date_modification': metadata_modified and metadata_modified.date(), # date_publication 'editor': editor, 'license': license, 'owner_email': self.organisation.email or DEFAULT_CONTACT_EMAIL, 'owner_name': self.organisation.legal_name or DEFAULT_PLATFORM_NAME, 'organisation': self.organisation, 'published': not package.get('private'), 'remote_instance': self, 'remote_dataset': ckan_id, 'remote_organisation': value, 'update_frequency': update_frequency, # bbox # broadcaster_email # broadcaster_name # data_type # geocover # geonet_id # granularity # thumbnail # support } dataset, created = Dataset.harvested_ckan.update_or_create(**kvp) mapping_categories = MappingCategory.objects.filter( remote_ckan=self, slug__in=[m['name'] for m in package.get('groups', [])]) if mapping_categories: dataset.categories = set(mc.category for mc in mapping_categories) if not created: dataset.keywords.clear() keywords = [tag['display_name'] for tag in package.get('tags')] dataset.keywords.add(*keywords) dataset.save(current_user=None, synchronize=True, activate=False) ckan_ids.append(dataset.ckan_id) for resource in package.get('resources', []): try: ckan_id = uuid.UUID(resource['id']) except ValueError as e: logger.exception(e) logger.error("I can't crash here, so I do not pay any attention to this error.") continue try: ckan_format = resource['format'].upper() format_type = ResourceFormats.objects.get(ckan_format=ckan_format) except (ResourceFormats.MultipleObjectsReturned, ResourceFormats.DoesNotExist, TypeError) as e: logger.exception(e) logger.error("I can't crash here, so I do not pay any attention to this error.") format_type = None kvp = { 'ckan_id': ckan_id, 'dataset': dataset, 'format_type': format_type, 'title': resource['name'], 'referenced_url': resource['url'], } try: resource = Resource.objects.get(ckan_id=ckan_id) except Resource.DoesNotExist: resource = Resource.default.create( save_opts={'current_user': None, 'synchronize': True}, **kvp) else: for k, v in kvp.items(): setattr(resource, k, v) resource.save(current_user=None, synchronize=True) except Exception as e: for id in ckan_ids: CkanHandler.purge_dataset(str(id)) logger.error(e) raise CriticalError() else: for id in ckan_ids: CkanHandler.publish_dataset(id=str(id), state='active') def delete(self, *args, **kwargs): Dataset = apps.get_model(app_label='idgo_admin', model_name='Dataset')
# -*- coding: utf-8 -*- import os import sqlite3 import sys try: from StringIO import StringIO except ImportError: from io import StringIO # New stdlib location in 3.0 from . import _unittest as unittest from .common import TempDirTestCase from toron._gpn_node import Node from toron.connector import _schema from toron.connector import _SharedConnection from toron import IN_MEMORY from toron import TEMP_FILE from toron import READ_ONLY class TestInstantiation(TempDirTestCase): def setUp(self): self.addCleanup(self.cleanup_temp_files) def _make_node(self, filename): global _schema self._existing_node = filename connection = sqlite3.connect(self._existing_node) cursor = connection.cursor() cursor.execute('PRAGMA synchronous=OFF') for operation in _schema: cursor.execute(operation) cursor.execute('PRAGMA synchronous=FULL') connection.close() def test_existing_node(self): """Existing node should load without errors.""" filename = 'temp_node.node' self._make_node(filename) ptn = Node(self._existing_node) # Use existing file. self.assertEqual(ptn.name, 'temp_node') @unittest.skipIf(sqlite3.sqlite_version_info < (3, 8, 0), 'The query_only PRAGMA was added to SQLite in version 3.8.0') def test_read_only_node(self): """The READ_ONLY flag should open a Node in read-only mode.""" self._make_node('existing_node') ptn = Node(self._existing_node, mode=READ_ONLY) connection = ptn._connect() cursor = connection.cursor() regex = 'attempt to write a readonly database' with self.assertRaisesRegex((sqlite3.OperationalError, sqlite3.IntegrityError), regex): cursor.execute('INSERT INTO cell DEFAULT VALUES') def test_new_node(self): """Named nodes that do not exist should be created.""" filepath = 'new_node.node' self.assertFalse(os.path.exists(filepath)) ptn = Node(filepath) # Create new file. del ptn self.assertTrue(os.path.exists(filepath)) def test_subdirectory(self): """Subdirectory reference should also be supported.""" os.mkdir('subdir') filepath = 'subdir/new_node.node' self.assertFalse(os.path.exists(filepath)) ptn = Node(filepath) # Create new file. self.assertEqual(ptn.name, 'subdir/new_node') del ptn self.assertTrue(os.path.exists(filepath)) def test_path_name_error(self): """If a path is specified, it should be used to set the node name. If a `name` attribute is also provided, it must not be accepted. """ regex = 'Cannot specify both path and name.' with self.assertRaisesRegex(AssertionError, regex): Node('some_path.node', name='some_name') def test_temporary_node(self): """Unnamed nodes should be temporary (in memory or tempfile).""" # In memory. ptn = Node() self.assertFalse(ptn._connect._init_as_temp) self.assertIsInstance(ptn._connect._dbsrc, _SharedConnection) self.assertIsNone(ptn.name) # On disk. ptn = Node(mode=TEMP_FILE) self.assertTrue(ptn._connect._init_as_temp) self.assertTrue(os.path.isfile(ptn._connect._dbsrc)) self.assertIsNone(ptn.name) def test_named_temporary_nodes(self): # In memory. node_name = 'temp_with_name' ptn = Node(name=node_name) self.assertFalse(ptn._connect._init_as_temp) self.assertIsInstance(ptn._connect._dbsrc, _SharedConnection) self.assertEqual(ptn.name, node_name) # On disk. ptn = Node(name=node_name, mode=TEMP_FILE) self.assertTrue(ptn._connect._init_as_temp) self.assertTrue(os.path.isfile(ptn._connect._dbsrc)) self.assertEqual(ptn.name, node_name) class TestHash(unittest.TestCase): def test_get_hash(self): node = Node(mode=IN_MEMORY) connection = node._connect() cursor = connection.cursor() # Hash of empty node should be None. result = node._get_hash(cursor) self.assertIsNone(result) # Build node. cursor.execute("INSERT INTO hierarchy VALUES (1, 'state', 0)") cursor.execute("INSERT INTO hierarchy VALUES (2, 'county', 1)") cursor.execute("INSERT INTO cell VALUES (1, 0)") cursor.execute("INSERT INTO label VALUES (1, 1, 'Indiana')") cursor.execute("INSERT INTO label VALUES (2, 2, 'LaPorte')") cursor.execute("INSERT INTO cell_label VALUES (1, 1, 1, 1)") cursor.execute("INSERT INTO cell_label VALUES (2, 1, 2, 2)") # Expected hash of "11Indiana12LaPorte" (independently verified). expected = 'a0eadc7b0547b9405dae9e3c50e038a550d9a718af10b53e567995a9378c22d7' result = node._get_hash(cursor) self.assertEqual(expected, result) class TestTransactionHandling(unittest.TestCase): def setUp(self): self._node = Node(mode=IN_MEMORY) connection = self._node._connect() cursor = connection.cursor() cursor.executescript(""" INSERT INTO hierarchy VALUES (1, 'country', 0); INSERT INTO hierarchy VALUES (2, 'region', 1); INSERT INTO cell VALUES (1, 0); INSERT INTO label VALUES (1, 1, 'USA'); INSERT INTO label VALUES (2, 2, 'Northeast'); INSERT INTO cell_label VALUES (1, 1, 1, 1); INSERT INTO cell_label VALUES (2, 1, 2, 2); INSERT INTO cell VALUES (2, 0); INSERT INTO label VALUES (3, 2, 'Midwest'); INSERT INTO cell_label VALUES (3, 2, 1, 1); INSERT INTO cell_label VALUES (4, 2, 2, 3); """) def test_commit(self): with self._node._connect() as connection: connection.isolation_level = None cursor = connection.cursor() cursor.execute('BEGIN TRANSACTION') cursor.execute('INSERT INTO cell VALUES (3, 0)') # <- Change. cursor.execute('SELECT COUNT(*) FROM cell') msg = 'Changes should be committed.' self.assertEqual([(3,)], cursor.fetchall(), msg) def test_rollback(self): try: with self._node._connect() as connection: connection.isolation_level = None # <- REQUIRED! cursor = connection.cursor() # <- REQUIRED! cursor.execute('BEGIN TRANSACTION') # <- REQUIRED! cursor.execute('DROP TABLE cell_label') # <- Change. cursor.execute('INSERT INTO cell VALUES (3, 0)') # <- Change. cursor.execute('This is not valid SQL -- operational error!') # <- Error! except sqlite3.OperationalError: pass connection = self._node._connect() cursor = connection.cursor() msg = 'Changes should be rolled back.' cursor.execute('SELECT COUNT(*) FROM cell') self.assertEqual([(2,)], cursor.fetchall(), msg) cursor.execute('SELECT COUNT(*) FROM cell_label') self.assertEqual([(4,)], cursor.fetchall(), msg) class TestInsert(unittest.TestCase): def test_insert_one_cell(self): node = Node(mode=IN_MEMORY) connection = node._connect() cursor = connection.cursor() cursor.execute("INSERT INTO hierarchy VALUES (1, 'state', 0)") cursor.execute("INSERT INTO hierarchy VALUES (2, 'county', 1)") cursor.execute("INSERT INTO hierarchy VALUES (3, 'town', 2)") items = [('state', 'OH'), ('county', 'Franklin'), ('town', 'Columbus')] node._insert_one_cell(cursor, items) # <- Inserting here! # Cell table. cursor.execute('SELECT * FROM cell ORDER BY cell_id') expected = [(1, 0)] self.assertEqual(expected, cursor.fetchall()) # Label table. cursor.execute('SELECT * FROM label ORDER BY label_id') expected = [(1, 1, 'OH'), (2, 2, 'Franklin'), (3, 3, 'Columbus')] self.assertEqual(expected, cursor.fetchall()) # Cell_label table, expected = [(1, 1, 1, 1), (2, 1, 2, 2), (3, 1, 3, 3)] cursor.execute('SELECT * FROM cell_label ORDER BY cell_label_id') self.assertEqual(expected, cursor.fetchall()) def test_insert_cells(self): self.maxDiff = None fh = StringIO('state,county,town\n' 'OH,Allen,Lima\n' 'OH,Cuyahoga,Cleveland\n' 'OH,Franklin,Columbus\n' 'OH,Hamilton,Cincinnati\n' 'OH,Montgomery,Dayton\n') node = Node(mode=IN_MEMORY) node._insert_cells(fh) # <- Inserting here! connection = node._connect() cursor = connection.cursor() # Hierarchy table. cursor.execute('SELECT * FROM hierarchy ORDER BY hierarchy_level') expected = [(1, 'state', 0), (2, 'county', 1), (3, 'town', 2)] self.assertEqual(expected, cursor.fetchall()) # Cell table. cursor.execute('SELECT * FROM cell ORDER BY cell_id') expected = [(1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0)] self.assertEqual(expected, cursor.fetchall()) # Label table. cursor.execute('SELECT * FROM label ORDER BY label_id') expected = [(1, 1, 'OH'), (2, 2, 'Allen'), (3, 3, 'Lima'), (4, 2, 'Cuyahoga'), (5, 3, 'Cleveland'), (6, 2, 'Franklin'), (7, 3, 'Columbus'), (8, 2, 'Hamilton'), (9, 3, 'Cincinnati'), (10, 2, 'Montgomery'), (11, 3, 'Dayton'), (12, 1, 'UNMAPPED'), (13, 2, 'UNMAPPED'), (14, 3, 'UNMAPPED')] self.assertEqual(expected, cursor.fetchall()) # Cell_label table, cursor.execute('SELECT * FROM cell_label ORDER BY cell_label_id') expected = [(1, 1, 1, 1), (2, 1, 2, 2), (3, 1, 3, 3), (4, 2, 1, 1), (5, 2, 2, 4), (6, 2, 3, 5), (7, 3, 1, 1), (8, 3, 2, 6), (9, 3, 3, 7), (10, 4, 1, 1), (11, 4, 2, 8), (12, 4, 3, 9), (13, 5, 1, 1), (14, 5, 2, 10), (15, 5, 3, 11), (16, 6, 1, 12), (17, 6, 2, 13), (18, 6, 3, 14)] self.assertEqual(expected, cursor.fetchall()) # Node table (hash should be set). cursor.execute('SELECT node_id, node_hash FROM node') hashval = '71eeab7a5b4609a1978bd5c19e7d490556c5e42c503b39480c504bbaf99efe30' self.assertEqual([(1, hashval)], cursor.fetchall()) def test_insert_cells_multiple_files(self): """Insert should accept multiple files.""" node = Node(mode=IN_MEMORY) fh = StringIO('state,county,town\n' 'OH,Allen,Lima\n') node._insert_cells(fh) # <- Inserting. fh = StringIO('state,county,town\n' 'OH,Cuyahoga,Cleveland\n') node._insert_cells(fh) # <- Inserting second file. connection = node._connect() cursor = connection.cursor() # Hierarchy table. cursor.execute('SELECT * FROM hierarchy ORDER BY hierarchy_level') expected = [(1, 'state', 0), (2, 'county', 1), (3, 'town', 2)] self.assertEqual(expected, cursor.fetchall()) # Cell table. cursor.execute('SELECT * FROM cell ORDER BY cell_id') expected = [(1, 0), (2, 0), (3, 0)] self.assertEqual(expected, cursor.fetchall()) # Label table. cursor.execute('SELECT * FROM label ORDER BY label_id') expected = [(1, 1, 'OH'), (2, 2, 'Allen'), (3, 3, 'Lima'), (4, 1, 'UNMAPPED'), (5, 2, 'UNMAPPED'), (6, 3, 'UNMAPPED'), (7, 2, 'Cuyahoga'), (8, 3, 'Cleveland')] self.assertEqual(expected, cursor.fetchall()) # Node table should have two hashes. cursor.execute('SELECT node_id, node_hash FROM node') expected = [(1, '5011d6c33da25f6a98422461595f275f' '289a7a745a9e89ab6b4d36675efd944b'), (2, '9184abbd5461828e01fe82209463221a' '65d4c21b40287d633cf7e324a27475f5')] self.assertEqual(expected, cursor.fetchall()) def test_insert_cells_bad_header(self): """Files must have the same header""" node = Node(mode=IN_MEMORY) fh = StringIO('state,county,town\n' 'OH,Hamilton,Cincinnati\n') node._insert_cells(fh) regex = 'Fieldnames must match hierarchy values.' with self.assertRaisesRegex(AssertionError, regex): fh = StringIO('state,county\n' 'OH,Montgomery\n') node._insert_cells(fh) def test_insert_cells_duplicate(self): """Duplicate rows should fail and rollback to previous state.""" fh = StringIO('state,county,town\n' 'OH,Cuyahoga,Cleveland\n') node = Node(mode=IN_MEMORY) node._insert_cells(fh) # <- First insert! regex = 'duplicate label set' with self.assertRaisesRegex(sqlite3.IntegrityError, regex): fh = StringIO('state,county,town\n' 'OH,Franklin,Columbus\n' 'OH,Hamilton,Cincinnati\n' 'OH,Hamilton,Cincinnati\n') node._insert_cells(fh) # <- Second insert! connection = node._connect() cursor = connection.cursor() # Cell table should include only values from first insert. cursor.execute('SELECT * FROM cell ORDER BY cell_id') expected = [(1, 0), (2, 0)] self.assertEqual(expected, cursor.fetchall()) # Label table should include only values from first insert. cursor.execute('SELECT * FROM label ORDER BY label_id') expected = [(1, 1, 'OH'), (2, 2, 'Cuyahoga'), (3, 3, 'Cleveland'), (4, 1, 'UNMAPPED'), (5, 2, 'UNMAPPED'), (6, 3, 'UNMAPPED')] self.assertEqual(expected, cursor.fetchall()) def test_unmapped_levels(self): """Unmapped cells must have valid hierarchy levels.""" fh = StringIO('state,county,town\n' 'OH,Cuyahoga,Cleveland\n') node = Node(mode=IN_MEMORY) node._insert_cells(fh) # <- First insert! regex = 'invalid unmapped level' with self.assertRaisesRegex(sqlite3.IntegrityError, regex): fh = StringIO('state,county,town\n' 'OH,Franklin,Columbus\n' 'OH,UNMAPPED,Cincinnati\n') node._insert_cells(fh) # <- Second insert! connection = node._connect() cursor = connection.cursor() # Cell table should
<reponame>IceCubeOpenSource/ic3-labels<gh_stars>1-10 """nuVeto Atmospheric Self-Veto Models This file implements a wrapper class around nuVeto (https://github.com/tianluyuan/nuVeto) which builds splines in energy and zenith. These can then be used to calculate the self-veto effect for atmospheric neutrinos. See also the paper to nuVeto: https://arxiv.org/abs/1805.11003 It is recommended to cache the results of nuVeto because these take a while to produce. By default, the cache file is chosen to be located in the 'resources' directory relative to the location of this file. You may also set the environment variable 'NUVETO_CACHE_DIR' in order to choose a different location for the cache file, or pass in an explicit cache file when initializing the AtmosphericNuVeto object. Environment Variables: 'NUVETO_CACHE_DIR': If provided, the MCEq cache file will be written to this directory. """ import os import logging import pkg_resources from copy import deepcopy import os import numpy as np from scipy.interpolate import RectBivariateSpline from multiprocessing import Pool import ic3_labels log = logging.getLogger('AtmosphericNuVeto') # If cashier is available, set up directory for caching of nuVeto results try: from ic3_labels.weights.resources.cashier import cache got_cashier = True if 'NUVETO_CACHE_DIR' in os.environ: cache_dir = os.environ['NUVETO_CACHE_DIR'] log.info( "Found 'NUVETO_CACHE_DIR' in environment variables: {}".format( cache_dir)) if not os.path.exists(cache_dir): log.info('Creating cache directory: {}'.format(cache_dir)) os.makedirs(cache_dir) CACHE_FILE = os.path.join(cache_dir, 'nuVeto.cache') else: script_dir = os.path.dirname(os.path.abspath(__file__)) CACHE_FILE = os.path.join(script_dir, 'resources', 'nuVeto.cache') log.info('Using nuVeto cache file: {}'.format(CACHE_FILE)) except ImportError: got_cashier = False CACHE_FILE = None log.info("Could not import 'cashier'. NuVeto results will not be cached!") # Dictionary that converts ptype -> nuVeto type string PTYPE_CONVERTER = { 12: 'nu_e', -12: 'nu_ebar', 14: 'nu_mu', -14: 'nu_mubar', 16: 'nu_tau', -16: 'nu_taubar', } def __solve_one_cos_theta__(settings): """Helper Function for Multiprocessing Solves for one cos(theta) grid point for the specified `settings`. Parameters ---------- settings : dict A dictionary with the settings to run nuVeto with. Returns ------- dict The passing fraction result for the total flux. dict The passing fraction result for the conv flux. dict The passing fraction result for the prompt flux. """ from nuVeto import nuveto from nuVeto.utils import Units nuveto_obj = nuveto.builder( cos_theta=settings['cos_theta'], pmodel=settings['pmodel'], hadr=settings['hadr'], barr_mods=settings['barr_mods'], depth=settings['depth'], density=settings['density'], ) total_pf_dict_i = {} conv_pf_dict_i = {} pr_pf_dict_i = {} for key in settings['ptype_converter'].keys(): shape = (len(settings['energy_grid']),) total_pf_dict_i[key] = np.ones(shape) conv_pf_dict_i[key] = np.ones(shape) pr_pf_dict_i[key] = np.ones(shape) # fill in passing fractions for key, value in settings['ptype_converter'].items(): print('At particle type:', value) for index_energy, energy_i in enumerate(settings['energy_grid']): # total num, den = nuveto_obj.get_fluxes( enu=energy_i*Units.GeV, kind='total {}'.format(value), accuracy=3.5, prpl=settings['prpl'], corr_only=False, ) if num == den == 0: # If both are zero, we will just set the passing # fraction to 1. This is the conservative choice, # since it does not change anython. Passing fractions # are uusall muliplied to weights. fraction = 1. else: fraction = num/den total_pf_dict_i[key][index_energy] = fraction # conv num, den = nuveto_obj.get_fluxes( enu=energy_i*Units.GeV, kind='conv {}'.format(value), accuracy=3.5, prpl=settings['prpl'], corr_only=False, ) if num == den == 0: # If both are zero, we will just set the passing # fraction to 1. This is the conservative choice, # since it does not change anython. Passing fractions # are uusall muliplied to weights. fraction = 1. else: fraction = num/den conv_pf_dict_i[key][index_energy] = fraction # prompt num, den = nuveto_obj.get_fluxes( enu=energy_i*Units.GeV, kind='pr {}'.format(value), accuracy=3.5, prpl=settings['prpl'], corr_only=False, ) if num == den == 0: # If both are zero, we will just set the passing # fraction to 1. This is the conservative choice, # since it does not change anython. Passing fractions # are uusall muliplied to weights. fraction = 1. else: fraction = num/den pr_pf_dict_i[key][index_energy] = fraction return total_pf_dict_i, conv_pf_dict_i, pr_pf_dict_i def get_spline( interaction_model, primary_model, prpl, months, theta_grid, theta_grid_cos, energy_grid, n_jobs=1, cached=True, cache_file=CACHE_FILE, cache_read_only=False): """Get nuVeto spline Caculates nuVeto results for the given parameters. The results are obtained for the provided grid and interpolated. Parameters ---------- interaction_model : str The interaction model. This is passed on to `MCEq` (via nuVeto). primary_model : str The primary model to use. Must be one of: GST_3-gen, GST_4-gen, H3a, H4a, poly-gonato, TIG, ZS, ZSP, GH prpl : str The detector veto probability PDF to use. This must be a valid prpl PDF created and available in nuVeto. This option is passed on to nuVeto. months : list of str The months for which to solve the cascade equations. These must be provided as a list of month names, e.g. ['January', 'August']. A list of splines will be returned of the same length as `months`. theta_grid : array_like The grid points in theta to evaluate on in degrees. If `theta_grid_cos` is True, this is instead cos(theta). theta_grid_cos : bool If True, `theta_grid` is interpreted as cos(theta), i.e. arccos() is applied first. energy_grid : array_like The energy grid points [in GeV] to evaluate on. n_jobs : int, optional Number of jobs to compute the splines. The grid evaluation points along zenith are distributed over the specified `n_jobs`. cached : bool, optional If True, the result will be cached, or taken from cache if previously already computed. This is recommended, as MCEq takes a while to run. cache_file : str, optional The path to the cache file to use. cache_read_only : bool, optional If True, the cache is read only. Returns ------- dict The result of nuVeto together with the fitted splines. The structure is as follows: { # first month provided via `months` 0: { 'total_spline_dict': dict of RectBivariateSpline A dictionary with the fitted splines for each particle type for the 'total' passing fraction. The dictionary keys are the PDG particle encodings. 'conv_spline_dict': dict of RectBivariateSpline A dictionary with the fitted splines for each particle type for the 'conv' passing fraction. The dictionary keys are the PDG particle encodings. 'pr_spline_dict': dict of RectBivariateSpline A dictionary with the fitted splines for each particle type for the 'pr' passing fraction. The dictionary keys are the PDG particle encodings. 'total_pf_dict': dict of array_like A dictionary with the total passing fraction for each grid point. This is the result obtained from nuVeto for the 'total' flux. 'conv_pf_dict': dict of array_like A dictionary with the conv passing fraction for each grid point. This is the result obtained from nuVeto for the 'conv' flux. 'pr_pf_dict': dict of array_like A dictionary with the prompt passing fraction for each grid point. This is the result obtained from nuVeto for the 'pr' flux. 'nuveto_version' : str The nuVeto version that was used to create the splines. 'ic3_labels_version' : str The version of the ic3-labels package that was used to create the splines. 'log10_e_grid' : array_like The grid of energy points in log10. 'theta_grid' : array_like The grid of thetas. } # second month provided via `months` 1: { ... } ... } """ log.info('Getting Spline for {}; {} (cached={})'.format( interaction_model, primary_model, cached)) def __solve_month__( interaction_model, pmodel, density_model, prpl, theta_grid, theta_grid_cos, energy_grid, n_jobs=1, ptype_converter=PTYPE_CONVERTER, eps=1e-128, ): """Compute passing fractions via nuVeto for the provided parameters Parameters ---------- interaction_model : str The interaction model. This is passed on to `MCEq` (via nuVeto). pmodel : tuple of crf.PrimaryModel, 'str' The primary model to use. This is passed on to `MCEq` (via nuVeto). density_model : (str, (str, str)) The density model to use. This is passed on to `MCEq` (via nuVeto). prpl : str The detector veto probability PDF to use. This must be a valid prpl PDF created and available in nuVeto. This option is passed on to nuVeto. theta_grid : array_like The grid points in theta to evaluate on in degrees. If `theta_grid_cos` is True, this is instead cos(theta). theta_grid_cos : bool If True, `theta_grid` is interpreted as cos(theta), i.e. arccos() is applied first. energy_grid : array_like The energy grid points [in GeV] to evaluate on. n_jobs : int, optional Number of jobs to compute the splines. The grid evaluation points along zenith are distributed over the specified `n_jobs`. ptype_converter : dict, optional A dictionary that converts PDG encoding to nuVeto type string. eps : float, optional A small float value > 0 that is used to clip the passing fraction prior to applying log10 for the spline fitting. Returns ------- list of dict
= target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend(gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i, postbuild in enumerate(postbuilds): if not postbuild.startswith('$'): postbuilds[i] = EscapeShellArgument(postbuild) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, 'Postbuilds do not work with custom product_dir' if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % (QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ("Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % (QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ("Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print("WARNING: no output for", self.type, self.target) # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony=True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment='Add target alias to "all" target.', phony=True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % (install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony=True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment='Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment='Short alias for building this %s.' % file_desc, phony=True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment='Add %s to "all" target.' % file_desc, phony=True) def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """ Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values)) # TODO(refack) `part_of_all` is not used, but is part of signature used in many other places # noinspection PyUnusedLocal def WriteDoCmd(self, outputs, inputs, command, part_of_all=False, comment=None, postbuilds=None): """ Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = '' if postbuilds: assert ',' not in command suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule( outputs, inputs, actions=['$(call do_cmd,%s%s)' % (command, suffix)], comment=comment, command=command, force=True ) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn('all_deps += %s' % ' '.join(outputs)) def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None): """ Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = [QuoteSpaces(o) for o in outputs] inputs = map(QuoteSpaces, inputs) if comment: self.WriteLn('# ' + comment) if phony: self.WriteLn('.PHONY: ' + ' '.join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = ' FORCE_DO_CMD' if force else '' if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn('%s: | %s%s' % (' '.join(outputs), ' '.join(inputs), force_append)) elif len(outputs) == 1: # Regular
<filename>EPS Powermiser.indigoPlugin/Contents/Server Plugin/lib/cache.py # lib.cache - Caches devices and items from Indigo for lookup # # Copyright (c) 2018 ColoradoFourWheeler / EPS # import indigo import logging import ext # CONSTANTS DEV_FIELDS = ["device", "device1", "device2", "device3", "device4", "device5"] VAR_FIELDS = ["variable", "variable1", "variable2", "variable3", "variable4", "variable5"] # # Main cache class # class cache: # # Initialize the class # def __init__(self, factory): self.logger = logging.getLogger ("Plugin.cache") self.factory = factory self.items = cacheDict(factory) self.pluginItems = indigo.Dict() # Plugin devices by type self.pluginDevices = indigo.List() # All plugin devices self.pluginLocalCache = indigo.List() # If the plugin needs to cache something special self.logger.threaddebug ("Caching initialized") # # Initialize local properties # def _initProps (self): return # # Add device to cache # def addDevice (self, dev): try: if self.items.isInCache (dev.id): self.logger.debug ("Not adding {0} to cache because it's already there".format(dev.name)) return else: self.logger.debug ("Adding {0} to cache".format(dev.name)) cDev = cacheDev(dev) self.items.add(cDev) if cDev.pluginId == self.factory.plugin.pluginId: self._autoCacheFields (dev) if cDev.id in self.pluginDevices: pass else: self.pluginDevices.append(cDev.id) pluginItem = indigo.Dict() if cDev.deviceTypeId in self.pluginItems: pluginItem = self.pluginItems[cDev.deviceTypeId] else: pluginItem = indigo.List() if cDev.id in pluginItem: pass else: pluginItem.append(cDev.id) self.pluginItems[cDev.deviceTypeId] = pluginItem except Exception as e: self.logger.error (ext.getException(e)) # # Remove device from cache # def removeDevice (self, obj): try: self.logger.threaddebug ("Removing '{0}' and any references from cache".format(obj.name)) self.items.remove(obj) except Exception as e: self.logger.error (ext.getException(e)) # # Automatically subscribe to changes # def subscribeToChanges (self, obj): try: if type(obj) is indigo.Variable and self.factory.plug.isSubscribedVariables == False: self.logger.threaddebug ("Variable is being watched, automatically subscribing to variable changes") indigo.variables.subscribeToChanges() self.factory.plug.isSubscribedVariables = True if type(obj) is indigo.ActionGroup and self.factory.plug.isSubscribedActionGroups == False: self.logger.threaddebug ("Action group is being watched, automatically subscribing to action group changes") indigo.actionGroups.subscribeToChanges() self.factory.plug.isSubscribedActionGroups = True else: if self.factory.plug.isSubscribedDevices == False: self.logger.threaddebug ("Device is being watched, automatically subscribing to device changes") indigo.devices.subscribeToChanges() self.factory.plug.isSubscribedDevices = True except Exception as e: self.logger.error (ext.getException(e)) # # Resolve an address to a cached device # def addressToDev (self, address): try: obj = self.items.addressIsInCache (address) if obj: self.logger.threaddebug("Address '{0}' is cached, returning '{1}'".format(address, obj.name)) return indigo.devices[obj.id] except Exception as e: self.logger.error (ext.getException(e)) # # Get devices that are watching an ID # def getDevicesWatchingId (self, id): ret = [] try: obj = self.items.isInCache (int(id)) if obj: for watchItem in obj.watchedBy: ret.append(watchItem.id) except Exception as e: self.logger.error (ext.getException(e)) return ret # # Add watched states # def addWatchedStates (self, parent, watchedItemsDict): try: # If we are watching something then automatically turn on subscribeToChanges self.subscribeToChanges(parent) for devId, state in watchedItemsDict.iteritems(): if int(devId) not in indigo.devices: self.logger.error ("Device '{0}' is referencing device ID {1} but that device is no longer an Indigo device. Please change the device reference or remove '{0}' to prevent this error".format(parent.name, str(devId))) continue states = [] # They can pass a single state or a list of states, we'll convert if needed if type(state) is list: states = state else: states.append(state) for state in states: if ext.valueValid (indigo.devices[devId].states, state): self.logger.threaddebug ("Adding watched state '{0}' to child device '{1}' being watched by '{2}'".format(state, indigo.devices[devId].name, parent.name)) self.items.addWatchedState (parent, indigo.devices[devId], state) else: # See if it's a custom state if state[0:7] == "custom_": self.logger.threaddebug ("Adding custom watched state '{0}' to child device '{1}' being watched by '{2}'".format(state, indigo.devices[devId].name, parent.name)) self.items.addWatchedState (parent, indigo.devices[devId], state) else: self.logger.warning ("Cannot watch state '{0}' on child device '{1}' for '{2}' because the child doesn't have that state".format(state, indigo.devices[devId].name, parent.name)) #self.logger.info(unicode(self.items)) except Exception as e: self.logger.error (ext.getException(e)) # # Add watched attributes # def addWatchedAttribute (self, parent, watchedItemsDict): try: for devId, attribute in watchedItemsDict.iteritems(): # If we are watching something then automatically turn on subscribeToChanges self.subscribeToChanges(indigo.devices[devId]) attributes = [] # They can pass a single state or a list of states, we'll convert if needed if type(attribute) is list: attributes = attribute else: attributes.append(attribute) for attribute in attributes: # Assuming we use our own factory to generate the list, get rid of "attr_" attribute = attribute.replace("attr_", "") # This should only come from our own core, therefore attributes should be pre-pended with "attr_", fix that attribute = attribute.replace("attr_", "") self.logger.threaddebug ("Adding watched attribute '{0}' to child device '{1}' being watched by '{2}'".format(attribute, indigo.devices[devId].name, parent.name)) self.items.addWatchedAttribute (parent, indigo.devices[devId], attribute) #self.logger.info(unicode(self.items)) except Exception as e: self.logger.error (ext.getException(e)) # # Add watched property # def addWatchedProperty (self, parent, watchedItemsDict): try: for devId, property in watchedItemsDict.iteritems(): # If we are watching something then automatically turn on subscribeToChanges self.subscribeToChanges(indigo.devices[devId]) properties = [] # They can pass a single state or a list of states, we'll convert if needed if type(property) is list: properties = property else: properties.append(property) for property in properties: if ext.valueValid (indigo.devices[devId].ownerProps, property): self.logger.threaddebug ("Adding watched property '{0}' to child device '{1}' being watched by '{2}'".format(property, indigo.devices[devId].name, parent.name)) self.items.addWatchedProperty (parent, indigo.devices[devId], property) else: # If using our own engine then if there are no properties to watch it should be "-none-" if property != "-none-" and property != "": self.logger.warning ("Cannot watch property '{0}' on child device '{1}' for '{2}' because the child doesn't have that property ID".format(property, indigo.devices[devId].name, parent.name)) #self.logger.info(unicode(self.items)) except Exception as e: self.logger.error (ext.getException(e)) # # Add watched variable - this is different in that we only ever look at one thing, the value of the variable # def addWatchedVariable (self, parent, watchedItemsDict): try: for varId, variable in watchedItemsDict.iteritems(): if int(varId) in indigo.variables: # If we are watching something then automatically turn on subscribeToChanges self.subscribeToChanges(indigo.variables[varId]) self.items.addWatchedItem (parent, indigo.variables[varId]) else: self.logger.warning ("Cannot watch variable '{0}' on child device '{1}' because the variable doesn't exist".format(str(varId), parent.name)) except Exception as e: self.logger.error (ext.getException(e)) # # Add watched action group - we don't look for anything that changed, it's here so we can notify the plugin that one we are watching was run # def addWatchedActionGroup (self, parent, watchedItemsDict): try: for agId, variable in watchedItemsDict.iteritems(): if int(agId) in indigo.actionGroups: # If we are watching something then automatically turn on subscribeToChanges self.subscribeToChanges(indigo.actionGroups[agId]) self.items.addWatchedItem (parent, indigo.actionGroups[agId]) else: self.logger.warning ("Cannot watch action group '{0}' on child device '{1}' because the action group doesn't exist".format(str(agId), parent.name)) except Exception as e: self.logger.error (ext.getException(e)) # # Add watched object without any attribute, states, props or values being watched - called when no other property is appropriate but we still want to monitor the object # def addWatchedObject (self, parent, watchedItemsDict): try: for objId, objNothing in watchedItemsDict.iteritems(): if int(objId) in indigo.devices: obj = indigo.devices[objId] elif int(objId) in indigo.variables: obj = indigo.variables[objId] else: self.logger.warn ("Trying to watch object id {0} on '{1}' but that id could not be resolved in Indigo, skipping cache".format(str(objId), parent.name)) self._watchObject (parent, obj) except Exception as e: self.logger.error (ext.getException(e)) # # After an update event, see if anything interesting changed # def watchedItemChanges (self, origObj, newObj): ret = [] #indigo.server.log(origObj.name) #return ret # This routine takes .2 to .4 extra CPU, without it it's 1.2 instead of 1.6 to 1.8 try: obj = self.items.isInCache (newObj.id) if obj: self.logger.threaddebug("'{0}' is cached, checking for changes".format(newObj.name)) #self.watchedItemChanged_ShowAllChanges (origObj, newObj) ret = obj.getWatchedByChanges (origObj, newObj) else: return ret except Exception as e: self.logger.error (ext.getException(e)) return ret # # Compare two devices and log the changes between them # def watchedItemChanged_ShowAllChanges (self, origObj, newObj): try: for s in newObj.states: if s in origObj.states: if newObj.states[s] != origObj.states[s]: self.logger.debug ("State {0} was {1} and is now {2}".format(s, unicode(origObj.states[s]), unicode(newObj.states[s]))) for s in newObj.pluginProps: if s in origObj.pluginProps: if newObj.pluginProps[s] != origObj.pluginProps[s]: self.logger.debug ("Property {0} was {1} and is now {2}".format(s, unicode(origObj.pluginProps[s]), unicode(newObj.pluginProps[s]))) except Exception as e: self.logger.error (ext.getException(e)) # # Watch an item (does not watch any states, props, attributes or values, just the device) # def _watchObject (self, dev, obj): try: self.subscribeToChanges (obj) self.items.addWatchedItem (dev, obj) except Exception as e: self.logger.error (ext.getException(e)) # # Check for standard watch fields in a plugin device # def _autoCacheFields (self, dev): try: for fieldName, fieldValue in dev.pluginProps.iteritems(): if fieldName in DEV_FIELDS and fieldValue != "": if int(fieldValue) not in indigo.devices: self.logger.error ("Device '{0}' is referencing device ID {1} but that device is no longer an Indigo device. Please change the device reference or remove '{0}' to prevent this error".format(dev.name, str(fieldValue))) return False d = indigo.devices[int(fieldValue)] self.logger.debug ("Found device reference field '{1}' in plugin device '{0}', auto-watching '{2}' for changes".format(dev.name, fieldName, d.name)) self._watchObject (dev, d) if fieldName in VAR_FIELDS and fieldValue != "": v = indigo.variables[int(fieldValue)] self.logger.debug ("Found variable reference field '{1}' in plugin device '{0}', auto-watching '{2}' for changes".format(dev.name, fieldName, v.name)) self._watchObject (dev, v) except Exception as e: self.logger.error (ext.getException(e)) # # Cache item list # class cacheDict: # # Initialize the class # def __init__(self, factory): self.logger = logging.getLogger ("Plugin.cacheDict") self.items = {} self.factory = factory def __len__ (self): try: return len(self.items) except Exception as e: self.logger.error (ext.getException(e)) def __iter__ (self): self.iter_index = 0 return self def next (self): try: if self.iter_index < len(self.items): idx = 0 rec = None for devId, props in self.items.iteritems(): if idx == self.iter_index: rec = props idx = idx + 1 self.iter_index = self.iter_index + 1 return rec else: raise StopIteration except Exception as e: #self.logger.error (ext.getException(e)) raise StopIteration def __str__(self): ret = "Cache List\n" for devId, props in self.items.iteritems(): ret += "\n" + props.itemType + "\n" proplist = [a for a in dir(props) if not a.startswith('__') and not callable(getattr(props,a))] for p in proplist: value = getattr(props, p) if type(value) is list: ret += "\t" + p + " : " if len(value) > 0: ret += " (list) :\n" for l in value: if isinstance(l, watchRec): ret += "\t\titem : " + str(l.id) + "\n" # If we have states then add them if len(l.states) > 0: ret += "\t\t\tstates : \n" for st in l.states: ret += "\t\t\t\t" + st + "\n" # If we have attributes then add them if len(l.attributes) > 0: ret += "\t\t\tattributes : \n" for st in l.attributes: ret += "\t\t\t\t" + st + "\n" # If we have plugin config properties then add them if len(l.attributes) > 0: ret += "\t\t\tproperties : \n" for st in l.properties: ret += "\t\t\t\t" + st + "\n" else: ret += "\t\titem : "
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ECCO v4 Python: Dataset Utililites This module includes utility routines to create the ECCO product as netcdf and for processing metadata. .. _ecco_v4_py Documentation : https://github.com/ECCO-GROUP/ECCOv4-py """ from __future__ import division, print_function import numpy as np import xarray as xr import datetime import time import xmitgcm as xm import dateutil import glob import os import sys import pyresample as pr import json from pathlib import Path import uuid import netCDF4 as nc4 from collections import OrderedDict import dask as dask from dask import delayed from .read_bin_llc import load_ecco_vars_from_mds from .ecco_utils import extract_yyyy_mm_dd_hh_mm_ss_from_datetime64 from .resample_to_latlon import resample_to_latlon #%% def sort_attrs(attrs): od = OrderedDict() keys = sorted(list(attrs.keys()),key=str.casefold) for k in keys: od[k] = attrs[k] return od #%% def create_native_grid_netcdf_files(mds_grid_dir, mds_var_dir, mds_filename, mds_freq_code, vars_to_load, dataset_name = 'by_variable', time_steps_to_load = 'all', tiles_to_load = 'all', output_array_precision = np.float32, global_metadata = 'default', coordinate_metadata = 'default', geometry_metadata = 'default', variable_metadata = 'default'): # if no specific file data passed, read default metadata from json file # -- variable specific meta data script_dir = Path(__file__).resolve().parent #if not meta_variable_specific: # meta_variable_rel_path = '../meta_json/ecco_meta_variable.json' # abs_meta_variable_path = os.path.join(script_dir, meta_variable_rel_path) # with open(abs_meta_variable_path, 'r') as fp: # meta_variable_specific = json.load(fp) ## METADATA metadata_json_dir = Path('/home/ifenty/git_repos_others/ECCO-GROUP/ECCO-ACCESS/metadata/ECCOv4r4_metadata_json') metadata_fields = ['ECCOv4_global_metadata_for_all_datasets', 'ECCOv4_global_metadata_for_latlon_datasets', 'ECCOv4_global_metadata_for_native_datasets', 'ECCOv4rcoordinate_metadata_for_native_datasets', 'ECCOv4r4_geometry_metadata_for_native_datasets', 'ECCOv4r4_variable_metadata'] print('\nLOADING METADATA') # load METADATA metadata = dict() for mf in metadata_fields: mf_e = mf + '.json' print(mf_e) with open(str(metadata_json_dir / mf_e), 'r') as fp: metadata[mf] = json.load(fp) # metadata for different variables global_metadata_for_all_datasets = metadata['ECCOv4r4_global_metadata_for_all_datasets'] global_metadata_for_latlon_datasets = metadata['ECCOv4r4_global_metadata_for_latlon_datasets'] global_metadata_for_native_datasets = metadata['ECCOv4r4_global_metadata_for_native_datasets'] coordinate_metadata_for_1D_datasets = metadata['ECCOv4r4_coordinate_metadata_for_1D_datasets'] coordinate_metadata_for_latlon_datasets = metadata['ECCOv4r4_coordinate_metadata_for_latlon_datasets'] coordinate_metadata_for_native_datasets = metadata['ECCOv4r4_coordinate_metadata_for_native_datasets'] geometry_metadata_for_latlon_datasets = metadata['ECCOv4r4_geometry_metadata_for_latlon_datasets'] geometry_metadata_for_native_datasets = metadata['ECCOv4r4_geometry_metadata_for_native_datasets'] groupings_for_1D_datasets = metadata['ECCOv4r4_groupings_for_1D_datasets'] groupings_for_latlon_datasets = metadata['ECCOv4r4_groupings_for_latlon_datasets'] groupings_for_native_datasets = metadata['ECCOv4r4_groupings_for_native_datasets'] variable_metadata_latlon = metadata['ECCOv4r4_variable_metadata_for_latlon_datasets'] variable_metadata = metadata['ECCOv4r4_variable_metadata'] global_metadata = global_metadata_for_all_datasets + global_metadata_for_native_datasets variable_metadata_combined = variable_metadata + geometry_metadata_for_native_datasets # #variable_metadata = variable_metadata + geometry_metadata_for_native_datasets short_mds_name = 'ETAN_mon_mean' output_freq_code= 'AVG_MON' cur_ts = 'all' vars_to_load = 'ETAN' #['ETAN'] F_DS = [] ecco_grid = load_ecco_vars_from_mds(str(mds_grid_dir), str(mds_grid_dir), '', vars_to_load = 'all', drop_unused_coords = False, grid_vars_to_coords = False, coordinate_metadata = coordinate_metadata_for_native_datasets, variable_metadata = geometry_metadata_for_native_datasets, global_metadata = global_metadata, less_output=False).load() F_DS = \ load_ecco_vars_from_mds(mds_var_dir,\ mds_grid_dir = mds_grid_dir, \ mds_files = short_mds_name,\ vars_to_load = vars_to_load, drop_unused_coords = True,\ grid_vars_to_coords = False,\ variable_metadata = variable_metadata_combined, coordinate_metadata = coordinate_metadata_for_native_datasets, #global_metadata = [[global_metadata]], output_freq_code=output_freq_code,\ model_time_steps_to_load=cur_ts, less_output = True) print(F_DS) # vars_to_drop = set(F_DS.data_vars).difference(set([var])) # F_DS.drop_vars(vars_to_drop) save_ecco_dataset_to_netcdf(F_DS.isel(time=[0]), Path('/home/ifenty/tmp/'), dataset_name = 'by_variable', time_method = 'by_year', output_freq_code='AVG_MON') #%%%%%%%%%%%%%%%%%%%% def save_ecco_dataset_to_netcdf(ecco_ds, output_dir, dataset_name = 'by_variable', time_method = 'by_record', output_array_precision = np.float32, output_freq_code=None): """Saves an ECCO dataset to one or more NetCDF files NetCDF files will be written with the following options ------------------------------------------------------- * compression level 5 * shuffle = True * zlib = True Parameters ---------- ecco_ds: xarray DataSet the DataSet to save. Can have one or more 'data variables' output_dir: String root directory for saved files. New files will be saved in a (new) subdirectory of output_dir dataset_name : String, optional. Default 'by_variable' name to use for NetCDF files. 'by_variable' will create a name based on the data variables present by concatenating all data variable names together separated by '_' For example, if ecco_ds has both 'ETAN' and 'SSH' the dataset_name will be 'ETAN_SSH' time_method : String, optional. Default 'by_record' options include 'by_record' - one file per time level 'by_year' - one file per calendar year output_array_precision : numpy type. Default np.float32 precision to use when saving data variables of type float options include np.float32 np.float64 output_freq_code: String, optional. Default = None a string code indicating the time level of averaging of the data variables options include 'AVG_MON' - monthly-averaged file 'AVG_DAY' - daily-averaged files 'SNAP' - snapshot files (instantaneous) RETURNS: ---------- nothing. files should be saved to disk """ # Create a name of the files if not specified # --------------------------------------------- if dataset_name =='by_variable': # concat all data variables together into a single string dataset_name = '_'.join(list(ecco_ds.data_vars)) # force load coordinate values in case they are in dask array # ----------------------------------------------------------- for coord in ecco_ds.coords: ecco_ds[coord].load() # Define fill values for NaN # --------------------------------------------- if output_array_precision == np.float32: netcdf_fill_value = nc4.default_fillvals['f4'] elif output_array_precision == np.float64: netcdf_fill_value = nc4.default_fillvals['f8'] # Create NetCDF encoding directives # --------------------------------------------- print('\n... creating variable encodings') # ... data variable encoding directives dv_encoding = dict() for dv in ecco_ds.data_vars: dv_encoding[dv] = {'zlib':True, \ 'complevel':5,\ 'shuffle':True,\ '_FillValue':netcdf_fill_value} # ... coordinate encoding directives print('\n... creating coordinate encodings') coord_encoding = dict() for coord in ecco_ds.coords: # set default no fill value for coordinate if output_array_precision == np.float32: coord_encoding[coord] = {'_FillValue':None, 'dtype':'float32'} elif output_array_precision == np.float64: coord_encoding[coord] = {'_FillValue':None, 'dtype':'float64'} # force 64 bit ints to be 32 bit ints if (ecco_ds[coord].values.dtype == np.int32) or \ (ecco_ds[coord].values.dtype == np.int64) : coord_encoding[coord]['dtype'] ='int32' # fix encoding of time if coord == 'time' or coord == 'time_bnds': coord_encoding[coord]['dtype'] ='int32' if 'units' in ecco_ds[coord].attrs: # apply units as encoding for time coord_encoding[coord]['units'] = ecco_ds[coord].attrs['units'] # delete from the attributes list del ecco_ds[coord].attrs['units'] elif coord == 'time_step': coord_encoding[coord]['dtype'] ='int32' # ... combined data variable and coordinate encoding directives encoding = {**dv_encoding, **coord_encoding} # Create directory for output files # --------------------------------------------- filepath = output_dir / dataset_name if not filepath.exists(): filepath.mkdir(parents=True, exist_ok=True) # Determine output freqency code. # --------------------------------------------- # user can specify directory or it can be found if the dataset # has the 'time_coverage_resolution' global attribute if output_freq_code == None: if 'time_coverage_resolution' in ecco_ds.attrs: print('dataset time averaging from metadata') time_coverage_resolution = ecco_ds.attrs['time_coverage_resolution'] if time_coverage_resolution == 'P1M': output_freq_code='AVG_MON' elif time_coverage_resolution == 'P1D': output_freq_code='AVG_DAY' elif time_coverage_resolution == 'P0S': output_freq_code='SNAP' else: print('output_freq_code not defined and not available in dataset metadata') print('... using full record time in filename') # Write records to disk as NetCDF # --------------------------------------------- # one file per time level if time_method == 'by_record': for time_i, rec_time in enumerate(ecco_ds.time): cur_ds = ecco_ds.isel(time=time_i) # cast data variables to desired precision (if necessary) #for data_var in cur_ds.data_vars: # if cur_ds[data_var].values.dtype != output_array_precision: # cur_ds[data_var].values = cur_ds[data_var].astype(output_array_precision) time_date_info =\ make_date_str_from_dt64(cur_ds.time.values, output_freq_code) # sort comments alphabetically print('\n... sorting global attributes') cur_ds.attrs = sort_attrs(cur_ds.attrs) # add one final comment (PODAAC request) cur_ds.attrs["coordinates_comment"] = \ "Note: the global 'coordinates' attribute descibes auxillary coordinates." fname = dataset_name + '_' + time_date_info['short'] +\ '_' + time_date_info['ppp_tttt'] + '.nc' print(fname) print(cur_ds) netcdf_output_filename = filepath / fname # SAVE print('\n... saving to netcdf ', netcdf_output_filename) cur_ds.to_netcdf(netcdf_output_filename, encoding=encoding) cur_ds.close() # one file per year elif time_method == 'by_year': unique_years = np.unique(ecco_ds.time.dt.year) print(unique_years) for year in unique_years: # pull out only records for this year cur_ds = ecco_ds.sel(time=slice(str(year), str(year))) first_time = cur_ds.time.values[0] last_time = cur_ds.time.values[-1] first_time_date_info =\ make_date_str_from_dt64(first_time, output_freq_code) last_time_date_info =\ make_date_str_from_dt64(last_time, output_freq_code) # sort comments alphabetically print('\n... sorting global attributes') cur_ds.attrs = sort_attrs(cur_ds.attrs) # add one final comment (PODAAC request) cur_ds.attrs["coordinates_comment"] = \ "Note: the global 'coordinates' attribute descibes auxillary coordinates." fname = dataset_name + '_' +\ first_time_date_info['short'] + '_' +\ last_time_date_info['short'] + '_' +\ first_time_date_info['ppp_tttt']+ '.nc' print(fname) print(cur_ds) netcdf_output_filename = filepath / fname # SAVE print('\n... saving to netcdf ', netcdf_output_filename) cur_ds.to_netcdf(netcdf_output_filename, encoding=encoding) cur_ds.close() #%%%% def make_date_str_from_dt64(dt64_time, output_freq_code): """Extracts components of a numpy date time 64 object Parameters ---------- dt_64_time: numpy.datetime64 a single datetime64 object output_freq_code: string a string code indicating the time level of averaging of the data variables options include 'AVG_MON' - monthly-averaged file 'AVG_DAY' - daily-averaged files 'SNAPSHOT' - snapshot files (instantaneous) RETURNS: ---------- a dictionary with the following string entries (all zero padded) date_str_full : YYYY-MM-DDTHHMMSS date_str_short : YYYY-MM (for AVG_MON) YYYY-MM-DD (for AVG_DAY) YYYY-MM-DDTHHMMSS (for SNAP) year : YYYY month : MM day : DD hour : HH ppp_tttt : one of 'mon_mean','day_mean','snap' """ print(dt64_time) date_str_full = str(dt64_time)[0:19].replace(':','') year = date_str_full[0:4] month = date_str_full[5:7] day = date_str_full[8:10] hour = date_str_full[11:13] print(year, month, day, hour) ppp_tttt = "" date_str_short ="" if output_freq_code == 'AVG_MON': date_str_short = str(np.datetime64(dt64_time,'M')) ppp_tttt = 'mon_mean' # --- AVG DAY elif output_freq_code == 'AVG_DAY': date_str_short = str(np.datetime64(dt64_time,'D')) ppp_tttt = 'day_mean' # --- SNAPSHOT elif 'SNAP' in output_freq_code: # convert from oroginal # '1992-01-16T12:00:00.000000000' # to new format # '1992-01-16T120000' date_str_short = str(dt64_time)[0:19].replace(':','') ppp_tttt = 'snap' date_str = dict() date_str['full'] = date_str_full date_str['short'] = date_str_short date_str['year'] = year date_str['month'] = month date_str['day'] = day date_str['hour']
# Copyright 2022 <NAME>, MIT license """ Module with all the definitions (routines) of general use of the multitaper routines. Contains: * set_xint - setup Ierly's quadrature * xint - Quadrature by Ierley's method of Chebychev sampling. * dpss_ev - Recalculate the DPSS eigenvalues using Quadrature * dpss - calculate the DPSS for given NW, NPTS * eigenspec - calculate eigenspectra using DPSS sequences. * adaptspec - calculate adaptively weighted power spectrum * jackspec - calculate adaptively weighted jackknifed 95% confidence limits * qiinv - calculate the Stationary Inverse Theory Spectrum. * ftest - performs the F-test for a line component * yk_reshape - reshape eigenft's around significant spectral lines * wt2dof - calculate the d.o.f. of the multitaper * df_spec - Dual frequency spectrum, using two MTSPEC classes to compute. * sft - the slow Fourier transform * squick - for sine multitaper, constructs average multitaper * squick2 - for sine multitaper, constructs average multitaper, 2 signals * sadapt - for sine multitaper, adaptive estimation of # of tapers * sadapt2 - for sine multitaper, same but for 2 signals * north - for sine multitaper, derivatives of spectrum * curb - for sine multitaper, clips # of tapers * get_data - download data and load into numpy array | """ #----------------------------------------------------- # Import main libraries and modules #----------------------------------------------------- import numpy as np import scipy from scipy import signal import scipy.linalg as linalg import scipy.interpolate as interp import scipy.optimize as optim import os #------------------------------------------------------------------------- # SET_XINT - Set up weights and sample points for Ierly quadrature #------------------------------------------------------------------------- def set_xint(ising): """ Sets up weights and sample points for Ierley quadrature, Slightly changed from original code, to avoid using common blocks. Also avoided using some go to statements, not needed. *Parameters* ising : integer ising=1 integrand is analytic in closed interval ising=2 integrand may have bounded singularities at end points *Returns* w : ndarray (nomx,lomx+1) weights x : sample points (lomx+1) sample points lomx=number of samples = 2**nomx *Modified* November 2004 (<NAME>) | """ nomx = 8 lomx = 256 w = np.zeros((nomx,lomx+1),dtype=float) x = np.zeros(lomx+1,dtype=float) pi = np.pi n = 2 for index in range(1,nomx+1): n = 2*n nx = n-2 if (index == 1): nx=4 pin = pi/float(n) nhalf = int(n/2) for i in range(nhalf+1): t = float(i)*pin si = 0.0 for k in range(0,nx+1,2): ck=4.0 if (k == 0): ck=2.0 rk=float(k) si=si+ck*np.cos(rk*t)/(1.0-rk*rk) if (i==0 or i==nhalf): si=0.5*si t = np.cos(t) if (ising == 2): t=0.5*pi*(1.0 +t) si=si*0.5 * np.sin(t)*pi t=np.cos(t) x[i] = 0.5 *(1.0 +t) w[index-1, i] = 0.5 *si/float(n) elif (ising == 1): x[i] = 0.5 *(1.0 +t) w[index-1,i] = 0.5 *si/float(n) # end i loop # end index loop return w, x #------------------------------------------------------------------------- # XINT - Numerical integration in the Fourier Domain using Ierly's method #------------------------------------------------------------------------- def xint(a,b,tol,vn,npts): """ Quadrature by Ierley's method of Chebychev sampling. *Parameters* a : float upper limit of integration b : float upper limit of integration tol : float tolerance for integration vn : ndarray taper or Slepian sequence to convert-integrate npts : int number of points of tapers *Notes* This is a slight variation of Gleen Ierly's code. What was mainly done, was to avoid use of common blocks, defining all variables and performing the numerical integration inside (previously done by function pssevf). Exponential convergence rate for analytic functions! Much faster than Romberg; competitive with Gauss integration, without awkward weights. Integrates the function dpsw on (a, b) to absolute accuracy tol > 0. the function in time is given by rpar with ipar points I removed the optional printing routine part of the code, to make it easier to read. I also moved both nval, etol as normal variables inside the routine. nval = number of function calls made by routine etol = approximate magnitude of the error of the result NB: function set_xint is called once before xint to provide quadrature samples and weights. I also altered the subroutine call, to get the weights and not save them in a common block, but get them directly back. lomx=number of samples = 2**nomx *Modified* November 2004 (<NAME>) *Calls* utils.set_xint | """ pi = np.pi tpi = 2.0 * pi nomx = 8 lomx = 256 ising = 1 w, x = set_xint(ising) #--------------------------- # Check tol #--------------------------- if (tol <= 0.0): raise ValueError("In xint tol must be > 0 ", tol) est = np.zeros(nomx,dtype=float) fv = np.zeros(lomx+1,dtype=float) n = 1 im = 2**(nomx+1) for index in range(1,nomx+1): n = 2*n im = int(im/2) im2 = int(im/2) if (index <= 1): for i in range(n+1): # Bottom y = a+(b-a)*x[im2*i] om = tpi*y ct, st = sft(vn,om) f1 = ct*ct+st*st # Top y = b-(b-a)*x[im2*i] om = tpi*y ct, st = sft(vn,om) f2 = ct*ct+st*st fv[im2*i] = f1 + f2 # end i loop, index 1, else: for i in range(1,n,2): # Bottom y = a+(b-a)*x[im2*i] om = tpi*y ct,st = sft(vn,om) f1 = ct*ct+st*st # Top y = b-(b-a)*x[im2*i] om = tpi*y ct, st = sft(vn,om) f2 = ct*ct+st*st fv[im2*i]= f1 + f2 # end i loop, index > 1 # end index 1, or more x_int = 0.00 for i in range(n+1): x_int = x_int + w[index-1, i]*fv[im2*i] x_int = x_int*(b-a) est[index-1] = x_int etol = 0.0 # # Check for convergence. # nval = 2*n if (index == 2): if ( est[index-1] == est[index-2] ): return x_int elif (index > 2): sq = (est[index-1]-est[index-2])**2 bot = (0.01*sq + np.abs(est[index-1]-est[index-2]) ) if (sq == 0.0): etol = 0.0 else: etol = sq/bot if (etol <= tol): return x_int # end check convergence # end index loop print('******** WARNING *********') print(' xint unable to provide requested accuracy') return x_int #------------------------------------------------------------------------- # end XINT #------------------------------------------------------------------------- #------------------------------------------------------------------------- # DPSS_EV - Eigenvalues of the DPSS sequences #------------------------------------------------------------------------- def dpss_ev(vn,w,atol=1e-14): """ Recalculate the DPSS eigenvalues, performing the integration in the -W:W range, using Quadrature. computes eigenvalues for the discrete prolate spheroidal sequences in efn by integration of the corresponding squared discrete prolate spheroidal wavefunctions over the inner domain. Due to symmetry, we perform integration from zero to w. We use Chebychev quadrature for the numerical integration. *Parameters* vn : ndarray [npts,kspec] DPSS to calculate eigenvalues w : float the bandwidth (= time-bandwidth product/ndata) atol : float, optional absolute error tolerance for the integration. this should be set to 10**-n, where n is the number of significant figures that can be be represented on the machine. default = 1e-14 *Returns* lamb : ndarray [kspec] vector of length vn.shape[1], contains the eigenvalues *Modified* November 2004 (<NAME>) *Calls* xint | """ npts = np.shape(vn)[0] kspec = np.shape(vn)[1] lamb = np.zeros(kspec) for k in range(kspec): result = xint(0.0,w,atol,vn[:,k],npts) lamb[k] = 2.0*result return lamb #------------------------------------------------------------------------- # end DPSS_EV #------------------------------------------------------------------------- def dpss(npts,nw,kspec=None): """ Calculation of the Discrete Prolate Spheroidal Sequences, and the correspondent eigenvalues. - <NAME>. 1978 Bell Sys Tech J v57 n5 1371-1430 - <NAME>. 1982 Proc IEEE v70 n9 1055-1096 **Parameters** npts : int the number of points in the series nw : float the time-bandwidth product (number of Rayleigh bins) kspec : int Optional, the desired number of tapers default = 2*nw-1 **Returns** v : ndarray (npts,kspec) the eigenvectors (tapers) are returned in v[npts,nev] lamb : ndarray (kspec) the eigenvalues of the v's **Notes** In SCIPY the codes are already available to calculate the DPSS. Eigenvalues are calculated using Chebeshev Quadrature. Code also performs interpolation if NPTS>1e5 Also, define DPSS to be positive-standard, meaning vn's always start positive, whether symmetric or not. **Modified** December 2020 February 2022 - Changed a for
<reponame>MPGek/client #!/usr/bin/env python """PyTorch-specific functionality """ from collections import namedtuple import itertools import weakref from six.moves import reduce from distutils.version import LooseVersion from operator import mul from wandb import util from wandb.data_types import Node, Edge import wandb torch = None def nested_shape(array_or_tuple, seen=None): """Figures out the shape of tensors possibly embedded in tuples i.e [0,0] returns (2) ([0,0], [0,0]) returns (2,2) (([0,0], [0,0]),[0,0]) returns ((2,2),2) """ if seen is None: seen = set() if hasattr(array_or_tuple, 'size'): # pytorch tensors use V.size() to get size of tensor return list(array_or_tuple.size()) elif hasattr(array_or_tuple, 'get_shape'): # tensorflow uses V.get_shape() to get size of tensor return array_or_tuple.get_shape().as_list() elif hasattr(array_or_tuple, 'shape'): return array_or_tuple.shape seen.add(id(array_or_tuple)) try: # treat object as iterable return [nested_shape(item, seen) if id(item) not in seen else 0 for item in list(array_or_tuple)] except TypeError: # object is not actually iterable # LB: Maybe we should throw an error? return [] LOG_TRACK_COUNT, LOG_TRACK_THRESHOLD = range(2) def log_track_init(log_freq): """create tracking structure used by log_track_update """ l = [0] * 2 l[LOG_TRACK_THRESHOLD] = log_freq return l def log_track_update(log_track): """count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached """ log_track[LOG_TRACK_COUNT] += 1 if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]: return False log_track[LOG_TRACK_COUNT] = 0 return True class TorchHistory(object): """History methods specific to PyTorch """ def __init__(self, history): global torch torch = wandb.util.get_module("torch", "Could not import torch") self._history = weakref.ref(history) self._hook_handles = {} self._num_bins = 64 self._is_cuda_histc_supported = None self._jupyter_run = None def add_log_hooks_to_pytorch_module(self, module, name=None, prefix='', log_parameters=True, log_gradients=True, log_freq=0, jupyter_run=None): """ This instuments hooks into the pytorch module log_parameters - log parameters after a forward pass log_gradients - log gradients after a backward pass log_freq - log gradients/parameters every N batches """ if name is not None: prefix = prefix + name if jupyter_run: self._jupyter_run = weakref.ref(jupyter_run) module._wandb_hook_names = [] if log_parameters: def parameter_log_hook(module, input_, output, log_track): if not log_track_update(log_track): return for name, parameter in module.named_parameters(): # for pytorch 0.3 Variables if isinstance(parameter, torch.autograd.Variable): data = parameter.data else: data = parameter self.log_tensor_stats( data.cpu(), 'parameters/' + prefix + name) log_track_params = log_track_init(log_freq) hook = module.register_forward_hook( lambda mod, inp, outp: parameter_log_hook(mod, inp, outp, log_track_params)) self._hook_handles['parameters/'+prefix] = hook module._wandb_hook_names.append('parameters/'+prefix) if log_gradients: for name, parameter in module.named_parameters(): if parameter.requires_grad: log_track_grad = log_track_init(log_freq) module._wandb_hook_names.append('gradients/' + prefix + name) self._hook_variable_gradient_stats( parameter, 'gradients/' + prefix + name, log_track_grad) def log_tensor_stats(self, tensor, name): """Add distribution statistics on a tensor's elements to the current History entry """ # TODO Handle the case of duplicate names. if (isinstance(tensor, tuple) or isinstance(tensor, list)): while (isinstance(tensor, tuple) or isinstance(tensor, list)) and (isinstance(tensor[0], tuple) or isinstance(tensor[0], list)): tensor = [item for sublist in tensor for item in sublist] tensor = torch.cat([t.view(-1) for t in tensor]) # checking for inheritance from _TensorBase didn't work for some reason if not hasattr(tensor, 'shape'): cls = type(tensor) raise TypeError('Expected Tensor, not {}.{}'.format( cls.__module__, cls.__name__)) history = self._history() # recover history from run if using jupyter if history is None and self._jupyter_run: jupyter_run = self._jupyter_run() if jupyter_run: history = jupyter_run.history if history is None or not history.compute: return # HalfTensors on cpu do not support view(), upconvert to 32bit if isinstance(tensor, torch.HalfTensor): tensor = tensor.clone().type(torch.FloatTensor).detach() # Sparse tensors have a bunch of implicit zeros. In order to histo them correctly, # we have to count them up and add them to the histo ourselves. sparse_zeros = None if tensor.is_sparse: # Have to call this on a sparse tensor before most other ops. tensor = tensor.cpu().coalesce().clone().detach() backing_values = tensor._values() non_zero_values = backing_values.numel() all_values = tensor.numel() sparse_zeros = all_values - non_zero_values tensor = backing_values flat = tensor.view(-1) # For pytorch 0.3 we use unoptimized numpy histograms (detach is new in 0.4) if not hasattr(flat, "detach"): tensor = flat.cpu().clone().numpy() history.row.update({ name: wandb.Histogram(tensor) }) return if flat.is_cuda: # TODO(jhr): see if pytorch will accept something upstream to check cuda support for ops # until then, we are going to have to catch a specific exception to check for histc support. if self._is_cuda_histc_supported is None: self._is_cuda_histc_supported = True check = torch.cuda.FloatTensor(1).fill_(0) try: check = flat.histc(bins=self._num_bins) except RuntimeError as e: # Only work around missing support with specific exception #if str(e).startswith("_th_histc is not implemented"): # self._is_cuda_histc_supported = False # On second thought, 0.4.1 doesnt have support and maybe there are other issues # lets disable more broadly for now self._is_cuda_histc_supported = False if not self._is_cuda_histc_supported: flat = flat.cpu().clone().detach() # As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32) if isinstance(flat, torch.cuda.HalfTensor): flat = flat.clone().type(torch.cuda.FloatTensor).detach() if isinstance(flat, torch.HalfTensor): flat = flat.clone().type(torch.FloatTensor).detach() tmin = flat.min().item() tmax = flat.max().item() if sparse_zeros: # If we've got zeros to add in, make sure zero is in the hist range. tmin = 0 if tmin > 0 else tmin tmax = 0 if tmax < 0 else tmax tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax) tensor = tensor.cpu().clone().detach() bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1) # Add back zeroes from a sparse tensor. if sparse_zeros: bins_np = bins.numpy() tensor_np = tensor.numpy() bin_idx = 0 num_buckets = len(bins_np) - 1 for i in range(num_buckets): start = bins_np[i] end = bins_np[i+1] # There are 3 cases to consider here, all of which mean we've found the right bucket # 1. The bucket range contains zero. # 2. The bucket range lower bound *is* zero. # 3. This is the last bucket and the bucket range upper bound is zero. if (start <= 0 and end > 0) or (i == num_buckets - 1 and end == 0): bin_idx = i break tensor_np[bin_idx] += sparse_zeros tensor = torch.Tensor(tensor_np) bins = torch.Tensor(bins_np) history.row.update({ name: wandb.Histogram(np_histogram=( tensor.tolist(), bins.tolist())) }) def _hook_variable_gradient_stats(self, var, name, log_track): """Logs a Variable's gradient's distribution statistics next time backward() is called on it. """ if not isinstance(var, torch.autograd.Variable): cls = type(var) raise TypeError('Expected torch.Variable, not {}.{}'.format( cls.__module__, cls.__name__)) handle = self._hook_handles.get(name) if handle is not None and self._torch_hook_handle_is_valid(handle): raise ValueError( 'A hook has already been set under name "{}"'.format(name)) def _callback(grad, log_track): if not log_track_update(log_track): return self.log_tensor_stats(grad.data, name) handle = var.register_hook(lambda grad: _callback(grad, log_track)) self._hook_handles[name] = handle return handle def unhook_all(self): for handle in self._hook_handles.values(): handle.remove() self._hook_handles = [] def unhook(self, name): handle = self._hook_handles.pop(name) handle.remove() def _torch_hook_handle_is_valid(self, handle): d = handle.hooks_dict_ref() if d is None: return False else: return handle.id in d class TorchGraph(wandb.data_types.Graph): def __init__(self): super(TorchGraph, self).__init__("torch") @classmethod def hook_torch(cls, model, criterion=None, graph_idx=0): graph = TorchGraph() graph.hook_torch_modules(model, criterion, graph_idx=graph_idx) return graph def create_forward_hook(self, name, modules): graph = self def after_forward_hook(module, input, output): if id(module) in modules: return modules.add(id(module)) if not isinstance(output, tuple): output = (output,) parameters = [(pname, list(param.size())) for pname, param in module.named_parameters()] node = Node( id=id(module), name=name, class_name=str(module), output_shape=nested_shape(output), parameters=parameters, num_parameters=[reduce(mul, size, 1) for (pname, size) in parameters] ) graph.nodes_by_id[id(module)] = node for param in module.parameters(): graph.nodes_by_id[id(param)] = node graph.add_node(node) if not graph.criterion_passed: if hasattr(output[0], 'grad_fn'): graph.criterion = output[0].grad_fn elif isinstance(output[0], list) and hasattr(output[0][0], 'grad_fn'): graph.criterion = output[0][0].grad_fn return after_forward_hook def hook_torch_modules(self, module, criterion=None, prefix=None, graph_idx=0): torch = util.get_module("torch", "Could not import torch") hooks = [] modules = set() layers = 0 graph = self if hasattr(module, "_wandb_watch_called") and module._wandb_watch_called: raise ValueError( "You can only call `wandb.watch` once per model. Pass a new instance of the model if you need to call wandb.watch again in your code.") module._wandb_watch_called = True if criterion: graph.criterion = criterion graph.criterion_passed = True for name, sub_module in module.named_children(): name = name or str(layers) if prefix: name = prefix + "." + name layers += 1 if not isinstance(sub_module, torch.nn.Module): # TODO: Why does this happen? break # Trying to support torch >0.3 making this code complicated # We want a list of types that we should recurse into # Torch 0.3 uses containers # 0.4 has ModuleList # 0.4.1 has ModuleDict module_types = [getattr(torch.nn, module_classname) for module_classname in ("Container", "Sequential", "ModuleList", "ModuleDict") if hasattr(torch.nn, module_classname)] if isinstance(sub_module, tuple(module_types)): self.hook_torch_modules(sub_module, prefix=name) else: def backward_hook(module, input, output): [hook.remove() for hook in hooks] graph.loaded = True if wandb.run: wandb.run.summary["graph_%i" % graph_idx] = graph else: wandb.termwarn( "wandb.watch
'66:40:92', '66:40:93', '66:40:94', '66:40:95', '66:40:96', '66:40:97', '66:40:98', '66:40:99', '66:41:00', '66:41:01', '66:41:02', '66:41:03', '66:41:04', '66:41:05', '66:41:06', '66:41:07', '66:41:08', '66:41:09', '66:41:10', '66:41:11', '66:41:12', '66:41:13', '66:41:14', '66:41:15', '66:41:16', '66:41:17', '66:41:18', '66:41:19', '66:41:20', '66:41:21', '66:41:22', '66:41:23', '66:41:24', '66:41:25', '66:41:26', '66:41:27', '66:41:28', '66:41:29', '66:41:30', '66:41:31', '66:41:32', '66:41:33', '66:41:34', '66:41:35', '66:41:36', '66:41:37', '66:41:38', '66:41:39', '66:41:40', '66:41:41', '66:41:42', '66:41:43', '66:41:44', '66:41:45', '66:41:46', '66:41:47', '66:41:48', '66:41:49', '66:41:50', '66:41:51', '66:41:52', '66:41:53', '66:41:54', '66:41:55', '66:41:56', '66:41:57', '66:41:58', '66:41:59', '66:41:60', '66:41:61', '66:41:62', '66:41:63', '66:41:64', '66:41:65', '66:41:66', '66:41:67', '66:41:68', '66:41:69', '66:41:70', '66:41:71', '66:41:72', '66:41:73', '66:41:74', '66:41:75', '66:41:76', '66:41:77', '66:41:78', '66:41:79', '66:41:80', '66:41:81', '66:41:82', '66:41:83', '66:41:84', '66:41:85', '66:41:86', '66:41:87', '66:41:88', '66:41:89', '66:41:90', '66:41:91', '66:41:92', '66:41:93', '66:41:94', '66:41:95', '66:41:96', '66:41:97', '66:41:98', '66:41:99', '66:42:00', '66:42:01', '66:42:02', '66:42:03', '66:42:04', '66:42:05', '66:42:06', '66:42:07', '66:42:08', '66:42:09', '66:42:10', '66:42:11', '66:42:12', '66:42:13', '66:42:14', '66:42:15', '66:42:16', '66:42:17', '66:42:18', '66:42:19', '66:42:20', '66:42:21', '66:42:22', '66:42:23', '66:42:24', '66:42:25', '66:42:26', '66:42:27', '66:42:28', '66:42:29', '66:42:30', '66:42:31', '66:42:32', '66:42:33', '66:42:34', '66:42:35', '66:42:36', '66:42:37', '66:42:38', '66:42:39', '66:42:40', '66:42:41', '66:42:42', '66:42:43', '66:42:44', '66:42:45', '66:42:46', '66:42:47', '66:42:48', '66:42:49', '66:42:50', '66:42:51', '66:42:52', '66:42:53', '66:42:54', '66:42:55', '66:42:56', '66:42:57', '66:42:58', '66:42:59', '66:42:60', '66:42:61', '66:42:62', '66:42:63', '66:42:64', '66:42:65', '66:42:66', '66:42:67', '66:42:68', '66:42:69', '66:42:70', '66:42:71', '66:42:72', '66:42:73', '66:42:74', '66:42:75', '66:42:76', '66:42:77', '66:42:78', '66:42:79', '66:42:80', '66:42:81', '66:42:82', '66:42:83', '66:42:84', '66:42:85', '66:42:86', '66:42:87', '66:42:88', '66:42:89', '66:42:90', '66:42:91', '66:42:92', '66:42:93', '66:42:94', '66:42:95', '66:42:96', '66:42:97', '66:42:98', '66:42:99', '66:43:00', '66:43:01', '66:43:02', '66:43:03', '66:43:04', '66:43:05', '66:43:06', '66:43:07', '66:43:08', '66:43:09', '66:43:10', '66:43:11', '66:43:12', '66:43:13', '66:43:14', '66:43:15', '66:43:16', '66:43:17', '66:43:18', '66:43:19', '66:43:20', '66:43:21', '66:43:22', '66:43:23', '66:43:24', '66:43:25', '66:43:26', '66:43:27', '66:43:28', '66:43:29', '66:43:30', '66:43:31', '66:43:32', '66:43:33', '66:43:34', '66:43:35', '66:43:36', '66:43:37', '66:43:38', '66:43:39', '66:43:40', '66:43:41', '66:43:42', '66:43:43', '66:43:44', '66:43:45', '66:43:46', '66:43:47', '66:43:48', '66:43:49', '66:43:50', '66:43:51', '66:43:52', '66:43:53', '66:43:54', '66:43:55', '66:43:56', '66:43:57', '66:43:58', '66:43:59', '66:43:60', '66:43:61', '66:43:62', '66:43:63', '66:43:64', '66:43:65', '66:43:66', '66:43:67', '66:43:68', '66:43:69', '66:43:70', '66:43:71', '66:43:72', '66:43:73', '66:43:74', '66:43:75', '66:43:76', '66:43:77', '66:43:78', '66:43:79', '66:43:80', '66:43:81', '66:43:82', '66:43:83', '66:43:84', '66:43:85', '66:43:86', '66:43:87', '66:43:88', '66:43:89', '66:43:90', '66:43:91', '66:43:92', '66:43:93', '66:43:94', '66:43:95', '66:43:96', '66:43:97', '66:43:98', '66:43:99', '66:44:00', '66:44:01', '66:44:02', '66:44:03', '66:44:04', '66:44:05', '66:44:06', '66:44:07', '66:44:08', '66:44:09', '66:44:10', '66:44:11', '66:44:12', '66:44:13', '66:44:14', '66:44:15', '66:44:16', '66:44:17', '66:44:18', '66:44:19', '66:44:20', '66:44:21', '66:44:22', '66:44:23', '66:44:24', '66:44:25', '66:44:26', '66:44:27', '66:44:28', '66:44:29', '66:44:30', '66:44:31', '66:44:32', '66:44:33', '66:44:34', '66:44:35', '66:44:36', '66:44:37', '66:44:38', '66:44:39', '66:44:40', '66:44:41', '66:44:42', '66:44:43', '66:44:44', '66:44:45', '66:44:46', '66:44:47', '66:44:48', '66:44:49', '66:44:50', '66:44:51', '66:44:52', '66:44:53', '66:44:54', '66:44:55', '66:44:56', '66:44:57', '66:44:58', '66:44:59', '66:44:60', '66:44:61', '66:44:62', '66:44:63', '66:44:64', '66:44:65', '66:44:66', '66:44:67', '66:44:68', '66:44:69', '66:44:70', '66:44:71', '66:44:72', '66:44:73', '66:44:74', '66:44:75', '66:44:76', '66:44:77', '66:44:78', '66:44:79', '66:44:80', '66:44:81', '66:44:82', '66:44:83', '66:44:84', '66:44:85', '66:44:86', '66:44:87', '66:44:88', '66:44:89', '66:44:90', '66:44:91', '66:44:92', '66:44:93', '66:44:94', '66:44:95', '66:44:96', '66:44:97', '66:44:98', '66:44:99', '66:45:00', '66:45:01', '66:45:02', '66:45:03', '66:45:04', '66:45:05', '66:45:06', '66:45:07', '66:45:08', '66:45:09', '66:45:10', '66:45:11', '66:45:12', '66:45:13', '66:45:14', '66:45:15', '66:45:16', '66:45:17', '66:45:18', '66:45:19', '66:45:20', '66:45:21', '66:45:22', '66:45:23', '66:45:24', '66:45:25', '66:45:26', '66:45:27', '66:45:28', '66:45:29', '66:45:30', '66:45:31', '66:45:32', '66:45:33', '66:45:34', '66:45:35', '66:45:36', '66:45:37', '66:45:38', '66:45:39', '66:45:40', '66:45:41', '66:45:42', '66:45:43', '66:45:44', '66:45:45', '66:45:46', '66:45:47', '66:45:48', '66:45:49', '66:45:50', '66:45:51', '66:45:52', '66:45:53', '66:45:54', '66:45:55', '66:45:56', '66:45:57', '66:45:58', '66:45:59', '66:45:60', '66:45:61', '66:45:62', '66:45:63', '66:45:64', '66:45:65', '66:45:66', '66:45:67', '66:45:68', '66:45:69', '66:45:70', '66:45:71', '66:45:72', '66:45:73', '66:45:74', '66:45:75', '66:45:76', '66:45:77', '66:45:78', '66:45:79', '66:45:80', '66:45:81', '66:45:82', '66:45:83', '66:45:84', '66:45:85', '66:45:86', '66:45:87', '66:45:88', '66:45:89', '66:45:90', '66:45:91', '66:45:92', '66:45:93', '66:45:94', '66:45:95', '66:45:96', '66:45:97', '66:45:98', '66:45:99', '66:46:00', '66:46:01', '66:46:02', '66:46:03', '66:46:04', '66:46:05', '66:46:06', '66:46:07', '66:46:08', '66:46:09', '66:46:10', '66:46:11', '66:46:12', '66:46:13', '66:46:14', '66:46:15', '66:46:16', '66:46:17', '66:46:18', '66:46:19', '66:46:20', '66:46:21', '66:46:22', '66:46:23', '66:46:24', '66:46:25', '66:46:26', '66:46:27', '66:46:28', '66:46:29', '66:46:30', '66:46:31', '66:46:32', '66:46:33', '66:46:34', '66:46:35', '66:46:36', '66:46:37', '66:46:38', '66:46:39', '66:46:40', '66:46:41', '66:46:42', '66:46:43', '66:46:44', '66:46:45', '66:46:46', '66:46:47', '66:46:48', '66:46:49', '66:46:50', '66:46:51', '66:46:52', '66:46:53', '66:46:54', '66:46:55', '66:46:56', '66:46:57', '66:46:58', '66:46:59', '66:46:60', '66:46:61', '66:46:62', '66:46:63', '66:46:64', '66:46:65', '66:46:66', '66:46:67', '66:46:68', '66:46:69', '66:46:70', '66:46:71', '66:46:72', '66:46:73', '66:46:74', '66:46:75', '66:46:76', '66:46:77', '66:46:78', '66:46:79', '66:46:80', '66:46:81', '66:46:82', '66:46:83', '66:46:84', '66:46:85', '66:46:86', '66:46:87', '66:46:88', '66:46:89', '66:46:90', '66:46:91', '66:46:92', '66:46:93', '66:46:94', '66:46:95', '66:46:96', '66:46:97', '66:46:98', '66:46:99', '66:47:00', '66:47:01', '66:47:02', '66:47:03', '66:47:04', '66:47:05', '66:47:06', '66:47:07', '66:47:08', '66:47:09', '66:47:10', '66:47:11', '66:47:12', '66:47:13', '66:47:14', '66:47:15', '66:47:16', '66:47:17', '66:47:18', '66:47:19', '66:47:20', '66:47:21', '66:47:22', '66:47:23', '66:47:24', '66:47:25', '66:47:26', '66:47:27', '66:47:28', '66:47:29', '66:47:30', '66:47:31', '66:47:32', '66:47:33', '66:47:34', '66:47:35', '66:47:36', '66:47:37', '66:47:38', '66:47:39', '66:47:40', '66:47:41', '66:47:42', '66:47:43', '66:47:44', '66:47:45', '66:47:46', '66:47:47', '66:47:48', '66:47:49', '66:47:50', '66:47:51', '66:47:52', '66:47:53', '66:47:54', '66:47:55', '66:47:56', '66:47:57', '66:47:58', '66:47:59', '66:47:60', '66:47:61', '66:47:62', '66:47:63', '66:47:64', '66:47:65', '66:47:66', '66:47:67', '66:47:68', '66:47:69', '66:47:70', '66:47:71', '66:47:72', '66:47:73', '66:47:74', '66:47:75', '66:47:76', '66:47:77', '66:47:78', '66:47:79', '66:47:80', '66:47:81', '66:47:82', '66:47:83', '66:47:84', '66:47:85', '66:47:86', '66:47:87', '66:47:88', '66:47:89', '66:47:90', '66:47:91', '66:47:92', '66:47:93', '66:47:94', '66:47:95', '66:47:96', '66:47:97', '66:47:98', '66:47:99', '66:48:00', '66:48:01', '66:48:02', '66:48:03', '66:48:04', '66:48:05', '66:48:06', '66:48:07', '66:48:08', '66:48:09', '66:48:10', '66:48:11', '66:48:12', '66:48:13', '66:48:14', '66:48:15', '66:48:16', '66:48:17', '66:48:18', '66:48:19', '66:48:20', '66:48:21', '66:48:22', '66:48:23', '66:48:24', '66:48:25', '66:48:26', '66:48:27', '66:48:28', '66:48:29', '66:48:30', '66:48:31', '66:48:32', '66:48:33', '66:48:34', '66:48:35', '66:48:36', '66:48:37', '66:48:38', '66:48:39', '66:48:40', '66:48:41', '66:48:42', '66:48:43', '66:48:44', '66:48:45', '66:48:46', '66:48:47', '66:48:48', '66:48:49', '66:48:50', '66:48:51', '66:48:52', '66:48:53', '66:48:54', '66:48:55', '66:48:56', '66:48:57', '66:48:58', '66:48:59', '66:48:60', '66:48:61', '66:48:62', '66:48:63', '66:48:64', '66:48:65', '66:48:66', '66:48:67', '66:48:68', '66:48:69', '66:48:70', '66:48:71', '66:48:72', '66:48:73', '66:48:74', '66:48:75', '66:48:76', '66:48:77', '66:48:78', '66:48:79', '66:48:80', '66:48:81', '66:48:82', '66:48:83', '66:48:84', '66:48:85', '66:48:86', '66:48:87', '66:48:88', '66:48:89', '66:48:90', '66:48:91', '66:48:92', '66:48:93', '66:48:94', '66:48:95', '66:48:96', '66:48:97', '66:48:98', '66:48:99', '66:49:00', '66:49:01', '66:49:02', '66:49:03', '66:49:04', '66:49:05', '66:49:06', '66:49:07', '66:49:08', '66:49:09', '66:49:10', '66:49:11', '66:49:12', '66:49:13', '66:49:14', '66:49:15', '66:49:16', '66:49:17', '66:49:18', '66:49:19', '66:49:20', '66:49:21', '66:49:22', '66:49:23', '66:49:24', '66:49:25', '66:49:26', '66:49:27', '66:49:28', '66:49:29', '66:49:30', '66:49:31', '66:49:32', '66:49:33', '66:49:34', '66:49:35', '66:49:36', '66:49:37', '66:49:38', '66:49:39', '66:49:40', '66:49:41', '66:49:42', '66:49:43', '66:49:44', '66:49:45', '66:49:46', '66:49:47', '66:49:48', '66:49:49', '66:49:50', '66:49:51', '66:49:52', '66:49:53', '66:49:54', '66:49:55', '66:49:56', '66:49:57', '66:49:58', '66:49:59', '66:49:60', '66:49:61', '66:49:62', '66:49:63', '66:49:64', '66:49:65', '66:49:66', '66:49:67', '66:49:68', '66:49:69', '66:49:70', '66:49:71', '66:49:72', '66:49:73', '66:49:74', '66:49:75', '66:49:76', '66:49:77', '66:49:78', '66:49:79', '66:49:80', '66:49:81', '66:49:82', '66:49:83', '66:49:84', '66:49:85', '66:49:86', '66:49:87', '66:49:88', '66:49:89', '66:49:90', '66:49:91', '66:49:92', '66:49:93', '66:49:94', '66:49:95', '66:49:96', '66:49:97', '66:49:98', '66:49:99', '66:50:00', '66:50:01', '66:50:02', '66:50:03', '66:50:04', '66:50:05', '66:50:06', '66:50:07', '66:50:08', '66:50:09', '66:50:10', '66:50:11', '66:50:12', '66:50:13', '66:50:14', '66:50:15', '66:50:16', '66:50:17', '66:50:18', '66:50:19', '66:50:20', '66:50:21', '66:50:22', '66:50:23', '66:50:24', '66:50:25', '66:50:26', '66:50:27', '66:50:28', '66:50:29', '66:50:30', '66:50:31', '66:50:32', '66:50:33', '66:50:34', '66:50:35', '66:50:36', '66:50:37', '66:50:38', '66:50:39', '66:50:40', '66:50:41', '66:50:42', '66:50:43', '66:50:44', '66:50:45', '66:50:46', '66:50:47', '66:50:48', '66:50:49', '66:50:50', '66:50:51', '66:50:52', '66:50:53', '66:50:54', '66:50:55', '66:50:56', '66:50:57', '66:50:58', '66:50:59', '66:50:60', '66:50:61', '66:50:62', '66:50:63', '66:50:64', '66:50:65', '66:50:66', '66:50:67', '66:50:68', '66:50:69', '66:50:70', '66:50:71', '66:50:72', '66:50:73', '66:50:74', '66:50:75', '66:50:76', '66:50:77', '66:50:78', '66:50:79', '66:50:80', '66:50:81', '66:50:82', '66:50:83', '66:50:84', '66:50:85', '66:50:86', '66:50:87', '66:50:88', '66:50:89', '66:50:90', '66:50:91', '66:50:92', '66:50:93', '66:50:94', '66:50:95', '66:50:96', '66:50:97', '66:50:98', '66:50:99', '66:51:00', '66:51:01', '66:51:02', '66:51:03', '66:51:04', '66:51:05', '66:51:06', '66:51:07', '66:51:08', '66:51:09', '66:51:10', '66:51:11', '66:51:12', '66:51:13', '66:51:14', '66:51:15', '66:51:16', '66:51:17', '66:51:18', '66:51:19', '66:51:20', '66:51:21', '66:51:22', '66:51:23', '66:51:24', '66:51:25', '66:51:26', '66:51:27', '66:51:28', '66:51:29', '66:51:30', '66:51:31', '66:51:32', '66:51:33', '66:51:34', '66:51:35', '66:51:36', '66:51:37', '66:51:38', '66:51:39', '66:51:40', '66:51:41', '66:51:42', '66:51:43', '66:51:44', '66:51:45', '66:51:46', '66:51:47', '66:51:48', '66:51:49', '66:51:50', '66:51:51', '66:51:52', '66:51:53', '66:51:54', '66:51:55', '66:51:56', '66:51:57', '66:51:58', '66:51:59', '66:51:60', '66:51:61', '66:51:62', '66:51:63', '66:51:64', '66:51:65', '66:51:66', '66:51:67', '66:51:68', '66:51:69', '66:51:70', '66:51:71', '66:51:72', '66:51:73', '66:51:74', '66:51:75', '66:51:76', '66:51:77', '66:51:78', '66:51:79', '66:51:80', '66:51:81', '66:51:82', '66:51:83', '66:51:84', '66:51:85', '66:51:86', '66:51:87', '66:51:88', '66:51:89', '66:51:90', '66:51:91', '66:51:92', '66:51:93', '66:51:94', '66:51:95', '66:51:96', '66:51:97', '66:51:98', '66:51:99', '66:52:00', '66:52:01', '66:52:02', '66:52:03', '66:52:04', '66:52:05', '66:52:06', '66:52:07', '66:52:08', '66:52:09', '66:52:10', '66:52:11', '66:52:12', '66:52:13', '66:52:14', '66:52:15', '66:52:16', '66:52:17', '66:52:18', '66:52:19', '66:52:20', '66:52:21', '66:52:22', '66:52:23', '66:52:24', '66:52:25', '66:52:26', '66:52:27', '66:52:28', '66:52:29', '66:52:30', '66:52:31', '66:52:32', '66:52:33', '66:52:34', '66:52:35', '66:52:36', '66:52:37', '66:52:38', '66:52:39', '66:52:40', '66:52:41', '66:52:42', '66:52:43', '66:52:44', '66:52:45', '66:52:46', '66:52:47', '66:52:48', '66:52:49', '66:52:50', '66:52:51', '66:52:52', '66:52:53', '66:52:54', '66:52:55', '66:52:56', '66:52:57', '66:52:58', '66:52:59', '66:52:60', '66:52:61', '66:52:62', '66:52:63', '66:52:64', '66:52:65', '66:52:66', '66:52:67', '66:52:68', '66:52:69', '66:52:70', '66:52:71', '66:52:72', '66:52:73', '66:52:74', '66:52:75', '66:52:76', '66:52:77', '66:52:78', '66:52:79', '66:52:80', '66:52:81', '66:52:82', '66:52:83', '66:52:84', '66:52:85', '66:52:86', '66:52:87', '66:52:88', '66:52:89', '66:52:90', '66:52:91', '66:52:92', '66:52:93', '66:52:94', '66:52:95', '66:52:96', '66:52:97', '66:52:98', '66:52:99', '66:53:00', '66:53:01', '66:53:02', '66:53:03', '66:53:04', '66:53:05', '66:53:06', '66:53:07', '66:53:08', '66:53:09', '66:53:10', '66:53:11', '66:53:12', '66:53:13', '66:53:14', '66:53:15', '66:53:16', '66:53:17', '66:53:18', '66:53:19', '66:53:20', '66:53:21', '66:53:22', '66:53:23', '66:53:24', '66:53:25', '66:53:26', '66:53:27', '66:53:28', '66:53:29', '66:53:30', '66:53:31', '66:53:32', '66:53:33', '66:53:34', '66:53:35', '66:53:36', '66:53:37', '66:53:38', '66:53:39', '66:53:40', '66:53:41', '66:53:42', '66:53:43', '66:53:44', '66:53:45', '66:53:46', '66:53:47', '66:53:48', '66:53:49', '66:53:50', '66:53:51', '66:53:52', '66:53:53', '66:53:54', '66:53:55', '66:53:56', '66:53:57', '66:53:58', '66:53:59', '66:53:60', '66:53:61', '66:53:62', '66:53:63', '66:53:64', '66:53:65', '66:53:66', '66:53:67', '66:53:68', '66:53:69', '66:53:70', '66:53:71',
<gh_stars>10-100 import SimpleITK as sitk import sitkUtils import os import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging import numpy as np import string # # SkyscanReconImport # class SkyscanReconImport(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "SkyscanReconImport" # TODO make this more human readable by adding spaces self.parent.categories = ["SlicerMorph.Input and Output"] self.parent.dependencies = [] self.parent.contributors = ["<NAME> (UW), <NAME> (UW)"] # replace with "Firstname Lastname (Organization)" self.parent.helpText = """ This module imports an image sequence from Bruker Skyscan microCT's into Slicer as a scalar 3D volume with correct image spacing. Accepted formats are TIF, PNG, JPG and BMP. User needs to be point out to the *_Rec.log file found in the reconstruction folder. """ self.parent.helpText += self.getDefaultModuleDocumentationLink() self.parent.acknowledgementText = """ This module was developed by <NAME> and <NAME> for SlicerMorph. SlicerMorph was originally supported by an NSF/DBI grant, "An Integrated Platform for Retrieval, Visualization and Analysis of 3D Morphology From Digital Biological Collections" awarded to <NAME> (1759883), <NAME> (1759637), and <NAME> (1759839). https://nsf.gov/awardsearch/showAward?AWD_ID=1759883&HistoricalAwards=false """ # replace with organization, grant and thanks. # # SkyscanReconImportWidget # class SkyscanReconImportWidget(ScriptedLoadableModuleWidget): """Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setup(self): ScriptedLoadableModuleWidget.setup(self) # Instantiate and connect widgets ... # # Parameters Area # parametersCollapsibleButton = ctk.ctkCollapsibleButton() parametersCollapsibleButton.text = "Parameters" self.layout.addWidget(parametersCollapsibleButton) # Layout within the dummy collapsible button parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton) # # input selector # # File dialog to select a file template for series self.inputFileSelector = ctk.ctkPathLineEdit() self.inputFileSelector.filters = ctk.ctkPathLineEdit().Files self.inputFileSelector.setToolTip( "Select log file from a directory of images." ) parametersFormLayout.addRow("Select log file from image series:", self.inputFileSelector) # # output volume selector # # self.outputSelector = slicer.qMRMLNodeComboBox() # self.outputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"] # self.outputSelector.selectNodeUponCreation = True # self.outputSelector.addEnabled = True # self.outputSelector.removeEnabled = True # self.outputSelector.noneEnabled = True # self.outputSelector.showHidden = False # self.outputSelector.showChildNodeTypes = False # self.outputSelector.renameEnabled = True # self.outputSelector.setMRMLScene( slicer.mrmlScene ) # self.outputSelector.setToolTip( "Pick the output to the algorithm." ) # parametersFormLayout.addRow("Output Volume: ", self.outputSelector) # # check box to trigger taking screen shots for later use in tutorials # self.enableScreenshotsFlagCheckBox = qt.QCheckBox() self.enableScreenshotsFlagCheckBox.checked = 0 self.enableScreenshotsFlagCheckBox.setToolTip("If checked, take screen shots for tutorials. Use Save Data to write them to disk.") parametersFormLayout.addRow("Enable Screenshots", self.enableScreenshotsFlagCheckBox) # # Apply Button # self.applyButton = qt.QPushButton("Apply") self.applyButton.toolTip = "Run the algorithm." self.applyButton.enabled = False parametersFormLayout.addRow(self.applyButton) # connections self.applyButton.connect('clicked(bool)', self.onApplyButton) #self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect) self.inputFileSelector.connect("currentPathChanged(const QString &)", self.onSelect) # Add vertical spacer self.layout.addStretch(1) # Refresh Apply button state self.onSelect() def cleanup(self): pass def onSelect(self): self.applyButton.enabled = bool(self.inputFileSelector.currentPath) def onApplyButton(self): logic = SkyscanReconImportLogic() enableScreenshotsFlag = self.enableScreenshotsFlagCheckBox.checked logic.run(self.inputFileSelector.currentPath, enableScreenshotsFlag) class LogDataObject: """This class i """ def __init__(self): self.FileType = "NULL" self.X = "NULL" self.Y = "NULL" self.Z = "NULL" self.Resolution = "NULL" self.Prefix = "NULL" self.IndexLength = "NULL" self.SequenceStart = "NULL" self.SequenceEnd = "NULL" def ImportFromFile(self, LogFilename): lines = [] #Declare an empty list to read file into with open (LogFilename, 'rt') as in_file: for line in in_file: lines.append(line.strip("\n")) # add that line list, get rid of line endings for element in lines: # For each element in list if(element.find("Result File Type=")>=0): self.FileType = element.split('=', 1)[1].lower() #get standard lowercase print(self.FileType) print(element.split('=', 1)[1]) if(element.find("Result Image Width (pixels)=")>=0): self.X = int(element.split('=', 1)[1]) if(element.find("Result Image Height (pixels)=")>=0): self.Y = int(element.split('=', 1)[1]) if(element.find("Sections Count=")>=0): self.Z = int(element.split('=', 1)[1]) if(element.find("Pixel Size (um)=")>=0): self.Resolution = float(element.split('=', 1)[1])/1000 #convert from um to mm if(element.find("Filename Prefix=")>=0): self.Prefix = element.split('=', 1)[1] if(element.find("Filename Index Length=")>=0): self.IndexLength = element.split('=', 1)[1] if(element.find("First Section=")>=0): self.SequenceStart = element.split('=', 1)[1] if(element.find("Last Section=")>=0): self.SequenceEnd = element.split('=', 1)[1] self.SequenceStart=self.SequenceStart.zfill(int(self.IndexLength)) #pad with zeros to index length self.SequenceEnd=self.SequenceEnd.zfill(int(self.IndexLength)) #pad with zeros to index length def VerifyParameters(self): for attr, value in self.__dict__.items(): if(str(value) == "NULL"): logging.debug("Read Failed: Please check log format") logging.debug(attr,value) return False return True # # SkyscanReconImportLogic # class SkyscanReconImportLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoadableModuleLogic base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def hasImageData(self,volumeNode): """This is an example logic method that returns true if the passed in volume node has valid image data """ if not volumeNode: logging.debug('hasImageData failed: no volume node') return False if volumeNode.GetImageData() is None: logging.debug('hasImageData failed: no image data in volume node') return False return True def isValidInputOutputData(self, inputVolumeNode, outputVolumeNode): """Validates if the output is not the same as input """ if not inputVolumeNode: logging.debug('isValidInputOutputData failed: no input volume node defined') return False if not outputVolumeNode: logging.debug('isValidInputOutputData failed: no output volume node defined') return False if inputVolumeNode.GetID()==outputVolumeNode.GetID(): logging.debug('isValidInputOutputData failed: input and output volume is the same. Create a new volume for output to avoid this error.') return False return True def isValidImageFileType(self, extension): """Checks for extensions from valid image types """ if not extension in ('tif', 'bmp', 'jpg', 'png', 'tiff', 'jpeg'): logging.debug('isValidImageFileType failed: not a supported image type') return False return True def takeScreenshot(self,name,description,type=-1): # show the message even if not taking a screen shot slicer.util.delayDisplay('Take screenshot: '+description+'.\nResult is available in the Annotations module.', 3000) lm = slicer.app.layoutManager() # switch on the type to get the requested window widget = 0 if type == slicer.qMRMLScreenShotDialog.FullLayout: # full layout widget = lm.viewport() elif type == slicer.qMRMLScreenShotDialog.ThreeD: # just the 3D window widget = lm.threeDWidget(0).threeDView() elif type == slicer.qMRMLScreenShotDialog.Red: # red slice window widget = lm.sliceWidget("Red") elif type == slicer.qMRMLScreenShotDialog.Yellow: # yellow slice window widget = lm.sliceWidget("Yellow") elif type == slicer.qMRMLScreenShotDialog.Green: # green slice window widget = lm.sliceWidget("Green") else: # default to using the full window widget = slicer.util.mainWindow() # reset the type so that the node is set correctly type = slicer.qMRMLScreenShotDialog.FullLayout # grab and convert to vtk image data qimage = ctk.ctkWidgetsUtils.grabWidget(widget) imageData = vtk.vtkImageData() slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData) annotationLogic = slicer.modules.annotations.logic() annotationLogic.CreateSnapShot(name, description, type, 1, imageData) def applySkyscanTransform(self, volumeNode): #set up transform node transformNode = slicer.vtkMRMLTransformNode() slicer.mrmlScene.AddNode(transformNode) volumeNode.SetAndObserveTransformNodeID(transformNode.GetID()) #set up Skyscan transform transformMatrixNp = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) transformMatrixVTK = vtk.vtkMatrix4x4() for row in range(4): for col in range(4): transformMatrixVTK.SetElement(row, col, transformMatrixNp[row,col]) transformNode.SetMatrixTransformToParent(transformMatrixVTK) #harden and clean up slicer.vtkSlicerTransformLogic().hardenTransform(volumeNode) slicer.mrmlScene.RemoveNode(transformNode) def run(self, inputFile, enableScreenshots=0): """ Run the actual algorithm """ #parse logfile logging.info('Processing started') imageLogFile = LogDataObject() #initialize log object imageLogFile.ImportFromFile(inputFile) #import image parameters of log object if not(imageLogFile.VerifyParameters()): #check that all parameters were set logging.info('Failed: Log file parameters not set') return False if not(self.isValidImageFileType(imageLogFile.FileType)): #check for valid file type logging.info('Failed: Invalid image type') logging.info(imageLogFile.FileType) return False # read image (inputDirectory,logPath) = os.path.split(inputFile) imageFileTemplate = os.path.join(inputDirectory, imageLogFile.Prefix + imageLogFile.SequenceStart + "." + imageLogFile.FileType) readVolumeNode = slicer.util.loadVolume(imageFileTemplate) #calculate image spacing spacing = [imageLogFile.Resolution, imageLogFile.Resolution, imageLogFile.Resolution] # if vector image, convert to scalar using luminance (0.30*R + 0.59*G + 0.11*B + 0.0*A) #check if loaded volume is vector type, if so convert to scalar if readVolumeNode.GetClassName() =='vtkMRMLVectorVolumeNode': scalarVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLScalarVolumeNode', imageLogFile.Prefix) ijkToRAS = vtk.vtkMatrix4x4() readVolumeNode.GetIJKToRASMatrix(ijkToRAS) scalarVolumeNode.SetIJKToRASMatrix(ijkToRAS) scalarVolumeNode.SetSpacing(spacing) extractVTK = vtk.vtkImageExtractComponents() extractVTK.SetInputConnection(readVolumeNode.GetImageDataConnection()) extractVTK.SetComponents(0, 1, 2) luminance = vtk.vtkImageLuminance() luminance.SetInputConnection(extractVTK.GetOutputPort()) luminance.Update() scalarVolumeNode.SetImageDataConnection(luminance.GetOutputPort()) # apply slicer.mrmlScene.RemoveNode(readVolumeNode) else: scalarVolumeNode = readVolumeNode scalarVolumeNode.SetSpacing(spacing) scalarVolumeNode.SetName(imageLogFile.Prefix) self.applySkyscanTransform(scalarVolumeNode) slicer.util.resetSliceViews() #update the field of view # Capture screenshot if enableScreenshots: self.takeScreenshot('SkyscanReconImportTest-Start','MyScreenshot',-1) logging.info('Processing completed') return True class SkyscanReconImportTest(ScriptedLoadableModuleTest): """ This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0) def runTest(self): """Run as few or as many tests as needed here. """ self.setUp() self.test_SkyscanReconImport1() def test_SkyscanReconImport1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on,
cls( cpu=Resources.parse_cpu(payload.get("cpu", "0")), memory=Resources.parse_memory(payload.get("memory", "0Mi")), gpu=int(payload.get(cls.gpu_key, 0)), ) @property def any(self) -> bool: return self.cpu_mcores > 0 or self.memory > 0 or self.gpu > 0 @property def cpu_mcores(self) -> int: return int(self.cpu * 1000) def are_sufficient(self, pod: PodDescriptor) -> bool: r = pod.resources if not r: return True return ( self.cpu_mcores >= r.cpu_mcores and self.memory >= r.memory and self.gpu >= (r.gpu or 0) ) def __add__(self, other: "NodeResources") -> "NodeResources": return self.__class__( cpu=self.cpu + other.cpu, memory=self.memory + other.memory, gpu=self.gpu + other.gpu, ) def __sub__(self, other: "NodeResources") -> "NodeResources": return self.__class__( cpu=self.cpu - other.cpu, memory=self.memory - other.memory, gpu=self.gpu - other.gpu, ) def __str__(self) -> str: return f"cpu={self.cpu_mcores}m, memory={self.memory}Mi, gpu={self.gpu}" class NodeConditionType(enum.Enum): UNKNOWN = "Unknown" DISK_PRESSURE = "DiskPressure" MEMORY_PRESSURE = "MemoryPressure" NETWORK_UNAVAILABLE = "NetworkUnavailable" PID_PRESSURE = "PIDPressure" READY = "Ready" @classmethod def parse(cls, value: str) -> "NodeConditionType": try: return cls(value) except (KeyError, ValueError): return cls.UNKNOWN @dataclass(frozen=True) class NodeCondition: type: NodeConditionType status: Optional[bool] transition_time: datetime message: str = "" reason: str = "" @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "NodeCondition": return cls( type=NodeConditionType.parse(payload["type"]), status=cls._parse_status(payload["status"]), message=payload.get("message", ""), reason=payload.get("reason", ""), transition_time=iso8601.parse_date(payload["lastTransitionTime"]), ) @classmethod def _parse_status(cls, value: str) -> Optional[bool]: if value == "Unknown": return None elif value == "True": return True elif value == "False": return False raise ValueError(f"Invalid status {value!r}") @dataclass(frozen=True) class NodeStatus: allocatable_resources: NodeResources conditions: list[NodeCondition] = field(default_factory=list) @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "NodeStatus": return cls( allocatable_resources=NodeResources.from_primitive(payload["allocatable"]), conditions=[ NodeCondition.from_primitive(p) for p in payload.get("conditions", ()) ], ) @property def is_ready(self) -> bool: for cond in self.conditions: if cond.type == NodeConditionType.READY: return bool(cond.status) return False @dataclass(frozen=True) class Node: name: str status: NodeStatus = field(compare=False) labels: dict[str, str] = field(default_factory=dict, compare=False) @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "Node": metadata = payload["metadata"] return cls( name=metadata["name"], labels=metadata.get("labels", {}), status=NodeStatus.from_primitive(payload["status"]), ) def get_free_resources(self, resource_requests: NodeResources) -> NodeResources: return self.status.allocatable_resources - resource_requests @dataclass(frozen=True) class ListResult: resource_version: str items: list[dict[str, Any]] @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "ListResult": return cls( resource_version=payload["metadata"]["resourceVersion"], items=payload["items"], ) class WatchEventType(str, Enum): ADDED = "ADDED" MODIFIED = "MODIFIED" DELETED = "DELETED" ERROR = "ERROR" @dataclass(frozen=True) class WatchBookmarkEvent: resource_version: str @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "WatchBookmarkEvent": return cls( resource_version=payload["object"]["metadata"]["resourceVersion"], ) @classmethod def is_bookmark(cls, payload: dict[str, Any]) -> bool: return "BOOKMARK" == payload["type"].upper() @dataclass(frozen=True) class WatchEvent: type: WatchEventType resource: dict[str, Any] @classmethod def from_primitive(cls, payload: dict[str, Any]) -> "WatchEvent": return cls(type=WatchEventType(payload["type"]), resource=payload["object"]) @classmethod def is_error(cls, payload: dict[str, Any]) -> bool: return WatchEventType.ERROR == payload["type"].upper() @classmethod def create_added(cls, resource: dict[str, Any]) -> "WatchEvent": return cls(type=WatchEventType.ADDED, resource=resource) @classmethod def create_modified(cls, resource: dict[str, Any]) -> "WatchEvent": return cls(type=WatchEventType.MODIFIED, resource=resource) @classmethod def create_deleted(cls, resource: dict[str, Any]) -> "WatchEvent": return cls(type=WatchEventType.DELETED, resource=resource) class KubeClient: def __init__( self, *, base_url: str, namespace: str, cert_authority_path: Optional[str] = None, cert_authority_data_pem: Optional[str] = None, auth_type: KubeClientAuthType = KubeClientAuthType.CERTIFICATE, auth_cert_path: Optional[str] = None, auth_cert_key_path: Optional[str] = None, token: Optional[str] = None, token_path: Optional[str] = None, conn_timeout_s: int = 300, read_timeout_s: int = 100, conn_pool_size: int = 100, trace_configs: Optional[list[aiohttp.TraceConfig]] = None, ) -> None: self._base_url = base_url self._namespace = namespace self._api_resources: APIResources = APIResources() self._cert_authority_data_pem = cert_authority_data_pem self._cert_authority_path = cert_authority_path self._auth_type = auth_type self._auth_cert_path = auth_cert_path self._auth_cert_key_path = auth_cert_key_path self._token = token self._token_path = token_path self._conn_timeout_s = conn_timeout_s self._read_timeout_s = read_timeout_s self._conn_pool_size = conn_pool_size self._trace_configs = trace_configs self._client: Optional[aiohttp.ClientSession] = None self._kubelet_port = 10255 @property def _is_ssl(self) -> bool: return urlsplit(self._base_url).scheme == "https" def _create_ssl_context(self) -> Optional[ssl.SSLContext]: if not self._is_ssl: return None ssl_context = ssl.create_default_context( cafile=self._cert_authority_path, cadata=self._cert_authority_data_pem ) if self._auth_type == KubeClientAuthType.CERTIFICATE: ssl_context.load_cert_chain( self._auth_cert_path, # type: ignore self._auth_cert_key_path, ) return ssl_context async def init(self) -> None: if self._client: return connector = aiohttp.TCPConnector( limit=self._conn_pool_size, ssl=self._create_ssl_context() ) if self._auth_type == KubeClientAuthType.TOKEN: token = self._token if not token: assert self._token_path is not None token = Path(self._token_path).read_text() headers = {"Authorization": "Bearer " + token} else: headers = {} timeout = aiohttp.ClientTimeout( connect=self._conn_timeout_s, total=self._read_timeout_s ) self._client = aiohttp.ClientSession( connector=connector, timeout=timeout, headers=headers, trace_configs=self._trace_configs, ) async def init_api_resources(self) -> None: assert self._client for gv in APIResources.group_versions: try: self._api_resources[gv] = await self.get_api_resource(gv) except aiohttp.ClientResponseError as ex: if ex.status != 404: raise async def close(self) -> None: if self._client: await self._client.close() self._client = None async def __aenter__(self) -> "KubeClient": await self.init() await self.init_api_resources() return self async def __aexit__(self, *args: Any) -> None: await self.close() @property def _api_v1_url(self) -> str: return f"{self._base_url}/api/v1" @property def _apis_networking_v1_url(self) -> str: return f"{self._base_url}/apis/networking.k8s.io/v1" def _generate_namespace_url(self, namespace_name: str) -> str: return f"{self._api_v1_url}/namespaces/{namespace_name}" @property def _namespace_url(self) -> str: return self._generate_namespace_url(self._namespace) @property def _pods_url(self) -> str: return f"{self._namespace_url}/pods" @property def _all_pods_url(self) -> str: return f"{self._api_v1_url}/pods" def _generate_pod_url(self, pod_id: str) -> str: return f"{self._pods_url}/{pod_id}" def _generate_pods_url(self, all_namespaces: bool = False) -> str: return self._all_pods_url if all_namespaces else self._pods_url def _generate_all_network_policies_url( self, namespace_name: Optional[str] = None ) -> str: namespace_name = namespace_name or self._namespace namespace_url = f"{self._apis_networking_v1_url}/namespaces/{namespace_name}" return f"{namespace_url}/networkpolicies" def _generate_network_policy_url( self, name: str, namespace_name: Optional[str] = None ) -> str: all_nps_url = self._generate_all_network_policies_url(namespace_name) return f"{all_nps_url}/{name}" def _generate_endpoint_url(self, name: str, namespace: str) -> str: return f"{self._generate_namespace_url(namespace)}/endpoints/{name}" @property def _nodes_url(self) -> str: return f"{self._api_v1_url}/nodes" def _generate_node_url(self, name: str) -> str: return f"{self._nodes_url}/{name}" @property def _networking_v1beta1_namespace_url(self) -> str: return ( f"{self._base_url}/apis/networking.k8s.io/v1beta1" f"/namespaces/{self._namespace}" ) @property def _networking_v1_namespace_url(self) -> str: return ( f"{self._base_url}/apis/networking.k8s.io/v1" f"/namespaces/{self._namespace}" ) @property def _ingresses_url(self) -> str: if self._api_resources.has_networking_v1_ingress: return f"{self._networking_v1_namespace_url}/ingresses" return f"{self._networking_v1beta1_namespace_url}/ingresses" def _generate_ingress_url(self, ingress_name: str) -> str: return f"{self._ingresses_url}/{ingress_name}" @property def _services_url(self) -> str: return f"{self._namespace_url}/services" def _generate_service_url(self, service_name: str) -> str: return f"{self._services_url}/{service_name}" def _generate_pod_log_url(self, pod_name: str, container_name: str) -> str: return ( f"{self._generate_pod_url(pod_name)}/log" f"?container={pod_name}&follow=true" ) def _generate_all_secrets_url(self, namespace_name: Optional[str] = None) -> str: namespace_name = namespace_name or self._namespace namespace_url = self._generate_namespace_url(namespace_name) return f"{namespace_url}/secrets" def _generate_all_pvcs_url(self, namespace_name: Optional[str] = None) -> str: namespace_name = namespace_name or self._namespace namespace_url = self._generate_namespace_url(namespace_name) return f"{namespace_url}/persistentvolumeclaims" def _generate_secret_url( self, secret_name: str, namespace_name: Optional[str] = None ) -> str: all_secrets_url = self._generate_all_secrets_url(namespace_name) return f"{all_secrets_url}/{secret_name}" def _generate_pvc_url( self, pvc_name: str, namespace_name: Optional[str] = None ) -> str: all_pvcs_url = self._generate_all_pvcs_url(namespace_name) return f"{all_pvcs_url}/{pvc_name}" async def _request(self, *args: Any, **kwargs: Any) -> dict[str, Any]: assert self._client async with self._client.request(*args, **kwargs) as response: # TODO (A Danshyn 05/21/18): check status code etc payload = await response.json() logging.debug("k8s response payload: %s", payload) return payload async def _watch( self, url: str, params: Optional[dict[str, str]] = None, resource_version: Optional[str] = None, ) -> AsyncIterator[Union[WatchEvent, WatchBookmarkEvent]]: params = params or {} params.update(watch="true", allowWatchBookmarks="true") if resource_version: params["resourceVersion"] = resource_version assert self._client async with self._client.get( url, params=params, timeout=aiohttp.ClientTimeout() ) as response: if response.status == 410: raise ResourceGoneException async for line in response.content: payload = json.loads(line) if WatchEvent.is_error(payload): self._check_status_payload(payload["object"]) if WatchBookmarkEvent.is_bookmark(payload): yield WatchBookmarkEvent.from_primitive(payload) else: yield WatchEvent.from_primitive(payload) async def get_api_resource(self, group_version: str) -> APIResource: url = f"{self._base_url}/apis/{group_version}" payload = await self._request(method="GET", url=url, raise_for_status=True) return APIResource.from_primitive(payload) async def _delete_resource_url(self, url: str, uid: Optional[str] = None) -> None: request_payload = None if uid: request_payload = {"preconditions": {"uid": uid}} payload = await self._request(method="DELETE", url=url, json=request_payload) if ( uid and payload["kind"] == "Status" and payload["status"] == "Failure" and payload["reason"] == "Conflict" ): raise NotFoundException(payload["reason"]) self._check_status_payload(payload) async def get_endpoint( self, name: str, namespace: Optional[str] = None ) -> dict[str, Any]: url = self._generate_endpoint_url(name, namespace or self._namespace) return await self._request(method="GET", url=url) async def create_node( self, name: str, capacity: dict[str, Any], labels: Optional[dict[str, str]] = None, taints: Optional[Sequence[NodeTaint]] = None, ) -> None: taints = taints or [] payload = { "apiVersion": "v1", "kind": "Node", "metadata": {"name": name, "labels": labels or {}}, "spec": {"taints": [taint.to_primitive() for taint in taints]}, "status": { # TODO (ajuszkowski, 29-0-2019) add enum for capacity "capacity": capacity, "conditions": [{"status": "True", "type": "Ready"}], }, } url = self._nodes_url result = await self._request(method="POST", url=url, json=payload) self._check_status_payload(result) async def delete_node(self, name: str) -> None: url = self._generate_node_url(name) await self._delete_resource_url(url) async def get_nodes(self) -> Sequence[Node]: payload = await self._request(method="GET", url=self._nodes_url) self._check_status_payload(payload) assert payload["kind"] == "NodeList" pods = [] for item in payload["items"]: pods.append(Node.from_primitive(item)) return pods async def get_node(self, name: str) -> Node: payload = await self._request(method="GET", url=self._generate_node_url(name)) self._check_status_payload(payload) assert payload["kind"] == "Node" return Node.from_primitive(payload) async def get_raw_nodes( self, labels: Optional[dict[str, str]] = None ) -> ListResult: params: dict[str, str] = {} if labels: params["labelSelector"] = ",".join( "=".join(item) for
# Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Go to Upload File and check upload file with size zero bytes result = CanonizerUploadFilePage(self.driver).click_upload_file_page_button().upload_file_with_size_zero_bytes( FILE_WITH_ZERO_BYTES, "testpngfile" ) self.assertIn("Error! The file must be at least 1 kilobytes.", result) # TC_UPLOAD_FILE_16 def test_verify_recent_upload_file_name_from_list_of_files(self): print("\n" + str(test_cases("TC_UPLOAD_FILE_16"))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Go to Upload File and check upload file with size zero bytes result = CanonizerUploadFilePage(self.driver).click_upload_file_page_button().verify_recent_upload_file_name_from_list_of_files( RECENT_FILE, "testrecentfileone" ) self.assertIn("upload", result.get_url()) # TC_UPLOAD_FILE_17 def test_verify_uploaded_image_file_format(self): print("\n" + str(test_cases("TC_UPLOAD_FILE_16"))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Go to Upload File and check upload file with size zero bytes result = CanonizerUploadFilePage( self.driver).click_upload_file_page_button().verify_uploaded_image_file_format( OTHER_FILE_TYPE, "textfileone" ) self.assertIn("upload", result.get_url()) # ----- File Upload Test Cases End ----- # ----- Search Test Cases Start ----- # 147 def test_click_search_button(self): print("\n" + str(test_cases(146))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() result = CanonizerSearchPage(self.driver).click_search_button() self.assertIn("", result.get_url()) # 148 def test_click_search_button_web(self): print("\n" + str(test_cases(147))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() result = CanonizerSearchPage(self.driver).click_search_button_web() self.assertIn("", result.get_url()) # 149 def test_click_search_button_keyword_web(self): print("\n" + str(test_cases(148))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() result = CanonizerSearchPage(self.driver).click_search_button_keyword_web('Testing') self.assertIn("", result.get_url()) # 150 def test_click_search_button_keyword_canonizer_com(self): print("\n" + str(test_cases(149))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() result = CanonizerSearchPage(self.driver).click_search_button_keyword_canonizer_com('Testing') self.assertIn("", result.get_url()) # ----- Search Test Cases End ----- # 151 def test_verify_phone_number_with_blank_phone_number(self): print("\n" + str(test_cases(150))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the username->Account Settings->Manage Profile Info sub tab CanonizerAccountSettingsPage( self.driver).click_username_link_button().click_account_settings_page_button().click_account_settings_manage_profile_info_page_button() result = AccountSettingsManageProfileInfoPage(self.driver).verify_phone_number_with_blank_phone_number() self.assertIn("Phone number is required.", result) # 152 def test_select_by_value_crypto_currency_ethereum(self): print("\n" + str(test_cases(151))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Browse link self.assertIn("/browse", CanonizerBrowsePage( self.driver).click_browse_page_button().select_dropdown_value().select_by_value_crypto_currency_ethereum().get_url()) # 153 def test_select_by_value_crypto_currency_ethereum_only_my_topics(self): print("\n" + str(test_cases(152))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Browse link self.assertIn("/browse", CanonizerBrowsePage( self.driver).select_by_value_crypto_currency_ethereum_only_my_topics().get_url()) # 154 def test_check_Canonizer_is_the_final_word_on_everything_page_loaded(self): print("\n" + str(test_cases(153))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Help and click on Canonizer is the final word on everything CanonizerHelpPage( self.driver).check_what_is_canonizer_help_page_loaded().check_Canonizer_is_the_final_word_on_everything_page_loaded().open( "https://vimeo.com/307590745") # 155 def test_check_Canonizer_is_the_final_word_on_everything_page_loaded_without_login(self): print("\n" + str(test_cases(154))) # Click on the Help and Click on Canonizer is the final word on everything CanonizerHelpPage( self.driver).check_what_is_canonizer_help_page_loaded().check_Canonizer_is_the_final_word_on_everything_page_loaded().open( "https://vimeo.com/307590745") # 156 def test_check_consensus_out_of_controversy_use_case_page_loaded(self): print("\n" + str(test_cases(155))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Help and click on Consensus out of controversy use case CanonizerHelpPage( self.driver).check_what_is_canonizer_help_page_loaded().check_consensus_out_of_controversy_use_case_page_loaded().open( "topic/132-Consensus-out-of-controversy/2") # 157 def test_check_consensus_out_of_controversy_use_case_page_loaded_without_login(self): print("\n" + str(test_cases(156))) # Click on the Help and Click on Consensus out of controversy use case CanonizerHelpPage( self.driver).check_what_is_canonizer_help_page_loaded().check_consensus_out_of_controversy_use_case_page_loaded().open( "topic/132-Consensus-out-of-controversy/2") # 158 def test_load_create_new_camp_page(self): # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() print("\n" + str(test_cases(157))) self.assertIn("camp/create/173-Software-Testing/1-Agreement", CanonizerCampPage(self.driver).load_create_new_camp_page().get_url()) # 159 def test_save_with_invalid_new_password(self): print("\n" + str(test_cases(158))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the username->Account Settings->Change Password sub tab CanonizerAccountSettingsPage( self.driver).click_username_link_button().click_account_settings_page_button().click_account_settings_change_password_page_button() result = CanonizerAccountSettingsChangePasswordPage(self.driver).save_with_invalid_new_password( '<PASSWORD>', '<PASSWORD>', '<PASSWORD>') self.assertIn( "Password must be at least 8 characters, including at least one digit, one lower case letter and one special character(@,# !,$..)", result) # 160 def test_login_with_blank_email(self): print("\n" + str(test_cases(159))) result = CanonizerLoginPage(self.driver).click_login_page_button().login_with_blank_email(DEFAULT_PASS) self.assertIn("The Email/Phone Number field is required.", result) # 161 def test_login_with_blank_password(self): print("\n" + str(test_cases(160))) result = CanonizerLoginPage(self.driver).click_login_page_button().login_with_blank_password( DEFAULT_USER) self.assertIn("The password is required.", result) # 162 def test_login_page_mandatory_fields_are_marked_with_asterisk(self): print("\n" + str(test_cases(161))) self.assertTrue(CanonizerLoginPage( self.driver).click_login_page_button().login_page_mandatory_fields_are_marked_with_asterisk()) # 163 def test_login_should_have_forgot_password_link(self): print("\n" + str(test_cases(162))) self.assertIn('login', CanonizerLoginPage( self.driver).click_login_page_button().login_should_have_forgot_password_link().get_url()) # 164 def test_registration_with_duplicate_email(self): print("\n" + str(test_cases(163))) result = CanonizerRegisterPage(self.driver).click_register_button().registration_with_duplicate_email( DEFAULT_FIRST_NAME, DEFAULT_MIDDLE_NAME, DEFAULT_LAST_NAME, DEFAULT_USER, DEFAULT_PASS, DEFAULT_PASS, '') self.assertIn("The email has already been taken.", result) # 165 def test_check_topic_page_from_my_supports_loaded(self): print("\n" + str(test_cases(164))) # Click on Account Settings->My Supports->Topic name self.login_to_canonizer_app() # Click on the Account Settings->My Supports->Topic name link CanonizerAccountSettingsPage( self.driver).click_username_link_button().click_account_settings_page_button().click_account_settings_my_supports_page_button() result = AccountSettingsMySupportsPage(self.driver).check_topic_page_from_my_supports_loaded() self.assertIn("topic/631-Verify-Single-Support-Camp-4/1-Agreement", result.get_url()) # 166 def test_check_camp_page_from_my_supports_loaded(self): print("\n" + str(test_cases(165))) # Click on Account Settings->My Supports->Topic name self.login_to_canonizer_app() # Click on the Account Settings->My Supports->Camp name link CanonizerAccountSettingsPage( self.driver).click_username_link_button().click_account_settings_page_button().click_account_settings_my_supports_page_button() result = AccountSettingsMySupportsPage(self.driver).check_camp_page_from_my_supports_loaded() self.assertIn("topic/631-Verify-Single-Support-Camp-4/1-Agreement", result.get_url()) # 167 def test_submit_update_with_blank_topic_name(self): print("\n" + str(test_cases(166))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Topic update and check if topic name is blank result = CanonizerTopicUpdatePage(self.driver).load_topic_update_page().submit_update_with_blank_topic_name( "Test", "", "") self.assertIn("manage/topic/", result.get_url()) # 168 def test_submit_topic_update_with_duplicate_topic_name(self): print("\n" + str(test_cases(167))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Topic update and check if topic name is duplicate result = CanonizerTopicUpdatePage( self.driver).load_topic_update_page().submit_topic_update_with_duplicate_topic_name( "", DUPLICATE_TOPIC_NAME, "", "") self.assertIn("manage/topic/", result.get_url()) # 169 def test_create_camp_with_duplicate_camp_name(self): print("\n" + str(test_cases(168))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link and check if camp name is duplicate result = CanonizerCampPage(self.driver).load_create_camp_page().create_camp_with_duplicate_camp_name( "", "", DUPLICATE_CAMP_NAME, "", "", "", "") self.assertIn("camp/create", result.get_url()) # 170 def test_submit_camp_update_with_duplicate_camp_name(self): print("\n" + str(test_cases(169))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Manage/Edit This Camp link and check if camp name is duplicate result = CanonizerEditCampPage(self.driver).load_camp_update_page().submit_camp_update_with_duplicate_camp_name( "", "", DUPLICATE_CAMP_NAME, "", "", "", "") self.assertIn("manage/camp", result) # 171 def test_edit_news_page_mandatory_fields_are_marked_with_asterisk(self): print("\n" + str(test_cases(170))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Edit News link result = CanonizerEditNewsFeedsPage(self.driver).load_edit_news_feed_page() if result: self.assertTrue( CanonizerEditNewsFeedsPage(self.driver).edit_news_page_mandatory_fields_are_marked_with_asterisk()) # ----- Add Camp Statement Test Cases Start ----- # 172 def test_load_add_camp_statement_page(self): # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() print("\n" + str(test_cases(171))) result = AddCampStatementPage(self.driver).load_add_camp_statement_page() self.assertIn("create/statement/", result.get_url()) # 173 def test_add_camp_statement_page_mandatory_fields_are_marked_with_asterisk(self): print("\n" + str(test_cases(172))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue( AddCampStatementPage(self.driver).add_camp_statement_page_mandatory_fields_are_marked_with_asterisk()) # TC_ADD_CAMP_STATEMENT_01 def test_add_camp_statement_page_without_mandatory_fields(self): print("\n" + str(test_cases('TC_ADD_CAMP_STATEMENT_01'))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue("The statement field is required.", AddCampStatementPage(self.driver).add_camp_statement_page_without_mandatory_fields(" ")) # TC_ADD_CAMP_STATEMENT_02 def test_add_camp_statement_page_mandatory_fields_only(self): print("\n" + str(test_cases('TC_ADD_CAMP_STATEMENT_02'))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue("Success! Statement submitted successfully.", AddCampStatementPage(self.driver).add_camp_statement_page_mandatory_fields_only( "Test statement")) # TC_ADD_CAMP_STATEMENT_03 def test_add_camp_statement_page_valid_data(self): print("\n" + str(test_cases('TC_ADD_CAMP_STATEMENT_03'))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue("Success! Statement submitted successfully.", AddCampStatementPage(self.driver).add_camp_statement_page_valid_data( "Test statement", "Testing for note")) # TC_ADD_CAMP_STATEMENT_04 def test_add_camp_statement_page_valid_data_with_enter_key(self): print("\n" + str(test_cases('TC_ADD_CAMP_STATEMENT_04'))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue("Success! Statement submitted successfully.", AddCampStatementPage(self.driver).add_camp_statement_page_valid_data_with_enter_key( "Test statement with Enter Key", "Testing for note 11111")) # TC_ADD_CAMP_STATEMENT_05 def test_add_camp_statement_page_data_with_trailing_spaces(self): print("\n" + str(test_cases('TC_ADD_CAMP_STATEMENT_05'))) # Click on the Login Page and Create a Login Session and for further actions. self.login_to_canonizer_app() # Click on the Create New camp link result = AddCampStatementPage(self.driver).load_add_camp_statement_page() if result: self.assertTrue("Success! Statement submitted successfully.", AddCampStatementPage(self.driver).add_camp_statement_page_data_with_trailing_spaces( " Test statement Trailing spaces", " Testing for with trailing spaces")) # 174 def test_submit_statement_with_blank_nick_name(self): print("\n" + str(test_cases(173))) # Click on the Login Page
M[:,task+3]-errM[:,task+3], M[:,task+3]+errM[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Dot task: VTC') plt.subplot(2,3,5) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+1]-errM1[:,task+1], M1[:,task+1]+errM1[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+3]-errM1[:,task+3], M1[:,task+3]+errM1[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,6) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+1]-errM2[:,task+1], M2[:,task+1]+errM2[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+3]-errM2[:,task+3], M2[:,task+3]+errM2[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') #%% temp1 = X11[vtc_vertices_l,:,:,:] s_group = good_readers for iSub in np.arange(0,len(s_group)): plt.figure(100+iSub) plt.clf() plt.subplot(1,2,1) plt.hold(True) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],0],axis=0), '-', color=c_table[5]) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],1],axis=0), '-', color=c_table[3]) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],3],axis=0), '-', color=c_table[1]) ## plt.plot([0.1, 0.1],[0, 8],'-',color='k') plt.title(subs[s_group[iSub]]) plt.subplot(1,2,2) plt.hold(True) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],5],axis=0), '-', color=c_table[5]) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],6],axis=0), '-', color=c_table[3]) plt.plot(times, np.mean(temp1[:,:,s_group[iSub],8],axis=0), '-', color=c_table[1]) # plt.plot([0.1, 0.1],[0, 8],'-',color='k') plt.title(subs[s_group[iSub]]) #%% """ Correlation """ X11 = X13[w_vertices,:,:,:] mask = np.logical_and(times >= 0.22, times <= 0.26) #dot_task = np.mean(X11[:,:,:,0],axis=0) dot_task = np.mean(X11[:,mask,:,:],axis=0) sts_response = np.mean(dot_task[:,:,0],axis=0) - np.mean(dot_task[:,:,3],axis=0) #sts_response = np.mean(temp[mask,:],axis=0) #plt.figure(20) #plt.clf() #ax = plt.subplot() #ax.scatter(wid_ss[all_subject], sts_response[all_subject], s=30, c='k', alpha=0.5) #for i, txt in enumerate(all_subject): # ax.annotate(subs[txt], (wid_ss[txt], sts_response[txt])) # #np.corrcoef(sts_response[all_subject],wid_ss[all_subject]) plt.figure(20) plt.clf() ax = plt.subplot() ax.scatter(twre[all_subject], sts_response[all_subject], s=30, c='k', alpha=0.5) for i, txt in enumerate(all_subject): ax.annotate(subs[txt], (twre[txt], sts_response[txt])) np.corrcoef(sts_response[all_subject],twre[all_subject]) stats.pearsonr(sts_response[all_subject],twre[all_subject]) stats.ttest_ind(sts_response[good_readers],sts_response[poor_readers]) #sns.regplot( #%% """ V1 responses """ task = 5 plt.figure(5) plt.clf() M = np.mean(np.mean(X11[v1_vertices_l,:,:,:],axis=0),axis=1) errM = np.std(np.mean(X11[v1_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(all_subject)) temp1 = X11[:,:,good_readers,:] M1 = np.mean(np.mean(temp1[v1_vertices_l,:,:,:],axis=0),axis=1) errM1 = np.std(np.mean(temp1[v1_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(good_readers)) del temp1 temp2 = X11[:,:,poor_readers,:] M2 = np.mean(np.mean(temp2[v1_vertices_l,:,:,:],axis=0),axis=1) errM2 = np.std(np.mean(temp2[v1_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) del temp2 plt.subplot(2,3,1) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+1]-errM[:,task+1], M[:,task+1]+errM[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+3]-errM[:,task+3], M[:,task+3]+errM[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Lexical task: V1') plt.subplot(2,3,2) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+1]-errM1[:,task+1], M1[:,task+1]+errM1[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+3]-errM1[:,task+3], M1[:,task+3]+errM1[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,3) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+1]-errM2[:,task+1], M2[:,task+1]+errM2[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+3]-errM2[:,task+3], M2[:,task+3]+errM2[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Poor Readers') task = 0 plt.subplot(2,3,4) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+1]-errM[:,task+1], M[:,task+1]+errM[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+3]-errM[:,task+3], M[:,task+3]+errM[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Dot task: V1') plt.subplot(2,3,5) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+1]-errM1[:,task+1], M1[:,task+1]+errM1[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+3]-errM1[:,task+3], M1[:,task+3]+errM1[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,6) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+1]-errM2[:,task+1], M2[:,task+1]+errM2[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+3]-errM2[:,task+3], M2[:,task+3]+errM2[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([0, 7]) plt.title('Poor Readers') #%% plt.figure(6) plt.clf() task = 5 plt.subplot(2,3,1) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+2]-errM[:,task+2], M[:,task+2]+errM[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+4]-errM[:,task+4], M[:,task+4]+errM[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Lexical task: VTC') plt.subplot(2,3,2) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+2]-errM1[:,task+2], M1[:,task+2]+errM1[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+4]-errM1[:,task+4], M1[:,task+4]+errM1[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,3) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+2]-errM2[:,task+2], M2[:,task+2]+errM2[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+4]-errM2[:,task+4], M2[:,task+4]+errM2[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') task = 0 plt.subplot(2,3,4) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+2]-errM[:,task+2], M[:,task+2]+errM[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+4]-errM[:,task+4], M[:,task+4]+errM[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Dot task: VTC') plt.subplot(2,3,5) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+2]-errM1[:,task+2], M1[:,task+2]+errM1[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+4]-errM1[:,task+4], M1[:,task+4]+errM1[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,6) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+2],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+2]-errM2[:,task+2], M2[:,task+2]+errM2[:,task+2], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+4],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+4]-errM2[:,task+4], M2[:,task+4]+errM2[:,task+4], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') #%% """ For FLUX """ plt.figure(400) plt.clf() cond = 5 X11 = X13[ventral_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.hold(True) plt.plot(times, M2[:,cond],'-',linewidth=3,color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,cond]-errM2[:,cond], M2[:,cond]+errM2[:,cond], facecolor=c_table[5], alpha=0.2, edgecolor='none') #plt.plot(times, M[:,6],'-',linewidth=3,color=c_table[3],label='Med noise') #plt.fill_between(times, M[:,6]-errM[:,6], M[:,6]+errM[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,cond+3],'--',linewidth=3,color=c_table[3],label='High noise') plt.fill_between(times, M2[:,cond+3]-errM2[:,cond+3], M2[:,cond+3]+errM2[:,cond+3], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-2, 3.5]) plt.xlim([-0.1,0.7]) plt.yticks([-2,-1,0,1,2,3]) #plt.title('Lexical task: VWFA') plt.savefig('Lexical_ventral_bottomtop_poor.pdf') #%% for iSub in np.arange(0,len(poor_readers)): plt.figure(100+iSub) plt.clf() plt.subplot(1,2,1) plt.hold(True) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],0],axis=0), '-', color=c_table[5]) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],1],axis=0), '-', color=c_table[3]) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],3],axis=0), '-', color=c_table[1]) ## plt.plot([0.1, 0.1],[0, 8],'-',color='k') plt.title(subs[poor_readers[iSub]]) plt.subplot(1,2,2) plt.hold(True) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],5],axis=0), '-', color=c_table[5]) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],6],axis=0), '-', color=c_table[3]) plt.plot(times, np.mean(X11[:,:,poor_readers[iSub],8],axis=0), '-', color=c_table[1]) # plt.plot([0.1, 0.1],[0, 8],'-',color='k') plt.title(subs[poor_readers[iSub]]) #%% """ Broca """ task = 5 plt.figure(3) plt.clf() M = np.mean(np.mean(X11[broca_vertices_l,:,:,:],axis=0),axis=1) errM = np.std(np.mean(X11[broca_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(all_subject)) temp1 = X11[:,:,good_readers,:] M1 = np.mean(np.mean(temp1[broca_vertices_l,:,:,:],axis=0),axis=1) errM1 = np.std(np.mean(temp1[broca_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(good_readers)) del temp1 temp2 = X11[:,:,poor_readers,:] M2 = np.mean(np.mean(temp2[broca_vertices_l,:,:,:],axis=0),axis=1) errM2 = np.std(np.mean(temp2[broca_vertices_l,:,:,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) del temp2 plt.subplot(2,3,1) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+1]-errM[:,task+1], M[:,task+1]+errM[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+3]-errM[:,task+3], M[:,task+3]+errM[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Lexical task: STS') plt.subplot(2,3,2) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+1]-errM1[:,task+1], M1[:,task+1]+errM1[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+3]-errM1[:,task+3], M1[:,task+3]+errM1[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,3) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+1]-errM2[:,task+1], M2[:,task+1]+errM2[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+3]-errM2[:,task+3], M2[:,task+3]+errM2[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') task = 0 plt.subplot(2,3,4) plt.hold(True) plt.plot(times, M[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,task]-errM[:,task], M[:,task]+errM[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,task+1]-errM[:,task+1], M[:,task+1]+errM[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,task+3]-errM[:,task+3], M[:,task+3]+errM[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Dot task: STS') plt.subplot(2,3,5) plt.hold(True) plt.plot(times, M1[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,task]-errM1[:,task], M1[:,task]+errM1[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,task+1]-errM1[:,task+1], M1[:,task+1]+errM1[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,task+3]-errM1[:,task+3], M1[:,task+3]+errM1[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') #plt.legend(loc='upper right') plt.subplot(2,3,6) plt.hold(True) plt.plot(times, M2[:,task],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,task]-errM2[:,task], M2[:,task]+errM2[:,task], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,task+1]-errM2[:,task+1], M2[:,task+1]+errM2[:,task+1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,task+3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,task+3]-errM2[:,task+3], M2[:,task+3]+errM2[:,task+3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') #%% """ Lexical task: All subjects """ plt.figure(4) plt.clf() X11 = np.abs(X13[ventral_vertices,:,:,:]) M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,1) plt.hold(True) plt.plot(times, M[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,5]-errM[:,5], M[:,5]+errM[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,6]-errM[:,6], M[:,6]+errM[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,8]-errM[:,8], M[:,8]+errM[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Lexical task: VWFA') plt.subplot(3,3,2) plt.hold(True) plt.plot(times, M1[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,5]-errM1[:,5], M1[:,5]+errM1[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,6]-errM1[:,6], M1[:,6]+errM1[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,8]-errM1[:,8], M1[:,8]+errM1[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Good Readers') plt.subplot(3,3,3) plt.hold(True) plt.plot(times, M2[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,5]-errM2[:,5], M2[:,5]+errM2[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,6]-errM2[:,6], M2[:,6]+errM2[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,8]-errM2[:,8], M2[:,8]+errM2[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 5]) plt.title('Poor Readers') X11 = X13[pt_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,4) plt.hold(True) plt.plot(times, M[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,5]-errM[:,5], M[:,5]+errM[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,6]-errM[:,6], M[:,6]+errM[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,8]-errM[:,8], M[:,8]+errM[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Lexical task: Frontal') plt.subplot(3,3,5) plt.hold(True) plt.plot(times, M1[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,5]-errM1[:,5], M1[:,5]+errM1[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,6]-errM1[:,6], M1[:,6]+errM1[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,8]-errM1[:,8], M1[:,8]+errM1[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Good Readers') plt.subplot(3,3,6) plt.hold(True) plt.plot(times, M2[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,5]-errM2[:,5], M2[:,5]+errM2[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,6]-errM2[:,6], M2[:,6]+errM2[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,8]-errM2[:,8], M2[:,8]+errM2[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Poor Readers') X11 = X13[w_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,good_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,poor_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,7) plt.hold(True) plt.plot(times, M[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,5]-errM[:,5], M[:,5]+errM[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,6]-errM[:,6], M[:,6]+errM[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,8]-errM[:,8], M[:,8]+errM[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Lexical task: STS') plt.subplot(3,3,8) plt.hold(True) plt.plot(times, M1[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,5]-errM1[:,5], M1[:,5]+errM1[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,6]-errM1[:,6], M1[:,6]+errM1[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,8]-errM1[:,8], M1[:,8]+errM1[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Good Readers') plt.subplot(3,3,9) plt.hold(True) plt.plot(times, M2[:,5],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,5]-errM2[:,5], M2[:,5]+errM2[:,5], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,6],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,6]-errM2[:,6], M2[:,6]+errM2[:,6], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,8],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,8]-errM2[:,8], M2[:,8]+errM2[:,8], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Poor Readers') #%% """ Young vs. old """ plt.figure(3) plt.clf() X11 = X13[ventral_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,1) plt.hold(True) plt.plot(times, M[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,0]-errM[:,0], M[:,0]+errM[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,1]-errM[:,1], M[:,1]+errM[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,3]-errM[:,3], M[:,3]+errM[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Dot task: VWFA') plt.subplot(3,3,2) plt.hold(True) plt.plot(times, M1[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,0]-errM1[:,0], M1[:,0]+errM1[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,1]-errM1[:,1], M1[:,1]+errM1[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,3]-errM1[:,3], M1[:,3]+errM1[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Good Readers') plt.subplot(3,3,3) plt.hold(True) plt.plot(times, M2[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,0]-errM2[:,0], M2[:,0]+errM2[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,1]-errM2[:,1], M1[:,1]+errM2[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,3]-errM2[:,3], M2[:,3]+errM2[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Poor Readers') X11 = X13[pt_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,4) plt.hold(True) plt.plot(times, M[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,0]-errM[:,0], M[:,0]+errM[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,1]-errM[:,1], M[:,1]+errM[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,3]-errM[:,3], M[:,3]+errM[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Dot task: Frontal') plt.subplot(3,3,5) plt.hold(True) plt.plot(times, M1[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,0]-errM1[:,0], M1[:,0]+errM1[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,1]-errM1[:,1], M1[:,1]+errM1[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,3]-errM1[:,3], M1[:,3]+errM1[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Good Readers') plt.subplot(3,3,6) plt.hold(True) plt.plot(times, M2[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,0]-errM2[:,0], M2[:,0]+errM2[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,1]-errM2[:,1], M2[:,1]+errM2[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,3]-errM2[:,3], M2[:,3]+errM2[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Poor Readers') X11 = X13[w_vertices,:,:,:] M = np.mean(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) M1 = np.mean(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) M2 = np.mean(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) errM = np.std(np.mean(X11[:,:,all_subject,:],axis=0),axis=1) / np.sqrt(len(all_subject)) errM1 = np.std(np.mean(X11[:,:,old_readers,:],axis=0),axis=1) / np.sqrt(len(good_readers)) errM2 = np.std(np.mean(X11[:,:,young_readers,:],axis=0),axis=1) / np.sqrt(len(poor_readers)) plt.subplot(3,3,7) plt.hold(True) plt.plot(times, M[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M[:,0]-errM[:,0], M[:,0]+errM[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M[:,1]-errM[:,1], M[:,1]+errM[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M[:,3]-errM[:,3], M[:,3]+errM[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Dot task: STG') plt.subplot(3,3,8) plt.hold(True) plt.plot(times, M1[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M1[:,0]-errM1[:,0], M1[:,0]+errM1[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M1[:,1]-errM1[:,1], M1[:,1]+errM1[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M1[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M1[:,3]-errM1[:,3], M1[:,3]+errM1[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1, 3]) plt.title('Good Readers') plt.subplot(3,3,9) plt.hold(True) plt.plot(times, M2[:,0],'-',color=c_table[5],label='Low noise') plt.fill_between(times, M2[:,0]-errM2[:,0], M2[:,0]+errM2[:,0], facecolor=c_table[5], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,1],'-',color=c_table[3],label='Med noise') plt.fill_between(times, M2[:,1]-errM2[:,1], M2[:,1]+errM2[:,1], facecolor=c_table[3], alpha=0.2, edgecolor='none') plt.plot(times, M2[:,3],'-',color=c_table[1],label='High noise') plt.fill_between(times, M2[:,3]-errM2[:,3], M2[:,3]+errM2[:,3], facecolor=c_table[1], alpha=0.2, edgecolor='none') plt.grid(b=True) plt.ylim([-1,
<filename>kivy/core/window/window_sdl2.py # found a way to include it more easily. ''' SDL2 Window =========== Windowing provider directly based on our own wrapped version of SDL. TODO: - fix keys - support scrolling - clean code - manage correctly all sdl events ''' __all__ = ('WindowSDL', ) from os.path import join import sys from typing import Optional from kivy import kivy_data_dir from kivy.logger import Logger from kivy.base import EventLoop from kivy.clock import Clock from kivy.config import Config from kivy.core.window import WindowBase try: from kivy.core.window._window_sdl2 import _WindowSDL2Storage except ImportError: from kivy.core import handle_win_lib_import_error handle_win_lib_import_error( 'window', 'sdl2', 'kivy.core.window._window_sdl2') raise from kivy.input.provider import MotionEventProvider from kivy.input.motionevent import MotionEvent from kivy.resources import resource_find from kivy.utils import platform, deprecated from kivy.compat import unichr from collections import deque # SDL_keycode.h, https://wiki.libsdl.org/SDL_Keymod KMOD_NONE = 0x0000 KMOD_LSHIFT = 0x0001 KMOD_RSHIFT = 0x0002 KMOD_LCTRL = 0x0040 KMOD_RCTRL = 0x0080 KMOD_LALT = 0x0100 KMOD_RALT = 0x0200 KMOD_LGUI = 0x0400 KMOD_RGUI = 0x0800 KMOD_NUM = 0x1000 KMOD_CAPS = 0x2000 KMOD_MODE = 0x4000 SDLK_SHIFTL = 1073742049 SDLK_SHIFTR = 1073742053 SDLK_LCTRL = 1073742048 SDLK_RCTRL = 1073742052 SDLK_LALT = 1073742050 SDLK_RALT = 1073742054 SDLK_LEFT = 1073741904 SDLK_RIGHT = 1073741903 SDLK_UP = 1073741906 SDLK_DOWN = 1073741905 SDLK_HOME = 1073741898 SDLK_END = 1073741901 SDLK_PAGEUP = 1073741899 SDLK_PAGEDOWN = 1073741902 SDLK_SUPER = 1073742051 SDLK_CAPS = 1073741881 SDLK_INSERT = 1073741897 SDLK_KEYPADNUM = 1073741907 SDLK_KP_DIVIDE = 1073741908 SDLK_KP_MULTIPLY = 1073741909 SDLK_KP_MINUS = 1073741910 SDLK_KP_PLUS = 1073741911 SDLK_KP_ENTER = 1073741912 SDLK_KP_1 = 1073741913 SDLK_KP_2 = 1073741914 SDLK_KP_3 = 1073741915 SDLK_KP_4 = 1073741916 SDLK_KP_5 = 1073741917 SDLK_KP_6 = 1073741918 SDLK_KP_7 = 1073741919 SDLK_KP_8 = 1073741920 SDLK_KP_9 = 1073741921 SDLK_KP_0 = 1073741922 SDLK_KP_DOT = 1073741923 SDLK_F1 = 1073741882 SDLK_F2 = 1073741883 SDLK_F3 = 1073741884 SDLK_F4 = 1073741885 SDLK_F5 = 1073741886 SDLK_F6 = 1073741887 SDLK_F7 = 1073741888 SDLK_F8 = 1073741889 SDLK_F9 = 1073741890 SDLK_F10 = 1073741891 SDLK_F11 = 1073741892 SDLK_F12 = 1073741893 SDLK_F13 = 1073741894 SDLK_F14 = 1073741895 SDLK_F15 = 1073741896 class SDL2MotionEvent(MotionEvent): def __init__(self, *args, **kwargs): kwargs.setdefault('is_touch', True) kwargs.setdefault('type_id', 'touch') super().__init__(*args, **kwargs) self.profile = ('pos', 'pressure') def depack(self, args): self.sx, self.sy, self.pressure = args super().depack(args) class SDL2MotionEventProvider(MotionEventProvider): win = None q = deque() touchmap = {} def update(self, dispatch_fn): touchmap = self.touchmap while True: try: value = self.q.pop() except IndexError: return action, fid, x, y, pressure = value y = 1 - y if fid not in touchmap: touchmap[fid] = me = SDL2MotionEvent( 'sdl', fid, (x, y, pressure) ) else: me = touchmap[fid] me.move((x, y, pressure)) if action == 'fingerdown': dispatch_fn('begin', me) elif action == 'fingerup': me.update_time_end() dispatch_fn('end', me) del touchmap[fid] else: dispatch_fn('update', me) class WindowSDL(WindowBase): _win_dpi_watch: Optional['_WindowsSysDPIWatch'] = None _do_resize_ev = None managed_textinput = True def __init__(self, **kwargs): self._pause_loop = False self._cursor_entered = False self._drop_pos = None self._win = _WindowSDL2Storage() super(WindowSDL, self).__init__() self.titlebar_widget = None self._mouse_x = self._mouse_y = -1 self._meta_keys = ( KMOD_LCTRL, KMOD_RCTRL, KMOD_RSHIFT, KMOD_LSHIFT, KMOD_RALT, KMOD_LALT, KMOD_LGUI, KMOD_RGUI, KMOD_NUM, KMOD_CAPS, KMOD_MODE) self.command_keys = { 27: 'escape', 9: 'tab', 8: 'backspace', 13: 'enter', 127: 'del', 271: 'enter', 273: 'up', 274: 'down', 275: 'right', 276: 'left', 278: 'home', 279: 'end', 280: 'pgup', 281: 'pgdown'} self._mouse_buttons_down = set() self.key_map = {SDLK_LEFT: 276, SDLK_RIGHT: 275, SDLK_UP: 273, SDLK_DOWN: 274, SDLK_HOME: 278, SDLK_END: 279, SDLK_PAGEDOWN: 281, SDLK_PAGEUP: 280, SDLK_SHIFTR: 303, SDLK_SHIFTL: 304, SDLK_SUPER: 309, SDLK_LCTRL: 305, SDLK_RCTRL: 306, SDLK_LALT: 308, SDLK_RALT: 307, SDLK_CAPS: 301, SDLK_INSERT: 277, SDLK_F1: 282, SDLK_F2: 283, SDLK_F3: 284, SDLK_F4: 285, SDLK_F5: 286, SDLK_F6: 287, SDLK_F7: 288, SDLK_F8: 289, SDLK_F9: 290, SDLK_F10: 291, SDLK_F11: 292, SDLK_F12: 293, SDLK_F13: 294, SDLK_F14: 295, SDLK_F15: 296, SDLK_KEYPADNUM: 300, SDLK_KP_DIVIDE: 267, SDLK_KP_MULTIPLY: 268, SDLK_KP_MINUS: 269, SDLK_KP_PLUS: 270, SDLK_KP_ENTER: 271, SDLK_KP_DOT: 266, SDLK_KP_0: 256, SDLK_KP_1: 257, SDLK_KP_2: 258, SDLK_KP_3: 259, SDLK_KP_4: 260, SDLK_KP_5: 261, SDLK_KP_6: 262, SDLK_KP_7: 263, SDLK_KP_8: 264, SDLK_KP_9: 265} if platform == 'ios': # XXX ios keyboard suck, when backspace is hit, the delete # keycode is sent. fix it. self.key_map[127] = 8 elif platform == 'android': # map android back button to escape self.key_map[1073742094] = 27 self.bind(minimum_width=self._set_minimum_size, minimum_height=self._set_minimum_size) self.bind(allow_screensaver=self._set_allow_screensaver) def get_window_info(self): return self._win.get_window_info() def _set_minimum_size(self, *args): minimum_width = self.minimum_width minimum_height = self.minimum_height if minimum_width and minimum_height: self._win.set_minimum_size(minimum_width, minimum_height) elif minimum_width or minimum_height: Logger.warning( 'Both Window.minimum_width and Window.minimum_height must be ' 'bigger than 0 for the size restriction to take effect.') def _set_allow_screensaver(self, *args): self._win.set_allow_screensaver(self.allow_screensaver) def _event_filter(self, action, *largs): from kivy.app import App if action == 'app_terminating': EventLoop.quit = True elif action == 'app_lowmemory': self.dispatch('on_memorywarning') elif action == 'app_willenterbackground': from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, pause.') elif not app.dispatch('on_pause'): Logger.info( 'WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return 0 self._pause_loop = True elif action == 'app_didenterforeground': # on iOS, the did enter foreground is launched at the start # of the application. in our case, we want it only when the app # is resumed if self._pause_loop: self._pause_loop = False app = App.get_running_app() if app: app.dispatch('on_resume') elif action == 'windowresized': self._size = largs self._win.resize_window(*self._size) # Force kivy to render the frame now, so that the canvas is drawn. EventLoop.idle() return 0 def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.custom_titlebar = \ self.borderless = self._fake_fullscreen = False elif self.custom_titlebar: if platform == 'win': # use custom behaviour # To handle aero snapping and rounded corners self.borderless = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # ensure we have an event filter self._win.set_event_filter(self._event_filter) # setup window w, h = self.system_size resizable = Config.getboolean('graphics', 'resizable') state = (Config.get('graphics', 'window_state') if self._is_desktop else None) self.system_size = _size = self._win.setup_window( pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable, state, self.get_gl_backend_name()) # calculate density/dpi if platform == 'win': from ctypes import windll self._density = 1. try: hwnd = windll.user32.GetActiveWindow() self.dpi = float(windll.user32.GetDpiForWindow(hwnd)) except AttributeError: pass else: sz = self._win._get_gl_size()[0] self._density = density = sz / _size[0] if self._is_desktop and self.size[0] != _size[0]: self.dpi = density * 96. # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) self._set_minimum_size() self._set_allow_screensaver() if state == 'hidden': self._focus = False else: w, h = self.system_size self._win.resize_window(w, h) if platform == 'win': if self.custom_titlebar: # check dragging+resize or just dragging if Config.getboolean('graphics', 'resizable'): import win32con import ctypes self._win.set_border_state(False) # make windows dispatch, # WM_NCCALCSIZE explicitly ctypes.windll.user32.SetWindowPos( self._win.get_window_info().window, win32con.HWND_TOP, *self._win.get_window_pos(), *self.system_size, win32con.SWP_FRAMECHANGED ) else: self._win.set_border_state(True) else: self._win.set_border_state(self.borderless) else: self._win.set_border_state(self.borderless or self.custom_titlebar) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # set mouse visibility self._set_cursor_state(self.show_cursor) if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon') if platform == 'win' and self._win_dpi_watch is None: self._win_dpi_watch = _WindowsSysDPIWatch(window=self) self._win_dpi_watch.start() def close(self): self._win.teardown_window() super(WindowSDL, self).close() if self._win_dpi_watch is not None: self._win_dpi_watch.stop() self._win_dpi_watch = None self.initialized = False def maximize(self): if self._is_desktop: self._win.maximize_window() else: Logger.warning('Window: maximize() is used only on desktop OSes.') def minimize(self): if self._is_desktop: self._win.minimize_window() else: Logger.warning('Window: minimize() is used only on desktop OSes.') def restore(self): if self._is_desktop: self._win.restore_window() else: Logger.warning('Window: restore() is used only on desktop OSes.') def hide(self): if self._is_desktop: self._win.hide_window() else: Logger.warning('Window: hide() is used only on desktop OSes.') def show(self): if self._is_desktop: self._win.show_window() else: Logger.warning('Window: show() is used only on desktop OSes.') def raise_window(self): if self._is_desktop: self._win.raise_window() else: Logger.warning('Window: show() is used only on desktop OSes.') @deprecated def toggle_fullscreen(self): if self.fullscreen in (True, 'auto'): self.fullscreen = False else: self.fullscreen = 'auto' def set_title(self, title): self._win.set_window_title(title) def set_icon(self, filename): self._win.set_window_icon(str(filename)) def screenshot(self, *largs, **kwargs): filename = super(WindowSDL, self).screenshot(*largs, **kwargs) if filename is None: return from kivy.graphics.opengl import glReadPixels, GL_RGB, GL_UNSIGNED_BYTE width, height = self.size data = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE) self._win.save_bytes_in_png(filename, data, width, height) Logger.debug('Window: Screenshot saved at <%s>' % filename) return filename def flip(self): self._win.flip() super(WindowSDL, self).flip() def set_system_cursor(self, cursor_name): result = self._win.set_system_cursor(cursor_name) return result def _get_window_pos(self): return self._win.get_window_pos() def _set_window_pos(self, x, y): self._win.set_window_pos(x, y) # Transparent Window background def _is_shaped(self): return self._win.is_window_shaped() def _set_shape(self, shape_image, mode='default', cutoff=False, color_key=None): modes = ('default', 'binalpha', 'reversebinalpha', 'colorkey')
== tree[1:] # skip the first line # use del instead of Group.remove() del root.a.b.c tree = """ <Root '' (5 groups, 5 datasets, 0 metadata)> <Group '/a' (1 groups, 3 datasets, 0 metadata)> <Group '/a/b' (0 groups, 1 datasets, 0 metadata)> <Dataset '/a/b/d2' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/a/d1' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/a/d3' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/d4' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/d7' shape=(0,) dtype='<f8' (0 metadata)> <Group '/x' (2 groups, 0 datasets, 0 metadata)> <Group '/x/y' (1 groups, 0 datasets, 0 metadata)> <Group '/x/y/z' (0 groups, 0 datasets, 0 metadata)>""" # Python 2.7 64-bit has shape=(0L,) and we don't care about (0L,) vs (0,) assert root.tree().replace('shape=(0L,)', 'shape=(0,)') == tree[1:] # skip the first line # use Group.remove() instead of del root.remove('a') tree = """ <Root '' (3 groups, 2 datasets, 0 metadata)> <Dataset '/d4' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/d7' shape=(0,) dtype='<f8' (0 metadata)> <Group '/x' (2 groups, 0 datasets, 0 metadata)> <Group '/x/y' (1 groups, 0 datasets, 0 metadata)> <Group '/x/y/z' (0 groups, 0 datasets, 0 metadata)>""" # Python 2.7 64-bit has shape=(0L,) and we don't care about (0L,) vs (0,) assert root.tree().replace('shape=(0L,)', 'shape=(0,)') == tree[1:] # skip the first line # increase the indentation tree = """ <Root '' (3 groups, 2 datasets, 0 metadata)> <Dataset '/d4' shape=(0,) dtype='<f8' (0 metadata)> <Dataset '/d7' shape=(0,) dtype='<f8' (0 metadata)> <Group '/x' (2 groups, 0 datasets, 0 metadata)> <Group '/x/y' (1 groups, 0 datasets, 0 metadata)> <Group '/x/y/z' (0 groups, 0 datasets, 0 metadata)>""" # Python 2.7 64-bit has shape=(0L,) and we don't care about (0L,) vs (0,) assert root.tree(indent=5).replace('shape=(0L,)', 'shape=(0,)') == tree[1:] # skip the first line def test_add_group(): root = Root('some file') for item in [dict(), tuple(), list(), None, Dataset('dset', None, False)]: with pytest.raises(TypeError): root.add_group('name', item) root2 = Root('New') assert len(root2) == 0 # # add a Group that does not contain sub-Groups nor Datasets # # add to the Root Group root2.add_group('', root.create_group('a', one=1, foo='bar')) assert len(root2) == 1 assert root2.a is not root.a assert '/a' in root2 assert len(root2.a.metadata) == 2 assert root2.a.metadata.one == 1 assert root2.a.metadata['foo'] == 'bar' root2.clear() # also tests Root.clear() assert len(root2) == 0 # creates an "/B" Group and then add to it root2.add_group('B', root.create_group('b', two=2)) assert len(root2) == 2 assert root2.B.b is not root.b assert '/B/b' in root2 assert 'B' in root2 assert 'b' in root2.B assert '/B/b' in root2 assert len(root2.B.metadata) == 0 assert len(root2.B.b.metadata) == 1 assert root2.B.b.metadata.two == 2 root2.clear() assert len(root2) == 0 # creates an "/A/B/C" Group and then add to it (add a ridiculous amount of '/') root2.add_group('/////A/B/C//////////', root.create_group('c', x='x', y='y')) assert len(root2) == 4 assert root2.A.B.C.c is not root.c assert '/A' in root2 assert 'A/B' in root2 assert '/A/B/C' in root2 assert '/A/B/C/c' in root2 assert '/c' in root2.A.B.C assert len(root2.A.metadata) == 0 assert len(root2.A.B.metadata) == 0 assert len(root2.A.B.C.metadata) == 0 assert len(root2.A.B.C.c.metadata) == 2 assert root2.A.B.C.c.metadata.x == 'x' assert root2['A']['B'].C['c'].metadata['y'] == 'y' # verify root's tree assert len(root) == 3 assert 'a' in root assert '/b' in root assert 'c' in root assert len(root.a.metadata) == 2 assert root.a.metadata.one == 1 assert root.a.metadata.foo == 'bar' assert len(root.b.metadata) == 1 assert root.b.metadata.two == 2 assert len(root.c.metadata) == 2 assert root.c.metadata.x == 'x' assert root.c.metadata.y == 'y' # add some Datasets to root root.b.create_dataset('/x', data=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) root.c.create_dataset('y/z', shape=(3, 4), meta='data') assert 'x' in root.b assert 'z' in root.c.y # add root to root2 root2.add_group('/old', root) assert len(root2) == 11 assert '/A' in root2 assert 'A/B' in root2 assert '/A/B/C' in root2 assert '/A/B/C/c' in root2 assert '/c' in root2.A.B.C assert 'old' in root2 assert 'old/a' in root2 assert '/old/b' in root2 assert '/old/c' in root2 assert '/old/b/x' in root2 assert 'y' in root2.old.c assert '/y/z' in root2.old.c assert len(root2.A.metadata) == 0 assert len(root2.A.B.metadata) == 0 assert len(root2.A.B.C.metadata) == 0 assert len(root2.A.B.C.c.metadata) == 2 assert root2.A.B.C.c.metadata.x == 'x' assert root2['A']['B'].C['c'].metadata['y'] == 'y' assert len(root2.old.a.metadata) == 2 assert root2.old.a.metadata.one == 1 assert root2.old.a.metadata.foo == 'bar' assert len(root2.old.b.metadata) == 1 assert root2.old.b.metadata.two == 2 assert len(root2.old.c.metadata) == 2 assert root2.old.c.metadata.x == 'x' assert root2.old.c.metadata.y == 'y' assert len(root2.old.b.metadata) == 1 assert root2.old.b.metadata.two == 2 assert len(root2.old.c.metadata) == 2 assert root2.old.c.metadata.x == 'x' assert root2.old['c'].metadata['y'] == 'y' assert len(root2.old.c.y.metadata) == 0 assert len(root2.old.c.y.z.metadata) == 1 assert root2.old.c.y.z.metadata.meta == 'data' assert root2.old.b.x.shape == (10,) assert root2.old.c.y.z.shape == (3, 4) # the Metadata is a copy root2.old.c.y.z.metadata.meta = 'new value' assert root2.old.c.y.z.metadata.meta is not root.c.y.z.metadata.meta assert root2.old.c.y.z.metadata.meta == 'new value' assert root.c.y.z.metadata.meta == 'data' # the data in the Dataset is a copy assert root2.old.b.x.data is not root.b.x.data assert root2.old.c.y.z.data is not root.c.y.z.data root2.old.b.x[:] = 1 assert sum(root2.old.b.x.data) == 10 for val in root.b.x.data.tolist(): assert val == 0 def test_add_dataset(): root = Root('some file') for item in [dict(), tuple(), list(), None, 1.0, Root('r'), Group('group', None, True)]: with pytest.raises(TypeError): root.add_dataset('name', item) assert len(root) == 0 dset1 = Dataset('dset1', None, False, data=[1, 2, 3], dtype=int) dset2 = Dataset('dset2', None, False, data=[4.0, 5.0, 6.0], foo='bar') dset3 = Dataset('dset3', None, False, data=[-23.4, 1.78], one=1, two=2) root.add_dataset('dset1_copy', dset1) d = root.create_group('a/b/c/d') c = d.parent assert c is root.a.b.c c.add_dataset('dset2_copy', dset2) c.add_dataset('/x/y/dset3_copy', dset3) assert len(list(root.datasets())) == 3 assert len(list(root.a.datasets())) == 2 assert len(list(root.a.b.datasets())) == 2 assert len(list(root.a.b.c.datasets())) == 2 assert len(list(root.a.b.c.x.datasets())) == 1 assert len(list(root.a.b.c.x.y.datasets())) == 1 assert len(list(root.a.b.c.d.datasets())) == 0 assert root.dset1_copy is not dset1 assert root.a.b.c.dset2_copy is not dset2 assert root.a.b.c.x.y.dset3_copy is not dset3 assert all(v1 == v2 for v1, v2 in zip(dset1, root.dset1_copy)) assert all(v1 == v2 for v1, v2 in zip(dset2, root.a.b.c.dset2_copy)) assert all(v1 == v2 for v1, v2 in zip(dset3, root.a.b.c.x.y.dset3_copy)) assert len(root.dset1_copy.metadata) == 0 assert len(c.dset2_copy.metadata) == 1 assert c.dset2_copy.metadata.foo == 'bar' assert len(c.x.y.dset3_copy.metadata) == 2 assert c.x.y.dset3_copy.metadata['one'] == 1 assert c['x']['y']['dset3_copy'].metadata.two == 2 def test_add_dataset_logging(): num_initial_handlers = len(logging.getLogger().handlers) logger = logging.getLogger('test_add_dataset_logging') root = Root('some file') for item in [dict(), tuple(), list(), None, 1.0, Root('r'), Group('group', None, True), Dataset('d', None, True)]: with pytest.raises(TypeError): root.add_dataset_logging('name', item) assert len(root) == 0 assert len(logger.handlers) == 0 assert len(logging.getLogger().handlers) == num_initial_handlers dsetlog1 = root.create_dataset_logging('dsetlog1', level='DEBUG', attributes=['levelname', 'message'], logger=logger, date_fmt='%H-%M') logger.info('bang!') root2 = Root('some file') root2.create_group('a/b/c') b = root2.a.b b.add_dataset_logging('x/y/dsetlog2', dsetlog1) assert len(logger.handlers) == 2 assert len(logging.getLogger().handlers) == num_initial_handlers logger.debug('hello') logger.info('world') dsetlog1.remove_handler() assert len(logger.handlers) == 1 assert len(logging.getLogger().handlers) == num_initial_handlers logger.warning('foo') logger.error('bar') assert dsetlog1.metadata['logging_level'] == logging.DEBUG assert dsetlog1.metadata.logging_level_name == 'DEBUG' assert dsetlog1.metadata.logging_date_format == '%H-%M' assert dsetlog1.level == logging.DEBUG assert dsetlog1.date_fmt == '%H-%M' assert dsetlog1.logger is logger assert all(a == b for a, b in zip(dsetlog1.attributes, ['levelname', 'message'])) assert b.x.y.dsetlog2.metadata['logging_level'] == logging.DEBUG assert b.x.y.dsetlog2.metadata.logging_level_name == 'DEBUG' assert b.x.y.dsetlog2.metadata.logging_date_format == '%H-%M' assert b.x.y.dsetlog2.level == logging.DEBUG assert b.x.y.dsetlog2.date_fmt == '%H-%M' assert b.x.y.dsetlog2.logger is logger assert all(a == b for a, b in zip(dsetlog1.attributes, b.x.y.dsetlog2.attributes)) assert root.dsetlog1.data.size == 3 row = root.dsetlog1.data[0] assert row['levelname'] == 'INFO' and row['message'] == 'bang!' row = root.dsetlog1.data[1] assert row['levelname'] == 'DEBUG' and row['message'] == 'hello' row = root.dsetlog1.data[2] assert row['levelname'] == 'INFO' and row['message'] == 'world' assert root2.a.b.x.y.dsetlog2.data.size == 5 y = b.x.y row = root.dsetlog1.data[0] assert row['levelname'] == 'INFO' and row['message'] == 'bang!' row = y.dsetlog2.data[1] assert row['levelname'] == 'DEBUG' and row['message'] == 'hello' row = y.dsetlog2.data[2] assert row['levelname'] == 'INFO' and row['message'] == 'world' row = y.dsetlog2.data[3] assert row['levelname'] == 'WARNING' and row['message'] == 'foo' row = y.dsetlog2.data[4] assert row['levelname'] == 'ERROR' and row['message'] == 'bar' root2.a.b.x.y.dsetlog2.remove_handler() assert len(logger.handlers) == 0 assert len(logging.getLogger().handlers) == num_initial_handlers def test_remove(): root = Root('') a = root.create_group('a') a.create_dataset('d1') b = a.create_group('b') b.create_dataset('d2') c = b.create_group('c') z = root.create_group('x/y/z') d = c.create_group('d') a.create_dataset('d3') root.create_dataset('d4') d.create_dataset('d5') d.create_dataset('d6') d7 = root.create_dataset('d7') assert len(root) == 14 assert len(list(root.groups())) == 7 assert len(list(root.datasets())) == 7 assert 'a' in root assert 'd1' in root.a assert 'b' in root.a assert 'd2' in root.a.b assert 'c' in root.a.b assert 'x' in root assert 'x/y' in root assert 'y' in root.x assert 'x/y/z' in root assert 'z' in root.x.y
# script for Robofont # written by <NAME> # august 2014 # Script using glyphPreview to build a 3x3 matrix allowing preview of interpolated and/or extrapolated glyphs from vanilla import * from mojo.glyphPreview import GlyphPreview from mojo.events import addObserver, removeObserver from AppKit import NSColor from math import cos, sin, pi def errorGlyph(): glyph = RGlyph() glyph.width = 500 pen = glyph.getPen() l = 50 p = (220, 200) a = pi/4 pen.moveTo(p) px, py = p for i in range(12): x = px+(l*cos(a)) y = py+(l*sin(a)) pen.lineTo((x, y)) px = x py = y if i%3 == 0: a -= pi/2 elif i%3 != 0: a += pi/2 pen.closePath() return glyph def rawGlyph(glyph): components = glyph.components font = glyph.getParent() decomposedGlyph = RGlyph() if font is not None: for component in components: base = font[component.baseGlyph] if len(base.components) > 0: base = rawGlyph(base) decomponent = RGlyph() decomponent.appendGlyph(base) decomponent.scale((component.scale[0], component.scale[1])) decomponent.move((component.offset[0], component.offset[1])) decomposedGlyph.appendGlyph(decomponent) for contour in glyph.contours: decomposedGlyph.appendContour(contour) return decomposedGlyph class SingleFontList(List): def __init__(self, parent, fontList, posSize): fontNames = [' '.join([font.info.familyName, font.info.styleName]) for font in fontList] super(SingleFontList, self).__init__(posSize, fontNames, selectionCallback=self.selectedFont, allowsMultipleSelection=False) self.fonts = fontList self.selection = fontList[0] self.parent = parent def update(self): self.fonts = AllFonts() self.set([' '.join([font.info.familyName, font.info.styleName]) for font in AllFonts()]) def selectedFont(self, info): if len(info.getSelection()) == 1: index = info.getSelection()[0] self.selection = self.fonts[index] self.parent.updateFont(self.selection) else: self.selection = None self.parent.updateFont(None) def selected(self): return self.selection def select(self, thisFont): selection = [] for i, font in enumerate(self.fonts): if thisFont == font: selection.append(i) self.setSelection(selection) class interpolationMatrixController(object): def __init__(self): bgColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(255, 255, 255, 255) self.w = Window((1200, 900), minSize=(900, 600)) self.w.getNSWindow().setBackgroundColor_(bgColor) self.w.fontList = SingleFontList(self, AllFonts(), (0, 0, 300, 250)) self.w.matrixModel = Group((15, 265, 270, 270)) self.w.matrixView = Group((300, 0, 0, -0)) self.master_matrix = [] self.instance_matrix = [] self.ipf = .5 self.xpf = 1 x, y, wi, he = self.w.getPosSize() wi = (wi-300)/3 he /= 3 for i, k in enumerate(['a','b','c']): self.master_matrix.append([]) self.instance_matrix.append([]) for j, l in enumerate(['a','b','c']): setattr(self.w.matrixView, 'back'+k+l, Box((wi*i, he*j, wi, he))) setattr(self.w.matrixView, k+l, GlyphPreview((wi*i, he*j, wi, he))) setattr(self.w.matrixModel, 'back'+k+l, Box((90*i, 90*j, 90, 90))) setattr(self.w.matrixModel, k+l, SquareButton((5+(90*i), 5+(90*j), 80, 80), '', callback=self.pickSpot, sizeStyle='mini')) setattr(self.w.matrixModel, 'reset'+k+l, SquareButton((1+(90*i), 1+(90*j), 20, 20), 'x', callback=self.clearSpot, sizeStyle='mini')) spotButton = getattr(self.w.matrixModel, k+l) resetpot = getattr(self.w.matrixModel, 'reset'+k+l) resetpot.key = spotButton.key = (i,j,k,l) spotButton.getNSButton().setBordered_(False) resetpot.getNSButton().setBezelStyle_(7) self.master_matrix[i].append([k+l, None]) self.instance_matrix[i].append([k+l, None]) self.w.interpolation = Group((10, 565, 280, 50)) self.w.interpolation.start = TextBox((7, 2, 20, 12), '0', sizeStyle='mini') self.w.interpolation.end = TextBox((-20, 2, 20, 12), '1', sizeStyle='mini') self.w.interpolation.title = TextBox((20, 0, -20, 17), 'Interpolation factor', sizeStyle='small', alignment='center') self.w.interpolation.slider = Slider((5, 27, -5, 15), minValue=0, maxValue=1, value=self.ipf, callback=self.sliderInput, tickMarkCount=5) self.w.interpolation.slider.name = 'ipf' self.w.extrapolation = Group((10, 632, 280, 50)) self.w.extrapolation.start = TextBox((7, 2, 20, 12), '1', sizeStyle='mini') self.w.extrapolation.end = TextBox((-20, 2, 20, 12), '3', sizeStyle='mini') self.w.extrapolation.title = TextBox((20, 0, -20, 17), 'Extrapolation factor', sizeStyle='small', alignment='center') self.w.extrapolation.slider = Slider((5, 27, -5, 15), minValue=0, maxValue=2, value=self.xpf, callback=self.sliderInput, tickMarkCount=5) self.w.extrapolation.slider.name = 'xpf' self.spotFocus = getattr(self.w.matrixModel, 'bb') self.w.updateMatrixButton = Button((10, 727, 280, 20), 'Update', callback=self.updateMasters) self.w.resetMatrixButton = Button((10, 755, 280, 20), 'Reset', callback=self.resetMatrix) self.newFont = [] addObserver(self, 'updateMasters', 'currentGlyphChanged') addObserver(self, 'updateMasters', 'draw') addObserver(self, 'updateFontList', 'fontDidOpen') addObserver(self, 'updateFontList', 'fontDidClose') self.w.bind('close', self.windowClose) self.w.bind('resize', self.windowResize) self.w.open() def updateFontList(self, info): self.w.fontList.update() def updateInstances(self): for i, k in enumerate(['a','b','c']): for j, l in enumerate(['a','b','c']): if self.master_matrix[i][j][1] is None: self.makeInstance(i,j,k,l) def updateMasters(self, notification=None): for i, line in enumerate(self.master_matrix): for j, spot in enumerate(line): if spot[1] is not None: stringKey = [char for char in spot[0]] key = i, j, stringKey[0], stringKey[1] self.setMaster(key) elif spot[1] is None: self.master_matrix[i][j][1] = None self.updateInstances() def updateFont(self, font): self.newFont = [font] spotFocus = self.spotFocus key = spotFocus.key self.setMaster(key) self.clearMatrix(True) self.updateMasters() def pickSpot(self, notifier): self.spotFocus = notifier key = notifier.key # print dir(notifier.getNSButton()) notifier.getNSButton().setBezelStyle_(15) notifier.getNSButton().setBordered_(True) self.resetSpotStates() self.setMaster(key) self.clearMatrix(True) self.updateMasters() def clearSpot(self, notifier): key = notifier.key i,j,k,l = key self.master_matrix[i][j][1] = None spotButton = getattr(self.w.matrixModel, k+l) spotButton.setTitle('') if self.spotFocus is spotButton: self.w.fontList.select(None) self.clearInstanceMatrix() self.updateMasters() def resetSpotStates(self): for k in ['a', 'b', 'c']: for l in ['a', 'b', 'c']: matrixButton = getattr(self.w.matrixModel, k+l) if matrixButton is not self.spotFocus: matrixButton.getNSButton().setBezelStyle_(10) matrixButton.getNSButton().setBordered_(False) def clearInstanceMatrix(self): for i, k in enumerate(['a','b','c']): for j, l in enumerate(['a','b','c']): self.instance_matrix[i][j][1] = None def setMaster(self, key): i, j, k, l = key if CurrentGlyph() is None: return g = CurrentGlyph().name selectedFont = self.getFont(i, j) spotButton = getattr(self.w.matrixModel, k+l) matrixView = getattr(self.w.matrixView, k+l) if (selectedFont is not None) and (g in selectedFont.keys()): for spotKey, spotGlyph in [spot for line in self.master_matrix for spot in line]: if (spotGlyph == selectedFont[g]) and (spotKey != k+l): spotGlyph = None break glyph = rawGlyph(selectedFont[g]) glyph.setParent(selectedFont) glyph.width = 1000 # glyph.angledLeftMargin = glyph.angledRightMargin = (glyph.angledLeftMargin + glyph.angledRightMargin)/2 glyph.leftMargin = glyph.rightMargin = (glyph.leftMargin + glyph.rightMargin)/2 glyph.scale((.75, .75), (glyph.width/2, 0)) glyph.move((0, -50)) matrixView.show(True) matrixView.setGlyph(glyph) self.master_matrix[i][j][1] = glyph self.instance_matrix[i][j][1] = glyph familyName = selectedFont.info.familyName styleName = selectedFont.info.styleName spotButton.setTitle('\n'.join([familyName,styleName])) elif selectedFont is None: self.master_matrix[i][j][1] = None self.instance_matrix[i][j][1] = None spotButton.setTitle('') self.newFont = [] def getFont(self, i, j): selectedFont = None if self.master_matrix[i][j][1] is None: selectedFont = self.w.fontList.selected() elif self.master_matrix[i][j][1] is not None: if len(self.newFont) == 0: selectedFont = self.master_matrix[i][j][1].getParent() elif len(self.newFont) > 0: selectedFont = self.newFont[0] self.w.fontList.select(selectedFont) return selectedFont def makeInstance(self, i, j, k, l, instancesAsMasters=False): instance = RGlyph() previousInstance = None matrixView = getattr(self.w.matrixView, k+l) matrix = self.master_matrix if instancesAsMasters: matrix = self.instance_matrix prevHspot = matrix[i][(j-1)%3][1] nextHspot = matrix[i][(j+1)%3][1] prevVspot = matrix[(i-1)%3][j][1] nextVspot = matrix[(i+1)%3][j][1] # look for masters in one direction if (prevHspot is not None) and (nextHspot is not None): master1 = prevHspot master2 = nextHspot instance = self.linearInterpolation(j, master1, master2) # look for masters in second direction if (prevVspot is not None) and (nextVspot is not None): master1 = prevVspot master2 = nextVspot if instance.isEmpty() == False: previousInstance = instance instance = self.linearInterpolation(i, master1, master2, previousInstance) # if no masters in line found #if instance.isEmpty(): corner_1 = matrix[(i-1)%3][(j-1)%3][1] corner_2 = matrix[(i-1)%3][(j+1)%3][1] corner_3 = matrix[(i+1)%3][(j+1)%3][1] corner_4 = matrix[(i+1)%3][(j-1)%3][1] if (prevHspot is not None) and (prevVspot is not None) and (corner_1 is not None): if instance.isEmpty() == False: previousInstance = instance instance = self.triangularInterpolation(prevHspot, prevVspot, corner_1, previousInstance) elif (nextHspot is not None) and (prevVspot is not None) and (corner_2 is not None): if instance.isEmpty() == False: previousInstance = instance instance = self.triangularInterpolation(nextHspot, prevVspot, corner_2, previousInstance) elif (nextHspot is not None) and (nextVspot is not None) and (corner_3 is not None): if instance.isEmpty() == False: previousInstance = instance instance = self.triangularInterpolation(nextHspot, nextVspot, corner_3, previousInstance) elif (nextHspot is not None) and (prevVspot is not None) and (corner_4 is not None): if instance.isEmpty() == False: previousInstance = instance instance = self.triangularInterpolation(nextHspot, prevVspot, corner_4, previousInstance) if instance.isEmpty() and not instancesAsMasters: self.makeInstance(i,j,k,l, True) return matrixView.show(True) matrixView.setGlyph(instance) self.instance_matrix[i][j][1] = instance def linearInterpolation(self, i, master1, master2, previousInstance=None): instance = RGlyph() ipf = self.ipf xpf = self.xpf if ((i-1)%3 < i) and ((i+1)%3 < i): instance.interpolate(-xpf, master1, master2) elif ((i-1)%3 > i) and ((i+1)%3 > i): instance.interpolate(1+xpf, master1, master2) elif ((((i-1)%3 < i) and ((i+1)%3 > i)) or (((i-1)%3 > i) and (i+1)%3 < i)): instance.interpolate(ipf, master1, master2) if previousInstance is not None: instance.interpolate(ipf, instance, previousInstance) # if instance.isEmpty(): # instance = errorGlyph() return instance def triangularInterpolation(self, master1, master2, master3, previousInstance=None): ipf = self.ipf xpf = self.xpf instance = RGlyph() midInstance = RGlyph() midInstance.interpolate(ipf, master1, master2) instance.interpolate(1+xpf, master3, midInstance) if previousInstance is not None: instance.interpolate(ipf, instance, previousInstance) # if instance.isEmpty(): # instance = errorGlyph() return instance def sliderInput(self, sender): mode = sender.name value = sender.get() setattr(self, mode, value) self.updateMasters() def resetMatrix(self, sender): self.clearMatrix() def clearMatrix(self, keepMasters=False): saveMasters = list(self.master_matrix) self.master_matrix = [] self.instance_matrix = [] for i, k in enumerate(['a','b','c']): self.master_matrix.append([]) self.instance_matrix.append([]) for j, l in enumerate(['a','b','c']): if keepMasters and (saveMasters[i][j][1] is not None): master = saveMasters[i][j][1] self.master_matrix[i].append([k+l, master]) else: self.master_matrix[i].append([k+l, None]) self.instance_matrix[i].append([k+l, None]) glyphCell = getattr(self.w.matrixView, k+l) glyphCell.setGlyph(None) spot = getattr(self.w.matrixModel, k+l) spot.setTitle('') def windowResize(self, info): x, y, w, h = info.getPosSize() w -= 300 cW = w / 3 cH = h /
+ e * x ** mn) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1417(a, c, d, e, f, m, mn, n2, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int(x ** m * (a + c * x ** (S(2) * n)) ** p * (d + e * x ** mn) ** q, x), x, ) def replacement1418(a, b, c, d, e, m, mn, n, p, q, x): return Int( x ** (m - n * p) * (d + e * x ** n) ** q * (a * x ** n + b + c * x ** (S(2) * n)) ** p, x, ) def replacement1419(a, b, c, d, e, m, mn, n, p, q, x): return Dist( x ** (n * FracPart(p)) * (a + b * x ** (-n) + c * x ** n) ** FracPart(p) * (a * x ** n + b + c * x ** (S(2) * n)) ** (-FracPart(p)), Int( x ** (m - n * p) * (d + e * x ** n) ** q * (a * x ** n + b + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1420(a, b, c, d, e, f, m, mn, n, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int(x ** m * (d + e * x ** n) ** q * (a + b * x ** (-n) + c * x ** n) ** p, x), x, ) def replacement1421(a, b, c, d1, d2, e1, e2, f, m, n, n2, non2, p, q, x): return Int( (f * x) ** m * (d1 * d2 + e1 * e2 * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ) def replacement1422(a, b, c, d1, d2, e1, e2, f, m, n, n2, non2, p, q, x): return Dist( (d1 + e1 * x ** (n / S(2))) ** FracPart(q) * (d2 + e2 * x ** (n / S(2))) ** FracPart(q) * (d1 * d2 + e1 * e2 * x ** n) ** (-FracPart(q)), Int( (f * x) ** m * (d1 * d2 + e1 * e2 * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1423(a, b, c, n, p, q, r, x): return Int((x ** n * (a + b + c)) ** p, x) def replacement1424(a, b, c, n, p, q, r, x): return Int( x ** (p * q) * (a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) ** p, x ) def replacement1425(a, b, c, n, q, r, x): return Dist( x ** (-q / S(2)) * sqrt(a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) / sqrt(a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)), Int( x ** (q / S(2)) * sqrt(a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)), x, ), x, ) def replacement1426(a, b, c, n, q, r, x): return Dist( x ** (q / S(2)) * sqrt(a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) / sqrt(a * x ** q + b * x ** n + c * x ** (S(2) * n - q)), Int( x ** (-q / S(2)) / sqrt(a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)), x, ), x, ) def replacement1427(a, b, c, n, p, q, r, x): return Dist( p * (n - q) / (p * (S(2) * n - q) + S(1)), Int( x ** q * (S(2) * a + b * x ** (n - q)) * (a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** (p + S(-1)), x, ), x, ) + Simp( x * (a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** p / (p * (S(2) * n - q) + S(1)), x, ) def replacement1428(a, b, c, n, p, q, r, x): return Dist( S(1) / (a * (n - q) * (p + S(1)) * (-S(4) * a * c + b ** S(2))), Int( x ** (-q) * (a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** (p + S(1)) * ( b * c * x ** (n - q) * (p * q + (n - q) * (S(2) * p + S(3)) + S(1)) + (n - q) * (p + S(1)) * (-S(4) * a * c + b ** S(2)) + (-S(2) * a * c + b ** S(2)) * (p * q + S(1)) ), x, ), x, ) - Simp( x ** (S(1) - q) * (-S(2) * a * c + b ** S(2) + b * c * x ** (n - q)) * (a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** (p + S(1)) / (a * (n - q) * (p + S(1)) * (-S(4) * a * c + b ** S(2))), x, ) def replacement1429(a, b, c, n, p, q, r, x): return Dist( x ** (-p * q) * (a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) ** (-p) * (a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** p, Int( x ** (p * q) * (a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) ** p, x, ), x, ) def replacement1430(a, b, c, n, p, q, r, x): return Int((a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** p, x) def replacement1431(a, b, c, n, p, q, r, u, x): return Dist( S(1) / Coefficient(u, x, S(1)), Subst(Int((a * x ** q + b * x ** n + c * x ** (S(2) * n - q)) ** p, x), x, u), x, ) def replacement1432(a, b, c, m, n, p, q, r, x): return Int(x ** m * (x ** n * (a + b + c)) ** p, x) def replacement1433(a, b, c, m, n, p, q, r, x): return Int( x ** (m + p * q) * (a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) ** p, x, ) def replacement1434(a, b, c, m, n, q, r, x): return Dist( x ** (q / S(2)) * sqrt(a + b * x ** (n - q) + c * x ** (S(2) * n - S(2) * q)) / sqrt(a * x ** q + b
<gh_stars>0 ''' This module contains the classes necessary to handle both `JSONRPC <http://json-rpc.org/>`_ and `XMLRPC <http://www.xmlrpc.com/>`_ requests. It also contains a decorator to mark methods as rpc methods. ''' import inspect import pydoc from django.contrib.auth import authenticate, login, logout from .jsonrpcdispatcher import JSONRPCDispatcher, json from .xmlrpcdispatcher import XMLRPCDispatcher from django.conf import settings try: from importlib import import_module except ImportError: from django.utils.importlib import import_module from django.core.urlresolvers import get_mod_func try: # Python2.x from xmlrpclib import Fault except ImportError: # Python3 from xmlrpc.client import Fault from defusedxml import xmlrpc # This method makes the XMLRPC parser (used by loads) safe # from various XML based attacks xmlrpc.monkey_patch() # this error code is taken from xmlrpc-epi # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php APPLICATION_ERROR = -32500 class RPCMethod(object): ''' A method available to be called via the rpc dispatcher **Attributes** ``method`` The underlying Python method to call when this method is invoked ``help`` Help message (usually the docstring) printed by the introspection functions when detail about a method is requested ``name`` name of the method by which it can be called ``signature`` See :meth:`rpc4django.rpcdispatcher.rpcmethod` ``permission`` Any Django permissions required to call this method ``login_required`` The method can only be called by a logged in user ''' def __init__(self, method, name=None, signature=None, docstring=None): self.method = method self.help = '' self.signature = [] self.name = '' self.permission = None self.login_required = False self.args = [] # set the method name based on @rpcmethod or the passed value # default to the actual method name if hasattr(method, 'external_name'): self.name = method.external_name elif name is not None: self.name = name else: try: # Python2 self.name = method.func_name except AttributeError: # Python3 self.name = method.__name__ # get the help string for each method if docstring is not None: self.help = docstring else: self.help = pydoc.getdoc(method) # set the permissions based on the decorator self.permission = getattr(method, 'permission', None) # set the permissions based on the decorator self.login_required = getattr(method, 'login_required', self.permission is not None) # use inspection (reflection) to get the arguments # If we're using Python 3, look for function annotations, but allow # the signature parameter override them. try: args, varargs, keywords, defaults = inspect.getargspec(method) # varargs = None # varkw = None # kwonlyargs = None # kwonlydefaults = None annotations = {} except ValueError: full_args = inspect.getfullargspec(method) args = full_args.args # varargs = full_args.varargs # varkw = full_args.varkw # defaults = full_args.defaults # kwonlyargs = full_args.kwonlyargs # kwonlydefaults = full_args.kwonlydefaults annotations = full_args.annotations self.args = [arg for arg in args if arg != 'self'] self.signature.append(annotations.get('return', object).__name__) for i, arg in enumerate(self.args): annotation = annotations.get(arg, None) if annotation: self.signature.append(annotation.__name__) else: try: self.signature.append(method.signature[i]) except (IndexError, AttributeError): self.signature.append('object') if hasattr(method, 'signature') and \ len(method.signature) == len(self.args) + 1: # use the @rpcmethod signature if it has the correct # number of args self.signature = method.signature elif signature is not None and len(self.args) + 1 == len(signature): # use the passed signature if it has the correct number # of arguments self.signature = signature def get_stub(self): ''' Returns JSON for a JSONRPC request for this method This is used to generate the introspection method output ''' params = self.get_params() plist = ['"' + param['name'] + '"' for param in params] jsonlist = [ '{', '"id": "djangorpc",', '"method": "' + self.name + '",', '"params": [', ' ' + ','.join(plist), ']', '}', ] return '\n'.join(jsonlist) def get_returnvalue(self): ''' Returns the return value which is the first element of the signature ''' if len(self.signature) > 0: return self.signature[0] return None def get_params(self): ''' Returns a list of dictionaries containing name and type of the params eg. [{'name': 'arg1', 'rpctype': 'int'}, {'name': 'arg2', 'rpctype': 'int'}] ''' if len(self.signature) > 0: arglist = [] if len(self.signature) == len(self.args) + 1: for argnum in range(len(self.args)): arglist.append({'name': self.args[argnum], 'rpctype': self.signature[argnum + 1]}) return arglist else: # this should not happen under normal usage for argnum in range(len(self.args)): arglist.append({'name': self.args[argnum], 'rpctype': 'object'}) return arglist return [] class RPCDispatcher(object): ''' Keeps track of the methods available to be called and then dispatches method calls to either the :class:`XMLRPCDispatcher <rpc4django.xmlrpcdispatcher.XMLRPCDispatcher>` or the :class:`JSONRPCDispatcher <rpc4django.jsonrpcdispatcher.JSONRPCDispatcher>` Disables RPC introspection methods (eg. ``system.list_methods()`` if ``restrict_introspection`` is set to ``True``. Disables out of the box authentication if ``restrict_ootb_auth`` is ``True``. **Attributes** ``url`` The URL that handles RPC requests (eg. ``/RPC2``) This is needed by ``system.describe``. ``rpcmethods`` A list of :class:`RPCMethod<rpc4django.rpcdispatcher.RPCMethod>` instances available to be called by the dispatcher ``xmlrpcdispatcher`` An instance of :class:`XMLRPCDispatcher <rpc4django.xmlrpcdispatcher.XMLRPCDispatcher>` where XMLRPC calls are dispatched to using :meth:`xmldispatch` ``jsonrpcdispatcher`` An instance of :class:`JSONRPCDispatcher <rpc4django.jsonrpcdispatcher.JSONRPCDispatcher>` where JSONRPC calls are dispatched to using :meth:`jsondispatch` ''' def __init__(self, restrict_introspection=False, restrict_ootb_auth=True, json_encoder=None): self.rpcmethods = [] # a list of RPCMethod objects self.jsonrpcdispatcher = JSONRPCDispatcher(json_encoder) self.xmlrpcdispatcher = XMLRPCDispatcher() if not restrict_introspection: self.register_method(self.system_listmethods, 'system.listMethods', ['array']) self.register_method(self.system_methodhelp, 'system.methodHelp', ['string', 'string']) self.register_method(self.system_methodsignature, 'system.methodSignature', ['array', 'string']) self.register_method(self.system_describe, 'system.describe', ['struct']) if not restrict_ootb_auth: self.register_method(self.system_login, 'system.login', ['boolean', 'string', 'string']) self.register_method(self.system_logout, 'system.logout', ['boolean']) def system_describe(self, **kwargs): ''' Returns a simple method description of the methods supported ''' request = kwargs.get('request', None) description = {} description['serviceType'] = 'RPC4Django JSONRPC+XMLRPC' description['serviceURL'] = request.path, description['methods'] = [{'name': method.name, 'summary': method.help, 'params': method.get_params(), 'return': method.get_returnvalue()} for method in self.rpcmethods] return description def system_listmethods(self): ''' Returns a list of supported methods ''' methods = [method.name for method in self.rpcmethods] methods.sort() return methods def system_methodhelp(self, method_name): ''' Returns documentation for a specified method ''' for method in self.rpcmethods: if method.name == method_name: return method.help # this differs from what implementation in SimpleXMLRPCServer does # this will report via a fault or error while SimpleXMLRPCServer # just returns an empty string raise Fault(APPLICATION_ERROR, 'No method found with name: ' + str(method_name)) def system_methodsignature(self, method_name): ''' Returns the signature for a specified method ''' for method in self.rpcmethods: if method.name == method_name: return method.signature raise Fault(APPLICATION_ERROR, 'No method found with name: ' + str(method_name)) def system_login(self, username, password, **kwargs): ''' Authorizes a user to enable sending protected RPC requests ''' request = kwargs.get('request', None) user = authenticate(username=username, password=password) if user is not None and request is not None: if user.is_active: login(request, user) return True return False def system_logout(self, **kwargs): ''' Deauthorizes a user ''' request = kwargs.get('request', None) if request is not None: logout(request) return True return False def jsondispatch(self, raw_post_data, **kwargs): ''' Sends the post data to :meth:`rpc4django.jsonrpcdispatcher.JSONRPCDispatcher.dispatch` ''' return self.jsonrpcdispatcher.dispatch(raw_post_data.decode('utf-8'), **kwargs) def xmldispatch(self, raw_post_data, **kwargs): ''' Sends the post data to :meth:`rpc4django.xmlrpcdispatcher.XMLRPCDispatcher.dispatch` ''' return self.xmlrpcdispatcher.dispatch(raw_post_data, **kwargs) def get_method_name(self, raw_post_data, request_format='xml'): ''' Gets the name of the method to be called given the post data and the format of the data ''' if request_format == 'xml': # xmlrpclib.loads could throw an exception, but this is fine # since _marshaled_dispatch would throw the same thing try: params, method = xmlrpc.xmlrpc_client.loads(raw_post_data.decode('utf-8')) return method except Exception: return None else: try: # attempt to do a json decode on the data jsondict = json.loads(raw_post_data.decode('utf-8')) if not isinstance(jsondict, dict) or 'method' not in jsondict: return None else: return jsondict['method'] except ValueError: return None def list_methods(self): ''' Returns a list of RPCMethod objects supported by the server ''' return self.rpcmethods def register_method(self, method, name=None, signature=None, helpmsg=None): ''' Instantiates an RPCMethod object and adds it to ``rpcmethods`` so that it can be called by RPC requests **Parameters** ``method`` A callable Python method that the dispatcher will delegate to when requested via RPC ``name`` The name to make the method availabe. ``None`` signifies to use the method's actual name ``signature`` The signature of the method. See :meth:`rpc4django.rpcdispatcher.rpcmethod` ``helpmsg`` The "help" message displayed by introspection functions asking about the method ''' meth = RPCMethod(method, name, signature, helpmsg) if meth.name not in self.system_listmethods(): self.xmlrpcdispatcher.register_function(method, meth.name) self.jsonrpcdispatcher.register_function(method, meth.name) self.rpcmethods.append(meth) RESTRICT_INTROSPECTION = getattr(settings, 'RPC4DJANGO_RESTRICT_INTROSPECTION', False) RESTRICT_OOTB_AUTH = getattr(settings, 'RPC4DJANGO_RESTRICT_OOTB_AUTH', True) JSON_ENCODER = getattr(settings, 'RPC4DJANGO_JSON_ENCODER', 'django.core.serializers.json.DjangoJSONEncoder') try: # Python2 basestring except NameError: # Python3 basestring = str # resolve JSON_ENCODER to class if it's a string if isinstance(JSON_ENCODER, basestring): mod_name, cls_name = get_mod_func(JSON_ENCODER) json_encoder = getattr(import_module(mod_name), cls_name) else: json_encoder = JSON_ENCODER # instantiate the rpcdispatcher -- this examines the INSTALLED_APPS # for any @rpcmethod decorators and adds them to the callable methods dispatcher
<reponame>svz71195/XRBs import numpy as np from scipy.special import gammaincc, gamma from numba import njit class Integrate: @staticmethod def Riemann(func: np.ufunc, lim_l: float, lim_u: float, n: int, *arg: tuple) -> float: eval = np.linspace(lim_l,lim_u,n+1) delta = np.diff(eval) res = func(eval[:n]+delta/2,*arg)*delta return np.sum(res) @staticmethod def Riemann_log(func: np.ufunc, lim_l: float, lim_u: float, n: int, *arg: tuple) -> float: """ Custom implementation of a mid-point Riemann sum approximation with logarithmic measure. This is faster than and equally precise as 'scipy.integrate.quad()' specifically when integrating 'self.diff_Nhxb_met()'. Might also be faster than """ eval = np.logspace(np.log10(lim_l),np.log10(lim_u),n+1) delta = np.diff(eval) res = func(eval[:n]+delta/2,*arg)*delta return np.sum(res) @staticmethod def Riemann_log_log(func,lim_l,lim_u,n): eval = np.logspace(np.log10(lim_l),np.log10(lim_u),n) leval = np.log(eval) delta = np.diff(leval) res = func(eval[:n-1])*delta*eval[:n-1] return np.sum(res) @staticmethod def Simpson(func,lim_l,lim_u,n,*arg): eval = np.linspace(lim_l,lim_u,n+1) delta = np.diff(eval[::2]) f = func(eval,*arg) S = 1./6. * np.sum((f[0:-1:2] + 4*f[1::2] + f[2::2])*delta) return S @staticmethod def Simpson_log(func,lim_l,lim_u,n,*arg): eval = np.logspace(np.log10(lim_l),np.log10(lim_u),n+1) delta = np.diff(eval[::2]) f = func(eval,*arg) S = 1./6. * np.sum((f[0:-1:2] + 4*f[1::2] + f[2::2])*delta) return S @staticmethod def Trapez(func,lim_l,lim_u,n,*arg): eval = np.linspace(lim_l,lim_u,n+1) f = func(eval,*arg) delta = np.diff(eval) T = .5 * np.sum((f[1:]+f[:-1])*delta) return T @staticmethod def Trapez_log(func,lim_l,lim_u,n,*arg): eval = np.logspace(np.log10(lim_l),np.log10(lim_u),n+1) f = func(eval,*arg) delta = np.diff(eval) T = .5 * np.sum((f[1:]+f[:-1])*delta) return T def calc_sideon_matrix(angmom_vec): vec_in = np.asarray(angmom_vec) vec_in = vec_in / np.sum(vec_in ** 2).sum() ** 0.5 vec_p1 = np.cross([1, 0, 0], vec_in) vec_p1 = vec_p1 / np.sum(vec_p1 ** 2).sum() ** 0.5 vec_p2 = np.cross(vec_in, vec_p1) matr = np.concatenate((vec_p2, vec_in, vec_p1)).reshape((3, 3)) return matr def calc_faceon_matrix(angmom_vec, up=[0.0, 1.0, 0.0]): vec_in = np.asarray(angmom_vec) vec_in = vec_in / np.sum(vec_in ** 2).sum() ** 0.5 vec_p1 = np.cross(up, vec_in) vec_p1 = vec_p1 / np.sum(vec_p1 ** 2).sum() ** 0.5 vec_p2 = np.cross(vec_in, vec_p1) matr = np.concatenate((vec_p1, vec_p2, vec_in)).reshape((3, 3)) return matr def GammaIncc(a,x): """ Incomplete upper Gamma function optimized to also work with a < 0 (native scipy functions don't allow this) using recursion. See "http://en.wikipedia.org/wiki/Incomplete_gamma_function#Properties" Used for integration of HMXB LF model from Lehmer+21 of the form: exp(-x/b) * x**(-a) >>>> integration >>>> -b**(1-a)*Gamma(1-a,x/b) + C """ if a >= 0.: res = gammaincc(a,x)*gamma(a) else: res = ( GammaIncc(a+1,x)-x**(a)*np.exp(-x) ) / a return res class experimental: def diff_Nhxb_met(self, lum_in: float, A: float, logLb: float, logLc: float, logLc_logZ: float, g1: float, g2: float, g2_logZ: float, logOH12: float ) -> float: """ Differential function dN/dL for metallicity enhanced HMXB LF in Lehmer+21\\ Needs to be integrated numerically. See implementation of 'self.Riemann_log(func: ufunc, l_min: float, l_max: float, *par: tuple)'. NOTE: authors were not clear about normalization A in the Lehmer+21. They refer to Lehmer+19 for a non-metallicity model of HMXBs which is normalized to 1e38 erg/s ----- lum_in : input luminosity in units of 1.e38 erg/s A : model normalization at L = 1.e38 erg/s Lb : Power-law break luminosity logLc : base 10 logarithm of solar reference cut-off luminosity logLc_logZ : expansion constant of first derivative of log10(Z) dependent cut-off luminosity used to calculate LcZ g1 : Power-law slope of low luminosity regime g2 : solar Z reference Power-law slope of high luminosity regime g2_logZ : expansion constant of first derivative log10(Z) dependent Power-law slope logOH12 : metallicity measured as 12+log(O/H) ----- in function LcZ : metallicity dependent cut-off luminosity g2Z : metallicity dependent high L slope """ # need to rescale to 1.e38 erg/s normalization LcZ = 10**( logLc + logLc_logZ * ( logOH12 - 8.69 ) ) / 1.e38 Lb = 10**(logLb-38) g2Z = g2 + g2_logZ * ( logOH12 - 8.69 ) if lum_in < Lb: return A * np.exp(-lum_in/LcZ) * lum_in**(-g1) else: return A * np.exp(-lum_in/LcZ) * lum_in**(-g2Z) * Lb**(g2Z-g1) def model_Nhxb(self, case: str = '0', SFR: float = 1., bRand: bool = False ): """ Vectorization of analytic solutions. Depending on value passed to 'case',\\ different model parameters can be loaded ----- SFR : Rescaling parameter in units of Msun/yr bRand : boolean switching between randomized parameters\\ according to their uncertainty case : Decides which model to use, by passing KeyWord strings\\ 'Mi12s' -> Mineo+2012 single PL\\ 'Mi12b' -> Mineo+2012 broken PL\\ 'Le20' -> Lehmer+2020 broken PL\\ 'Le21' -> Lehmer+2021 metallicity\\ ... Can also be accessed by passing integers starting from 0 """ vec_calc_Nhxb_SPL = np.vectorize(self.calc_Nhxb_SPL) vec_calc_Nhxb_BPL = np.vectorize(self.calc_Nhxb_BPL) vec_calc_Nhxb_met = np.vectorize(self.diff_Nhxb_met) try: par: tuple = self.modelsH[case](bRand) except KeyError: raise KeyError("Desired model '"+str(case)+"' not implemented! Available models are", [key for key in self.modelsH.keys() if len(str(key))>2] ) if len(par) == 3: Nhx_arr = vec_calc_Nhxb_SPL(self.lumarr/1.e38, *par) elif len(par) == 5: Nhx_arr = vec_calc_Nhxb_BPL(self.lumarr/1.e38, *par) elif len(par) == 8: Nhx_arr = np.zeros_like(self.lumarr) # need integral of each input luminosity in self.lumarr normalized to 1.e38 # ----- # the step number 'n' is scaled by how far we are into lumarr # this is to save time at integration since the contribution of near LcZ is # marginal # for loop takes < 5 sec # ----- # par are parameters passed to func end = self.lumarr[-1] / 1.e38 N = len(self.lumarr) for i,lum in enumerate(self.lumarr/1.e38): if i <= 2000: steps = N else: # i == 2001 steps = int( N/np.sqrt((i-2000)/10.) ) Nhx_arr[i] = self.Riemann_log(func = vec_calc_Nhxb_met, lum_l = lum, lum_u = end, n = steps, *par) return Nhx_arr * SFR import xrb_units as xu class XRB: def __init__(self, nchan: int = 10000, Lmin: float = 35, Lmax: float = 41, Emin: float = 0.05, Emax: float = 50.1) -> None: self.nchan = nchan self.Lmin = Lmin self.Lmax = Lmax if self.Lmax < self.Lmin: raise ValueError("Lmax can't be smaller than Lmin!") if self.Lmin < 0: raise ValueError("Lmin can't be smaller than 0!") self.lumarr = np.logspace(Lmin, Lmax, self.nchan) self.Emin = Emin self.Emax = Emax if self.Emax < self.Emin: raise ValueError("Emax can't be smaller than Emin!") if self.Emin < 0: raise ValueError("Emin can't be smaller than 0!") # THIS WORKS !!! Sadly, too convoluted. Simpler is to instanciate subclasses of # XRB with model functions returning the complete model array # # self.modelsL = { # "Zh12" : self.Zhang12, # "0" : self.Zhang12, # 0 : self.Zhang12 # } # self.modelsH = { # "Mi12S" : self.Mineo12S, # "0" : self.Mineo12S, # 0 : self.Mineo12S, # "Mi12B" : self.Mineo12B, # "1" : self.Mineo12B, # 1 : self.Mineo12B, # "Le21" : self.Lehmer21, # "2" : self.Lehmer21, # 2 : self.Lehmer21, # } def calc_Zhang12(self, lum_in: float, K1: float, Lb1: float, Lb2: float, Lcut: float, alpha1: float, alpha2: float, alpha3: float) -> float: """ Analytic solution of broken Power-Law LMXB luminosity function (Zhang+12)\\ Used for vectorization in model_Nlxb() ----- lum_in : input luminosity in units of 1.e36 erg/s K1,K2,K3 : Normalization in units of 1.e11 solar masses Lb1 : First luminosity break in units of 1e36 erg/s Lb2 : Second luminosity break in 1e36 erg/s Lcut : Luminosity cut-off in 1.e36 erg/s alpha1 : Power-Law slope up to first break alpha2 : Power-Law slope from first to second break alpha3 : Power-Law slope from second break to cut-off """ K2: float = self.Knorm(K1,Lb1,Lb2,alpha2) K3: float = self.Knorm(K2,Lb2,Lcut,alpha3) if lum_in < Lb1: return( K1*Lb1**alpha1 * ( lum_in**(1.-alpha1) - Lb1**(1.-alpha1) ) / (alpha1-1.) + K2*Lb2**alpha2 * ( Lb1**(1.-alpha2)-Lb2**(1.-alpha2) ) / (alpha2-1.) + K3*Lcut**alpha3 * ( Lb2**(1.-alpha3)-Lcut**(1.-alpha3) ) / (alpha3-1.) ) elif lum_in >= Lb1 and lum_in < Lb2: return( K2*Lb2**alpha2 * ( lum_in**(1.-alpha2) - Lb2**(1.-alpha2) ) / (alpha2-1.) + K3*Lcut**alpha3 * ( Lb2**(1.-alpha3) - Lcut**(1.-alpha3) ) / (alpha3-1.) ) elif lum_in >= Lb2 and lum_in < Lcut: return K3*Lcut**alpha3 * ( lum_in**(1.-alpha3) - Lcut**(1.-alpha3) ) / (alpha3-1.) else: return 0 def calc_SPL(self, lum_in: float, xi: float, Lcut: float, gamma: float ) -> float: """ Analytic solution of single Power-Law integral for luminosity functions\\ Used for vectorization in model_Nhxb() ----- lum_in : input luminosity in units of 1.e38 erg/s xi : normalization constant Lcut : Luminosity cut-off in 1.e38 erg/s gamma : Power-Law slope SFR : Star-Formation-Rate
0: gdaltest.post_reason('fail') return 'fail' lyr = ds.GetLayer(0) f = lyr.GetNextFeature() lyr.SetFeature(f) f = None gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' ds = None shutil.rmtree('tmp/test.gdb.ogredited') lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: if filename.find('.tmp') >= 0: gdaltest.post_reason('fail') print(lst) return 'fail' # Test an error case where we simulate a failure in moving # a file into original directory (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' lyr = ds.GetLayer(0) f = lyr.GetNextFeature() lyr.SetFeature(f) f = None gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE3') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' ds = None shutil.rmtree('tmp/test.gdb.ogredited') # Remove left over .tmp files lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: if filename.find('.tmp') >= 0: os.remove('tmp/test.gdb/' + filename) # Test not critical error in removing a temporary file for case in ('CASE4', 'CASE5'): (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' lyr = ds.GetLayer(0) f = lyr.GetNextFeature() lyr.SetFeature(f) f = None gdal.SetConfigOption('FGDB_SIMUL_FAIL', case) gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret != 0: gdaltest.post_reason('fail') print(case) return 'fail' ds = None if case == 'CASE4': try: os.stat('tmp/test.gdb.ogredited') gdaltest.post_reason('fail') print(case) return 'fail' except: pass else: shutil.rmtree('tmp/test.gdb.ogredited') # Remove left over .tmp files lst = gdal.ReadDir('tmp/test.gdb') for filename in lst: if filename.find('.tmp') >= 0: os.remove('tmp/test.gdb/' + filename) else: # Test an error case where we simulate a failure of rename from .gdb to .gdb.ogrtmp during commit (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE1') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' ds = None # Test an error case where we simulate a failure of rename from .gdb.ogredited to .gdb during commit (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' ds = None os.rename('tmp/test.gdb.ogrtmp', 'tmp/test.gdb') # Test an error case where we simulate a failure of removing from .gdb.ogrtmp during commit (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE3') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret != 0: gdaltest.post_reason('fail') return 'fail' ds = None shutil.rmtree('tmp/test.gdb.ogrtmp') # Test an error case where we simulate a failure of reopening the committed DB (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE_REOPEN') gdal.PushErrorHandler() ret = ds.CommitTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' if ds.GetLayerCount() != 0: gdaltest.post_reason('fail') return 'fail' ds = None # Test an error case where we simulate a failure of removing from .gdb.ogredited during rollback (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE1') gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' ds = None shutil.rmtree('tmp/test.gdb.ogredited') # Test an error case where we simulate a failure of reopening the rollbacked DB (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') lyr = ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() if ds.StartTransaction(force = True) != 0: gdaltest.post_reason('fail') return 'fail' gdal.SetConfigOption('FGDB_SIMUL_FAIL', 'CASE2') gdal.PushErrorHandler() ret = ds.RollbackTransaction() gdal.PopErrorHandler() gdal.SetConfigOption('FGDB_SIMUL_FAIL', None) if ret == 0: gdaltest.post_reason('fail') return 'fail' if ds.GetLayerCount() != 0: gdaltest.post_reason('fail') return 'fail' ds = None if ogrtest.openfilegdb_drv is not None: ogrtest.openfilegdb_drv.Deregister() return 'success' # Same, but retry without per-layer copying optimization (in the case # this was what was tested in previous step) def ogr_fgdb_19bis(): if ogrtest.fgdb_drv is None: return 'skip' (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update('tmp/test.gdb') del ds if not bPerLayerCopyingForTransaction: return 'skip' gdal.SetConfigOption('FGDB_PER_LAYER_COPYING_TRANSACTION', 'FALSE') ret = ogr_fgdb_19() gdal.SetConfigOption('FGDB_PER_LAYER_COPYING_TRANSACTION', None) return ret ############################################################################### # Test CreateFeature() with user defined FID def ogr_fgdb_20(): if ogrtest.fgdb_drv is None: return 'skip' if ogrtest.openfilegdb_drv is None: return 'skip' if not os.path.exists('tmp/test.gdb'): ds = ogrtest.fgdb_drv.CreateDataSource("tmp/test.gdb") ds = None # We need the OpenFileGDB driver for CreateFeature() with user defined FID ogrtest.openfilegdb_drv.Register() ds = ogr.Open('tmp/test.gdb', update = 1) ogrtest.openfilegdb_drv.Deregister() ogrtest.fgdb_drv.Deregister() # Force OpenFileGDB first ogrtest.openfilegdb_drv.Register() ogrtest.fgdb_drv.Register() lyr = ds.CreateLayer('ogr_fgdb_20', geom_type = ogr.wkbNone) lyr.CreateField(ogr.FieldDefn('id', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('str', ogr.OFTString)) ds.ExecuteSQL('CREATE INDEX ogr_fgdb_20_id ON ogr_fgdb_20(id)') f = ogr.Feature(lyr.GetLayerDefn()) f.SetField('id', 1) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 1 or lyr.GetMetadataItem('1', 'MAP_OGR_FID_TO_FGDB_FID') is not None: gdaltest.post_reason('fail') return 'fail' # Existing FID gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') return 'fail' for invalid_fid in [-2,0,9876543210]: f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(invalid_fid) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') print(invalid_fid) return 'fail' f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(2) f.SetField('id', 2) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 2 or lyr.GetMetadataItem('2', 'MAP_OGR_FID_TO_FGDB_FID') is not None: gdaltest.post_reason('fail') f.DumpReadable() return 'fail' # OGR FID = 4, FileGDB FID = 3 f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(4) f.SetField('id', 4) # Cannot call CreateFeature() with a set FID when a dataset is opened more than once ds2 = ogr.Open('tmp/test.gdb', update = 1) gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') return 'fail' ds2 = None ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 4 or lyr.GetMetadataItem('4', 'MAP_OGR_FID_TO_FGDB_FID') != '3': gdaltest.post_reason('fail') f.DumpReadable() print(lyr.GetMetadataItem('4', 'MAP_OGR_FID_TO_FGDB_FID')) return 'fail' # Cannot open geodatabase at the moment since it is in 'FID hack mode' gdal.PushErrorHandler() ds2 = ogr.Open('tmp/test.gdb', update = 1) gdal.PopErrorHandler() if ds2 is not None: gdaltest.post_reason('fail') return 'fail' ds2 = None # Existing FID, but only in OGR space gdal.PushErrorHandler() ret = lyr.CreateFeature(f) gdal.PopErrorHandler() if ret == 0: gdaltest.post_reason('fail') return 'fail' # This FID exists as a FGDB ID, but should not be user visible. f.SetFID(3) ret = lyr.SetFeature(f) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: gdaltest.post_reason('fail') return 'fail' ret = lyr.DeleteFeature(3) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: gdaltest.post_reason('fail') return 'fail' ret = lyr.GetFeature(3) if ret is not None: gdaltest.post_reason('fail') return 'fail' # Trying to set OGR FID = 3 --> FileGDB FID = 4 f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(3) f.SetField('id', 3) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 3 or lyr.GetMetadataItem('3', 'MAP_OGR_FID_TO_FGDB_FID') != '4': gdaltest.post_reason('fail') f.DumpReadable() return 'fail' lyr.ResetReading() expected = [ (1, None), (2, None), (4, 3), (3, 4) ] for i in range(2): for (fid, fgdb_fid) in expected: if i == 0: f = lyr.GetNextFeature() else: f = lyr.GetFeature(fid) if f is None: gdaltest.post_reason('fail') return 'fail' if f.GetFID() != fid or f.GetField('id') != fid: gdaltest.post_reason('fail') f.DumpReadable() print(fid) return 'fail' got_fgdb_fid = lyr.GetMetadataItem(str(f.GetFID()), 'MAP_OGR_FID_TO_FGDB_FID') if got_fgdb_fid is None: if fgdb_fid is not None: gdaltest.post_reason('fail') return 'fail' elif int(got_fgdb_fid) != fgdb_fid: gdaltest.post_reason('fail') print(got_fgdb_fid) print(fgdb_fid) return 'fail' for fid in [ -9876543210, 0, 100]: f = lyr.GetFeature(fid) if f is not None: gdaltest.post_reason('fail') f.DumpReadable() return 'fail' for invalid_fid in [-2,0,9876543210]: f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(invalid_fid) ret = lyr.SetFeature(f) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: gdaltest.post_reason('fail') return 'fail' ret = lyr.DeleteFeature(invalid_fid) if ret != ogr.OGRERR_NON_EXISTING_FEATURE: gdaltest.post_reason('fail') return 'fail' f = lyr.GetFeature(3) f.SetField('str', '3') ret = lyr.SetFeature(f) if ret != 0: gdaltest.post_reason('fail') return 'fail' f = lyr.GetFeature(3) if f.GetField('str') != '3': gdaltest.post_reason('fail') return 'fail' ret = lyr.DeleteFeature(1) if ret != 0: gdaltest.post_reason('fail') return 'fail' ret = lyr.DeleteFeature(3) if ret != 0: gdaltest.post_reason('fail') return 'fail' for (fid, fgdb_fid) in [ (3, 5), (2049,6), (10,7), (7,8), (9, None), (8, 10), (12, 11) ]: f = ogr.Feature(lyr.GetLayerDefn()) f.SetFID(fid) f.SetField('id', fid) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != fid or str(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) != str(fgdb_fid): gdaltest.post_reason('fail') f.DumpReadable() print(fid) print(lyr.GetMetadataItem(str(fid), 'MAP_OGR_FID_TO_FGDB_FID')) return 'fail' # Normally 12 should be attributed, but it has already been reserved f = ogr.Feature(lyr.GetLayerDefn()) ret = lyr.CreateFeature(f) if ret != 0 or f.GetFID() != 13: gdaltest.post_reason('fail') f.DumpReadable() return 'fail' f.SetField('id', f.GetFID()) lyr.SetFeature(f) lyr.ResetReading() expected = [ (2, None), (4, 3), (3, 5), (2049,6), (10,7), (7,8), (9, None), (8, 10) ] for (fid, fgdb_fid) in expected: f = lyr.GetNextFeature() if f is None: gdaltest.post_reason('fail') return 'fail' if f.GetFID() != fid or f.GetField('id') != fid
actions = list(zip(moregrofman_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) # Own previous move was C, opponent defected 3 or more times in last 8 moregrofman_actions = ([C] * 3 + [D] * 3 + [C]) + [D] opponent_actions = ([C] * 2 + [D] * 3 + [C] * 2) + [D] opponent = axl.MockPlayer(actions=opponent_actions) actions = list(zip(moregrofman_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) # Own previous move was D, opponent defected once or less in last 8 moregrofman_actions = ([C] * 6 + [D]) + [C] opponent_actions = ([C] * 5 + [D] * 1 + [C]) + [D] opponent = axl.MockPlayer(actions=opponent_actions) actions = list(zip(moregrofman_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) # Own previous move was D, opponent defected more than once in last 8 moregrofman_actions = ([C] * 2 + [D] * 5) + [D] opponent_actions = ([D] * 7) + [D] opponent = axl.MockPlayer(actions=opponent_actions) actions = list(zip(moregrofman_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) # Test to make sure logic matches Fortran (discrepancy found 8/23/2017) opponent = axl.AntiTitForTat() # Actions come from a match run by Axelrod Fortran using Player('k86r') actions = [ (C, C), (C, D), (D, D), (D, C), (C, C), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), ] self.versus_test(opponent, expected_actions=actions) # Test to match the Fortran implementation for 30 rounds opponent = axl.AntiTitForTat() actions = [ (C, C), (C, D), (D, D), (D, C), (C, C), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), (C, D), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), ] self.versus_test(opponent, expected_actions=actions) # Test to match the Fortran implementation for 60 rounds opponent = axl.AntiTitForTat() actions = [ (C, C), (C, D), (D, D), (D, C), (C, C), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), (C, D), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), (C, D), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), (C, D), (C, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (D, C), (C, C), (C, D), (C, D), (C, D), (C, D), (D, D), (D, C), ] self.versus_test(opponent, expected_actions=actions) class TestKluepfel(TestPlayer): name = "<NAME>" player = axl.SecondByKluepfel expected_classifier = { "memory_depth": float("inf"), "stochastic": True, "makes_use_of": set(), "long_run_time": False, "inspects_source": False, "manipulates_source": False, "manipulates_state": False, } def test_strategy(self): actions = [(C, C)] * 100 # Cooperate forever self.versus_test(axl.Cooperator(), expected_actions=actions) # Since never two in a row, will respond in kind with 70% if # coop and 60% otherwise, after first couple actions = [ (C, C), (C, D), # Views first three as the same. # A random gets used in each of the first two. (D, C), (D, D), (C, C), (C, D), ] self.versus_test(axl.Alternator(), expected_actions=actions, seed=1) actions = [(C, C), (C, D), (C, C), (D, D), (D, C), (C, D)] self.versus_test(axl.Alternator(), expected_actions=actions, seed=2) actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] self.versus_test(axl.Alternator(), expected_actions=actions, seed=3) # Now we have to test the detect-random logic, which doesn't pick up # until after 26 turns. So we need a big sample. actions = [ (C, D), (D, D), (D, D), (D, D), (D, D), (D, C), (C, C), (C, D), (C, C), (D, D), (D, C), (C, C), (C, D), (D, D), (C, D), (D, D), (D, C), (C, C), (D, C), (C, C), (C, D), (D, D), (D, C), (C, D), (D, C), (C, C), (C, D), # Success detect random opponent for remaining turns. (D, D), (D, D), (D, D), (D, C), (D, D), (D, C), (D, D), (D, C), (D, D), (D, C), (D, C), (D, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, D), (D, C), (D, C), (D, C), (D, C), (D, D), ] self.versus_test(axl.Random(0.5), expected_actions=actions, seed=10) class TestBorufsen(TestPlayer): name = "<NAME>" player = axl.SecondByBorufsen expected_classifier = { "memory_depth": float("inf"), "stochastic": False, "makes_use_of": set(), "long_run_time": False, "inspects_source": False, "manipulates_source": False, "manipulates_state": False, } def test_strategy(self): actions = [(C, C)] * 100 # Cooperate forever self.versus_test(axl.Cooperator(), expected_actions=actions) # Tries to cooperate every third time until detecting defective actions = ( [(C, D), (D, D), (D, D), (D, D)] * 6 + [(C, D), (D, D)] + [(D, D)] * 100 ) self.versus_test(axl.Defector(), expected_actions=actions) # Alternates with additional coop, every sixth turn # Won't be labeled as random, since 2/3 of opponent's C follow # player's C # `flip_next_defect` will get set on the sixth turn, which changes the # seventh action # Note that the first two turns of each period of six aren't # marked as echoes, and the third isn't marked that way until the # fourth turn. actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D)] * 20 self.versus_test(axl.Alternator(), expected_actions=actions) # Basically does tit-for-tat against Win-Shift, Lose-Stay D # After 26 turns, will detect random since half of opponent's C follow # Cs # Coming out of it, there will be new pattern. Then random is detected # again. actions = ( [(C, D), (D, C), (C, C)] * 8 + [(C, D), (D, C)] + [(D, C)] * 25 + [(D, C)] + [(C, C), (C, D), (D, C)] * 8 + [(D, C)] * 25 ) self.versus_test(axl.WinShiftLoseStay(D), expected_actions=actions) class TestCave(TestPlayer): name = "<NAME>" player = axl.SecondByCave expected_classifier = { "memory_depth": float("inf"), "stochastic": True, "makes_use_of": set(), "long_run_time": False, "inspects_source": False, "manipulates_source": False, "manipulates_state": False, } def test_strategy(self): actions = [(C, C)] * 100 self.versus_test(axl.Cooperator(), expected_actions=actions) # It will take until turn 18 to respond decide to repond D->D actions = [(C, D)] actions += [ (C, D), (D, D), (D, D), (C, D), (C, D), (C, D), (D, D), (D, D), (C, D), (C, D), (D, D), (C, D), (D, D), (C, D), (C, D), (D, D), (C, D), ] # Randomly choose actions += [(D, D)] * 30 # Defect self.versus_test(axl.Defector(), expected_actions=actions, seed=1) # Highly-defective opponent # It will take until turn 20 to respond decide to repond D to C opponent_actions = [D] * 17 + [C, C, C, C] almost_defector = axl.MockPlayer(actions=opponent_actions) actions = [(C, D)] actions += [ (C, D), (D, D), (D, D), (C, D), (C, D), (C, D), (D, D), (D, D), (C, D), (C, D), (D, D), (C, D), (D, D), (C, D), (C, D), (D, D), (C, C), ] # Randomly choose actions += [(C, C)] # Coop for a minute actions += [(D, C), (D, C)] self.versus_test(almost_defector, expected_actions=actions, seed=1) # Here it will take until turn 40 to detect random and defect actions = [(C, C)] actions += [ (C, D), (D, C), (C, D), (D, C), (C, D), (C, C), (C, D), (C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (D, C), (C, D), (C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (D, C), (C, D), (C, C), (C, D), (C, C), (C, D), (C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (D, C), (C, D), ] # Randomly choose actions += [ (D, C), (C, D), (D, C), ] # 17 D have come, so tit for tat for a while actions += [(D, D), (D, C)] * 100 # Random finally detected self.versus_test(axl.Alternator(), expected_actions=actions, seed=2) class TestWmAdams(TestPlayer): name = "<NAME>" player = axl.SecondByWmAdams expected_classifier = { "memory_depth": float("inf"), "stochastic": True, "makes_use_of": set(),
# Copyright 2017 <NAME>, <EMAIL> # # Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee # is hereby granted, provided that the above copyright notice and this permission notice appear in all # copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE # FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, # ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import numpy as np import cPickle as cPickle import os import matplotlib.pyplot as plt from py_dp.dispersion.dispersion_visualization_tools import plume_msd_com_multiple_times, \ plume_location_multiple_times, plume_bt_multiple_locations, save_plume_2d_with_kde def generate_plot_data(t_end, t_scale, stencil_dt, data_save_folder, model_array, data, l, theta, n_points_moments=12, n_steps_plumes=5, moments=True, plumes=True, bt=True, two_d=False, kdepoints = 200000, n_pores=500, bt_bound_box=None, hists=True, avg_data=None, trajectories = True, avg_data_folder=None, plume_target_times=None, plume_target_flag=None, moment_data_target_times=None, moment_model_target_times=None, l_frac_array=None): if not stencil_dt: stencil_dt = 1e-3 # save t_end, t_scale, stencil_dt. Useful for the plots. time_file_path = os.path.join(data_save_folder, 'time_file.npz') np.savez(time_file_path, t_end=t_end, t_scale=t_scale, stencil_dt=stencil_dt) # save l. theta network_spec_file = os.path.join(data_save_folder, 'network_specs.npz') np.savez(network_spec_file, l=l, theta=theta) xmax = n_pores * l * np.cos(theta) dt_mean = t_scale # set plotting times for plumes and moments if plume_target_times is None: print 'Warning: target times for plumes not specified.' print 'trying to set reasonable times...' target_time_array = np.linspace(stencil_dt, t_end, n_steps_plumes)[1:] target_time_array = np.floor(target_time_array / (1.0 * dt_mean)) * 1.0 * dt_mean # flag used to specify whether the target time is for validation target_time_validation_flag = np.zeros(len(target_time_array)) else: target_time_array = plume_target_times if plume_target_flag is None: target_time_validation_flag = np.zeros(len(target_time_array)) else: target_time_validation_flag = plume_target_flag n_points = n_points_moments print 'calculating plume moments...' if moment_data_target_times is None: print 'Warning: target times for data moments not specified.' print 'trying to set reasonable times...' target_time_array_data = np.linspace(0.0, np.log(t_end / dt_mean), n_points) target_time_array_data = np.hstack((0.0, np.exp(target_time_array_data))) * dt_mean else: target_time_array_data = moment_data_target_times if moment_model_target_times is None: print 'Warning: target times for model moments not specified.' print 'trying to set reasonable times...' target_time_array_model = np.linspace(np.log(stencil_dt / dt_mean), np.log(t_end / dt_mean), n_points) target_time_array_model = np.exp(target_time_array_model) * dt_mean else: target_time_array_model = moment_model_target_times # save plotting times for plumes and moments target_times_path = os.path.join(data_save_folder, 'target_times.npz') np.savez(target_times_path, target_time_array=target_time_array, target_time_validation_flag=target_time_validation_flag, target_time_array_data=target_time_array_data, target_time_array_model=target_time_array_model) # plot the evolution first and second moment of the plume if moments: com_x_model_array = [] com_y_model_array = [] msd_x_model_array = [] msd_y_model_array = [] kurt_x_model_array, kurt_y_model_array, skew_x_model_array, \ skew_y_model_array = [[] for _ in range(4)] for model in model_array: com_x_model, msd_x_model, com_y_model, msd_y_model, skew_x_model, skew_y_model, kurt_x_model,\ kurt_y_model = plume_msd_com_multiple_times(target_time_array_model, model) for parent, child in zip([com_x_model_array, com_y_model_array, msd_x_model_array, msd_y_model_array, skew_x_model_array, skew_y_model_array, kurt_x_model_array, kurt_y_model_array], [com_x_model, com_y_model, msd_x_model, msd_y_model, skew_x_model, skew_y_model, kurt_x_model, kurt_y_model]): parent.append(child) # com_x_model_array.append(com_x_model) # com_y_model_array.append(com_y_model) # msd_x_model_array.append(msd_x_model) # msd_y_model_array.append(msd_y_model) save_name = 'model_moments' save_path = os.path.join(data_save_folder, save_name+'.npz') np.savez(save_path, com_x=com_x_model_array, com_y=com_y_model_array, msd_x=msd_x_model_array, msd_y=msd_y_model_array, skew_x=skew_x_model_array, skew_y=skew_y_model_array, kurt_x=kurt_x_model_array, kurt_y=kurt_y_model_array) com_x_data, msd_x_data, com_y_data, msd_y_data, skew_x_data, skew_y_data, kurt_x_data,\ kurt_y_data = plume_msd_com_multiple_times(target_time_array_data, data) save_name = 'data_moments' save_path = os.path.join(data_save_folder, save_name + '.npz') np.savez(save_path, com_x=com_x_data, com_y=com_y_data, msd_x=msd_x_data, msd_y=msd_y_data, skew_x=skew_x_data, skew_y=skew_y_data, kurt_x=kurt_x_data, kurt_y=kurt_y_data) if plumes: print "calculating the plume spreading in x and y direction" n_steps = n_steps_plumes data_plume_x_array = [] data_plume_y_array = [] data_labels = [] #no loop needed for data xtemp, ytemp = plume_location_multiple_times(target_time_array, data.x_array, data.y_array, data.t_array) data_plume_x_array.append(xtemp) data_plume_y_array.append(ytemp) data_labels.append(data.label) #loop for model model_plume_x_array = [] model_plume_y_array = [] stencil_labels = [] for model in model_array: xtemp, ytemp = plume_location_multiple_times(target_time_array, model.x_array, model.y_array, model.t_array) model_plume_x_array.append(xtemp) model_plume_y_array.append(ytemp) stencil_labels.append(model.label) save_name = 'data_plumes' save_path = os.path.join(data_save_folder, save_name + '.pkl') out = [data_plume_x_array, data_plume_y_array] with open(save_path, 'wb') as outfile: cPickle.dump(out, outfile, cPickle.HIGHEST_PROTOCOL) save_name = 'model_plumes' save_path = os.path.join(data_save_folder, save_name+'.pkl') out = [model_plume_x_array, model_plume_y_array] with open(save_path, 'wb') as outfile: cPickle.dump(out, outfile, cPickle.HIGHEST_PROTOCOL) if bt: print 'BT curves: calculating time to a given location' if l_frac_array is None: l_frac_array = np.array([0.25, 0.5, 0.75]) # save l_frac_array, multiples of one domain length used for plotting l_frac_path = os.path.join(data_save_folder, 'l_frac.npz') np.savez(l_frac_path, l_frac_array=l_frac_array) target_x_array = l_frac_array*xmax data_bt_array = [] data_labels = [] #no loop needed for data # for data in data_array: print 'data BT' ttemp = plume_bt_multiple_locations(target_x_array, data.x_array, data.t_array) data_bt_array.append(ttemp) data_labels.append(data.label) model_bt_array = [] stencil_labels = [] print 'model BT' for model in model_array: ttemp = plume_bt_multiple_locations(target_x_array, model.x_array, model.t_array) model_bt_array.append(ttemp) stencil_labels.append(model.label) save_name = 'data_bt' save_path = os.path.join(data_save_folder, save_name + '.pkl') with open(save_path, 'wb') as outfile: cPickle.dump(data_bt_array, outfile, cPickle.HIGHEST_PROTOCOL) save_name = 'model_bt' save_path = os.path.join(data_save_folder, save_name + '.pkl') with open(save_path, 'wb') as outfile: cPickle.dump(model_bt_array, outfile, cPickle.HIGHEST_PROTOCOL) if two_d: #plot the average plume in 2d print 'generating 2d plume data only for the first model...' plt.rc('text', usetex=False) n_query = 100j model = model_array[0] save_plume_2d_with_kde(target_time_array, n_query, model, data, data_save_folder, max_samples=kdepoints) if hists: print 'generating data for velocity and angle histogram...' if avg_data is None: print 'histograms need the average data to be passed in!' else: data_hist_v, data_hist_theta, v_edges, theta_edges = get_v_theta_hist_avg_data(avg_data) model_hist_v_array , model_hist_theta_array = [[] for _ in range(2)] save_name = 'data_hists' save_path = os.path.join(data_save_folder, save_name + '.npz') np.savez(save_path, hist_v=data_hist_v, hist_theta=data_hist_theta, v_edges=v_edges, theta_edges=theta_edges) for model in model_array: model_hist_v, model_hist_theta = get_v_theta_hist_model(model, v_edges, theta_edges) model_hist_v_array.append(model_hist_v) model_hist_theta_array.append(model_hist_theta) save_name = 'model_hists' save_path = os.path.join(data_save_folder, save_name + '.npz') np.savez(save_path, hist_v=model_hist_v_array, hist_theta=model_hist_theta_array) if trajectories: # make subfolder for trajectories traj_save_folder = os.path.join(data_save_folder, 'traj_data') if not os.path.exists(traj_save_folder): os.mkdir(traj_save_folder) if avg_data_folder is None: print 'path to average data is needed' else: print 'generating data for comparison of v, theta trajectories btw model and averaged data' # load average data files cartesian = np.load(os.path.join(avg_data_folder, 'avg_cartesian_0.npz')) polar = np.load(os.path.join(avg_data_folder, 'avg_polar_0.npz')) # save 10 trajectories n_traj = 8 # Assuming there is one model model = model_array[0] model_dict = generate_model_dict(model) rand_idx = np.random.randint(0, model_dict['DX'].shape[0], n_traj) for plot_variable in ['Theta', 'V', 'DX', 'DY']: if plot_variable in ['DY', 'DX', 'Y']: holder = cartesian else: holder = polar target, t_array, min_length, min_val, max_val = get_traj_details_npz(holder, plot_variable, n_traj, dt_mean) file_name = 'data_traj_'+plot_variable file_path = os.path.join(traj_save_folder, file_name) np.savez(file_path, target=target, t_array=t_array, min_length=min_length, min_val=min_val, max_val=max_val) model_target = [] for i in rand_idx: model_target.append(model_dict[plot_variable][i,:]) file_name = 'model_traj_' + plot_variable file_path = os.path.join(traj_save_folder, file_name) np.savez(file_path, target=model_target) def generate_model_dict(model): ''' make a small sample of particle trajectories and put them in a dictionary :param model: :return: ''' sample_idx = np.random.randint(0, model.x_array.shape[0], 100) dx_model = np.diff(model.x_array[sample_idx, :]) dy_model = np.diff(model.y_array[sample_idx, :]) dt_model = np.diff(model.t_array[sample_idx, :]) + 1e-15 VMatrix = np.sqrt(np.power(dx_model, 2) + np.power(dy_model, 2)) / dt_model thetaMatrix = np.arctan2(dy_model, dx_model) # put it all in one dictionary model_dict = {} model_dict['DX'] = dx_model model_dict['DY'] = dy_model model_dict['V'] = VMatrix model_dict['Theta'] = thetaMatrix return model_dict def get_traj_details_npz(store_object, field, n_traj, t_scale): indices = np.random.randint(0, len(store_object['ptr'])-1, n_traj) ptr_array = store_object['ptr'] target_array = [] target_len_array = [] min_val, max_val = np.inf, -np.inf for i in indices: start, end = int(ptr_array[i]), int(ptr_array[i+1]) temp_target = store_object[field][start:end] target_array.append(temp_target) target_len_array.append(len(temp_target)) min_val = min(min(temp_target), min_val) max_val = max(max(temp_target), max_val) min_length = min(target_len_array) dt = store_object['dt'] dt_array = range(min_length)*dt/t_scale t_array = np.cumsum(dt_array) return target_array, t_array, min_length, min_val, max_val def get_v_theta_hist_avg_data(avg_data, n_bins=100): hist_v, edges_v = np.histogram(np.log(avg_data['v_flat_f_added']), n_bins, density=True) hist_theta, edges_theta = np.histogram(avg_data['theta_flat_f_added'], n_bins, density=True) return hist_v, hist_theta, edges_v, edges_theta def get_v_theta_hist_model(model, v_edges, theta_edges): v_mat = np.sqrt(np.diff(model.x_array) ** 2 + np.diff(model.y_array) ** 2) v_mat = v_mat / np.diff(model.t_array) model_v_flat = np.reshape(v_mat, (-1, 1)) theta_mat = np.arctan2(np.diff(model.y_array), np.diff(model.x_array)) model_theta_flat = np.reshape(theta_mat, (-1, 1)) hist_v, _ = np.histogram(np.log(model_v_flat), v_edges, density=True) hist_theta, _ = np.histogram(model_theta_flat, theta_edges, density=True) return hist_v, hist_theta # def plot_wrapper(t_end, dt_mean, stencil_dt, save_folder, save_name, model_array, data, # model_labels, l, theta, y_correction, lw, fmt, moments=True, plumes=True, bt = True, two_d=False): # """ # :param t_end: final pot time # :param dt_mean: average jump time from data # :param stencil_dt: dt used for the stencil # :param save_folder: main folder to save these plots # :param save_name: prefix name for saving # :param model_array: # :param data: # :param model_labels: # :param l: # :param theta: # :param y_correction: # :param lw: # :param fmt: # :return: # """ # t_scale = dt_mean # l_scale = l # data.label = r'$data$' # data_array = [data] # # binning extents # xmin = 0.0 # xmax = 500.0 * l * np.cos(theta) # # plot the evolution
.push() .new_branch("drop-constraint") .commit("Drop unneeded SQL constraints") .check_out("call-ws") .commit("2nd round of fixes") .check_out("root") .new_branch("master") .commit("Master commit") .push() .new_branch("hotfix/add-trigger") .commit("HOTFIX Add the trigger") .push() .commit_amend("HOTFIX Add the trigger (amended)") .new_branch("ignore-trailing") .commit("Ignore trailing data") .sleep(1) .commit_amend("Ignore trailing data (amended)") .push() .reset_to("ignore-trailing@{1}") .delete_branch("root") ) self.launch_command("discover", "-y", "--roots=develop,master") self.assert_command( ["status"], """ develop | x-allow-ownership-link (ahead of origin) | | | x-build-chain (untracked) | o-call-ws (ahead of origin) | x-drop-constraint (untracked) master | o-hotfix/add-trigger (diverged from origin) | o-ignore-trailing * (diverged from & older than origin) """, ) @mock.patch('git_machete.cli.exit_script', mock_exit_script) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_branch_reappears_in_definition(self) -> None: body: str = \ """master \tdevelop \t\n develop """ self.repo_sandbox.new_branch("root") self.rewrite_definition_file(body) expected_error_message: str = '.git/machete, line 5: branch `develop` re-appears in the tree definition. ' \ 'Edit the definition file manually with `git machete edit`' with self.assertRaises(MacheteException) as e: self.launch_command('status') if e: self.assertEqual(e.exception.parameter, expected_error_message, 'Verify that expected error message has appeared a branch re-appears in tree definition.') @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_show(self) -> None: self.setup_discover_standard_tree() self.assertEqual( self.launch_command( "show", "up", ).strip(), "hotfix/add-trigger" ) self.assertEqual( self.launch_command( "show", "up", "call-ws", ).strip(), "develop" ) self.assertEqual( self.launch_command( "show", "current" ).strip(), "ignore-trailing" ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_traverse_no_push(self) -> None: self.setup_discover_standard_tree() self.launch_command("traverse", "-Wy", "--no-push") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes o-allow-ownership-link (diverged from origin) | | | | Build arbitrarily long chains | o-build-chain (untracked) | | Call web service | 1st round of fixes | 2nd round of fixes o-call-ws (ahead of origin) | | Drop unneeded SQL constraints o-drop-constraint (untracked) master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger (diverged from origin) | | Ignore trailing data (amended) o-ignore-trailing * """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_traverse_no_push_override(self) -> None: self.setup_discover_standard_tree() self.repo_sandbox.check_out("hotfix/add-trigger") self.launch_command("t", "-Wy", "--no-push", "--push", "--start-from=here") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes x-allow-ownership-link (ahead of origin) | | | | Build arbitrarily long chains | x-build-chain (untracked) | | Call web service | 1st round of fixes | 2nd round of fixes o-call-ws (ahead of origin) | | Drop unneeded SQL constraints x-drop-constraint (untracked) master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger * | | Ignore trailing data (amended) o-ignore-trailing """, ) self.repo_sandbox.check_out("ignore-trailing") self.launch_command("t", "-Wy", "--no-push", "--push") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes o-allow-ownership-link | | | | Build arbitrarily long chains | o-build-chain | | Call web service | 1st round of fixes | 2nd round of fixes o-call-ws | | Drop unneeded SQL constraints o-drop-constraint master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger | | Ignore trailing data (amended) o-ignore-trailing * """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_traverse_no_push_untracked(self) -> None: self.setup_discover_standard_tree() self.launch_command("traverse", "-Wy", "--no-push-untracked") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes o-allow-ownership-link | | | | Build arbitrarily long chains | o-build-chain (untracked) | | Call web service | 1st round of fixes | 2nd round of fixes o-call-ws | | Drop unneeded SQL constraints o-drop-constraint (untracked) master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger | | Ignore trailing data (amended) o-ignore-trailing * """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_discover_traverse_squash(self) -> None: self.setup_discover_standard_tree() self.launch_command("traverse", "-Wy") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes o-allow-ownership-link | | | | Build arbitrarily long chains | o-build-chain | | Call web service | 1st round of fixes | 2nd round of fixes o-call-ws | | Drop unneeded SQL constraints o-drop-constraint master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger | | Ignore trailing data (amended) o-ignore-trailing * """, ) # Go from ignore-trailing to call-ws which has >1 commit to be squashed for _ in range(4): self.launch_command("go", "prev") self.launch_command("squash") self.assert_command( ["status", "-l"], """ develop | | Allow ownership links | 1st round of fixes o-allow-ownership-link | | | | Build arbitrarily long chains | o-build-chain | | Call web service o-call-ws * (diverged from origin) | | Drop unneeded SQL constraints x-drop-constraint master | | HOTFIX Add the trigger (amended) o-hotfix/add-trigger | | Ignore trailing data (amended) o-ignore-trailing """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_slide_out(self) -> None: ( self.repo_sandbox.new_branch("develop") .commit("develop commit") .push() .new_branch("slide_root") .commit("slide_root_1") .push() .check_out("slide_root") .new_branch("child_a") .commit("child_a_1") .push() .check_out("slide_root") .new_branch("child_b") .commit("child_b_1") .push() .check_out("child_b") .new_branch("child_c") .commit("child_c_1") .push() .new_branch("child_d") .commit("child_d_1") .push() ) self.launch_command("discover", "-y", "--roots=develop") self.assert_command( ["status", "-l"], """ develop | | slide_root_1 o-slide_root | | child_a_1 o-child_a | | child_b_1 o-child_b | | child_c_1 o-child_c | | child_d_1 o-child_d * """, ) # Slide-out a single interior branch with one downstream. (child_c) # This rebases the single downstream onto the new upstream. (child_b -> child_d) self.launch_command("go", "up") self.launch_command("slide-out", "-n") self.assert_command( ["status", "-l"], """ develop | | slide_root_1 o-slide_root | | child_a_1 o-child_a | | child_b_1 o-child_b | | child_d_1 o-child_d * (diverged from origin) """, ) # Slide-out an interior branch with multiple downstreams. (slide_root) # This rebases all the downstreams onto the new upstream. (develop -> [child_a, child_b]) self.launch_command("traverse", "-Wy") self.launch_command("go", "up") self.launch_command("go", "up") self.assert_command( ["status", "-l"], """ develop | | slide_root_1 o-slide_root * | | child_a_1 o-child_a | | child_b_1 o-child_b | | child_d_1 o-child_d """, ) self.launch_command("slide-out", "-n") self.assert_command( ["status", "-l"], """ develop | | child_a_1 o-child_a (diverged from origin) | | child_b_1 o-child_b * (diverged from origin) | | child_d_1 x-child_d """, ) self.launch_command("traverse", "-Wy") self.assert_command( ["status", "-l"], """ develop | | child_a_1 o-child_a | | child_b_1 o-child_b * | | child_d_1 o-child_d """, ) # Slide-out a terminal branch. (child_d) # This just slices the branch off the tree. self.launch_command("go", "down") self.launch_command("slide-out", "-n") self.assert_command( ["status", "-l"], """ develop | | child_a_1 o-child_a | | child_b_1 o-child_b * """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_squash_merge(self) -> None: ( self.repo_sandbox.new_branch("root") .commit("root") .push() .new_branch("develop") .commit("develop") .push() .new_branch("feature") .commit("feature_1") .commit("feature_2") .push() .new_branch("child") .commit("child_1") .commit("child_2") .push() ) self.launch_command("discover", "-y", "--roots=root") self.assert_command( ["status", "-l"], """ root | | develop o-develop | | feature_1 | feature_2 o-feature | | child_1 | child_2 o-child * """, ) # squash-merge feature onto develop ( self.repo_sandbox.check_out("develop") .execute("git merge --squash feature") .execute("git commit -m squash_feature") .check_out("child") ) # in default mode, feature is detected as "m" (merged) into develop self.assert_command( ["status", "-l"], """ root | | develop | squash_feature o-develop (ahead of origin) | m-feature | | child_1 | child_2 o-child * """, ) # but under --no-detect-squash-merges, feature is detected as "x" (behind) develop self.assert_command( ["status", "-l", "--no-detect-squash-merges"], """ root | | develop | squash_feature o-develop (ahead of origin) | | feature_1 | feature_2 x-feature | | child_1 | child_2 o-child * """, ) # traverse then slides out the branch self.launch_command("traverse", "-w", "-y") self.assert_command( ["status", "-l"], """ root | | develop | squash_feature o-develop | | child_1 | child_2 o-child * """, ) # simulate an upstream squash-merge of the feature branch ( self.repo_sandbox.check_out("develop") .new_branch("upstream_squash") .execute("git merge --squash child") .execute("git commit -m squash_child") .execute("git push origin upstream_squash:develop") .check_out("child") .execute("git branch -D upstream_squash") ) # status before fetch will show develop as out of date self.assert_command( ["status", "-l"], """ root | | develop | squash_feature o-develop (behind origin) | | child_1 | child_2 o-child * """, ) # fetch-traverse will fetch upstream squash, detect, and slide out the child branch self.launch_command("traverse", "-W", "-y") self.assert_command( ["status", "-l"], """ root | | develop | squash_feature | squash_child o-develop * """, ) @mock.patch('git_machete.utils.run_cmd', mock_run_cmd) # to hide git outputs in tests def test_help(self) -> None: expected_exit_code = None with self.assertRaises(SystemExit) as e: self.launch_command("help") self.assertEqual( expected_exit_code, e.exception.code, msg="Verify that `git machete help` causes SystemExit with " f"{expected_exit_code} exit code.") for
# Copyright 2016 Tesora, Inc. # 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. # """Model classes that form the core of Module functionality.""" import hashlib import six from sqlalchemy.sql.expression import or_ from oslo_log import log as logging from trove.common import cfg from trove.common import crypto_utils from trove.common import exception from trove.common.i18n import _ from trove.common import timeutils from trove.common import utils from trove.datastore import models as datastore_models from trove.db import models from trove.taskmanager import api as task_api CONF = cfg.CONF LOG = logging.getLogger(__name__) class Modules(object): DEFAULT_LIMIT = CONF.modules_page_size ENCRYPT_KEY = CONF.module_aes_cbc_key VALID_MODULE_TYPES = [mt.lower() for mt in CONF.module_types] MATCH_ALL_NAME = 'all' @staticmethod def load(context, datastore=None): if context is None: raise TypeError(_("Argument context not defined.")) elif id is None: raise TypeError(_("Argument is not defined.")) query_opts = {'deleted': False} if datastore: if datastore.lower() == Modules.MATCH_ALL_NAME: datastore = None query_opts['datastore_id'] = datastore if context.is_admin: db_info = DBModule.find_all(**query_opts) if db_info.count() == 0: LOG.debug("No modules found for admin user") else: # build a query manually, since we need current tenant # plus the 'all' tenant ones query_opts['visible'] = True db_info = DBModule.query().filter_by(**query_opts) db_info = db_info.filter( or_(DBModule.tenant_id == context.project_id, DBModule.tenant_id.is_(None)) ) if db_info.count() == 0: LOG.debug("No modules found for tenant %s", context.project_id) modules = db_info.all() return modules @staticmethod def load_auto_apply(context, datastore_id, datastore_version_id): """Return all the auto-apply modules for the given criteria.""" if context is None: raise TypeError(_("Argument context not defined.")) elif id is None: raise TypeError(_("Argument is not defined.")) query_opts = {'deleted': False, 'auto_apply': True} db_info = DBModule.query().filter_by(**query_opts) db_info = Modules.add_tenant_filter(db_info, context.project_id) db_info = Modules.add_datastore_filter(db_info, datastore_id) db_info = Modules.add_ds_version_filter(db_info, datastore_version_id) if db_info.count() == 0: LOG.debug("No auto-apply modules found for tenant %s", context.project_id) modules = db_info.all() return modules @staticmethod def add_tenant_filter(query, tenant_id): return query.filter(or_(DBModule.tenant_id == tenant_id, DBModule.tenant_id.is_(None))) @staticmethod def add_datastore_filter(query, datastore_id): return query.filter(or_(DBModule.datastore_id == datastore_id, DBModule.datastore_id.is_(None))) @staticmethod def add_ds_version_filter(query, datastore_version_id): return query.filter(or_( DBModule.datastore_version_id == datastore_version_id, DBModule.datastore_version_id.is_(None))) @staticmethod def load_by_ids(context, module_ids): """Return all the modules for the given ids. Screens out the ones for other tenants, unless the user is admin. """ if context is None: raise TypeError(_("Argument context not defined.")) elif id is None: raise TypeError(_("Argument is not defined.")) modules = [] if module_ids: query_opts = {'deleted': False} db_info = DBModule.query().filter_by(**query_opts) if not context.is_admin: db_info = Modules.add_tenant_filter(db_info, context.project_id) db_info = db_info.filter(DBModule.id.in_(module_ids)) modules = db_info.all() return modules @staticmethod def validate(modules, datastore_id, datastore_version_id): for module in modules: if (module.datastore_id and module.datastore_id != datastore_id): reason = (_("Module '%(mod)s' cannot be applied " " (Wrong datastore '%(ds)s' - expected '%(ds2)s')") % {'mod': module.name, 'ds': module.datastore_id, 'ds2': datastore_id}) raise exception.ModuleInvalid(reason=reason) if (module.datastore_version_id and module.datastore_version_id != datastore_version_id): reason = (_("Module '%(mod)s' cannot be applied " " (Wrong datastore version '%(ver)s' " "- expected '%(ver2)s')") % {'mod': module.name, 'ver': module.datastore_version_id, 'ver2': datastore_version_id}) raise exception.ModuleInvalid(reason=reason) class Module(object): def __init__(self, context, module_id): self.context = context self.module_id = module_id @staticmethod def create(context, name, module_type, contents, description, tenant_id, datastore, datastore_version, auto_apply, visible, live_update, priority_apply, apply_order, full_access): if module_type.lower() not in Modules.VALID_MODULE_TYPES: LOG.error("Valid module types: %s", Modules.VALID_MODULE_TYPES) raise exception.ModuleTypeNotFound(module_type=module_type) Module.validate_action( context, 'create', tenant_id, auto_apply, visible, priority_apply, full_access) datastore_id, datastore_version_id = ( datastore_models.get_datastore_or_version( datastore, datastore_version)) if Module.key_exists( name, module_type, tenant_id, datastore_id, datastore_version_id): datastore_str = datastore_id or Modules.MATCH_ALL_NAME ds_version_str = datastore_version_id or Modules.MATCH_ALL_NAME raise exception.ModuleAlreadyExists( name=name, datastore=datastore_str, ds_version=ds_version_str) md5, processed_contents = Module.process_contents(contents) is_admin = context.is_admin if full_access: is_admin = 0 module = DBModule.create( name=name, type=module_type.lower(), contents=processed_contents, description=description, tenant_id=tenant_id, datastore_id=datastore_id, datastore_version_id=datastore_version_id, auto_apply=auto_apply, visible=visible, live_update=live_update, priority_apply=priority_apply, apply_order=apply_order, is_admin=is_admin, md5=md5) return module # Certain fields require admin access to create/change/delete @staticmethod def validate_action(context, action_str, tenant_id, auto_apply, visible, priority_apply, full_access): admin_options_str = None option_strs = [] if tenant_id is None: option_strs.append(_("Tenant: %s") % Modules.MATCH_ALL_NAME) if auto_apply: option_strs.append(_("Auto: %s") % auto_apply) if not visible: option_strs.append(_("Visible: %s") % visible) if priority_apply: option_strs.append(_("Priority: %s") % priority_apply) if full_access is not None: if full_access and option_strs: admin_options_str = "(" + ", ".join(option_strs) + ")" raise exception.InvalidModelError( errors=_('Cannot make module full access: %s') % admin_options_str) option_strs.append(_("Full Access: %s") % full_access) if option_strs: admin_options_str = "(" + ", ".join(option_strs) + ")" if not context.is_admin and admin_options_str: raise exception.ModuleAccessForbidden( action=action_str, options=admin_options_str) return admin_options_str @staticmethod def key_exists(name, module_type, tenant_id, datastore_id, datastore_version_id): try: DBModule.find_by( name=name, type=module_type, tenant_id=tenant_id, datastore_id=datastore_id, datastore_version_id=datastore_version_id, deleted=False) return True except exception.ModelNotFoundError: return False # We encrypt the contents (which should be encoded already, since it # might be in binary format) and then encode them again so they can # be stored in a text field in the Trove database. @staticmethod def process_contents(contents): md5 = contents if isinstance(md5, six.text_type): md5 = md5.encode('utf-8') md5 = hashlib.md5(md5).hexdigest() encrypted_contents = crypto_utils.encrypt_data( contents, Modules.ENCRYPT_KEY) return md5, crypto_utils.encode_data(encrypted_contents) # Do the reverse to 'deprocess' the contents @staticmethod def deprocess_contents(processed_contents): encrypted_contents = crypto_utils.decode_data(processed_contents) return crypto_utils.decrypt_data( encrypted_contents, Modules.ENCRYPT_KEY) @staticmethod def delete(context, module): Module.validate_action( context, 'delete', module.tenant_id, module.auto_apply, module.visible, module.priority_apply, None) Module.enforce_live_update(module.id, module.live_update, module.md5) module.deleted = True module.deleted_at = timeutils.utcnow() module.save() @staticmethod def enforce_live_update(module_id, live_update, md5): if not live_update: instances = DBInstanceModule.find_all( module_id=module_id, md5=md5, deleted=False).all() if instances: raise exception.ModuleAppliedToInstance() @staticmethod def load(context, module_id): module = None try: if context.is_admin: module = DBModule.find_by(id=module_id, deleted=False) else: module = DBModule.find_by( id=module_id, tenant_id=context.project_id, visible=True, deleted=False) except exception.ModelNotFoundError: # See if we have the module in the 'all' tenant section if not context.is_admin: try: module = DBModule.find_by( id=module_id, tenant_id=None, visible=True, deleted=False) except exception.ModelNotFoundError: pass # fall through to the raise below if not module: msg = _("Module with ID %s could not be found.") % module_id raise exception.ModelNotFoundError(msg) # Save the encrypted contents in case we need to put it back # when updating the record module.encrypted_contents = module.contents module.contents = Module.deprocess_contents(module.contents) return module @staticmethod def update(context, module, original_module, full_access): Module.enforce_live_update( original_module.id, original_module.live_update, original_module.md5) # we don't allow any changes to 'is_admin' modules by non-admin if original_module.is_admin and not context.is_admin: raise exception.ModuleAccessForbidden( action='update', options='(Module is an admin module)') # we don't allow any changes to admin-only attributes by non-admin admin_options = Module.validate_action( context, 'update', module.tenant_id, module.auto_apply, module.visible, module.priority_apply, full_access) # make sure we set the is_admin flag, but only if it was # originally is_admin or we changed an admin option module.is_admin = original_module.is_admin or ( 1 if admin_options else 0) # but we turn it on/off if full_access is specified if full_access is not None: module.is_admin = 0 if full_access else 1 ds_id, ds_ver_id = datastore_models.get_datastore_or_version( module.datastore_id, module.datastore_version_id) if module.contents != original_module.contents: md5, processed_contents = Module.process_contents(module.contents) module.md5 = md5 module.contents = processed_contents elif hasattr(original_module, 'encrypted_contents'): # on load the contents may have been decrypted, so # we need to put the encrypted contents back before we update module.contents = original_module.encrypted_contents if module.datastore_id: module.datastore_id = ds_id if module.datastore_version_id: module.datastore_version_id = ds_ver_id module.updated = timeutils.utcnow() DBModule.save(module) @staticmethod def reapply(context, id, md5, include_clustered, batch_size, batch_delay, force): task_api.API(context).reapply_module( id, md5, include_clustered, batch_size, batch_delay, force) class InstanceModules(object): @staticmethod def load(context, instance_id=None, module_id=None, md5=None): db_info = InstanceModules.load_all( context, instance_id=instance_id, module_id=module_id, md5=md5) if db_info.count() == 0: LOG.debug("No instance module records found") limit = utils.pagination_limit( context.limit, Modules.DEFAULT_LIMIT) data_view = DBInstanceModule.find_by_pagination( 'modules', db_info, 'foo', limit=limit, marker=context.marker) next_marker = data_view.next_page_marker return data_view.collection, next_marker @staticmethod def load_all(context, instance_id=None, module_id=None, md5=None): query_opts = {'deleted': False} if instance_id: query_opts['instance_id'] = instance_id if module_id: query_opts['module_id'] = module_id if md5: query_opts['md5'] = md5 return DBInstanceModule.find_all(**query_opts) class InstanceModule(object): def __init__(self, context, instance_id, module_id): self.context = context self.instance_id = instance_id self.module_id = module_id @staticmethod def create(context, instance_id, module_id, md5): instance_module = None # First mark any 'old' records as deleted and/or update the # current one. old_ims = InstanceModules.load_all( context, instance_id=instance_id, module_id=module_id) for old_im in old_ims: if old_im.md5 == md5 and not instance_module: instance_module = old_im InstanceModule.update(context, instance_module) else: if old_im.md5 == md5 and instance_module: LOG.debug("Found dupe IM record %(old_im)s; marking as " "deleted (instance %(instance_id)s, " "module
<filename>tests/cmds/test_securitydata.py import json import logging import py42.sdk.queries.fileevents.filters as f import pytest from c42eventextractor.extractors import FileEventExtractor from py42.sdk.queries.fileevents.file_event_query import FileEventQuery from py42.sdk.queries.fileevents.filters.file_filter import FileCategory from tests.cmds.conftest import filter_term_is_in_call_args from tests.cmds.conftest import get_filter_value_from_json from tests.cmds.conftest import get_mark_for_search_and_send_to from tests.conftest import get_test_date_str from code42cli import errors from code42cli.cmds.search.cursor_store import FileEventCursorStore from code42cli.logger.enums import ServerProtocol from code42cli.main import cli BEGIN_TIMESTAMP = 1577858400.0 END_TIMESTAMP = 1580450400.0 CURSOR_TIMESTAMP = 1579500000.0 TEST_LIST_RESPONSE = { "searches": [ { "id": "a083f08d-8f33-4cbd-81c4-8d1820b61185", "name": "test-events", "notes": "py42 is here", }, ] } TEST_EMPTY_LIST_RESPONSE = {"searches": []} ADVANCED_QUERY_VALUES = { "within_last_value": "P30D", "hostname_1": "DESKTOP-H88BEKO", "hostname_2": "W10E-X64-FALLCR", "event_type": "CREATED", } ADVANCED_QUERY_JSON = """ {{ "purpose": "USER_EXECUTED_SEARCH", "groups": [ {{ "filterClause": "AND", "filters": [ {{ "value": "{within_last_value}", "operator": "WITHIN_THE_LAST", "term": "eventTimestamp" }} ] }}, {{ "filterClause": "AND", "filters": [ {{ "value": ".*", "operator": "IS", "term": "fileName" }} ] }}, {{ "filterClause": "OR", "filters": [ {{ "value": "{hostname_1}", "operator": "IS", "term": "osHostName" }}, {{ "value": "{hostname_2}", "operator": "IS", "term": "osHostName" }} ] }}, {{ "filterClause": "OR", "filters": [ {{ "value": "{event_type}", "operator": "IS", "term": "eventType" }} ] }} ], "pgSize": 100, "pgNum": 1 }}""".format( **ADVANCED_QUERY_VALUES ) advanced_query_incompat_test_params = pytest.mark.parametrize( "arg", [ ("--begin", "1d"), ("--end", "1d"), ("--c42-username", "<EMAIL>"), ("--actor", "test.testerson"), ("--md5", "abcd1234"), ("--sha256", "abcdefg12345678"), ("--source", "Gmail"), ("--file-name", "test.txt"), ("--file-path", "C:\\Program Files"), ("--file-category", "IMAGE"), ("--process-owner", "root"), ("--tab-url", "https://example.com"), ("--type", "SharedViaLink"), ("--include-non-exposure",), ], ) saved_search_incompat_test_params = pytest.mark.parametrize( "arg", [ ("--begin", "1d"), ("--end", "1d"), ("--c42-username", "<EMAIL>"), ("--actor", "test.testerson"), ("--md5", "abcd1234"), ("--sha256", "abcdefg12345678"), ("--source", "Gmail"), ("--file-name", "test.txt"), ("--file-path", "C:\\Program Files"), ("--file-category", "IMAGE"), ("--process-owner", "root"), ("--tab-url", "https://example.com"), ("--type", "SharedViaLink"), ("--include-non-exposure",), ("--use-checkpoint", "test"), ], ) search_and_send_to_test = get_mark_for_search_and_send_to("security-data") @pytest.fixture def file_event_extractor(mocker): mock = mocker.patch("code42cli.cmds.securitydata._get_file_event_extractor") mock.return_value = mocker.MagicMock(spec=FileEventExtractor) return mock.return_value @pytest.fixture def file_event_cursor_with_checkpoint(mocker): mock = mocker.patch("code42cli.cmds.securitydata._get_file_event_cursor_store") mock_cursor = mocker.MagicMock(spec=FileEventCursorStore) mock_cursor.get.return_value = CURSOR_TIMESTAMP mock.return_value = mock_cursor mock.expected_timestamp = "2020-01-20T06:00:00+00:00" return mock @pytest.fixture def file_event_cursor_without_checkpoint(mocker): mock = mocker.patch("code42cli.cmds.securitydata._get_file_event_cursor_store") mock_cursor = mocker.MagicMock(spec=FileEventCursorStore) mock_cursor.get.return_value = None mock.return_value = mock_cursor return mock @pytest.fixture def begin_option(mocker): mock = mocker.patch("code42cli.cmds.securitydata.convert_datetime_to_timestamp") mock.return_value = BEGIN_TIMESTAMP mock.expected_timestamp = "2020-01-01T06:00:00.000Z" return mock @pytest.fixture def send_to_logger_factory(mocker): return mocker.patch("code42cli.cmds.search._try_get_logger_for_server") @search_and_send_to_test def test_search_and_send_to_when_advanced_query_passed_as_json_string_builds_expected_query( runner, cli_state, file_event_extractor, command ): runner.invoke( cli, [*command, "--advanced-query", ADVANCED_QUERY_JSON], obj=cli_state ) passed_filter_groups = file_event_extractor.extract.call_args[0] expected_event_filter = f.EventTimestamp.within_the_last( ADVANCED_QUERY_VALUES["within_last_value"] ) expected_hostname_filter = f.OSHostname.is_in( [ADVANCED_QUERY_VALUES["hostname_1"], ADVANCED_QUERY_VALUES["hostname_2"]] ) expected_event_type_filter = f.EventType.is_in( [ADVANCED_QUERY_VALUES["event_type"]] ) expected_event_type_filter.filter_clause = "OR" assert expected_event_filter in passed_filter_groups assert expected_hostname_filter in passed_filter_groups assert expected_event_type_filter in passed_filter_groups @search_and_send_to_test def test_search_and_send_to_when_advanced_query_passed_as_filename_builds_expected_query( runner, cli_state, file_event_extractor, command ): with runner.isolated_filesystem(): with open("query.json", "w") as jsonfile: jsonfile.write(ADVANCED_QUERY_JSON) runner.invoke(cli, [*command, "--advanced-query", "@query.json"], obj=cli_state) passed_filter_groups = file_event_extractor.extract.call_args[0] expected_event_filter = f.EventTimestamp.within_the_last( ADVANCED_QUERY_VALUES["within_last_value"] ) expected_hostname_filter = f.OSHostname.is_in( [ADVANCED_QUERY_VALUES["hostname_1"], ADVANCED_QUERY_VALUES["hostname_2"]] ) expected_event_type_filter = f.EventType.is_in( [ADVANCED_QUERY_VALUES["event_type"]] ) expected_event_type_filter.filter_clause = "OR" assert expected_event_filter in passed_filter_groups assert expected_hostname_filter in passed_filter_groups assert expected_event_type_filter in passed_filter_groups @search_and_send_to_test def test_search_and_send_to_when_advanced_query_passed_non_existent_filename_raises_error( runner, cli_state, command ): with runner.isolated_filesystem(): result = runner.invoke( cli, [*command, "--advanced-query", "@not_a_file"], obj=cli_state ) assert result.exit_code == 2 assert "Could not open file: not_a_file" in result.stdout @advanced_query_incompat_test_params def test_search_with_advanced_query_and_incompatible_argument_errors( runner, arg, cli_state ): result = runner.invoke( cli, ["security-data", "search", "--advanced-query", ADVANCED_QUERY_JSON, *arg], obj=cli_state, ) assert result.exit_code == 2 assert f"{arg[0]} can't be used with: --advanced-query" in result.output @advanced_query_incompat_test_params def test_send_to_with_advanced_query_and_incompatible_argument_errors( runner, arg, cli_state ): result = runner.invoke( cli, [ "security-data", "send-to", "0.0.0.0", "--advanced-query", ADVANCED_QUERY_JSON, *arg, ], obj=cli_state, ) assert result.exit_code == 2 assert f"{arg[0]} can't be used with: --advanced-query" in result.output @saved_search_incompat_test_params def test_search_with_saved_search_and_incompatible_argument_errors( runner, arg, cli_state ): result = runner.invoke( cli, ["security-data", "search", "--saved-search", "test_id", *arg], obj=cli_state, ) assert result.exit_code == 2 assert f"{arg[0]} can't be used with: --saved-search" in result.output @saved_search_incompat_test_params def test_send_to_with_saved_search_and_incompatible_argument_errors( runner, arg, cli_state ): result = runner.invoke( cli, ["security-data", "send-to", "0.0.0.0", "--saved-search", "test_id", *arg], obj=cli_state, ) assert result.exit_code == 2 assert f"{arg[0]} can't be used with: --saved-search" in result.output @pytest.mark.parametrize("protocol", (ServerProtocol.UDP, ServerProtocol.TCP)) def test_send_to_when_given_ignore_cert_validation_with_non_tls_protocol_fails_expectedly( cli_state, runner, protocol ): res = runner.invoke( cli, [ "security-data", "send-to", "0.0.0.0", "--begin", "1d", "--protocol", protocol, "--ignore-cert-validation", ], obj=cli_state, ) assert ( "'--ignore-cert-validation' can only be used with '--protocol TLS-TCP'" in res.output ) @pytest.mark.parametrize("protocol", (ServerProtocol.UDP, ServerProtocol.TCP)) def test_send_to_when_given_certs_with_non_tls_protocol_fails_expectedly( cli_state, runner, protocol ): res = runner.invoke( cli, [ "security-data", "send-to", "0.0.0.0", "--begin", "1d", "--protocol", protocol, "--certs", "certs.pem", ], obj=cli_state, ) assert "'--certs' can only be used with '--protocol TLS-TCP'" in res.output @search_and_send_to_test def test_search_and_send_to_when_given_begin_and_end_dates_uses_expected_query( runner, cli_state, file_event_extractor, command ): begin_date = get_test_date_str(days_ago=89) end_date = get_test_date_str(days_ago=1) runner.invoke( cli, [ *command, "--begin", get_test_date_str(days_ago=89), "--end", get_test_date_str(days_ago=1), ], obj=cli_state, ) filters = file_event_extractor.extract.call_args[0][1] actual_begin = get_filter_value_from_json(filters, filter_index=0) expected_begin = f"{begin_date}T00:00:00.000Z" actual_end = get_filter_value_from_json(filters, filter_index=1) expected_end = f"{end_date}T23:59:59.999Z" assert actual_begin == expected_begin assert actual_end == expected_end @search_and_send_to_test def test_search_and_send_to_when_given_begin_and_end_date_and_time_uses_expected_query( runner, cli_state, file_event_extractor, command ): begin_date = get_test_date_str(days_ago=89) end_date = get_test_date_str(days_ago=1) time = "15:33:02" runner.invoke( cli, [*command, "--begin", f"{begin_date} {time}", "--end", f"{end_date} {time}"], obj=cli_state, ) filters = file_event_extractor.extract.call_args[0][1] actual_begin = get_filter_value_from_json(filters, filter_index=0) expected_begin = f"{begin_date}T{time}.000Z" actual_end = get_filter_value_from_json(filters, filter_index=1) expected_end = f"{end_date}T{time}.000Z" assert actual_begin == expected_begin assert actual_end == expected_end @search_and_send_to_test def test_search_and_send_to_when_given_begin_date_and_time_without_seconds_uses_expected_query( runner, cli_state, file_event_extractor, command ): date = get_test_date_str(days_ago=89) time = "15:33" runner.invoke( cli, [*command, "--begin", f"{date} {time}"], obj=cli_state, ) actual = get_filter_value_from_json( file_event_extractor.extract.call_args[0][1], filter_index=0 ) expected = f"{date}T{time}:00.000Z" assert actual == expected @search_and_send_to_test def test_search_and_send_to_when_given_end_date_and_time_uses_expected_query( runner, cli_state, file_event_extractor, command ): begin_date = get_test_date_str(days_ago=10) end_date = get_test_date_str(days_ago=1) time = "15:33" runner.invoke( cli, [*command, "--begin", begin_date, "--end", f"{end_date} {time}"], obj=cli_state, ) actual = get_filter_value_from_json( file_event_extractor.extract.call_args[0][1], filter_index=1 ) expected = f"{end_date}T{time}:00.000Z" assert actual == expected @search_and_send_to_test def test_search_send_to_when_given_begin_date_more_than_ninety_days_back_errors( runner, cli_state, command ): result = runner.invoke( cli, [*command, "--begin", get_test_date_str(days_ago=91) + " 12:51:00"], obj=cli_state, ) assert result.exit_code == 2 assert "must be within 90 days" in result.output @search_and_send_to_test def test_search_and_send_to_when_given_begin_date_past_90_days_and_use_checkpoint_and_a_stored_cursor_exists_and_not_given_end_date_does_not_use_any_event_timestamp_filter( runner, cli_state, file_event_cursor_with_checkpoint, file_event_extractor, command ): begin_date = get_test_date_str(days_ago=91) + " 12:51:00" runner.invoke( cli, [*command, "--begin", begin_date, "--use-checkpoint", "test"], obj=cli_state, ) assert not filter_term_is_in_call_args( file_event_extractor, f.InsertionTimestamp._term ) @search_and_send_to_test def test_search_and_send_to_when_given_begin_date_and_not_use_checkpoint_and_cursor_exists_uses_begin_date( runner, cli_state, file_event_extractor, command ): begin_date = get_test_date_str(days_ago=1) runner.invoke(cli, [*command, "--begin", begin_date], obj=cli_state) actual_ts = get_filter_value_from_json( file_event_extractor.extract.call_args[0][1], filter_index=0 ) expected_ts = f"{begin_date}T00:00:00.000Z" assert actual_ts == expected_ts assert filter_term_is_in_call_args(file_event_extractor, f.EventTimestamp._term) @search_and_send_to_test def test_search_and_send_to_when_end_date_is_before_begin_date_causes_exit( runner, cli_state, command ): begin_date = get_test_date_str(days_ago=1) end_date = get_test_date_str(days_ago=3) result = runner.invoke( cli, [*command, "--begin", begin_date, "--end", end_date], obj=cli_state, ) assert result.exit_code == 2 assert "'--begin': cannot be after --end date" in result.output @search_and_send_to_test def test_search_and_send_to_with_only_begin_calls_extract_with_expected_args( runner, cli_state, file_event_extractor, begin_option, command ): result = runner.invoke(cli, [*command, "--begin", "1h"], obj=cli_state) assert result.exit_code == 0 assert ( str(file_event_extractor.extract.call_args[0][1]) == f'{{"filterClause":"AND", "filters":[{{"operator":"ON_OR_AFTER", "term":"eventTimestamp", ' f'"value":"{begin_option.expected_timestamp}"}}]}}' ) @search_and_send_to_test def test_search_and_send_to_with_use_checkpoint_and_without_begin_and_without_checkpoint_causes_expected_error( runner, cli_state, file_event_cursor_without_checkpoint, command ): result = runner.invoke(cli, [*command, "--use-checkpoint", "test"], obj=cli_state) assert result.exit_code == 2 assert ( "--begin date is required for --use-checkpoint when no checkpoint exists yet." in result.output ) @search_and_send_to_test def test_search_and_send_to_with_use_checkpoint_and_with_begin_and_without_checkpoint_calls_extract_with_begin_date( runner, cli_state, file_event_extractor, begin_option, file_event_cursor_without_checkpoint, command, ): result = runner.invoke( cli, [*command, "--use-checkpoint", "test", "--begin", "1h"], obj=cli_state, ) assert result.exit_code == 0 assert len(file_event_extractor.extract.call_args[0]) == 2 assert begin_option.expected_timestamp in str( file_event_extractor.extract.call_args[0][1] ) @search_and_send_to_test def test_search_and_send_to_with_use_checkpoint_and_with_begin_and_with_stored_checkpoint_calls_extract_with_checkpoint_and_ignores_begin_arg( runner, cli_state, file_event_extractor, file_event_cursor_with_checkpoint, command, ): result = runner.invoke( cli, [*command, "--use-checkpoint", "test", "--begin", "1h"], obj=cli_state, ) assert result.exit_code == 0 assert len(file_event_extractor.extract.call_args[0]) == 1 assert ( f"checkpoint of {file_event_cursor_with_checkpoint.expected_timestamp} exists" in result.output ) @search_and_send_to_test def test_search_and_send_to_when_given_invalid_exposure_type_causes_exit( runner, cli_state, command ): result = runner.invoke( cli, [*command, "--begin", "1d", "-t", "NotValid"], obj=cli_state, ) assert result.exit_code == 2 assert "invalid choice: NotValid" in result.output @search_and_send_to_test def test_search_and_send_to_when_given_username_uses_username_filter( runner, cli_state, file_event_extractor, command ): c42_username = "<EMAIL>" command = [*command, "--begin", "1h", "--c42-username", c42_username] runner.invoke( cli, [*command], obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.DeviceUsername.is_in([c42_username])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_actor_is_uses_username_filter( runner, cli_state, file_event_extractor, command ): actor_name = "test.testerson" command = [*command, "--begin", "1h", "--actor", actor_name] runner.invoke( cli, [*command], obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.Actor.is_in([actor_name])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_md5_uses_md5_filter( runner, cli_state, file_event_extractor, command ): md5 = "abcd12345" command = [*command, "--begin", "1h", "--md5", md5] runner.invoke(cli, [*command], obj=cli_state) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.MD5.is_in([md5])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_sha256_uses_sha256_filter( runner, cli_state, file_event_extractor, command ): sha_256 = "abcd12345" command = [*command, "--begin", "1h", "--sha256", sha_256] runner.invoke( cli, command, obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.SHA256.is_in([sha_256])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_source_uses_source_filter( runner, cli_state, file_event_extractor, command ): source = "Gmail" command = [*command, "--begin", "1h", "--source", source] runner.invoke(cli, command, obj=cli_state) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.Source.is_in([source])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_file_name_uses_file_name_filter( runner, cli_state, file_event_extractor, command ): filename = "test.txt" command = [*command, "--begin", "1h", "--file-name", filename] runner.invoke( cli, command, obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.FileName.is_in([filename])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_file_path_uses_file_path_filter( runner, cli_state, file_event_extractor, command ): filepath = "C:\\Program Files" command = [*command, "--begin", "1h", "--file-path", filepath] runner.invoke( cli, command, obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.FilePath.is_in([filepath])) in filter_strings @search_and_send_to_test def test_search_and_send_to_when_given_file_category_uses_file_category_filter( runner, cli_state, file_event_extractor, command ): file_category = FileCategory.IMAGE command = [*command, "--begin", "1h", "--file-category", file_category] runner.invoke( cli, command, obj=cli_state, ) filter_strings = [str(arg) for arg in file_event_extractor.extract.call_args[0]] assert str(f.FileCategory.is_in([file_category])) in filter_strings @pytest.mark.parametrize( "category_choice", [ ("AUDIO", FileCategory.AUDIO), ("DOCUMENT", FileCategory.DOCUMENT), ("EXECUTABLE", FileCategory.EXECUTABLE), ("IMAGE", FileCategory.IMAGE),
dict' ] ) self.emailCompleter = QCompleter( self.all_emails ) self.nameCompleter = QCompleter( self.all_names ) self.emailListAddEmailName = EmailListDialog.EmailListAddEmailName( self ) self.emailListTableModel = EmailListDialog.EmailListTableModel( self ) emailListTableView = EmailListDialog.EmailListTableView( self ) # self.emailListAddEmailName.statusSignal.connect( self.emailListTableModel.addEmail ) hideAction = QAction( self ) hideAction.setShortcut( 'Ctrl+W' ) hideAction.triggered.connect( self.hide ) self.addAction( hideAction ) # myLayout = QVBoxLayout( ) self.setLayout( myLayout ) # topWidget = QWidget( ) topLayout = QHBoxLayout( ) topWidget.setLayout( topLayout ) topLayout.addWidget( QLabel( 'FILTER' ) ) topLayout.addWidget( self.emailListTableModel.filterOnNamesOrEmails ) myLayout.addWidget( topWidget) # myLayout.addWidget( emailListTableView ) # myLayout.addWidget( self.emailListTableModel.showingEmailsLabel ) # self.setFixedWidth( 600 ) self.setFixedHeight( 600 ) emailListTableView.resizeTableColumns( self.size( ) ) self.hide( ) class FromDialog( QDialogWithPrinting ): class EmailListModel( QAbstractListModel ): def __init__( self, emails ): super( FromDialog.EmailListModel, self ).__init__( None ) self.emails = [ ] self.changeData( emails ) def rowCount( self, parent ): return len( self.emails ) def data( self, index, role ): if not index.isValid( ): return None row = index.row( ) return self.emails[ row ] def changeData( self, new_emails ): self.beginResetModel( ) self.emails = sorted( set( new_emails ) ) self.endResetModel( ) class NameListModel( QAbstractListModel ): def __init__( self, names ): super( FromDialog.NameListModel, self ).__init__( None ) self.beginResetModel( ) self.names = sorted( set( names ) ) self.endResetModel( ) def rowCount( self, parent ): return len( self.names ) def data( self, index, role ): if not index.isValid( ): return None row = index.row( ) return self.names[ row ] def __init__( self, parent ): super( FromDialog, self ).__init__( parent, doQuit = False, isIsolated = False ) self.setWindowTitle( 'SENDING EMAIL' ) assert( 'from name' in parent.allData ) assert( 'from email' in parent.allData ) # self.parent = parent self.emailLineEdit = QLineEdit( '' ) self.nameLineEdit = QLineEdit( '' ) self.emailListModel = FromDialog.EmailListModel( sorted( self.parent.allData[ 'emails dict rev' ] ) ) self.nameListModel = FromDialog.NameListModel( sorted( self.parent.allData[ 'emails dict' ] ) ) # myLayout = QGridLayout( ) self.setLayout( myLayout ) myLayout.addWidget( QLabel( 'EMAIL:' ), 0, 0, 1, 1 ) myLayout.addWidget( self.emailLineEdit, 0, 1, 1, 3 ) myLayout.addWidget( QLabel( 'NAME:' ), 1, 0, 1, 1 ) myLayout.addWidget( self.nameLineEdit, 1, 1, 1, 3 ) # self.emailLineEdit.returnPressed.connect( self.setValidEmail ) self.nameLineEdit.returnPressed.connect( self.setValidName ) self.setCompleters( ) hideAction = QAction( self ) hideAction.setShortcut( 'Ctrl+W' ) hideAction.triggered.connect( self.actuallyCloseHide ) self.addAction( hideAction ) # self.setFixedWidth( 300 ) self.hide( ) def setCompleters( self ): emailC = QCompleter( self ) emailC.setPopup( QListView( self ) ) emailC.setModel( self.emailListModel ) emailC.setCompletionMode( QCompleter.PopupCompletion ) emailC.setMaxVisibleItems( 7 ) #self.emailLineEdit.setCompleter( emailC ) self.emailLineEdit.setCompleter( QCompleter( sorted( self.parent.allData[ 'emails dict rev' ] ) ) ) # nameC = QCompleter( self ) nameC.setModel( self.nameListModel ) nameC.setCompletionMode( QCompleter.PopupCompletion ) nameC.setMaxVisibleItems( 7 ) #self.nameLineEdit.setCompleter( nameC ) self.nameLineEdit.setCompleter( QCompleter( sorted( self.parent.allData[ 'emails dict' ] ) ) ) def closeEvent( self, evt ): self.actuallyCloseHide( ) def actuallyCloseHide( self ): self.hide( ) self.setValidEmail( False ) self.setValidName( False ) self.parent.emailAndNameChangedSignal.emit( ) def setValidEmail( self, emit = True ): _, checkEmail = parseaddr( self.emailLineEdit.text( ) ) if checkEmail == '': validEmail = self.parent.allData[ 'from email' ] self.emailLineEdit.setText( validEmail ) return self.parent.allData[ 'from email' ] = checkEmail self.emailLineEdit.setText( checkEmail ) if checkEmail in self.parent.allData[ 'emails dict rev' ]: checkName = self.parent.allData[ 'emails dict rev' ][ checkEmail ] self.parent.allData[ 'from name' ] = checkName self.nameLineEdit.setText( checkName ) emails = self.parent.allData[ 'emails dict' ][ checkName ] #self.emailListModel.changeData( emails ) #self.emailLineEdit.setCompleter( QCompleter( sorted( emails ) ) ) if emit: self.parent.emailAndNameChangedSignal.emit( ) def setValidName( self, emit = True, setEmail = False ): checkName = self.nameLineEdit.text( ).strip( ) self.parent.allData[ 'from name' ] = checkName self.nameLineEdit.setText( checkName ) if checkName == '' or checkName not in self.parent.allData[ 'emails dict' ]: emails = sorted( self.parent.allData[ 'emails dict rev' ] ) #self.emailListModel.changeData( emails ) self.emailLineEdit.setCompleter( QCompleter( sorted( emails ) ) ) elif checkName in self.parent.allData[ 'emails dict' ]: emails = self.parent.allData[ 'emails dict' ][ checkName ] #self.emailListModel.changeData( emails ) #self.emailLineEdit.setCompleter( QCompleter( sorted( emails ) ) ) if emit: self.parent.emailAndNameChangedSignal.emit( ) def getEmailAndName( self ): validEmail = self.parent.allData[ 'from email' ] validName = self.parent.allData[ 'from name' ] if validEmail == '': return '' emailAndName = validEmail if validName == '': return emailAndName return formataddr( ( validName, validEmail ) ) class HowdyEmailDemoGUI( QDialogWithPrinting ): emailAndNameChangedSignal = pyqtSignal( ) def __init__( self, verify = True ): super( HowdyEmailDemoGUI, self ).__init__( None, doQuit = True, isIsolated = True ) self.setWindowTitle( 'RESTRUCTURED TEXT EMAILER' ) self.name = '<NAME>' self.form = 'rst' self.suffix = 'rst' self.verify = verify self.setStyleSheet(""" QWidget { font-family: Consolas; font-size: 11; }""" ) # qf = QFont( ) qf.setFamily( 'Consolas' ) qf.setPointSize( 11 ) qfm = QFontMetrics( qf ) self.allData = { 'from email' : '', 'from name' : '', 'to' : [ ], 'cc' : [ ], 'bcc' : [ ] } time0 = time.time( ) self.allData[ 'emails dict' ] = get_all_email_contacts_dict( verify = verify, pagesize = 2000 ) if len( self.allData[ 'emails dict' ] ) == 0: raise ValueError("Error, could find no Google contacts! Exiting..." ) emails_dict_rev = dict(chain.from_iterable( map(lambda name: map(lambda email: ( email, name ), self.allData[ 'emails dict' ][ name ] ), self.allData[ 'emails dict' ] ) ) ) self.allData[ 'emails dict rev' ] = emails_dict_rev logging.info( 'took %0.3f seconds to find all %d Google contacts.' % ( time.time( ) - time0, len( self.allData[ 'emails dict' ] ) ) ) # self.statusLabel = QLabel( ) self.rowColLabel = QLabel( ) self.textOutput = QPlainTextEdit( ) self.textOutput.setTabStopWidth( 2 * qfm.width( 'A' ) ) # self.fromDialog = FromDialog( self ) self.toEmailListDialog = EmailListDialog( self, key = 'to' ) self.ccEmailListDialog = EmailListDialog( self, key = 'cc' ) self.bccEmailListDialog = EmailListDialog( self, key = 'bcc' ) # self.fromButton = QPushButton( 'FROM' ) self.toButton = QPushButton( 'TO' ) # self.convertButton = QPushButton( 'CONVERT' ) self.sendButton = QPushButton( 'SEND' ) # self.fromLabel = QLabel( '' ) self.subjLineEdit = QLineEdit( '' ) # self.pngWidget = email_basegui.PNGWidget( self ) self.pngWidget.hide( ) # myLayout = QVBoxLayout( ) self.setLayout( myLayout ) # ## top widget ## email buttons topWidget = QWidget( ) topLayout = QGridLayout( ) topWidget.setLayout( topLayout ) topLayout.addWidget( self.fromButton, 0, 0, 1, 3 ) topLayout.addWidget( self.toButton, 0, 3, 1, 3 ) # ## editing buttons topLayout.addWidget( self.convertButton, 1, 0, 1, 3 ) topLayout.addWidget( self.sendButton, 1, 3, 1, 3 ) # ## email subject and from widgets topLayout.addWidget( QLabel( 'FROM:' ), 2, 0, 1, 1 ) topLayout.addWidget( self.fromLabel, 2, 1, 1, 5 ) topLayout.addWidget( QLabel( 'SUBJECT:' ), 3, 0, 1, 1 ) topLayout.addWidget( self.subjLineEdit, 3, 1, 1, 5 ) myLayout.addWidget( topWidget ) # ## middle widget, reStructuredText output myLayout.addWidget( self.textOutput ) # ## bottom widget botWidget = QWidget( ) botLayout = QHBoxLayout( ) botWidget.setLayout( botLayout ) botLayout.addWidget( self.rowColLabel ) botLayout.addWidget( self.statusLabel ) myLayout.addWidget( botWidget ) # self.fromButton.clicked.connect( self.fromDialog.show ) self.toButton.clicked.connect( self.toEmailListDialog.show ) self.sendButton.clicked.connect( self.sendEmail ) self.convertButton.clicked.connect( self.printHTML ) # self.emailAndNameChangedSignal.connect( self.changeEmailAndName ) # ## save reStructuredText file saveAction = QAction( self ) saveAction.setShortcut( 'Ctrl+S' ) saveAction.triggered.connect( self.saveFileName ) self.addAction( saveAction ) # ## load reStructuredText file openAction = QAction( self ) openAction.setShortcut( 'Ctrl+O' ) openAction.triggered.connect( self.loadFileName ) self.addAction( openAction ) # ## interactivity -- show row and column of text cursor in editor, and once press enter strip subject string self.textOutput.cursorPositionChanged.connect( self.showRowCol ) self.subjLineEdit.returnPressed.connect( self.fixSubject ) # ## make popup menu self.popupMenu = self._makePopupMenu( ) # ## geometry stuff and final initialization self.setFixedHeight( 700 ) self.setFixedWidth( 600 ) def _makePopupMenu( self ): menu = QMenu( self ) # menu.addSection( 'SENDING ACTIONS' ) ccAction = QAction( 'CC', self ) ccAction.triggered.connect( self.ccEmailListDialog.show ) menu.addAction( ccAction ) bccAction= QAction( 'BCC', self ) bccAction.triggered.connect( self.bccEmailListDialog.show ) menu.addAction(bccAction ) # menu.addSection( 'EMAIL ACTIONS' ) pngAction = QAction( 'SHOW PNGS', self ) pngAction.triggered.connect( self.pngWidget.show ) menu.addAction( pngAction ) loadAction = QAction( 'LOAD RST', self ) loadAction.triggered.connect( self.loadFileName ) menu.addAction( loadAction ) saveAction = QAction( 'SAVE RST', self ) saveAction.triggered.connect( self.saveFileName ) menu.addAction( saveAction ) # return menu def contextMenuEvent( self, evt ): self.popupMenu.popup( QCursor.pos( ) ) def sendEmail( self ): myString = self.getTextOutput( ) htmlString = convert_string_RST( myString ) if len( htmlString.strip( ) ) == 0: self.statusLabel.setText( 'OBVIOUSLY
<filename>utils/regression/master_init.py<gh_stars>100-1000 # # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the License for the specific language governing permissions and # limitations under the License. # # @package master_init.py # master_init.py # # Contains definition of parameters used by argparse in master_run. # import argparse import os import sys # # Purpose: used to configure an argparse argument parser instantiated in # module_run a superclass to master_run Caveats: setting defaults still # requires the user to change the defaults in the Defaults class as well as # in this CommandLineParameters class. # f_option_text = """- When present, overrides the default control file, "_def_fctrl.py", in the default initial control directory which can be specified as a full path or a filename. If a file name is specified then the control directory will be used. If a path is specified it will become the control directory in all cases. A control file must exist in the resolved control directory""" d_option_text = """- When present, overrides the default control path, "<test-base>/tests". This option can be a full path or a relative path from the master run folder. If a path was specified as part of the control file name on the command line, this option is ignored.""" c_option_text = """- When present, overrides the default config file, "_riscv_rv64_fcfg.py", located in the config directory which is found in the module directory which equates to the location of Master Run. A custom config file may be substituted by specifying a new file name or providing a full path to the desired config file. If a config file is not located, then the default config file is used. If that file does not exist, then default values are used. NOTE: Due to the complex configurations possible, relative paths are not supported at this time.""" r_option_text = """- Number of times to repeat the entire process control file or a control template, this cannot be specified in the control file, to repeat a control item line specify iterations in the options tag""" o_option_text = """- When present, overrides the default test base, calculated based using the master run location as a starting point, "/../../tests" must exist, along with the specified or defaut control file named if the test-base is to be used to determine the initial control directory.""" s_option_text = """- When present, overrides the default location of any client application used to process individual tasks, the default location is determined by using the directory where the executing master run is located.""" n_option_text = """- When present, overrides the default client application, "forrest_run.py", used to process individual tasks. The run name must reference an executable file in the default or specified directory. If a path is specified that path can be either a relative path having the same rules as the run directory or a full path to the executable.""" class CommandLineParameters(object): usage = ( """ Master Regression and Performance Utility Example: %s -f control_file_fctrl.py """ % sys.argv[0] ) # save and pass on remainder pass_remainder = False # Choosing the RawTextHelpFormatter means the endline characters in the # descriptions are not ignored. formatter_class = argparse.RawTextHelpFormatter # do not allow abbrev parameters, only in Python >3.5 # allow_abbrev = False # command line options are grouped into option groups a concept in argparse _group_1_name = "General options" _group_1_description = "basic, common, high-level options" _parameters_general_options = [ # -h and --help is not needed, provided by default. # "short option" "number of additonal args" "help text # | "long option" | "additional specifications" | # | | | | | # | | | | | [ "-f", "--control-name=", 1, {"default": "_def_fctrl.py", "metavar": ""}, f_option_text, ], ["-d", "--control-dir=", 1, {"metavar": ""}, d_option_text], ["-c", "--config=", 1, {"metavar": ""}, c_option_text], [ "-r", "--num-runs=", 1, {"default": 1, "metavar": ""}, r_option_text, ], [ "-z", "--seed=", 1, {"default": None, "metavar": ""}, "- Number to be used as a random seed for all test this run", ], [ "--no-archive", "--no-archive", 0, {"action": "store_true"}, "- previous output directories are removed when this option " "is present", ], ] _group_2_name = "Persistent, no override" _group_2_description = ( "options which are persistent and cannot be " "overridden in a control-file" ) _parameters_persisting_no_override = [ # "short option" "number of additonal args" "help text # | "long option" | "additional specifications" | # | | | | | # | | | | | ["-o", "--test-base=", 1, {"metavar": ""}, o_option_text], ["-s", "--run-dir=", 1, {"metavar": ""}, s_option_text], ["-n", "--run-name=", 1, {"metavar": ""}, n_option_text], [ "-j", "--run-launcher=", 1, {"default": "local", "metavar": ""}, "- lsf or local, defaults to local", ], [ "-x", "--process-max=", 1, {"default": 16, "metavar": ""}, "- When present, overrides the default number of concurrent " "processes which is\n" " currently 16", ], [ "--target-dir=", "--target-dir=", 1, {"default": os.getcwd(), "metavar": ""}, "- When present, overrides the default output base directory, " '"<current-dir>/output"\n' " If a relative path is specified that path will be calculated " "from the current\n" " directory and converted to a full path.", ], [ "--sum-level=", "--sum-level=", 1, {"default": 1, "choices": ["0", "1", "2", "3"], "metavar": ""}, "- overrides the default level to display only fails and errors " "in the summary.\n" " Allowed values:\n" " \t0 - Silent, 1 - instruction overrun, 2 - all fails, " "3 - everything", ], [ "-m", "--mode=", 1, { "default": "regress", "choices": ["mock", "regress", "perf", "count"], "metavar": "", }, '- When present, overrides the default, "regress" mode,\n' " Allowed values:\n" ' \t"mock", "regress", "perf"', ], ] _group_3_name = "Persistent, yes override" _group_3_description = ( "options which are persistent yet may be overridden in a " "control-file.\n" "NOTE: The following command line options can be overridden using the " "options tag\n" "in each control item line in any control file, unless overridden the " "default or\n" "specified values are persistent until changed" ) _parameters_persisting_yes_override = [ # "short option" "number of additional args" "help text # | "long option" | "additional specifications" | # | | | | | # | | | | | [ "-t", "--timeout=", 1, {"default": 600, "metavar": ""}, "- When present, overrides the default (600) maximum time in " "seconds that a\n" " process is allowed to run prior to a forced termination and " "reported error of\n" " that process.", ], [ "--num-chips=", "--num-chips=", 1, { "default": 1, "choices": [str(x) for x in range(1, 33)], "metavar": "", }, "- When present, overrides the default number of chips (1) to use " "in specified\n" " named test", ], [ "--num-cores=", "--num-cores=", 1, {"default": 1, "choices": ["1", "2", "3", "4"], "metavar": ""}, "- When present, overrides the default number of cores per chip " "(1) to use in\n" " specified named test", ], [ "--num-threads=", "--num-threads=", 1, {"default": 1, "choices": ["1", "2", "3", "4"], "metavar": ""}, "- When present, overrides the default number of threads per core " "(1) to use in\n" " specified named test", ], [ "--max-instr=", "--max-instr=", 1, {"default": 10000, "metavar": ""}, "- When present, overrides the default maximum number (10000) of " "instructions for\n" " a specified test", ], [ "--min-instr=", "--min-instr=", 1, {"default": 1, "metavar": ""}, "- When present, overrides the default minimum number (1) of " "instructions that\n" " must be executed for success", ], [ "--no-sim", "--no-sim", 0, {"action": "store_true"}, "- When present, the simulator does not run", ], [ "--max-fails=", "--max-fails=", 1, {"default": 10, "metavar": ""}, "- When present, sets the number of fails before the run is " "abandoned", ], [ "-k", "--keep=", 1, {"default": "", "metavar": ""},
<gh_stars>0 # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from textwrap import dedent from typing import Iterable, Type import pytest from pants.base.exceptions import ResolveError from pants.base.glob_match_error_behavior import GlobMatchErrorBehavior from pants.base.specs import ( AddressLiteralSpec, AncestorGlobSpec, DirGlobSpec, DirLiteralSpec, FileGlobSpec, FileLiteralSpec, RawSpecs, RawSpecsWithOnlyFileOwners, RawSpecsWithoutFileOwners, RecursiveGlobSpec, Spec, Specs, ) from pants.base.specs_parser import SpecsParser from pants.build_graph.address import Address from pants.engine.addresses import Addresses from pants.engine.fs import SpecsPaths from pants.engine.internals.parametrize import Parametrize from pants.engine.internals.scheduler import ExecutionError from pants.engine.internals.specs_rules import ( AmbiguousImplementationsException, NoApplicableTargetsException, TooManyTargetsException, ) from pants.engine.rules import QueryRule, rule from pants.engine.target import ( Dependencies, FieldSet, FilteredTargets, GeneratedTargets, GenerateTargetsRequest, MultipleSourcesField, NoApplicableTargetsBehavior, OverridesField, SingleSourceField, StringField, Tags, Target, TargetFilesGenerator, TargetGenerator, TargetRootsToFieldSets, TargetRootsToFieldSetsRequest, ) from pants.engine.unions import UnionMembership, UnionRule, union from pants.testutil.rule_runner import RuleRunner, engine_error from pants.util.frozendict import FrozenDict class ResolveField(StringField): alias = "resolve" class MockTarget(Target): alias = "target" core_fields = (Dependencies, MultipleSourcesField, Tags, ResolveField) class MockGeneratedFileTarget(Target): alias = "file_generated" core_fields = (Dependencies, SingleSourceField, Tags, ResolveField) class MockFileTargetGenerator(TargetFilesGenerator): alias = "file_generator" generated_target_cls = MockGeneratedFileTarget core_fields = (MultipleSourcesField, Tags, OverridesField) copied_fields = (Tags,) moved_fields = (Dependencies, ResolveField) class MockGeneratedNonfileTarget(Target): alias = "nonfile_generated" core_fields = (Dependencies, Tags, ResolveField) class MockNonfileTargetGenerator(TargetGenerator): alias = "nonfile_generator" core_fields = (Tags,) copied_fields = (Tags,) moved_fields = (Dependencies, ResolveField) class MockGenerateTargetsRequest(GenerateTargetsRequest): generate_from = MockNonfileTargetGenerator @rule async def generate_mock_generated_target(request: MockGenerateTargetsRequest) -> GeneratedTargets: return GeneratedTargets( request.generator, [ MockGeneratedNonfileTarget( request.template, request.generator.address.create_generated("gen") ) ], ) @pytest.fixture def rule_runner() -> RuleRunner: return RuleRunner( rules=[ generate_mock_generated_target, UnionRule(GenerateTargetsRequest, MockGenerateTargetsRequest), QueryRule(Addresses, [RawSpecs]), QueryRule(Addresses, [RawSpecsWithoutFileOwners]), QueryRule(Addresses, [RawSpecsWithOnlyFileOwners]), QueryRule(FilteredTargets, [Addresses]), QueryRule(Addresses, [Specs]), QueryRule(SpecsPaths, [Specs]), ], objects={"parametrize": Parametrize}, target_types=[MockTarget, MockFileTargetGenerator, MockNonfileTargetGenerator], ) # ----------------------------------------------------------------------------------------------- # RawSpecsWithoutFileOwners -> Targets # ----------------------------------------------------------------------------------------------- def resolve_raw_specs_without_file_owners( rule_runner: RuleRunner, specs: Iterable[Spec], ignore_nonexistent: bool = False, ) -> list[Address]: specs_obj = RawSpecs.create( specs, filter_by_global_options=True, convert_dir_literal_to_address_literal=False, unmatched_glob_behavior=( GlobMatchErrorBehavior.ignore if ignore_nonexistent else GlobMatchErrorBehavior.error ), ) result = rule_runner.request(Addresses, [RawSpecsWithoutFileOwners.from_raw_specs(specs_obj)]) return sorted(result) def test_raw_specs_without_file_owners_literals_vs_globs(rule_runner: RuleRunner) -> None: rule_runner.write_files( { "demo/BUILD": dedent( """\ file_generator(sources=['**/*.txt']) nonfile_generator(name="nonfile") """ ), "demo/f1.txt": "", "demo/f2.txt": "", "demo/f[3].txt": "", "demo/subdir/f.txt": "", "demo/subdir/f.another_ext": "", "demo/subdir/BUILD": "target(name='another_ext', sources=['f.another_ext'])", "another_dir/BUILD": "target(sources=[])", } ) def assert_resolved(spec: Spec, expected: set[Address]) -> None: result = resolve_raw_specs_without_file_owners(rule_runner, [spec]) assert set(result) == expected # Literals should be "one-in, one-out". assert_resolved(AddressLiteralSpec("demo"), {Address("demo")}) assert_resolved( AddressLiteralSpec("demo/f1.txt"), {Address("demo", relative_file_path="f1.txt")} ) assert_resolved( AddressLiteralSpec("demo", target_component="nonfile", generated_component="gen"), {Address("demo", target_name="nonfile", generated_name="gen")}, ) assert_resolved( AddressLiteralSpec("demo/subdir", target_component="another_ext"), {Address("demo/subdir", target_name="another_ext")}, ) demo_dir_generated_targets = { Address("demo", relative_file_path="f1.txt"), Address("demo", relative_file_path="f2.txt"), Address("demo", relative_file_path="f[[]3].txt"), Address("demo", target_name="nonfile", generated_name="gen"), } demo_subdir_generated_targets = { Address("demo", relative_file_path="subdir/f.txt"), Address("demo/subdir", target_name="another_ext"), } # `DirGlobSpec` matches all targets that "reside" in the directory, either because explicitly # declared there or generated into that dir. assert_resolved( # Note that this does not include `demo/subdir/f2.ext:../demo`, even though its target # generator matches. DirGlobSpec("demo"), {Address("demo"), Address("demo", target_name="nonfile"), *demo_dir_generated_targets}, ) assert_resolved( # Should include all generated targets that reside in `demo/subdir`, even though their # target generator is in an ancestor. DirGlobSpec("demo/subdir"), demo_subdir_generated_targets, ) # `DirLiteralSpec` matches all targets that "reside" in the directory, but it filters out # target generators. assert_resolved(DirLiteralSpec("demo"), demo_dir_generated_targets) assert_resolved(DirLiteralSpec("demo/subdir"), demo_subdir_generated_targets) all_tgts_in_demo = { Address("demo"), Address("demo", target_name="nonfile"), *demo_dir_generated_targets, *demo_subdir_generated_targets, } assert_resolved(RecursiveGlobSpec("demo"), all_tgts_in_demo) assert_resolved(AncestorGlobSpec("demo/subdir"), all_tgts_in_demo) assert_resolved( AncestorGlobSpec("demo"), { Address("demo"), Address("demo", target_name="nonfile"), Address("demo", target_name="nonfile", generated_name="gen"), Address("demo", relative_file_path="f1.txt"), Address("demo", relative_file_path="f2.txt"), Address("demo", relative_file_path="f[[]3].txt"), }, ) def test_raw_specs_without_file_owners_deduplication(rule_runner: RuleRunner) -> None: """When multiple specs cover the same address, we should deduplicate to one single Address.""" rule_runner.write_files( { "demo/f.txt": "", "demo/BUILD": dedent( """\ file_generator(sources=['f.txt']) nonfile_generator(name="nonfile") """ ), } ) specs = [ AddressLiteralSpec("demo"), DirLiteralSpec("demo"), DirGlobSpec("demo"), RecursiveGlobSpec("demo"), AncestorGlobSpec("demo"), AddressLiteralSpec("demo", target_component="nonfile", generated_component="gen"), AddressLiteralSpec("demo/f.txt"), ] assert resolve_raw_specs_without_file_owners(rule_runner, specs) == [ Address("demo"), Address("demo", target_name="nonfile"), Address("demo", target_name="nonfile", generated_name="gen"), Address("demo", relative_file_path="f.txt"), ] def test_raw_specs_without_file_owners_filter_by_tag(rule_runner: RuleRunner) -> None: rule_runner.set_options(["--tag=+integration"]) all_integration_tgts = [ Address("demo", target_name="b_f"), Address("demo", target_name="b_nf"), Address("demo", target_name="b_nf", generated_name="gen"), Address("demo", target_name="b_f", relative_file_path="f.txt"), ] rule_runner.write_files( { "demo/f.txt": "", "demo/BUILD": dedent( """\ file_generator(name="a_f", sources=["f.txt"]) file_generator(name="b_f", sources=["f.txt"], tags=["integration"]) file_generator(name="c_f", sources=["f.txt"], tags=["ignore"]) nonfile_generator(name="a_nf") nonfile_generator(name="b_nf", tags=["integration"]) nonfile_generator(name="c_nf", tags=["ignore"]) """ ), } ) assert ( resolve_raw_specs_without_file_owners(rule_runner, [DirGlobSpec("demo")]) == all_integration_tgts ) # The same filtering should work when given literal addresses, including generated targets and # file addresses. literals_result = resolve_raw_specs_without_file_owners( rule_runner, [ AddressLiteralSpec("demo", "a_f"), AddressLiteralSpec("demo", "b_f"), AddressLiteralSpec("demo", "c_f"), AddressLiteralSpec("demo", "a_nf"), AddressLiteralSpec("demo", "b_nf"), AddressLiteralSpec("demo", "c_nf"), AddressLiteralSpec("demo/f.txt", "a_f"), AddressLiteralSpec("demo/f.txt", "b_f"), AddressLiteralSpec("demo", "a_nf", "gen"), AddressLiteralSpec("demo", "b_nf", "gen"), AddressLiteralSpec("demo", "c_nf", "gen"), ], ) assert literals_result == all_integration_tgts def test_raw_specs_without_file_owners_filter_by_exclude_pattern(rule_runner: RuleRunner) -> None: rule_runner.set_options(["--exclude-target-regexp=exclude_me.*"]) rule_runner.write_files( { "demo/f.txt": "", "demo/BUILD": dedent( """\ file_generator(name="exclude_me_f", sources=["f.txt"]) file_generator(name="not_me_f", sources=["f.txt"]) nonfile_generator(name="exclude_me_nf") nonfile_generator(name="not_me_nf") """ ), } ) not_me_tgts = [ Address("demo", target_name="not_me_f"), Address("demo", target_name="not_me_nf"), Address("demo", target_name="not_me_nf", generated_name="gen"), Address("demo", target_name="not_me_f", relative_file_path="f.txt"), ] assert resolve_raw_specs_without_file_owners(rule_runner, [DirGlobSpec("demo")]) == not_me_tgts # The same filtering should work when given literal addresses, including generated targets and # file addresses. literals_result = resolve_raw_specs_without_file_owners( rule_runner, [ AddressLiteralSpec("demo", "exclude_me_f"), AddressLiteralSpec("demo", "exclude_me_nf"), AddressLiteralSpec("demo", "not_me_f"), AddressLiteralSpec("demo", "not_me_nf"), AddressLiteralSpec("demo", "exclude_me_nf", "gen"), AddressLiteralSpec("demo", "not_me_nf", "gen"), AddressLiteralSpec("demo/f.txt", "exclude_me_f"), AddressLiteralSpec("demo/f.txt", "not_me_f"), ], ) assert literals_result == not_me_tgts def test_raw_specs_without_file_owners_do_not_exist(rule_runner: RuleRunner) -> None: rule_runner.write_files( {"real/f.txt": "", "real/BUILD": "target(sources=['f.txt'])", "empty/BUILD": "# empty"} ) def assert_resolve_error(spec: Spec, *, expected: str) -> None: with engine_error(contains=expected): resolve_raw_specs_without_file_owners(rule_runner, [spec]) def assert_does_not_error(spec: Spec, *, ignore_nonexistent: bool = False) -> None: assert not resolve_raw_specs_without_file_owners( rule_runner, [spec], ignore_nonexistent=ignore_nonexistent ) # Literal addresses require for the target to be resolved. assert_resolve_error( AddressLiteralSpec("fake", "tgt"), expected="'fake' does not exist on disk" ) assert_resolve_error( AddressLiteralSpec("fake/f.txt", "tgt"), expected="'fake/f.txt' does not exist on disk", ) did_you_mean = ResolveError.did_you_mean( bad_name="fake_tgt", known_names=["real"], namespace="real" ) assert_resolve_error(AddressLiteralSpec("real", "fake_tgt"), expected=str(did_you_mean)) assert_resolve_error(AddressLiteralSpec("real/f.txt", "fake_tgt"), expected=str(did_you_mean)) assert_resolve_error( DirGlobSpec("fake"), expected='Unmatched glob from CLI arguments: "fake/*"' ) assert_does_not_error(DirGlobSpec("empty")) assert_does_not_error(DirGlobSpec("fake"), ignore_nonexistent=True) assert_resolve_error( DirLiteralSpec("fake"), expected='Unmatched glob from CLI arguments: "fake/*"' ) assert_does_not_error(DirLiteralSpec("empty")) assert_does_not_error(DirLiteralSpec("fake"), ignore_nonexistent=True) assert_resolve_error( RecursiveGlobSpec("fake"), expected='Unmatched glob from CLI arguments: "fake/**"' ) assert_does_not_error(RecursiveGlobSpec("empty")) assert_does_not_error(RecursiveGlobSpec("fake"), ignore_nonexistent=True) assert_resolve_error( AncestorGlobSpec("fake"), expected='Unmatched glob from CLI arguments: "fake/*"' ) assert_does_not_error(AncestorGlobSpec("empty")) assert_does_not_error(AncestorGlobSpec("fake"), ignore_nonexistent=True) def test_raw_specs_without_file_owners_generated_target_does_not_belong_to_generator( rule_runner: RuleRunner, ) -> None: rule_runner.write_files( { "demo/f.txt": "", "demo/other.txt": "", "demo/BUILD": dedent( """\ file_generator(name='owner', sources=['f.txt']) file_generator(name='not_owner', sources=['other.txt']) """ ), } ) with pytest.raises(ExecutionError) as exc: resolve_raw_specs_without_file_owners( rule_runner, [AddressLiteralSpec("demo/f.txt", "not_owner")] ) assert ( "The address `demo/f.txt:not_owner` was not generated by the target `demo:not_owner`" ) in str(exc.value) def test_raw_specs_without_file_owners_parametrize( rule_runner: RuleRunner, ) -> None: rule_runner.write_files( { "demo/f.txt": "", "demo/BUILD": dedent( """\ file_generator(sources=['f.txt'], resolve=parametrize("a", "b")) nonfile_generator(name="nonfile", resolve=parametrize("a", "b")) target(sources=['f.txt'], name="not_gen", resolve=parametrize("a", "b")) """ ), } ) def assert_resolved(spec: Spec, expected: set[Address]) -> None: assert set(resolve_raw_specs_without_file_owners(rule_runner, [spec])) == expected not_gen_resolve_a = Address("demo", target_name="not_gen", parameters={"resolve": "a"}) not_gen_resolve_b = Address("demo", target_name="not_gen", parameters={"resolve": "b"}) file_generator_resolve_a = { Address("demo", relative_file_path="f.txt", parameters={"resolve": "a"}), Address("demo", parameters={"resolve": "a"}), } file_generator_resolve_b = { Address("demo", relative_file_path="f.txt", parameters={"resolve": "b"}), Address("demo", parameters={"resolve": "b"}), } nonfile_generator_resolve_a = { Address("demo", target_name="nonfile", generated_name="gen", parameters={"resolve": "a"}), Address("demo", target_name="nonfile", parameters={"resolve": "a"}), } nonfile_generator_resolve_b = { Address("demo", target_name="nonfile", generated_name="gen", parameters={"resolve": "b"}), Address("demo", target_name="nonfile", parameters={"resolve": "b"}), } assert_resolved( RecursiveGlobSpec(""), { *file_generator_resolve_a, *file_generator_resolve_b, *nonfile_generator_resolve_a, *nonfile_generator_resolve_b, not_gen_resolve_a, not_gen_resolve_b, }, ) # A literal address for a parameterized target works as expected. assert_resolved( AddressLiteralSpec( "demo", target_component="not_gen", parameters=FrozenDict({"resolve": "a"}) ), {not_gen_resolve_a}, ) assert_resolved( AddressLiteralSpec("demo/f.txt", parameters=FrozenDict({"resolve": "a"})), {Address("demo", relative_file_path="f.txt", parameters={"resolve": "a"})}, ) assert_resolved( AddressLiteralSpec( "demo", "nonfile", generated_component="gen", parameters=FrozenDict({"resolve": "a"}) ), {Address("demo", target_name="nonfile", generated_name="gen", parameters={"resolve": "a"})}, ) assert_resolved( # A direct reference to the parametrized target generator. AddressLiteralSpec("demo", parameters=FrozenDict({"resolve": "a"})), {Address("demo", parameters={"resolve": "a"})}, ) # A literal address for a parametrized template should be expanded with the matching targets. assert_resolved( AddressLiteralSpec("demo", target_component="not_gen"), {not_gen_resolve_a, not_gen_resolve_b}, ) # The above affordance plays nicely with target generation. assert_resolved( # Note that this returns references to the two target generators. Certain goals like # `test` may then later replace those with their generated targets. AddressLiteralSpec("demo"), {Address("demo", parameters={"resolve": r}) for r in ("a", "b")}, ) assert_resolved( AddressLiteralSpec("demo", "nonfile", "gen"), { Address("demo", target_name="nonfile", generated_name="gen", parameters={"resolve": r}) for r in ("a", "b") }, ) assert_resolved( AddressLiteralSpec("demo/f.txt"), { Address("demo", relative_file_path="f.txt", parameters={"resolve": r}) for r in ("a", "b") }, ) # Error on invalid targets. def assert_errors(spec: AddressLiteralSpec) -> None: with engine_error(ValueError): resolve_raw_specs_without_file_owners(rule_runner, [spec]) assert_errors(AddressLiteralSpec("demo", parameters=FrozenDict({"fake": "v"}))) assert_errors(AddressLiteralSpec("demo", parameters=FrozenDict({"resolve": "fake"}))) # ----------------------------------------------------------------------------------------------- # RawSpecsWithOnlyFileOwners -> Targets # ----------------------------------------------------------------------------------------------- def resolve_raw_specs_with_only_file_owners( rule_runner: RuleRunner, specs: Iterable[Spec], ignore_nonexistent: bool = False ) -> list[Address]: specs_obj = RawSpecs.create( specs, filter_by_global_options=True, convert_dir_literal_to_address_literal=True, unmatched_glob_behavior=( GlobMatchErrorBehavior.ignore if ignore_nonexistent else GlobMatchErrorBehavior.error ), ) result = rule_runner.request(Addresses, [RawSpecsWithOnlyFileOwners.from_raw_specs(specs_obj)]) return sorted(result) def test_raw_specs_with_only_file_owners_literal_file(rule_runner: RuleRunner) -> None: rule_runner.write_files( { "demo/f1.txt": "", "demo/f2.txt": "", "demo/BUILD": dedent( """\ file_generator(name='generator', sources=['*.txt']) nonfile_generator(name='nonfile') target(name='not-generator', sources=['*.txt']) """ ), } ) assert resolve_raw_specs_with_only_file_owners( rule_runner, [FileLiteralSpec("demo/f1.txt")] ) == [ Address("demo", target_name="not-generator"), Address("demo", target_name="generator", relative_file_path="f1.txt"), ] def test_raw_specs_with_only_file_owners_glob(rule_runner: RuleRunner) -> None: rule_runner.write_files( { "demo/f1.txt": "", "demo/f2.txt": "", "demo/BUILD": dedent( """\ file_generator(name='generator', sources=['*.txt']) nonfile_generator(name='nonfile') target(name='not-generator', sources=['*.txt']) target(name='skip-me', sources=['*.txt']) target(name='bad-tag', sources=['*.txt'], tags=['skip']) """ ),
2, 10, 12, 14, 15, 21], 12: [11, 16, 3, 14, 15], 13: [8, 1, 10, 9, 7], 14: [11, 12, 2, 3, 4], 15: [6, 11, 12, 16, 17, 21, 22], 16: [3, 12, 5, 6, 15], 17: [18, 19, 22, 6, 15], 18: [8, 17, 19, 6, 7], 19: [8, 9, 17, 18, 20, 22], 20: [9, 10, 19, 21, 22], 21: [10, 11, 20, 22, 15], 22: [17, 19, 20, 21, 15]}, name = "Kittell Graph") _circle_embedding(g, list(range(3)), shift=.75) _circle_embedding(g, list(range(3, 13)), radius = .4) _circle_embedding(g, list(range(15, 22)), radius = .2, shift=-.15) pos = g.get_pos() pos[13] = (-.65,-.35) pos[14] = (.65,-.35) pos[22] = (0,0) return g def CameronGraph(): r""" Returns the Cameron graph. The Cameron graph is strongly regular with parameters `v = 231, k = 30, \lambda = 9, \mu = 3`. For more information on the Cameron graph, see `<http://www.win.tue.nl/~aeb/graphs/Cameron.html>`_. EXAMPLES:: sage: g = graphs.CameronGraph() sage: g.order() 231 sage: g.size() 3465 sage: g.is_strongly_regular(parameters = True) # long time (231, 30, 9, 3) """ from sage.groups.perm_gps.permgroup_named import MathieuGroup from itertools import combinations g = Graph(name="Cameron Graph") sets = MathieuGroup(22).orbit((1,2,3,7,10,20), action = "OnSets") for s in sets: for a,b,c,d in combinations(set(s),4): g.add_edges([((a,b),(c,d)),((a,c),(b,d)), ((a,d),(b,c))]) g.relabel() ordering = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19, 20, 21, 24, 25, 26, 27, 29, 31, 34, 35, 38, 39, 96, 97, 101, 105, 51, 117, 198, 32, 196, 201, 131, 167, 199, 197, 86, 102, 195, 200, 186, 144, 202, 177, 44, 53, 58, 45, 48, 54, 43, 57, 50, 46, 59, 133, 169, 104, 188, 118, 208, 157, 52, 207, 209, 132, 204, 13, 187, 33, 203, 70, 145, 103, 168, 178, 87, 124, 123, 125, 111, 120, 116, 119, 112, 95, 114, 115, 137, 218, 213, 108, 76, 77, 74, 62, 64, 67, 63, 68, 69, 61, 41, 75, 73, 66, 71, 72, 60, 22, 230, 151, 184, 138, 193, 109, 228, 174, 214, 219, 93, 126, 143, 150, 146, 224, 181, 16, 223, 171, 90, 135, 106, 205, 211, 121, 148, 160, 216, 222, 190, 36, 55, 185, 175, 94, 139, 110, 215, 152, 220, 229, 194, 40, 128, 99, 141, 173, 154, 82, 156, 164, 159, 28, 127, 158, 65, 162, 163, 153, 161, 155, 140, 98, 47, 113, 84, 180, 30, 129, 179, 183, 165, 176, 142, 100, 49, 134, 210, 170, 147, 91, 37, 206, 182, 191, 56, 136, 225, 221, 149, 227, 217, 17, 107, 172, 212, 122, 226, 23, 85, 42, 80, 92, 81, 89, 78, 83, 88, 79, 130, 192, 189, 166] _circle_embedding(g, ordering) return g def ChvatalGraph(): r""" Returns the Chvatal graph. Chvatal graph is one of the few known graphs to satisfy Grunbaum's conjecture that for every m, n, there is an m-regular, m-chromatic graph of girth at least n. For more information, see this `Wikipedia article on the Chvatal graph <http://en.wikipedia.org/wiki/Chv%C3%A1tal_graph>`_. EXAMPLES: The Chvatal graph has 12 vertices and 24 edges. It is a 4-regular, 4-chromatic graph with radius 2, diameter 2, and girth 4. :: sage: G = graphs.ChvatalGraph(); G Chvatal graph: Graph on 12 vertices sage: G.order(); G.size() 12 24 sage: G.degree() [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] sage: G.chromatic_number() 4 sage: G.radius(); G.diameter(); G.girth() 2 2 4 TESTS:: sage: import networkx sage: G = graphs.ChvatalGraph() sage: G.is_isomorphic(Graph(networkx.chvatal_graph())) True """ edges = {0:[1, 4, 6, 9], 1:[2, 5, 7], 2:[3, 6, 8], 3:[4, 7, 9], 4:[5, 8], 5:[10, 11], 6:[10, 11], 7:[8, 11], 8:[10], 9:[10, 11]} pos_dict = {} for i in range(5, 10): x = float(cos((pi / 2) + ((2 * pi) / 5) * i)) y = float(sin((pi / 2) + ((2 * pi) / 5) * i)) pos_dict[i] = (x, y) for i in range(5): x = float(2 * (cos((pi / 2) + ((2 * pi) / 5) * (i - 5)))) y = float(2 * (sin((pi / 2) + ((2 * pi) / 5) * (i - 5)))) pos_dict[i] = (x, y) pos_dict[10] = (0.5, 0) pos_dict[11] = (-0.5, 0) return Graph(edges, pos=pos_dict, name="Chvatal graph") def ClebschGraph(): r""" Return the Clebsch graph. EXAMPLES:: sage: g = graphs.ClebschGraph() sage: g.automorphism_group().cardinality() 1920 sage: g.girth() 4 sage: g.chromatic_number() 4 sage: g.diameter() 2 sage: g.show(figsize=[10, 10]) # long time """ g = Graph(pos={}) x = 0 for i in range(8): g.add_edge(x % 16, (x + 1) % 16) g.add_edge(x % 16, (x + 6) % 16) g.add_edge(x % 16, (x + 8) % 16) x += 1 g.add_edge(x % 16, (x + 3) % 16) g.add_edge(x % 16, (x + 2) % 16) g.add_edge(x % 16, (x + 8) % 16) x += 1 _circle_embedding(g, list(range(16)), shift=.5) g.name("Clebsch graph") return g def CoxeterGraph(): r""" Return the Coxeter graph. See the :wikipedia:`Wikipedia page on the Coxeter graph <Coxeter_graph>`. EXAMPLES:: sage: g = graphs.CoxeterGraph() sage: g.automorphism_group().cardinality() 336 sage: g.girth() 7 sage: g.chromatic_number() 3 sage: g.diameter() 4 sage: g.show(figsize=[10, 10]) # long time """ g = Graph({ 27: [6, 22, 14], 24: [0, 7, 18], 25: [8, 15, 2], 26: [10, 16, 23], }, pos={}) g.add_cycle(list(range(24))) g.add_edges([(5, 11), (9, 20), (12, 1), (13, 19), (17, 4), (3, 21)]) _circle_embedding(g, list(range(24))) _circle_embedding(g, [24, 25, 26], radius=.5) g.get_pos()[27] = (0, 0) g.name("Coxeter Graph") return g def DejterGraph(): r""" Return the Dejter graph. The Dejter graph is obtained from the binary 7-cube by deleting a copy of the Hamming code of length 7. It is 6-regular, with 112 vertices and 336 edges. For more information, see the :wikipedia:`Dejter_graph`. EXAMPLES:: sage: g = graphs.DejterGraph(); g Dejter Graph: Graph on 112 vertices sage: g.is_regular(k=6) True sage: g.girth() 4 """ from sage.graphs.generators.families import CubeGraph from sage.coding.hamming_code import HammingCode from sage.rings.finite_rings.finite_field_constructor import FiniteField g = CubeGraph(7) g.delete_vertices(["".join(map(str, x)) for x in HammingCode(FiniteField(2), 3)]) g.name("Dejter Graph") return g def DesarguesGraph(): """ Returns the Desargues graph. PLOTTING: The layout chosen is the same as on the cover of [1]. EXAMPLES:: sage: D = graphs.DesarguesGraph() sage: L = graphs.LCFGraph(20,[5,-5,9,-9],5) sage: D.is_isomorphic(L) True sage: D.show() # long time REFERENCE: - [1] <NAME>. Graph Theory. Reading, MA: Addison-Wesley, 1994. """ from sage.graphs.generators.families import GeneralizedPetersenGraph G = GeneralizedPetersenGraph(10,3) G.name("Desargues Graph") return G def DurerGraph(): r""" Returns the Dürer graph. For more information, see this `Wikipedia article on the Dürer graph <http://en.wikipedia.org/wiki/D%C3%BCrer_graph>`_. EXAMPLES: The Dürer graph is named after <NAME>. It is a planar graph with 12 vertices and 18 edges. :: sage: G = graphs.DurerGraph(); G Durer graph: Graph on 12 vertices sage: G.is_planar() True sage: G.order() 12 sage: G.size() 18 The Dürer graph has chromatic number 3, diameter 4, and girth 3. :: sage: G.chromatic_number() 3 sage: G.diameter() 4 sage: G.girth() 3 Its automorphism group is isomorphic to `D_6`. :: sage: ag = G.automorphism_group() sage: ag.is_isomorphic(DihedralGroup(6)) True """ edge_dict = { 0: [1,5,6], 1: [2,7], 2: [3,8], 3: [4,9], 4: [5,10], 5: [11], 6: [8,10], 7: [9,11], 8: [10], 9: [11]} pos_dict = { 0: [2, 0], 1: [1, 1.73205080756888], 2: [-1, 1.73205080756888], 3: [-2, 0], 4: [-1, -1.73205080756888], 5: [1, -1.73205080756888], 6: [1, 0], 7: [0.5, 0.866025403784439], 8: [-0.5, 0.866025403784439], 9: [-1, 0], 10: [-0.5, -0.866025403784439], 11: [0.5, -0.866025403784439]} return Graph(edge_dict, pos=pos_dict, name="Durer graph") def DyckGraph(): """ Returns the Dyck graph. For more information, see the `MathWorld article on the Dyck graph <http://mathworld.wolfram.com/DyckGraph.html>`_ or the `Wikipedia article on the Dyck graph <http://en.wikipedia.org/wiki/Dyck_graph>`_. EXAMPLES: The Dyck graph was defined by <NAME> in 1881. It has `32` vertices and `48` edges, and is a cubic graph (regular of degree `3`):: sage: G = graphs.DyckGraph(); G Dyck graph: Graph on 32 vertices sage: G.order() 32 sage: G.size() 48 sage: G.is_regular() True sage: G.is_regular(3) True It is non-planar and Hamiltonian, as well as bipartite (making it a bicubic graph):: sage: G.is_planar() False sage: G.is_hamiltonian() True sage: G.is_bipartite() True It has radius `5`, diameter `5`, and girth `6`::
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: library.py # # Copyright 2018 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # import json import logging import os import shlex import shutil import sys import stat import tempfile from contextlib import contextmanager from dataclasses import dataclass from subprocess import Popen, PIPE from pipenv.project import Project from configuration import LOGGERS_TO_DISABLE, ENVIRONMENT_VARIABLES, LOGGING_LEVEL logging_level = os.environ.get('LOGGING_LEVEL', '').upper() or LOGGING_LEVEL if logging_level == 'DEBUG': print(f'Current executing python version is {sys.version_info}') # needed to support alternate .venv path if PIPENV_PIPFILE is set # Loading PIPENV related variables early, but not overriding if already loaded. for name, value in ENVIRONMENT_VARIABLES.items(): if name.startswith('PIPENV_'): if not os.environ.get(name): if logging_level == 'DEBUG': print(f'Loading PIPENV related variable {name} : {value}') os.environ[name] = value else: if logging_level == 'DEBUG': print(f'Variable {name} already loaded, not overwriting...') # Provides possible python2.7 compatibility, not really a goal try: FileNotFoundError except NameError: FileNotFoundError = IOError # This is the main prefix used for logging LOGGER_BASENAME = '''_CI.library''' LOGGER = logging.getLogger(LOGGER_BASENAME) LOGGER.addHandler(logging.NullHandler()) @dataclass() class Package: name: str version: str index: str markers: str hashes: list REQUIREMENTS_HEADER = """# # Please do not manually update this file since the requirements are managed # by pipenv through Pipfile and Pipfile.lock . # # This file is created and managed automatically by the template and it is left # here only for backwards compatibility reasons with python's ecosystem. # # Please use Pipfile to update the requirements. # """ # The sequence here is important because it makes sure # that the virtual environment is loaded as soon as possible def is_venv_created(): with open(os.devnull, 'w') as dev_null: venv = Popen(['pipenv', '--venv'], stdout=PIPE, stderr=dev_null).stdout.read().strip() return True if venv else False def is_venv_active(): return hasattr(sys, 'real_prefix') def get_project_root_path(): current_file_path = os.path.dirname(os.path.abspath(__file__)) return os.path.abspath(os.path.join(current_file_path, '..', '..')) def get_venv_parent_path(): alternate_pipefile_location = os.environ.get('PIPENV_PIPFILE', None) if alternate_pipefile_location: venv_parent = os.path.abspath(os.path.dirname(alternate_pipefile_location)) else: venv_parent = os.path.abspath('.') return venv_parent def activate_virtual_environment(): os.chdir(get_project_root_path()) activation_script_directory = 'Scripts' if sys.platform == 'win32' else 'bin' venv_parent = get_venv_parent_path() activation_file = os.path.join(venv_parent, '.venv', activation_script_directory, 'activate_this.py') if is_venv_created(): if sys.version_info[0] == 3: with open(activation_file) as f: exec(f.read(), {'__file__': activation_file}) elif sys.version_info[0] == 2: execfile(activation_file, dict(__file__=activation_file)) # After this everything is executed inside a virtual environment if not is_venv_active(): activate_virtual_environment() try: import coloredlogs colored_logs = True except ImportError: colored_logs = False if is_venv_active(): import semver def get_emojize(): try: from emoji import emojize except ImportError: print('Unable to import emojize from created virtual environment.\n' 'Please make sure that the python version is 3.7 and that the virtual environment is properly created.\n' 'If not please remove the .venv directory and try again. Exiting...') raise SystemExit(1) return emojize def setup_logging(level): if colored_logs: coloredlogs.install(level=level.upper()) else: LOGGER = logging.getLogger() handler = logging.StreamHandler() handler.setLevel(level.upper()) formatter = logging.Formatter(('%(asctime)s - ' '%(name)s - ' '%(levelname)s - ' '%(message)s')) handler.setFormatter(formatter) LOGGER.addHandler(handler) LOGGER.setLevel(level.upper()) for logger in LOGGERS_TO_DISABLE: logging.getLogger(logger).disabled = True # TODO extend debug logging in the following methods def load_environment_variables(environment_variables): LOGGER.debug('Loading environment variables') for name, value in environment_variables.items(): if name in os.environ.keys(): LOGGER.debug('Environment variable "%s" already loaded, not overriding', name) else: LOGGER.debug('Loading environment variable "%s" with value "%s"', name, value) os.environ[name] = value def load_dot_env_file(): if os.path.isfile('.env'): LOGGER.info('Loading environment variables from .env file') variables = {} with open('.env', 'r') as dot_env: for line in dot_env.read().splitlines(): if line.strip().startswith('export '): line = line.replace('export ', '') key, value = line.strip().split('=', 1) variables[key.strip()] = value.strip() load_environment_variables(variables) def get_binary_path(executable): """Gets the software name and returns the path of the binary.""" if sys.platform == 'win32': if executable == 'start': return executable executable = executable + '.exe' if executable in os.listdir('.'): binary = os.path.join(os.getcwd(), executable) else: binary = next((os.path.join(path, executable) for path in os.environ['PATH'].split(os.pathsep) if os.path.isfile(os.path.join(path, executable))), None) else: venv_parent = get_venv_parent_path() venv_bin_path = os.path.join(venv_parent, '.venv', 'bin') if not venv_bin_path in os.environ.get('PATH'): if logging_level == 'DEBUG': print(f'Adding path {venv_bin_path} to environment PATH variable') os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path]) binary = shutil.which(executable) return binary if binary else None def validate_binary_prerequisites(software_list): LOGGER.debug('Trying to validate binary prerequisites') success = True for executable in software_list: if not get_binary_path(executable): success = False LOGGER.error('Executable "%s" not found', executable) else: LOGGER.debug('Executable "%s" found in the path!', executable) return success def validate_environment_variable_prerequisites(variable_list): LOGGER.debug('Trying to validate prerequisites') success = True for variable in variable_list: if not os.environ.get(variable): success = False LOGGER.error('Environment variable "%s" not found', variable) else: LOGGER.debug('Environment variable "%s" found in the path!', variable) return success def interpolate_executable(command): command_list = command.split() if len(command_list) == 1: command_list = [command_list[0], ] try: LOGGER.debug(f'Getting executable path for {command_list[0]}') command_list[0] = get_binary_path(command_list[0]) command = ' '.join(command_list) except IndexError: pass return command def execute_command(command): LOGGER.debug('Executing command "%s"', command) command = interpolate_executable(command) if sys.platform == 'win32': process = Popen(command, shell=True, bufsize=1) else: command = shlex.split(command) LOGGER.debug('Command split to %s for posix shell', command) process = Popen(command, bufsize=1) process.communicate() return True if not process.returncode else False def open_file(path): open_programs = {'darwin': 'open', 'linux': 'xdg-open', 'win32': 'start'} executable = get_binary_path(open_programs.get(sys.platform)) command = '{} {}'.format(executable, path) return execute_command(command) def clean_up(items): if not isinstance(items, (list, tuple)): items = [items] for item in items: if os.path.isdir(item): LOGGER.debug('Trying to remove directory "%s"', item) shutil.rmtree(item) elif os.path.isfile(item): LOGGER.debug('Trying to remove file "%s"', item) os.unlink(item) else: LOGGER.warning('Unable to remove file or directory "%s"', item) def get_top_level_dependencies(): packages = list(Project().parsed_pipfile.get('packages', {}).keys()) dev_packages = list(Project().parsed_pipfile.get('dev-packages', {}).keys()) return packages, dev_packages def get_all_packages(): try: venv_parent = get_venv_parent_path() lock_file = os.path.join(venv_parent, 'Pipfile.lock') with open(lock_file, 'r') as lock: all_packages = json.loads(lock.read()) except FileNotFoundError: LOGGER.error('Could not open Pipfile.lock, so cannot get dependencies, exiting...') raise SystemExit(1) packages = [Package(package_name, data.get('version'), data.get('index'), data.get('markers'), data.get('hashes', [])) for package_name, data in all_packages.get('default').items()] dev_packages = [Package(package_name, data.get('version'), data.get('index'), data.get('markers'), data.get('hashes', [])) for package_name, data in all_packages.get('develop').items()] return packages, dev_packages def format_marker(marker): return f' ; {marker}' if marker else '' def save_requirements(): top_level_packages, top_level_dev_packages = get_top_level_dependencies() all_packages, all_dev_packages = get_all_packages() packages = [package for package in all_packages if package.name in top_level_packages] dev_packages = [package for package in all_dev_packages if package.name in top_level_dev_packages] venv_parent = get_venv_parent_path() requirements_file = os.path.join(venv_parent, 'requirements.txt') with open(requirements_file, 'w') as f: requirements = '\n'.join([f'{package.name}{package.version.replace("==", "~=")}{format_marker(package.markers)}' for package in sorted(packages, key=lambda x: x.name)]) f.write(REQUIREMENTS_HEADER + requirements) dev_requirements_file = os.path.join(venv_parent, 'dev-requirements.txt') with open(dev_requirements_file, 'w') as f: dev_requirements = '\n'.join([f'{package.name}{package.version.replace("==", "~=")}{format_marker(package.markers)}' for package in sorted(dev_packages, key=lambda x: x.name)]) f.write(REQUIREMENTS_HEADER + dev_requirements) def get_version_file_path(): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '.VERSION')) def bump(segment=None, version_file=None): if not version_file: version_file = get_version_file_path() try: with open(version_file) as version: version_text = version.read().strip() _ = semver.parse(version_text) except FileNotFoundError: LOGGER.error('Could not find .VERSION file') raise SystemExit(1) except ValueError: LOGGER.error('Invalid version found in .VERSION file "%s"', version_text) raise SystemExit(1) if segment: if segment not in ('major', 'minor', 'patch'): LOGGER.error('Invalid segment "%s" was provided for semantic versioning, exiting...') raise SystemExit(1) new_version = getattr(semver, 'bump_{}'.format(segment))(version_text) with open(version_file, 'w') as vfile: vfile.write(new_version) return new_version else: return version_text @contextmanager def cd(new_directory, clean_up=lambda: True): # pylint: disable=invalid-name """Changes into a given directory and cleans up after it is done Args: new_directory: The directory to change to clean_up: A method to clean up the working directory once done """ previous_directory = os.getcwd() os.chdir(os.path.expanduser(new_directory)) try: yield finally: os.chdir(previous_directory) clean_up() @contextmanager def tempdir(): """Creates a temporary directory""" directory_path = tempfile.mkdtemp() def clean_up(): # pylint: disable=missing-docstring shutil.rmtree(directory_path, onerror=on_error) with cd(directory_path, clean_up): yield directory_path def on_error(func, path, exc_info): # pylint: disable=unused-argument """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises
"""Command line interface.""" from argparse import ( Action, ArgumentParser, ) from datetime import datetime from datetime import date import pandas as pd from pandas import DataFrame from sys import stdout from logging import INFO, basicConfig, getLogger import shlex import unicodedata import os import csv from penn_chime.constants import CHANGE_DATE from penn_chime.model.parameters import Parameters, Disposition from penn_chime.model.sir import Sir as Model from mhs_chime.SirWI import Sir as InflectedModel from clienv import ChimeCLIEnvironment from pdfgenerator.chime_pdf_generator import generate_pdf from mhs_chime.dumpProperties import dumpProperties import zipfile def compress_file(archive_name, file_name): rsp = file_name.rsplit("/",1) fn = rsp[1] covid_zip = zipfile.ZipFile(archive_name, 'a') # covid_zip = zipfile.ZipFile(fname.replace(".csv", ".zip"), 'a') covid_zip.write(file_name, arcname=fn, compress_type=zipfile.ZIP_DEFLATED) covid_zip.close() def sort_tuples(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used tup.sort(key = lambda x: x[0]) return tup basicConfig( level=INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", stream=stdout, ) logger = getLogger(__name__) VERBOSE = False GENERATE_MASTER_PDF = True OPEN_PDF = True class FromFile(Action): """From File.""" def __call__(self, parser, namespace, values, option_string=None): with values as f: parser.parse_args(f.read().split(), namespace) def cast_date(string): return datetime.strptime(string, '%Y-%m-%d').date() def validator(arg, cast, min_value, max_value, required, default ): """Validator.""" def validate(string): """Validate.""" if string == '' and cast != str: if required: raise AssertionError('%s is required.') return None value = cast(string) if min_value is not None: assert value >= min_value if max_value is not None: assert value <= max_value return value return validate def parse_args(args): """Parse args.""" parser = ArgumentParser(description="penn_chime: {CHANGE_DATE}") parser.add_argument("--file", type=open, action=FromFile) parser.add_argument( "--location", type=str, default="no location" ) parser.add_argument( "--scenario-id", type=str, default="no id", ) parser.add_argument("--hosp-capacity", type=int, help="MedSurg Capacity", default=0) parser.add_argument("--icu-capacity", type=int, help="ICU Capacity", default=0) parser.add_argument("--vent-capacity", type=int, help="Ventilators", default=0) parser.add_argument("--hosp-occupied", type=int, help="Non-COVID19 MedSurg Occupancy", default=0) parser.add_argument("--icu-occupied", type=int, help="Non-COVID19 ICU Occupancy", default=0) parser.add_argument("--vent-occupied", type=int, help="Non-COVID19 Ventilators in Use", default=0) parser.add_argument("--current-precautionary", type=int, help="Currently Hospitalized Precautionary COVID-19 Patients (>= 0)", default=0 ), # generate_pdf: 0 = None, 1=Generate a PDF for each scenario parser.add_argument("--create-pdf", type=int, help="Generate PDF Report for Scenario", default=0) parser.add_argument("--create-csv", type=int, help="Generate CSV Output for Scenario", default=0) parser.add_argument("--actuals-date", type=cast_date, help="Actuals Date", default=cast_date('1980-01-01') ) parser.add_argument("--mitigation-date", type=cast_date, help="Initial Mitigation", default=None) parser.add_argument("--mitigation-model", type=str, help="Model file with mitigations by date and impact", default=None) parser.add_argument("--current-date", type=cast_date, help="Current Date", default=date.today()) for arg, cast, min_value, max_value, help, required, default in ( ("--current-hospitalized", int, 0, None, "Currently Hospitalized COVID-19 Patients (>= 0)", True, None ), ("--date-first-hospitalized", cast_date, None, None, "Date of First Hospitalization", False, None ), ("--doubling-time-low", float, 0.0, None, "Doubling time (lower) before social distancing (days)", True, None ), ("--doubling-time-observed", float, 0.0, None, "Doubling time (observed) before social distancing (days)", True, None ), ("--doubling-time-high", float, 0.0, None, "Doubling time (upper) before social distancing (days)", True, None ), ("--hospitalized-days", int, 0, None, "Average Hospital Length of Stay (days)", True, None ), ("--hospitalized-rate", float, 0.00001, 1.0, "Hospitalized Rate: 0.00001 - 1.0", True, None ), ("--icu-days", int, 0, None, "Average Days in ICU", True, None), ("--icu-rate", float, 0.0, 1.0, "ICU Rate: 0.0 - 1.0", True, None), ("--market-share", float, 0.00001, 1.0, "Hospital Market Share (0.00001 - 1.0)", True, None ), ("--infectious-days", float, 0.0, None, "Infectious days", True, None), ("--n-days", int, 0, None, "Number of days to project >= 0", True, 200 ), ("--relative-contact-rate", float, 0.0, 1.0, "Social Distancing Reduction Rate: 0.0 - 1.0", True, None ), ("--relative-contact-rate-0", float, 0.0, 1.0, "Social Distancing Reduction Rate (0): 0.0 - 1.0", True, None ), ("--relative-contact-rate-1", float, 0.0, 1.0, "Social Distancing Reduction Rate (1): 0.0 - 1.0", True, None ), ("--population", int, 1, None, "Regional Population >= 1", True, None), ("--ventilated-days", int, 0, None, "Average Days on Ventilator", True, None), ("--ventilated-rate", float, 0.0, 1.0, "Ventilated Rate: 0.0 - 1.0", True, None), ("--start-day", int, None, None, "Start day for model output", False, None), ("--data-key", str, None, None, "Key for linking for displays", False, None), ): parser.add_argument( arg, type=validator(arg, cast, min_value, max_value, required, default), help=help, ) return parser.parse_args(shlex.split(args)) def main(): """Main.""" data = DataFrame() head = DataFrame() computed_data = DataFrame() mitigations = DataFrame() miti_data = DataFrame() m_start_date = date.today() cenv = ChimeCLIEnvironment() archive_name = cenv.output_dir + "/" + cenv.archive_file_name f = open(cenv.parameters_file, "r") for x in f: x = "".join(ch for ch in x if unicodedata.category(ch)[0]!="C") a = parse_args(x) a.scenario_id = a.scenario_id.replace("_", " ") a.location = a.location.replace("_", " ") logger.info("Processing %s", a.location) p = Parameters( current_hospitalized=a.current_hospitalized, doubling_time=a.doubling_time_low, infectious_days=a.infectious_days, market_share=a.market_share, n_days=a.n_days, relative_contact_rate=a.relative_contact_rate, population=a.population, hospitalized=Disposition(a.hospitalized_days, a.hospitalized_rate), icu=Disposition(a.icu_days, a.icu_rate), ventilated=Disposition(a.ventilated_days, a.ventilated_rate), mitigation_date=a.mitigation_date, current_date = a.current_date, recovered=0, # this will need to be fixed when CHIME catches up ) if a.mitigation_model is not None and os.path.exists(cenv.sd_model_dir + a.mitigation_model): # Test for the mitigation model, assumes a single row for each # scenario, date, social distancing combination with a date format of YYYY-MM-DD. # If there is a third column, the value is stored for pdf output # additional notes on each row are ignored. # # lines that don't have a date or a valid float (0 <= x <= 1.0) are ignored # with open(cenv.sd_model_dir + a.mitigation_model) as csv_file: p.mitigation_model = [] csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: if len(row) > 1: try : if row[0] in ('*', a.scenario_id): year,month,day = row[1].split('-') d = date(int(year),int(month),int(day)) sd = float( row[2] ) note = "" if len(row)>3: note = row[3] if sd >= 0 and sd <= 1.0 : p.mitigation_model.append([ d, sd, note ]) except ValueError : continue if len(p.mitigation_model) > 0 : p.mitigation_model = sort_tuples(p.mitigation_model) m_start_date = p.mitigation_model.pop(0) else : p.mitigation_model = None # if there are no valid records, don't try the rest... fndata = cenv.output_dir + "/chime-projection-" + a.scenario_id + ".csv" fncdata = cenv.output_dir + "/chime-computed-data-" + a.scenario_id + ".csv" fnhead = cenv.output_dir + "/chime-parameters-" + a.scenario_id + ".csv" fnmiti = cenv.output_dir + "/chime-mitigations-" + a.scenario_id + ".csv" fnmiti_data = cenv.output_dir + "/chime-mitigations-" + a.scenario_id + ".csv" doubling_rates = [ [a.doubling_time_low, "dt-low"], [a.doubling_time_high, "dt-high"], [a.doubling_time_observed, "dt-observed"]] #, [ None, "dt-computed"]] contact_rates = [ [a.relative_contact_rate, "sd-norm"], [a.relative_contact_rate_0, "sd-0"], [a.relative_contact_rate_1, "sd-1"] ] m = [] mit = [] mitis = DataFrame() mf = None for d in ( doubling_rates ): mr = [] for r in ( contact_rates ) : p.relative_contact_rate = r[0] p.doubling_time = d[0] p.date_first_hospitalized = None p.current_date = a.current_date p.n_days=a.n_days if p.doubling_time is None and p.date_first_hospitalized is None: p.doubling_time = doubling_rates[2][0] # dumpProperties(p, "Parameters for {}".format(a.scenario_id)) ds = Model (p) suffix = ' ' + d[1] + ' ' + r[1] ds.dispositions_df.rename( columns = { 'ever_hospitalized':'disp-hosp' + suffix, 'ever_icu':'disp-icu' + suffix, 'ever_ventilated':'disp-vent' + suffix }, inplace = True) ds.census_df.rename( columns = { 'census_hospitalized':'census-hosp' + suffix, 'census_icu':'census-icu' + suffix, 'census_ventilated':'census-vent' + suffix }, inplace = True) ds.admits_df.rename( columns = { 'admits_hospitalized':'new-hosp' + suffix, 'admits_icu':'new-icu' + suffix, 'admits_ventilated':'new-vent' + suffix }, inplace = True) ds.raw_df = ds.raw_df[[ "day", "susceptible", "infected", "recovered" ]] ds.raw_df.rename( columns = { 'susceptible':'susceptible' + suffix, 'infected':'infected' + suffix, 'recovered':'recovered' + suffix }, inplace = True) mr.append( ds ) m.append(mr) if p.mitigation_model is not None: p.relative_contact_rate = a.relative_contact_rate p.doubling_time = d[0] p.date_first_hospitalized = None p.n_days=365 p.current_date = m_start_date[0] if p.doubling_time is None and p.date_first_hospitalized is None: p.doubling_time = doubling_rates[2][0] ds = InflectedModel (p) suffix = ' ' + d[1] + ' sd-inflected' ds.dispositions_df.rename( columns = { 'ever_hospitalized':'disp-hosp' + suffix, 'ever_icu':'disp-icu' + suffix, 'ever_ventilated':'disp-vent' + suffix }, inplace = True) ds.census_df.rename( columns = { 'census_hospitalized':'census-hosp' + suffix, 'census_icu':'census-icu' + suffix, 'census_ventilated':'census-vent' + suffix }, inplace = True) ds.admits_df.rename( columns = { 'admits_hospitalized':'new-hosp' + suffix, 'admits_icu':'new-icu' + suffix, 'admits_ventilated':'new-vent' + suffix }, inplace = True) ds.raw_df = ds.raw_df[[ "day", "susceptible", "infected", "recovered" ]] ds.raw_df.rename( columns = { 'susceptible':'susceptible' + suffix, 'infected':'infected' + suffix, 'recovered':'recovered' + suffix }, inplace = True) # ds.dispositions_df["Doubling Model"] = d[1] # ds.census_df["Doubling Model"] = d[1] # ds.admits_df["Doubling Model"] = d[1] # ds.raw_df["Doubling Model"] = d[1] mit.append( ds ) for idx, miti in enumerate(p.mitigation_model) : row = { 'scenario_id' : [a.scenario_id], 'init-model' : [d[1]], 'mitigation_date' : [miti[0]], 'sd' : [miti[1]], 'r_t' : ds.r_t[idx], 'doubling_time_t' : ds.doubling_time_t[idx], 'daily_growth_rate_t' : ds.daily_growth_rate_t[idx], 'notes' : [miti[2]], } mf = DataFrame(row) if a.create_csv == 1: mf.to_csv( fnmiti, index=False ) compress_file( archive_name, fnmiti ) mitis = pd.concat([mitis, mf]) mitis.reset_index(drop=True, inplace=True) mitigations = pd.concat([mitigations, mf]) mitigations.reset_index(drop=True, inplace=True) # # assemble and merge datasets
x.lower()] if len(idx_list2) > 1: # There should only be one field print('The program is confused because there is more than one field name that could \ contain the year. Please check on this.') sys.exit() if count > 0: if int(information_stripped[idx_list[0]]) >= 10: year_month = str(int(information_stripped[idx_list2[0]]))+'-'+str(int(information_stripped[idx_list[0]])) else: year_month = str(int(information_stripped[idx_list2[0]]))+'-0'+str(int(information_stripped[idx_list[0]])) if year_month not in yearList: yearList.append(year_month) count+=1 date_dictionary[station_name[:-4]] =yearList with open('daily_lookup_file_TEMP.json', 'w') as fp: json.dump(date_dictionary, fp) def get_daily_lat_lon(file_path): '''Get the latitude and longitude of the daily stations and store in a json file in the directory Parameters ---------- file_path : string file path to the daily csv files provided by Environment & Climate Change Canada, including the name of the file ''' latlon_dictionary = {} #for station_name in lat_lon_list: #This is the list of available stations on that day for station_name in os.listdir(file_path): latlon_list = [] with open(file_path+station_name, encoding='latin1') as latlon_information: count=0 for row in latlon_information: information = row.rstrip('\n').split(',') information_stripped = [i.replace('"','') for i in information] if count==0: header= information_stripped #We will look for latitude and longitude keywords in the header and find the index keyword = 'lon' idx_list = [i for i, x in enumerate(header) if keyword in x.lower()] keyword2 = 'lat' idx_list2 = [i for i, x in enumerate(header) if keyword2 in x.lower()] if len(idx_list) > 1: # There should only be one field print('The program is confused because there is more than one field name that could \ contain the longitude. Please check on this.') sys.exit() if len(idx_list2) > 1: # There should only be one field print('The program is confused because there is more than one field name that could \ contain the latitude. Please check on this.') sys.exit() if count == 1: if float(information_stripped[idx_list2[0]]) != 0 or float(information_stripped[idx_list[0]]) != 0: #sometimes lat and lon is 0, need to exclude latlon_list.append((information_stripped[idx_list2[0]],information_stripped[idx_list[0]])) break else: pass count+=1 if len(set(latlon_list)) > 1: print('For %s there is more than one location in the list! You can only have one record per station so please check the data.'%(station_name)) elif len(set(latlon_list)) == 0: print('A valid lat lon for that station was not found in the file.') else: try: latlon_dictionary[station_name[:-4]]=latlon_list[0] except: print('There is a problem with the files for %s and the location has not been recorded. Please check.'%(station_name)) with open('daily_lat_lon_TEMP.json', 'w') as fp: json.dump(latlon_dictionary, fp) def get_pcp(input_date,file_path,date_dictionary): '''Get a dictionary of the precipitation data from the feather files of the daily stations Parameters ---------- input_date : string input date for the date of interest, in the format: YYYY-MM-DD HH:MM file_path : string path to the feather files containing the hourly data from Environment & Climate Change Canada date_dictionary : dictionary lookup file that has what day/month pairs each station is active on to speed up processing, loaded from the .json file Returns ---------- dictionary - dictionary containing rain amount for each station ''' rain_dictionary = {} yearMonth = input_date[0:7] for station_name in os.listdir(file_path): yearsMonths = date_dictionary[station_name[:-8]] #-8 bc we are now working with feather files if yearMonth in yearsMonths: file = file_path+station_name df = feather.read_dataframe(file) try: if pd.notnull(df.loc[df['date'] == input_date, 'total_precip'].item()): rain_dictionary[station_name[:-8]] = df.loc[df['date'] == input_date, 'total_precip'].item() if float(df.loc[df['date'] == input_date, 'total_precip'].item()) > 264: print('The amount of 24hr precipitation for %s exceeds the record recorded in Ontario or Québec'%(station_name)) else: pass except ValueError: pass #trace precip return rain_dictionary def get_lat_lon(file_path): '''Get the latitude and longitude of the hourly stations and write to hard drive as a json file Parameters ---------- file_path : string file path to the hourly csv files provided by Environment & Climate Change Canada, including the name of the file ''' latlon_dictionary = {} for station_name in os.listdir(file_path): latlon_list = [] files = os.listdir(file_path+station_name+'/')[0] with open(file_path+station_name+'/'+files, encoding='latin1') as latlon_information: print(station_name) count=0 for row in latlon_information: information = row.rstrip('\n').split(',') information_stripped = [i.replace('"','') for i in information] if count==0: header= information_stripped #We will look for latitude and longitude keywords in the header and find the index keyword = 'longitude' idx_list = [i for i, x in enumerate(header) if keyword in x.lower()] keyword2 = 'latitude' idx_list2 = [i for i, x in enumerate(header) if keyword2 in x.lower()] if len(idx_list) > 1: # There should only be one field print('The program is confused because there is more than one field name that could \ contain the longitude. Please check on this.') sys.exit() if len(idx_list2) > 1: # There should only be one field print('The program is confused because there is more than one field name that could \ contain the latitude. Please check on this.') sys.exit() if count == 1: latlon_list.append((information_stripped[idx_list2[0]],information_stripped[idx_list[0]])) break count+=1 if len(set(latlon_list)) > 1: print('For %s there is more than one location in the list! You can only have one record per station so please check the data.'%(station_name)) else: try: latlon_dictionary[station_name]=latlon_list[0] except: print('There is a problem with the files for %s and the location has not been recorded. Please check.'%(station_name)) with open('hourly_lat_lon_TEMP.json', 'w') as fp: json.dump(latlon_dictionary, fp) def convert_to_feather(file_path,out_path): '''Convert the Environment & Climate Change Canada csv files into feather files, to allow for faster processing Parameters ---------- file_path : string file path to the csv files provided by Environment & Climate Change Canada, not including the name of the file out_path : string where you want the new feather file to be written to in the computer, not including the new file name ''' for station_name in os.listdir(file_path): file = file_path+station_name df = pd.read_csv(file, sep=',', engine='c', low_memory=False,encoding='latin1') feather.write_dataframe(df,out_path+station_name[:-4]+'.feather') def get_intersect_boolean_array(ecozone_shapefile,shapefile,show,expand_area): '''Obtain a boolean array of where the ecozone is 0 = pixel NOT in ecozone, otherwise 1 Parameters ---------- ecozone_shapefile : string path to ecozone shapefile, including name shapefile : string path to shapefile show : bool show a map if you want to check it has rasterized the shapefile correctly expand_area : bool whether to expand study area by 200km Returns ---------- ndarray - array 1/0 if pixel was inside ecozone ''' study_map = gpd.read_file(shapefile) eco_map = gpd.read_file(ecozone_shapefile) #First, study area bounds = study_map.bounds #Get the bounding box of the shapefile if expand_area: xmax = bounds['maxx']+200000 xmin= bounds['minx']-200000 ymax = bounds['maxy']+200000 ymin = bounds['miny']-200000 else: xmax = bounds['maxx'] xmin= bounds['minx'] ymax = bounds['maxy'] ymin = bounds['miny'] pixelHeight = 10000 #We want a 10 by 10 pixel, or as close as we can get pixelWidth = 10000 num_col = int((xmax - xmin) / pixelHeight) #Calculate the number of rows cols to fill the bounding box at that resolution num_row = int((ymax - ymin) / pixelWidth) Yi = np.linspace(float(ymin),float(ymax),num_row+1) #Get the value for lat lon in each cell we just made Xi = np.linspace(float(xmin),float(xmax),num_col+1) #+1 otherwise we get banding on the image Xi,Yi = np.meshgrid(Xi,Yi) concat = np.array((Xi.flatten(), Yi.flatten())).T #Because we are not using the lookup file, send in X,Y order send_to_list = concat.tolist() #List of points inside the study area using the generated grid meshPoints = [Point(item) for item in send_to_list] study_df = pd.DataFrame(meshPoints) #our point dataframe study_gdf = gpd.GeoDataFrame(study_df, geometry=meshPoints) #Second, ecozone get points in the list we made that are inside the geodataframe pointList = [] for location in meshPoints: if (eco_map.geometry.contains(location)).any(): #if contained in any polygon in multipolygon pointList.append(location) #Make a grid of zeros in the right shape bool_initiate = np.zeros((num_row+1,num_col+1)) #Make consistent #Fill in the ones in the correct places for loc in pointList: pair = list(loc.coords) coord_pair = (pair[0][0],pair[0][1],)#lat,lon x_orig = int((coord_pair[0] - float(xmin))/pixelHeight) #lon y_orig = int((coord_pair[1] - float(ymin))/pixelWidth) #lat bool_initiate[y_orig][x_orig] = 1 #Plot to make sure everything is ok if new study area and you want to be sure if show: fig, ax = plt.subplots(figsize= (15,15)) crs = {'init':
self.__interface = t if hasattr(self, '_set'): self._set() def _unset_interface(self): self.__interface = YANGDynClass(base=YANGListType("name",yc_interface_nst__nst_netslice_subnet_instantiation_parameters_vnf_vdu_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='list', is_config=True) id = __builtin__.property(_get_id, _set_id) volume = __builtin__.property(_get_volume, _set_volume) interface = __builtin__.property(_get_interface, _set_interface) _pyangbind_elements = OrderedDict([('id', id), ('volume', volume), ('interface', interface), ]) class yc_dns_server_nst__nst_netslice_subnet_instantiation_parameters_vnf_internal_vld_ip_profile_dns_server(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module nst - based on the path /nst/netslice-subnet/instantiation-parameters/vnf/internal-vld/ip-profile/dns-server. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_path_helper', '_extmethods', '__address',) _yang_name = 'dns-server' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'nst', u'netslice-subnet', u'instantiation-parameters', u'vnf', u'internal-vld', u'ip-profile', u'dns-server'] def _get_address(self): """ Getter method for address, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dns_server/address (inet:ip-address) """ return self.__address def _set_address(self, v, load=False): """ Setter method for address, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dns_server/address (inet:ip-address) If this variable is read-only (config: false) in the source YANG file, then _set_address is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_address() directly. """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """address must be of a type compatible with inet:ip-address""", 'defined-type': "inet:ip-address", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True)""", }) self.__address = t if hasattr(self, '_set'): self._set() def _unset_address(self): self.__address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) address = __builtin__.property(_get_address, _set_address) _pyangbind_elements = OrderedDict([('address', address), ]) class yc_dhcp_params_nst__nst_netslice_subnet_instantiation_parameters_vnf_internal_vld_ip_profile_dhcp_params(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module nst - based on the path /nst/netslice-subnet/instantiation-parameters/vnf/internal-vld/ip-profile/dhcp-params. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_path_helper', '_extmethods', '__enabled','__count','__start_address',) _yang_name = 'dhcp-params' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__count = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="count", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='uint8', is_config=True) self.__start_address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="start-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) self.__enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='boolean', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'nst', u'netslice-subnet', u'instantiation-parameters', u'vnf', u'internal-vld', u'ip-profile', u'dhcp-params'] def _get_enabled(self): """ Getter method for enabled, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/enabled (boolean) """ return self.__enabled def _set_enabled(self, v, load=False): """ Setter method for enabled, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/enabled (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_enabled is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enabled() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """enabled must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='boolean', is_config=True)""", }) self.__enabled = t if hasattr(self, '_set'): self._set() def _unset_enabled(self): self.__enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='boolean', is_config=True) def _get_count(self): """ Getter method for count, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/count (uint8) """ return self.__count def _set_count(self, v, load=False): """ Setter method for count, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/count (uint8) If this variable is read-only (config: false) in the source YANG file, then _set_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_count() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="count", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='uint8', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """count must be of a type compatible with uint8""", 'defined-type': "uint8", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="count", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='uint8', is_config=True)""", }) self.__count = t if hasattr(self, '_set'): self._set() def _unset_count(self): self.__count = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="count", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='uint8', is_config=True) def _get_start_address(self): """ Getter method for start_address, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/start_address (inet:ip-address) """ return self.__start_address def _set_start_address(self, v, load=False): """ Setter method for start_address, mapped from YANG variable /nst/netslice_subnet/instantiation_parameters/vnf/internal_vld/ip_profile/dhcp_params/start_address (inet:ip-address) If this variable is read-only (config: false) in the source YANG file, then _set_start_address is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_start_address() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="start-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """start_address must be of a type compatible with inet:ip-address""", 'defined-type': "inet:ip-address", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="start-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True)""", }) self.__start_address = t if hasattr(self, '_set'): self._set() def _unset_start_address(self): self.__start_address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="start-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) enabled = __builtin__.property(_get_enabled, _set_enabled) count = __builtin__.property(_get_count, _set_count) start_address = __builtin__.property(_get_start_address, _set_start_address) _pyangbind_elements = OrderedDict([('enabled', enabled), ('count', count), ('start_address', start_address), ]) class yc_ip_profile_nst__nst_netslice_subnet_instantiation_parameters_vnf_internal_vld_ip_profile(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module nst - based on the path /nst/netslice-subnet/instantiation-parameters/vnf/internal-vld/ip-profile. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_path_helper', '_extmethods', '__ip_version','__subnet_address','__gateway_address','__dns_server','__dhcp_params',) _yang_name = 'ip-profile' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__ip_version = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={u'unknown': {u'value': 0}, u'ipv4': {u'value': 1}, u'ipv6': {u'value': 2}},), is_leaf=True, yang_name="ip-version", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-version', is_config=True) self.__gateway_address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'}),], is_leaf=True, yang_name="gateway-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-address', is_config=True) self.__dns_server = YANGDynClass(base=YANGListType("address",yc_dns_server_nst__nst_netslice_subnet_instantiation_parameters_vnf_internal_vld_ip_profile_dns_server, yang_name="dns-server", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='address', extensions=None), is_container='list', yang_name="dns-server", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='list', is_config=True) self.__subnet_address = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}),RestrictedClassType(base_type=six.text_type, restriction_dict={u'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'}),], is_leaf=True, yang_name="subnet-address", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='inet:ip-prefix', is_config=True) self.__dhcp_params = YANGDynClass(base=yc_dhcp_params_nst__nst_netslice_subnet_instantiation_parameters_vnf_internal_vld_ip_profile_dhcp_params, is_container='container', yang_name="dhcp-params", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:etsi:osm:yang:nst', defining_module='nst', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod =
<gh_stars>1-10 # Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container CONTAINER = "filipfilmar/ebook-buildenv:1.1" # Use this for quick local runs. #CONTAINER = "ebook-buildenv:local" EbookInfo = provider(fields=["figures", "markdowns"]) # Returns the docker_run script invocation command based on the # script path and its reference directory. # # Params: # script_path: (string) The full path to the script to invoke # dir_reference: (string) The path to a file used for figuring out # the reference directories (build root and repo root). def _script_cmd(script_path, dir_reference): return """\ {script} \ --container={container} \ --dir-reference={dir_reference}""".format( script=script_path, container=CONTAINER, dir_reference=dir_reference, ) def _drawtiming_png_impl(ctx): cmd = "drawtiming" docker_run = ctx.executable._script figures = [] for target in ctx.attr.srcs: for src in target.files.to_list(): in_file = src out_file = ctx.actions.declare_file(in_file.basename + ".png") figures += [out_file] script_cmd = _script_cmd(docker_run.path, in_file.path) ctx.actions.run_shell( progress_message = "timing diagram to PNG with {1}: {0}".format(in_file.short_path, cmd), inputs = [in_file], outputs = [out_file], tools = [docker_run], command = """\ {script} \ {cmd} --output "{out_file}" "{in_file}" """.format( cmd=cmd, out_file=out_file.path, in_file=in_file.path, script=script_cmd), ) deps = [] for target in ctx.attr.deps: ebook_provider = target[EbookInfo] if not ebook_provider: continue deps += ebook_provider.figures runfiles = ctx.runfiles(files = figures) return [ EbookInfo(figures=figures+deps, markdowns=[]), DefaultInfo(files=depset(figures+deps), runfiles=runfiles), ] drawtiming_png = rule(implementation = _drawtiming_png_impl, attrs = { "srcs": attr.label_list( allow_files = [".t"], doc = "The file to compile", ), "deps": attr.label_list( doc = "The dependencies, any targets should be allowed", ), "output": attr.output(doc="The generated file"), "_script": attr.label( default="//build:docker_run", executable=True, cfg="host"), }, doc = "Transform a timing diagram file into png using drawtiming", ) def _generalized_graphviz_rule_impl(ctx, cmd): docker_run = ctx.executable._script figures = [] for target in ctx.attr.srcs: for src in target.files.to_list(): in_file = src out_file = ctx.actions.declare_file(in_file.basename + ".png") figures += [out_file] script_cmd = _script_cmd(docker_run.path, in_file.path) ctx.actions.run_shell( progress_message = "graphviz to PNG with {1}: {0}".format(in_file.short_path, cmd), inputs = [in_file], outputs = [out_file], tools = [docker_run], command = """\ {script} \ {cmd} -Tpng -o "{out_file}" "{in_file}" """.format( cmd=cmd, out_file=out_file.path, in_file=in_file.path, script=script_cmd), ) deps = [] for target in ctx.attr.deps: ebook_provider = target[EbookInfo] if not ebook_provider: continue deps += ebook_provider.figures runfiles = ctx.runfiles(files = figures) return [ EbookInfo(figures=figures+deps, markdowns=[]), DefaultInfo(files=depset(figures+deps), runfiles=runfiles), ] def _neato_png_impl(ctx): return _generalized_graphviz_rule_impl(ctx, "neato") neato_png = rule(implementation = _neato_png_impl, attrs = { "srcs": attr.label_list( allow_files = [".dot"], doc = "The file to compile", ), "deps": attr.label_list( doc = "The dependencies, any targets should be allowed", ), "output": attr.output(doc="The generated file"), "_script": attr.label( default="//build:docker_run", executable=True, cfg="host"), }, doc = "Transform a graphviz dot file into png using neato", ) def _dot_png_impl(ctx): return _generalized_graphviz_rule_impl(ctx, "dot") dot_png = rule(implementation = _dot_png_impl, attrs = { "srcs": attr.label_list( allow_files = [".dot"], doc = "The file to compile", ), "deps": attr.label_list( doc = "The dependencies, any targets should be allowed", ), "output": attr.output(doc="The generated file"), "_script": attr.label( default="//build:docker_run", executable=True, cfg="host"), }, doc = "Transform a graphviz dot file into png using dot", ) def _asymptote_impl(ctx): asycc = ctx.executable._script figures = [] for target in ctx.attr.srcs: for src in target.files.to_list(): in_file = src out_file = ctx.actions.declare_file(in_file.basename + ".png") figures += [out_file] script_cmd = _script_cmd(asycc.path, in_file.path) ctx.actions.run_shell( progress_message = "ASY to PNG: {0}".format(in_file.short_path), inputs = [in_file], outputs = [out_file], tools = [asycc], command = """\ {script} \ asy -render 5 -f png -o "{out_file}" "{in_file}" """.format( out_file=out_file.path, in_file=in_file.path, script=script_cmd), ) deps = [] for target in ctx.attr.deps: ebook_provider = target[EbookInfo] if not ebook_provider: continue deps += ebook_provider.figures runfiles = ctx.runfiles(files=figures+deps) for dep in ctx.attr.deps: runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles) return [ EbookInfo(figures=figures+deps, markdowns=[]), DefaultInfo(files=depset(figures+deps), runfiles=runfiles), ] asymptote = rule(implementation = _asymptote_impl, attrs = { "srcs": attr.label_list( allow_files = [".asy"], doc = "The file to compile", ), "deps": attr.label_list( doc = "The dependencies, any targets should be allowed", ), "output": attr.output(doc="The generated file"), "_script": attr.label( default="//build:docker_run", executable=True, cfg="host"), }, doc = "Transform an asymptote file into png", ) def _copy_file_to_workdir_renamed(ctx, src): src_copy = ctx.actions.declare_file("{}_{}".format(ctx.label.name, src.short_path)) ctx.actions.run_shell( progress_message = "Copying {} to {}".format(src.short_path, src_copy.short_path), outputs = [src_copy], inputs = [src], command="cp {} {}".format(src.path, src_copy.path), ) return src_copy def _copy_file_to_workdir(ctx, src): src_copy = ctx.actions.declare_file(src.basename) ctx.actions.run_shell( progress_message = "Copying {}".format(src.short_path), outputs = [src_copy], inputs = [src], command="cp {} {}".format(src.path, src_copy.path), ) return src_copy def _markdown_lib_impl(ctx): markdowns = [] for target in ctx.attr.srcs: for src in target.files.to_list(): markdowns += [_copy_file_to_workdir(ctx, src)] figures = [] for target in ctx.attr.deps: provider = target[EbookInfo] figures += (provider.figures or []) markdowns += (provider.markdowns or []) runfiles = ctx.runfiles(files=figures+markdowns) for dep in ctx.attr.deps: runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles) return [ EbookInfo(figures=figures, markdowns=markdowns), DefaultInfo( files=depset(figures+markdowns), runfiles=runfiles, ), ] markdown_lib = rule( implementation = _markdown_lib_impl, doc = "Declares a set of markdown files", attrs = { "srcs": attr.label_list( allow_files = [".md"], doc = "The markdown source files", ), "deps": attr.label_list( doc = "The file to compile", providers = [EbookInfo], ), }, ) def _ebook_epub_impl(ctx): name = ctx.label.name # This is duplicated in _ebook_pdf_impl. # steps # run htex on all *md, gives book.htex markdowns = [] figures = [] for dep in ctx.attr.deps: provider = dep[EbookInfo] markdowns += provider.markdowns figures += provider.figures dir_reference = markdowns[0] htex_file = ctx.actions.declare_file("{}.htex".format(name)) markdowns_paths = [file.path for file in markdowns] markdowns_paths_stripped = _strip_reference_dir_from_files(dir_reference, markdowns) script = ctx.executable._script script_cmd = _script_cmd(script.path, markdowns_paths[0]) ctx.actions.run_shell( progress_message = "Building equation environments for: {}".format(name), inputs = markdowns, outputs = [htex_file], tools = [script], command = """\ {script} \ pandoc -s --gladtex -o {target} {sources} \ """.format( script=script_cmd, target=htex_file.path, sources=" ".join(markdowns_paths)) ) # run gladtex on the resulting htex to obtain html and output directory with figures. outdir = ctx.actions.declare_directory("{}.eqn".format(name)) html_file = ctx.actions.declare_file("{}.html".format(name)) ctx.actions.run_shell( progress_message = "Extracting equations for: {}".format(name), inputs = [htex_file], outputs = [outdir, html_file], tools = [script], command = """\ {script} --cd-to-dir-reference \ gladtex -r 200 -d {outdir} {htex_file} \ """.format( script=script_cmd, outdir=_strip_reference_dir(dir_reference, outdir.path), htex_file=_strip_reference_dir(dir_reference, htex_file.path), ) ) outdir_tar = ctx.actions.declare_file("{}.tar".format(outdir.basename)) tar_command = "(cd {base} ; tar cf {archive} {dir})".format( base=outdir_tar.dirname, archive=outdir_tar.basename, dir=outdir.basename) ctx.actions.run_shell( progress_message = "Archiving equations: {}".format(outdir_tar.short_path), inputs = [outdir], outputs = [outdir_tar], command = tar_command, ) # run htexepub to obtain book.epub. # This is gonna be fun! epub_metadata = ctx.attr.metadata_xml.files.to_list()[0] epub_metadata = _copy_file_to_workdir_renamed(ctx, epub_metadata) title_yaml = ctx.attr.title_yaml.files.to_list()[0] title_yaml = _copy_file_to_workdir_renamed(ctx, epub_metadata) ebook_epub = ctx.actions.declare_file("{}.epub".format(name)) inputs = [epub_metadata, title_yaml, html_file, outdir, outdir_tar] + markdowns + figures ctx.actions.run_shell( progress_message = "Building EPUB for: {}".format(name), inputs = inputs, tools = [script], outputs = [ebook_epub], command = """\ {script} --cd-to-dir-reference \ pandoc --epub-metadata={epub_metadata} \ -f html -t epub3 -o {ebook_epub} {html_file} \ """.format( script=script_cmd, epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path), ebook_epub=_strip_reference_dir(dir_reference, ebook_epub.path), html_file=_strip_reference_dir(dir_reference, html_file.path), )) runfiles = ctx.runfiles(files=[ebook_epub]) for dep in ctx.attr.deps: runfiles = runfiles.merge(dep[DefaultInfo].data_runfiles) return [ dep[EbookInfo], DefaultInfo( files=depset([ebook_epub, outdir, outdir_tar]), runfiles=runfiles, ) ] ebook_epub = rule( implementation = _ebook_epub_impl, attrs = { "deps": attr.label_list( doc = "All the targets you need to make this book work.", providers = [EbookInfo], ), "title_yaml": attr.label( allow_files = True, doc = "The title.yaml file to use for this book", ), "metadata_xml": attr.label( allow_files = True, doc = "The epub-metadata.xml file to use for this book", ), "_script": attr.label( default="//build:docker_run", executable=True, cfg="host"), }, doc = "Generate an ebook in EPUB format" ) def _strip_reference_dir(reference_dir, path): return path.replace(reference_dir.dirname+"/", "") def _strip_reference_dir_from_files(reference_dir, files): return [ _strip_reference_dir(reference_dir, file.path) for file in files] def _ebook_pdf_impl(ctx): name = ctx.label.name # steps # run htex on all *md, gives book.htex markdowns = [] figures = [] for dep in ctx.attr.deps: provider = dep[EbookInfo] markdowns += provider.markdowns figures += provider.figures dir_reference = markdowns[0] # Fixed up paths -- relative to the directory dir_reference, not the # directory where the build happens! This is needed because we can not control # figure inclusion. markdowns_paths = _strip_reference_dir_from_files(dir_reference, markdowns) script = ctx.executable._script script_cmd = _script_cmd(script.path, dir_reference.path) # run htexepub to obtain book.epub. # This is gonna be fun! epub_metadata = ctx.attr.metadata_xml.files.to_list()[0] epub_metadata = _copy_file_to_workdir(ctx, epub_metadata) title_yaml = ctx.attr.title_yaml.files.to_list()[0] title_yaml = _copy_file_to_workdir(ctx, title_yaml) ebook_pdf = ctx.actions.declare_file("{}.pdf".format(name)) inputs = [epub_metadata, title_yaml] + markdowns + figures ctx.actions.run_shell( progress_message = "Building PDF for: {}".format(name), inputs = inputs, tools = [script], outputs = [ebook_pdf], command = """\ {script} --cd-to-dir-reference \ pandoc --epub-metadata={epub_metadata} \ --mathml -o {ebook_pdf} {markdowns} \ """.format( script=script_cmd, epub_metadata=_strip_reference_dir(dir_reference, epub_metadata.path), ebook_pdf=_strip_reference_dir(dir_reference,
== 2 and ind.shape[0] == 1: # ind = ind[0] return ind def __getitem__(self, i): # determine the size of the new array if not hasattr(i, '__len__'): i = [i] nshp = _ndshape(self.msize, *i) #return _marray(self.dtype, nshp, self._a.__getitem__(reversed(i))) return _marray(self.dtype, nshp, self._a.__getitem__(i[::-1])) # >> a = reshape(1:15,5,3) # >> a(eye(3)==1) # ans = [1, 5, 9] def __getitem1__(self, i): # determine the size of the new array #if not hasattr(i, '__len__'): i = [i] nshp = _ndshape1(self.msize, *i) ri = [] if len(i) == 1: i = i[0] if self.msize[0] == 1: ri = (i.__base0__(self.msize[1]), 0) elif self.msize[1] == 1: ri = (0, i.__base0__(self.msize[0])) else: # access to a flat array msize = _size(i) if isinstance(i, mvar): i = i.__base0__(len(self._a.flat)) na = self._a.flat[i] return _marray(self.dtype, msize, na.reshape(msize[::-1])) else: di = len(self.msize)-1 for x in reversed(i): if isinstance(x, mvar): ri.append(x.__base0__(self.msize[di])) else: ri.append(x-1) di -= 1 na = self._a.__getitem__(tuple(ri)) return _marray(self.dtype, nshp, na.reshape(nshp[::-1])) def __setitem__(self, i, val): if isinstance(val, _marray): val = val._a self._a.__setitem__(i[::-1], val) def __setitem1__(self, i, val): # determine the size of the new array if isinstance(val, _marray): val = val._a ri = [] if len(i) == 1: # stupid numpy a = rand(1,10); b = rand(1,2); a[0,[3,4]] = b # doesn't work i = i[0] if self.msize[0] == 1: ri = (i.__base0__(self.msize[1]), 0) val = val[0] elif self.msize[1] == 1: ri = (0, i.__base0__(self.msize[0])) val = val[0] else: # access to a flat array msize = _size(i) if isinstance(i, mvar): i = i.__base0__(len(self._a.flat)) self._a.flat[i] = val return else: di = len(self.msize)-1 for x in reversed(i): if isinstance(x, mvar): ri.append(x.__base0__(self.msize[di])) else: ri.append(x-1) di -= 1 self._a.__setitem__(tuple(ri), val) # properties def transposed(self): return transpose(self) def ctransposed(self): return ctranspose(self) T = property(transposed, None, None, "Transpose.") cT = property(transposed, None, None, "Conjugate transpose.") # IO def __str__(self): return print_marray(self) def __repr__(self): return "marray(%r, %r)"%(self.dtype, self.msize) class mcellarray(mvar, list): pass # from the end of # http://code.activestate.com/recipes/52558/ class _MEnd(object): '''This object serves as an emulator of the "end" statement of MATLAB. We want to use the "is" operator therefore we need a singletion.''' __instance = None # the unique instance def __new__(cls): if cls.__instance is None: cls.__instance = object.__new__(cls) object.__init__(cls.__instance) return cls.__instance def __init__(self): # prevent the automatic call of object's __init__, it is init-ed once # in the __new__ function pass def __repr__(self): return 'end' def __str__(self): return '(m-end object)' def __int__(self): return sys.maxint end = _MEnd() def _mslicelen(start, stop, step): if stop is end or stop is None: return sys.maxint return int(np.floor(stop-start)/step + 1) class _mslice(mvar): """m-slice MATLAB style slice object. You can instantiate this class only by the helper mslice: >>> mslice[1:10] """ def __init__(self, start, stop=None, step=None): raise NotImplementedError("Direct instantiation is not allowed.") def init(self, start, stop, step): if start is None: start = 1 if step is None: step = 1 self.start = start self.stop = stop self.step = step self.dtype = 'double' self.msize = (1, _mslicelen(self.start, self.stop, self.step)) def init_data(self): if self._a is None: self._a = np.array(list(self), dtype='f8').reshape(self.msize[::-1]) def evaluate_end(self, i): start = self.start step = self.step stop = self.stop if stop is end: return mslice[start:step:i] else: return self def _ctypes_get(self): # Create and initialize a real data buffer, then let the default # function to return the ctypes pointer if self.stop is end: raise RuntimeError("Infinite slice can be only used as an index.") # return None self.init_data() return self._a.ctypes ctypes = property(_ctypes_get, None, None, "Ctypes-wrapped data object.") def __iter__(self): value = self.start if self.step < 0: while value >= self.stop: yield float(value) value += self.step else: while value <= self.stop: yield float(value) value += self.step def __getitem__(self, i): val = self.start + self.step*i if val > self.stop: raise OMPCException('Index exceeds matrix dimensions!') return float(val) # self.init_data() # na = self._a.__getitem__(i) # return _marray('double', na.shape[::-1], na.reshape(na.shape[::-1])) def __getitem1__(self, i): val = self.start + self.step*(i-1) if val > self.stop: raise OMPCException('Index exceeds matrix dimensions!') return float(val) # self.init_data() # return _marray('double', self.msize, self._a).__getitem1__(i) def __len__(self): if self.stop is end: # FIXME: how should this be done # raise AssertionError("This is impossible for a code translated " # "from a functional MATLAB code.") # Python allows returning of positive integers only! return sys.maxint return _mslicelen(self.start, self.stop, self.step) def __repr__(self): return 'mslice[%r:%r:%r]'%\ (self.start, self.step, self.stop) def __str__(self): if self.stop is None: it = iter(self) return ', '.join( str(it.next()) for i in xrange(3) ) + ' ...' elif len(self) > 10: it = iter(self) retval = self.__repr__() + '\n' retval += ', '.join( str(it.next()) for i in xrange(3) ) + ' ... ' lastval = self.start + (len(self)-1)*self.step return retval + str(lastval) return ', '.join( map(str, self) ) def hasnoend(self): 'Returns true if "self.stop is end".' return self.stop is end def __copy__(self): self.init_data() return _marray(self.dtype, self.msize, self._a.copy()) def __deepcopy__(self): self.init_data() return _marray(self.dtype, self.msize, self._a.copy()) def __base0__(self,shp=None): if self.hasnoend(): assert shp is not None return slice(self.start-1, shp, self.step) return slice(self.start-1, self.stop, self.step) class _mslice_helper: def __getitem__(self, i): s = _mslice.__new__(_mslice) # FIXME: there is no way of differentiating between mslice[:] # and mslice[0:], the second will never appear in a code written for # MATLAB. # !!! actually, maybe possible by look-back in the stack ?!! start, stop, step = i.start, end, 1 if i.step is None: # there are only 2 arguments, stop is i.stop if i.start == 0 and i.stop == sys.maxint: # a special case start = 1 elif i.stop == sys.maxint: # this is what happens when syntax [start:] is used raise IndexError( 'Use 2- and 3-slices only. Use "end" instead of "None".') else: stop = i.stop else: # there are all 3 arguments, stop is actually i.step # 1:2:10 -> slice(1,2,10) -> mslice(1,10,2) stop = i.step step = i.stop s.init(start, stop, step) return s class _mslice_helper: def __getitem__(self, i): s = _mslice.__new__(_mslice) # FIXME: there is no way of differentiating between mslice[:] # and mslice[0:], the second will never appear in a code written for # MATLAB. # !!! actually, maybe possible by look-back in the stack ?!! start, stop, step = i.start, end, 1 if i.step is None: # there are only 2 arguments, stop is i.stop if i.start == 0 and i.stop == sys.maxint: # a special case start = 1 elif i.stop == sys.maxint: # this is what happens when syntax [start:] is used raise IndexError( 'Use 2- and 3-slices only. Use "end" instead of "None".') else: stop = i.stop # there are all 3 arguments, stop is actually i.step elif i.stop < 0: stop = i.step step = i.stop else: # 1:2:10 -> slice(1,2,10) -> mslice(1,10,2) stop = i.step step = i.stop s.init(start, stop, step) if not s.hasnoend(): s.init_data() return _marray('double', s.msize, s._a.copy()) return s mslice = _mslice_helper() class mstring(mvar, str): def __init__(self, s): mvar.__init__(self) self.dtype = 'char' self.msize = (1, len(s)) self._a = s def __len__(self): return len(self._a) def __str__(self): return self._a def __repr__(self): return 'mstring(%r)'%self._a def _m_constructor_args(*X): from operator import isSequenceType dtype = 'double' if type(X[-1]) is str: dtype = X[-1] X = X[:-1] if len(X) == 1:# and isSequenceType(X): X = X[0] #X = X[0], X[0] return X, dtype @_ompc_base def empty(*X): # check for class X, dt = _m_constructor_args(*X) return _marray.empty(X, dt) @_ompc_base def zeros(*X): # check for class X, dt = _m_constructor_args(*X) return _marray.zeros(X, dt) @_ompc_base def ones(*X): # check for class X, dt = _m_constructor_args(*X) return _marray.ones(X, dt) @_ompc_base def eye(*X): if len(X) == 0: return _marray.ones((1,1), 'double') # check for class X, dt = _m_constructor_args(*X) kw = dict(dtype=_dtype2numpy[dt]) if not hasattr(X, '__len__'): X = (X,) na = np.eye(*X[::-1], **kw) return _marray(dt, na.shape[::-1], na) @_ompc_base def mcat(i): """Concatenate a list of matrices into a single matrix using separators ',' and ';'. The ',' means horizontal concatenation and the ';' means vertical concatenation. """ if i is None: return marray() # calculate the shape rows = [[]] final_rows = 0 final_cols = 0 crows
= #264653 [spacer] height = 2 [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_CTCF_ENCFF761RHS.bigWig # height of the track in cm (optional value) height = 2 title = HFF-CTCF summary_method = mean file_type = bigwig [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_DNase_ENCFF113YFF.bigWig # height of the track in cm (optional value) height = 2 title = HFF-DNase summary_method = mean file_type = bigwig color = #2A6D8F [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K4me3_ENCFF442WNT.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K4me3 summary_method = mean file_type = bigwig color = #E76F51 [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K27ac_ENCFF078JZB.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K27ac summary_method = mean file_type = bigwig color = #F4A261 [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K4me1_ENCFF449DEA.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K4me1 summary_method = mean file_type = bigwig color = #F4A261 [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K36me3_ENCFF954UKB.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K36me3 summary_method = mean file_type = bigwig color = #E9C46A [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K27me3_ENCFF027GWJ.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K27me3 summary_method = mean file_type = bigwig color = #264653 [bigwig file test] file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K9me3_ENCFF946TXL.bigWig # height of the track in cm (optional value) height = 2 title = HFF-H3K9me3 summary_method = mean file_type = bigwig color = #264653 """.format( ORCA_PATH=ORCA_PATH ) if show_tracks else "" ) ) filename = str(uuid.uuid4()) with open(f"/dev/shm/{filename}.ini", "w") as fh: fh.write(browser_tracks) gbfigs = [] for ii, label in enumerate(["32Mb", "16Mb", "8Mb", "4Mb", "2Mb", "1Mb"]): regionstr = ( output["chr"] + ":" + str(int(output["start_coords"][ii])) + "-" + str(int(output["end_coords"][ii])) ) args = ( f"--tracks /dev/shm/{filename}.ini --region {regionstr} " "--trackLabelFraction 0.03 --width 40 --dpi 10 " f"--outFileName /dev/shm/{filename}.png --title {label}".split() ) _ = pygenometracks.plotTracks.main(args) gbfigs.append(plt.gcf()) os.remove(f"/dev/shm/{filename}.png") os.remove(f"/dev/shm/{filename}.ini") if file is not None: with PdfPages(file) as pdf: pdf.savefig(fig, dpi=300) plt.show() with PdfPages((".").join(file.split(".")[:-1]) + ".anno.pdf") as pdf: for fig in reversed(gbfigs): pdf.savefig(fig) else: if file is not None: with PdfPages(file) as pdf: pdf.savefig(fig, dpi=300) plt.close("all") def genomeplot_256Mb( output, show_coordinates=True, unscaled=False, file=None, cmap=None, unscaled_cmap=None, colorbar=True, maskpred=True, vmin=-1, vmax=2, model_labels=["H1-ESC", "HFF"] ): """ Plot the multiscale prediction outputs for 256Mb output. Parameters ---------- output : dict The result dictionary to plot as returned by `genomepredict_256Mb`. show_coordinates : bool, optional Default is True. If True, annotate the generated plot with the genome coordinates. unscaled : bool, optional Default is False. If True, plot the predictions and observations without normalizing by distance-based expectation. file : str or None, optional Default is None. The output file prefix. No output file is generated if set to None. cmap : str or None, optional Default is None. The colormap for plotting scaled interactions (log fold over distance-based background). If None, use colormaps.hnh_cmap_ext5. unscaled_cmap : str or None, optional Default is None. The colormap for plotting unscaled interactions (log balanced contact score). If None, use colormaps.hnh_cmap_ext5. colorbar : bool, optional Default is True. Whether to plot the colorbar. maskpred : bool, optional Default is True. If True, the prediction heatmaps are masked at positions where the observed data have missing values when observed data are provided in output dict. vmin : int, optional Default is -1. The lowerbound value for heatmap colormap. vmax : int, optional Default is 2. The upperbound value for heatmap colormap. model_labels : list(str), optional Model labels for plotting. Default is ["H1-ESC", "HFF"]. Returns ------- None """ if cmap is None: cmap = hnh_cmap_ext5 if unscaled_cmap is None: unscaled_cmap = hnh_cmap_ext5 n_axes = len(output["predictions"]) try: assert output["predictions"][0][0].ndim == 2 except: raise ValueError("Plotting predictions with more than two-dimensions are not supported.") if output["experiments"] is not None: n_axes += len(output["predictions"]) fig, all_axes = plt.subplots(figsize=(24, 6 * n_axes), nrows=n_axes, ncols=4) for row_axes in all_axes: for ax in row_axes: ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) for i, xlabel in enumerate(["32Mb", "64Mb", "128Mb", "256Mb"]): all_axes[-1, i].set_xlabel(xlabel, labelpad=20, fontsize=20, weight="black") if output["experiments"] is not None: current_axis = 0 for label in model_labels: for suffix in [" Pred", " Obs"]: all_axes[current_axis, 0].set_ylabel( label + suffix, labelpad=20, fontsize=20, weight="black", rotation="horizontal", ha="right", va="center", ) current_axis += 1 else: current_axis = 0 for label in model_labels: for suffix in [" Pred"]: all_axes[current_axis, 0].set_ylabel( label + suffix, labelpad=20, fontsize=20, weight="black", rotation="horizontal", ha="right", va="center", ) current_axis += 1 def _plot_pred(ii, ax, model_i, key="predictions", maskpred=False): s = int(output["start_coords"][ii]) e = int(output["end_coords"][ii]) padlen = int(output["start_coords"][ii] + 256000000 / 2 ** (ii)) - e if padlen > 0 and output["padding_chr"] is not None: regionstr = ( output["chr"] + ":" + str(s) + "-" + str(e) + "; " + output["padding_chr"] + ":0-" + str(padlen) ) else: regionstr = output["chr"] + ":" + str(s) + "-" + str(e) if show_coordinates: ax.set_title(regionstr, fontsize=14, pad=4) if unscaled: plotmat = output[key][model_i][ii] + np.log(output["normmats"][model_i][ii]) im = ax.imshow( plotmat, interpolation="none", cmap=unscaled_cmap, vmax=np.max(np.diag(plotmat, k=1)), ) else: plotmat = output[key][model_i][ii] im = ax.imshow(plotmat, interpolation="none", cmap=cmap, vmin=vmin, vmax=vmax) if padlen > 0: # draw chr boundary chrlen_ratio = 1 - padlen / (256000000 / 2 ** (ii)) ax.plot( [chrlen_ratio * plotmat.shape[0] - 0.5, chrlen_ratio * plotmat.shape[0] - 0.5], [-0.5, plotmat.shape[0] - 0.5], color="black", linewidth=0.2, zorder=10, ) ax.plot( [-0.5, plotmat.shape[0] - 0.5], [chrlen_ratio * plotmat.shape[0] - 0.5, chrlen_ratio * plotmat.shape[0] - 0.5], color="black", linewidth=0.2, zorder=10, ) if output["annos"]: for r in output["annos"][ii]: if len(r) == 3: _draw_region(ax, r[0], r[1], r[2], plotmat.shape[1]) elif len(r) == 2: _draw_site(ax, r[0], r[1], plotmat.shape[1]) ax.axis([-0.5, plotmat.shape[1] - 0.5, -0.5, plotmat.shape[1] - 0.5]) ax.invert_yaxis() if maskpred: if output["experiments"]: ax.imshow( np.isnan(output["experiments"][0][ii]), interpolation="none", cmap=bwcmap, ) return im current_row = 0 for model_i in range(len(output["predictions"])): for ii, ax in enumerate(reversed(all_axes[current_row])): im = _plot_pred(ii, ax, model_i, key="predictions", maskpred=maskpred) current_row += 1 if output["experiments"]: for ii, ax in enumerate(reversed(all_axes[current_row])): im = _plot_pred(ii, ax, model_i, key="experiments") current_row += 1 if colorbar: fig.colorbar(im, ax=all_axes.ravel().tolist(), fraction=0.02, shrink=0.1, pad=0.005) if file is not None: with PdfPages(file) as pdf: pdf.savefig(fig, dpi=300) plt.close("all") GRange = namedtuple("GRange", ["chr", "start", "end", "strand"]) LGRange = namedtuple("LGRange", ["len", "ref"]) class StructuralChange2(object): """ This class stores and manupulating structural changes for a single chromosome and allow querying the mutated chromosome by coordinates by providing utilities for retrieving the corresponding reference genome segments. The basic operations that StructuralChange2 supports are duplication, deletion, inversion, insertion, and concatenation. StructuralChange2 objects can be concatenated with '+' operator, this operation allows concatenating two chromosomes. '+' can be combined with other basic operations to create fused chromosomes. These operations can be used sequentially to introduce arbitrarily complex structural changes. However, note that the coordinates are dynamically updated after each operation reflecting the current state of the chromosome, thus coordinates specified in later operation must take into account of the effects of all previous operations. Parameters ---------- chr_name : str Name of the reference chromosome. length : int The length of the reference chromosome. Attributes ------- segments : list(LGRange) List of reference genome segments that constitute the (mutated) chromosome. Each element is a LGRange namedtuple (length and a GRange namedtuple (chr: str, start: int, end: int, strand: str)). chr_name : str Name of the chromosome coord_points : list(int) Stores `N+1` key coordinates where `N` is the number of segments. The key coordinates are 0, segment junction positions, and chromosome end coordinate. `coord_points` reflects the current state of the chromosome. """ def __init__(self, chr_name, length): self.segments = [LGRange(length, GRange(chr_name, 0, length, "+"))] self.chr_name = chr_name self.coord_points = [0, length] def _coord_sync(self): self.coord_points = [0] for seg in self.segments: self.coord_points.append(self.coord_points[-1] + seg.len) def _split(self, pos): segind = bisect(self.coord_points, pos) - 1 segstart = self.coord_points[segind] if pos != segstart: # split segment ref_chr, ref_s, ref_e, ref_strand = self.segments[segind].ref if ref_strand == "+": ref_1 = GRange(ref_chr, ref_s, ref_s + pos - segstart, "+") ref_2 = GRange(ref_chr, ref_s
<filename>src/falconpy/real_time_response.py """CrowdStrike Falcon Real Time Response API interface class. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | |: 1 | |::.. . | CROWDSTRIKE FALCON |::.. . | FalconPy `-------' `-------' OAuth2 API - Customer SDK This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <https://unlicense.org> """ # pylint: disable=R0904 # Aligning method count to API service collection operation count from ._util import force_default, process_service_request, handle_single_argument from ._payload import aggregate_payload, command_payload, generic_payload_list from ._service_class import ServiceClass from ._endpoint._real_time_response import _real_time_response_endpoints as Endpoints class RealTimeResponse(ServiceClass): """The only requirement to instantiate an instance of this class is one of the following. - a valid client_id and client_secret provided as keywords. - a credential dictionary with client_id and client_secret containing valid API credentials { "client_id": "CLIENT_ID_HERE", "client_secret": "CLIENT_SECRET_HERE" } - a previously-authenticated instance of the authentication service class (oauth2.py) - a valid token provided by the authentication service class (oauth2.py) """ @force_default(defaults=["body"], default_types=["list"]) def aggregate_sessions(self: object, body: list = None, **kwargs) -> dict: """Get aggregates on session data. Supported aggregations: date_range term Keyword arguments: body -- full body payload, not required when using other keywords. List of dictionaries. [{ "date_ranges": [ { "from": "string", "to": "string" } ], "field": "string", "filter": "string", "interval": "string", "min_doc_count": 0, "missing": "string", "name": "string", "q": "string", "ranges": [ { "From": 0, "To": 0 } ], "size": 0, "sort": "string", "sub_aggregates": [ null ], "time_zone": "string", "type": "string" }] date_ranges -- If peforming a date range query specify the from and to date ranges. These can be in common date formats like 2019-07-18 or now. List of dictionaries. field -- Term you want to aggregate on. If doing a date_range query, this is the date field you want to apply the date ranges to. String. filter -- Optional filter criteria in the form of an FQL query. For more information about FQL queries, see our FQL documentation in Falcon. String. interval -- String. min_doc_count -- Minimum number of documents required to match. Integer. missing -- String. name -- Name of the aggregation. String. q -- FQL syntax. String. ranges -- List of dictionaries. size -- Size limit to apply to the queries. Integer. sort -- FQL syntax. String. sub_aggregates -- List of strings. time_zone -- String. type -- String. This method only supports keywords for providing arguments. This method does not support body payload validation. Returns: dict object containing API response. HTTP Method: POST Swagger URL https://assets.falcon.crowdstrike.com/support/api/swagger.html#/real-time-response/RTR-AggregateSessions """ if not body: body = [aggregate_payload(submitted_keywords=kwargs)] return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="RTR_AggregateSessions", body=body ) @force_default(defaults=["parameters", "body"], default_types=["dict", "dict"]) def batch_active_responder_command(self: object, body: dict = None, parameters: dict = None, **kwargs ) -> dict: """Batch executes a RTR active-responder command across hosts mapped to a given batch ID. Keyword arguments: body -- full body payload, not required if keywords are used. { "base_command": "string", "batch_id": "string", "command_string": "string", "optional_hosts": [ "string" ], "persist_all": true } base_command -- Active-Responder command type we are going to execute, for example: `get` or `cp`. String. Refer to the RTR documentation for the full list of commands. batch_id -- Batch ID to execute the command on. Received from batch_init_session. String. command_string -- Full command string for the command. For example `get some_file.txt`. optional_hosts -- List of a subset of hosts we want to run the command on. If this list is supplied, only these hosts will receive the command. parameters -- full parameters payload in JSON format. Not required if using other keywords. persist_all -- Boolean. timeout -- Timeout for how long to wait for the request in seconds. Default timeout: 30 seconds Max timeout: 10 minutes timeout_duration -- Timeout duration for how long to wait for the request in duration syntax. Example: `10s`. Default value: `30s`. Maximum is `10m`. Valid units: `ns`, `us`, `ms`, `s`, `m`, `h` This method only supports keywords for providing arguments. Returns: dict object containing API response. HTTP Method: POST Swagger URL https://assets.falcon.crowdstrike.com/support/api/swagger.html#/real-time-response/BatchActiveResponderCmd """ if not body: body = command_payload(passed_keywords=kwargs) return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="BatchActiveResponderCmd", body=body, keywords=kwargs, params=parameters ) @force_default(defaults=["parameters", "body"], default_types=["dict", "dict"]) def batch_command(self: object, body: dict = None, parameters: dict = None, **kwargs) -> dict: """Batch executes a RTR read-only command across the hosts mapped to the given batch ID. Keyword arguments: body -- full body payload, not required if keywords are used. { "base_command": "string", "batch_id": "string", "command_string": "string", "optional_hosts": [ "string" ], "persist_all": true } base_command -- Active-Responder command type we are going to execute, for example: `get` or `cp`. String. Refer to the RTR documentation for the full list of commands. batch_id -- Batch ID to execute the command on. Received from batch_init_session. String. command_string -- Full command string for the command. For example `get some_file.txt`. optional_hosts -- List of a subset of hosts we want to run the command on. If this list is supplied, only these hosts will receive the command. parameters -- full parameters payload in JSON format. Not required if using other keywords. persist_all -- Boolean. timeout -- Timeout for how long to wait for the request in seconds. Default timeout: 30 seconds Max timeout: 10 minutes timeout_duration -- Timeout duration for how long to wait for the request in duration syntax. Example: `10s`. Default value: `30s`. Maximum is `10m`. Valid units: `ns`, `us`, `ms`, `s`, `m`, `h` This method only supports keywords for providing arguments. Returns: dict object containing API response. HTTP Method: POST Swagger URL https://assets.falcon.crowdstrike.com/support/api/swagger.html#/real-time-response/BatchCmd """ if not body: body = command_payload(passed_keywords=kwargs) return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="BatchCmd", body=body, keywords=kwargs, params=parameters ) @force_default(defaults=["parameters"], default_types=["dict"]) def batch_get_command_status(self: object, *args, parameters: dict = None, **kwargs) -> dict: """Retrieve the status of the specified batch get command. Will return successful files when they are finished processing. Keyword arguments: timeout -- Timeout for how long to wait for the request in seconds. Default timeout: 30 seconds Max timeout: 10 minutes timeout_duration -- Timeout duration for how long to wait for the request in duration syntax. Example: `10s`. Maximum is `10m`. Valid units: `ns`, `us`, `ms`, `s`, `m`, `h` batch_get_cmd_req_id -- Batch Get Command Request ID received from batch_command. parameters -- full parameters payload, not required if ids is provided as a keyword. Arguments: When not specified, the first argument to this method is assumed to be 'batch_get_cmd_req_id'. All others are ignored. Returns: dict object containing API response. HTTP Method: GET Swagger URL https://assets.falcon.crowdstrike.com/support/api/swagger.html#/real-time-response/BatchGetCmdStatus """ return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="BatchGetCmdStatus", keywords=kwargs, params=handle_single_argument(args, parameters, "batch_get_cmd_req_id") ) @force_default(defaults=["parameters", "body"], default_types=["dict", "dict"]) def batch_get_command(self: object, body: dict = None, parameters: dict = None, **kwargs ) -> dict: """Batch executes `get` command across hosts to retrieve files. After this call is made batch_get_command_status is used to query for the results. Keyword arguments: body -- full body payload, not
import tempfile from os import path from typing import Tuple import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_daq as daq import dash_html_components as html # Create random data with numpy import pandas as pd import plotly.express as px # import plotly.express as px import plotly.graph_objects as go from dash.dependencies import Input, Output, State from flask import send_file from plotly.graph_objs import Layout from .data import ( COLUMNS, SIM_RESULT_FILENAME, Results, make_table, measure_avg_free_space, measure_bandwidth, measure_cost, measure_cost_ratio, measure_cpu_eff, measure_hit_over_miss, measure_hit_rate, measure_num_miss_after_delete, measure_read_on_hit_ratio, measure_redirect_volume, measure_std_dev_free_space, measure_throughput, measure_throughput_ratio, parse_simulation_report, ) _CSV_TEMP_FILE = tempfile.NamedTemporaryFile(mode="w", delete=False) _TEX_TEMP_FILE = tempfile.NamedTemporaryFile(mode="w", delete=False) _HTML_TEMP_FILE = tempfile.NamedTemporaryFile(mode="w", delete=False) _EXTERNAL_STYLESHEETS = ["https://codepen.io/chriddyp/pen/bWLwgP.css"] LAYOUT = Layout( paper_bgcolor="rgb(255,255,255)", plot_bgcolor="rgb(255,255,255)", yaxis={"gridcolor": "black"}, xaxis={"gridcolor": "black"}, ) _MEASURES = { "Throughput ratio": measure_throughput_ratio, "Cost ratio": measure_cost_ratio, "Throughput (TB)": measure_throughput, "Cost (TB)": measure_cost, "Read on hit ratio": measure_read_on_hit_ratio, "CPU Eff.": measure_cpu_eff, "Avg. Free Space": measure_avg_free_space, "Std. Dev. Free Space": measure_std_dev_free_space, "Bandwidth": measure_bandwidth, "Redirect Vol.": measure_redirect_volume, "Hit over Miss": measure_hit_over_miss, "Num. miss after del.": measure_num_miss_after_delete, "Hit rate": measure_hit_rate, } def get_files2plot( results: "Results", files: list, filters_all: list, filters_any: list, column: str = "", agents: bool = False, with_log: bool = False, ) -> list: """Returns a filtered list of files to plot (name and dataframe) :param results: the result object with simulation data :type results: Results :param files: list of current file selection :type files: list :param filters_all: filters to apply for all file :type filters_all: list :param filters_any: filters to apply not exclusively :type filters_any: list :param column: column to plot, defaults to "" :type column: str, optional :param agents: search for agents, defaults to False :type agents: bool, optional :return: a list of files and dataframes :rtype: list """ files2plot = [] for file_ in files: df = results.get_df(file_, filters_all, filters_any) if df is not None: if column != "": if column in df.columns: if with_log: log_df = results.get_log(file_, filters_all, filters_any) if log_df is not None: files2plot.append((file_, df, log_df)) else: files2plot.append((file_, df)) elif agents: if "Addition epsilon" in df.columns: if with_log: log_df = results.get_log(file_, filters_all, filters_any) if log_df is not None: files2plot.append((file_, df, log_df)) else: files2plot.append((file_, df)) else: if with_log: log_df = results.get_log(file_, filters_all, filters_any) if log_df is not None: files2plot.append((file_, df, log_df)) else: files2plot.append((file_, df)) return files2plot def get_prefix(files2plot: list) -> str: """Check the prefix of list of files to plot :param files2plot: list of files and dataframes to plot :type files2plot: list :return: the commond prefix of the list of files :rtype: str """ return path.commonprefix([file_ for file_, *_ in files2plot]) def create(results: "Results", server_ip: str = "localhost"): _CACHE = {"columns": {}, "measures": {}, "agents": {}, "tables": {}, "compare": {}} app = dash.Dash( "Result Dashboard", external_stylesheets=[_EXTERNAL_STYLESHEETS, dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True, ) @app.server.route("/table/csv") def download_csv(): _CSV_TEMP_FILE.seek(0) return send_file( _CSV_TEMP_FILE.name, mimetype="text/csv", attachment_filename="table.csv", as_attachment=True, ) @app.server.route("/table/tex") def download_tex(): _TEX_TEMP_FILE.seek(0) return send_file( _TEX_TEMP_FILE.name, mimetype="text/plain", attachment_filename="table.tex", as_attachment=True, ) @app.server.route("/table/html") def download_html(): _HTML_TEMP_FILE.seek(0) return send_file( _HTML_TEMP_FILE.name, mimetype="text/plain", attachment_filename="table.html", as_attachment=True, ) _TAB_FILES = dbc.Card( dbc.CardBody( [ dbc.Button( "Unselect all", color="warning", block=True, id="unselect-files", ), dbc.Button( "Select all", color="success", block=True, id="select-files", ), html.Hr(), dcc.Checklist( options=[ {"label": f" {filename}", "value": filename} for filename in results.files ], value=results.files, labelStyle={"display": "block"}, id="selected-files", ), ] ), ) _TAB_FILTERS = dbc.Card( dbc.CardBody( [ dcc.Input( id="num-of-results", type="number", placeholder="Max number of results", value=0, ), html.Hr(), html.H2("All"), dcc.Checklist( options=[ {"label": f" {component}", "value": component} for component in results.components ], value=[], labelStyle={"display": "block"}, id="selected-filters-all", ), html.Br(), html.H2("Any"), dcc.Checklist( options=[ {"label": f" {component}", "value": component} for component in results.components ], value=[], labelStyle={"display": "block"}, id="selected-filters-any", ), ] ), ) _TAB_COLUMNS = dbc.Card( dbc.Spinner( dbc.CardBody( id="graphs-columns", ), color="primary", ), ) _TAB_MEASURES = dbc.Card( dbc.Spinner( dbc.CardBody( id="graphs-measures", ), color="primary", ), ) _TAB_AGENTS = dbc.Card( dbc.Spinner( dbc.CardBody( id="graphs-agents", ), color="primary", ), ) _TAB_TABLE = dbc.Card( [ dbc.CardBody( dbc.ListGroup( [ dbc.ListGroup( [ dbc.ListGroupItem( dbc.Button( "", color="info", disabled=True, id="toggle-extended-table-output", ), ), dbc.ListGroupItem( daq.ToggleSwitch( id="toggle-extended-table", value=False, ) ), ], horizontal=True, ), dbc.ListGroup( [ dbc.ListGroupItem( dbc.Button( "", color="info", disabled=True, id="toggle-sort-by-roh-first-output", ), ), dbc.ListGroupItem( daq.ToggleSwitch( id="toggle-sort-by-roh-first", value=False, ) ), dbc.CardBody( dbc.ListGroup( [ dbc.ListGroupItem( dcc.Link( "Download as CSV", refresh=True, href="/table/csv", target="_blank", ) ), dbc.ListGroupItem( dcc.Link( "Download as Latex table", refresh=True, href="/table/tex", target="_blank", ) ), dbc.ListGroupItem( dcc.Link( "Download as html", refresh=True, href="/table/html", target="_blank", ) ), ], horizontal=True, ), ), ], horizontal=True, ), ], horizontal=True, ) ), dbc.Spinner( [ dbc.CardBody( id="table", ), ], color="primary", ), ], ) _TAB_COMPARE = dbc.Card( [ dbc.Spinner( dbc.CardBody( id="compare", ), color="primary", type="grow", ), dbc.CardBody( [ dbc.Input( id="sel-num-sim", placeholder="Number of simulation", type="number", ), dbc.Input( id="sel-tick", placeholder="tick of simulation", type="number" ), dbc.Spinner( [ dbc.CardBody( id="sel-sim-compare-plot-actions", ), dbc.CardBody( id="sel-sim-compare-plot-actions-hist-numReq", ), dbc.CardBody( id="sel-sim-compare-plot-actions-hist-size", ), dbc.CardBody( id="sel-sim-compare-plot-actions-hist-deltaT", ), dbc.CardBody( id="sel-sim-compare-plot-after", ), ], color="warning", type="grow", ), ], id="compare-row", ), dbc.CardBody( id="compare-tables", ), ] ) _TABS = dbc.Tabs( [ dbc.Tab(_TAB_FILES, label="Files", tab_id="tab-files"), dbc.Tab(_TAB_FILTERS, label="Filters", tab_id="tab-filters"), dbc.Tab(_TAB_COLUMNS, label="Columns", tab_id="tab-columns"), dbc.Tab(_TAB_MEASURES, label="Measures", tab_id="tab-measures"), dbc.Tab(_TAB_AGENTS, label="Agents", tab_id="tab-agents"), dbc.Tab(_TAB_TABLE, label="Table", tab_id="tab-table"), dbc.Tab(_TAB_COMPARE, label="Compare eviction", tab_id="tab-compare"), ], id="tabs", ) app.layout = html.Div( children=[ html.H1(children="Result Dashboard"), _TABS, ], style={"padding": "1em"}, ) def selection2hash( files: list, filters_all: list, filters_any: list, num_of_results: int, extended: bool = False, sort_by_roh_first: bool = False, ) -> str: return str( hash( " ".join( files + filters_all + filters_any + [str(num_of_results), str(extended), str(sort_by_roh_first)] ) ) ) @app.callback( dash.dependencies.Output("toggle-extended-table-output", "children"), [dash.dependencies.Input("toggle-extended-table", "value")], ) def extended_table(value): return "Extended table: {}".format(value) @app.callback( dash.dependencies.Output("toggle-sort-by-roh-first-output", "children"), [dash.dependencies.Input("toggle-sort-by-roh-first", "value")], ) def sort_by_read_on_hit(value): return "Sort by read on hit: {}".format(value) @app.callback( [ Output("sel-sim-compare-plot-actions", "children"), Output("sel-sim-compare-plot-actions-hist-numReq", "children"), Output("sel-sim-compare-plot-actions-hist-size", "children"), Output("sel-sim-compare-plot-actions-hist-deltaT", "children"), Output("sel-sim-compare-plot-after", "children"), ], [Input("sel-num-sim", "value"), Input("sel-tick", "value")], [ State("selected-files", "value"), State("selected-filters-all", "value"), State("selected-filters-any", "value"), State("num-of-results", "value"), ], ) def compare_results(num_sim, tick, files, filters_all, filters_any, num_of_results): cur_hash = selection2hash(files, filters_all, filters_any, num_of_results) if cur_hash in _CACHE["compare"]: data, *_ = _CACHE["compare"][cur_hash] keys = list(data.keys()) try: cur_sim = keys[num_sim] for evaluator in data[cur_sim]: if evaluator.tick == tick: scatterActionsFig = px.scatter_3d( evaluator.actions, x="num req", y="size", z="filename", color="delta t", size="size", opacity=0.9, ) scatterActionsFig.update_layout(LAYOUT) histActionNumReq = px.histogram(evaluator.actions, x="num req") histActionNumReq.update_layout(LAYOUT) histActionSize = px.histogram(evaluator.actions, x="size") histActionSize.update_layout(LAYOUT) histActionDeltaT = px.histogram(evaluator.actions, x="delta t") histActionDeltaT.update_layout(LAYOUT) after_data = evaluator.after4scatter scatterAfterFig = px.scatter_3d( after_data, x="num req", y="size", z="filename", color="delta t", size="size", opacity=0.9, ) scatterAfterFig.update_layout(LAYOUT) return ( [dcc.Graph(figure=scatterActionsFig)], [dcc.Graph(figure=histActionNumReq)], [dcc.Graph(figure=histActionSize)], [dcc.Graph(figure=histActionDeltaT)], [dcc.Graph(figure=scatterAfterFig)], ) else: return ( [ dbc.Alert( f"No tick found in simulation {num_sim}", color="danger" ) ], [""], [""], [""], [""], ) except (IndexError, TypeError): return ( [ dbc.Alert( f"No simulation found at index {num_sim}", color="danger" ) ], [""], [""], [""], [""], ) else: return [dbc.Alert("No results", color="warning")], [""], [""], [""], [""] @app.callback( [Output(f"collapse-{i}", "is_open") for i in range(len(results))], [Input(f"group-{i}-toggle", "n_clicks") for i in range(len(results))], [State(f"collapse-{i}", "is_open") for i in range(len(results))], ) def toggle_collapse_table(*args): ctx = dash.callback_context if not ctx.triggered: return [False] * len(results) else: button_id = ctx.triggered[0]["prop_id"].split(".")[0] button_idx = int(button_id.split("-")[1]) # "group-idx-toggle" res = [False] * len(results) for idx in range(len(res)): # update all is open to current status res[idx] = args[idx + len(results)] if args[button_idx]: # Check input n res[button_idx] = not args[button_idx + len(results)] # is open return res @app.callback( dash.dependencies.Output("selected-files", "value"), [ dash.dependencies.Input("unselect-files", "n_clicks"), dash.dependencies.Input("select-files", "n_clicks"), ], ) def unselect_all_files(unselect_n_clicks, select_n_clicks): # Ref: https://dash.plotly.com/advanced-callbacks changed_id = [ p["prop_id"].split(".")[0] for p in dash.callback_context.triggered ][0] if changed_id == "unselect-files": return [] elif changed_id == "select-files": return results.files return results.files @app.callback( [ Output("graphs-columns", "children"), Output("graphs-measures", "children"), Output("graphs-agents", "children"), Output("table", "children"), Output("compare", "children"), Output("compare-tables", "children"), ], [ Input("tabs", "active_tab"), Input("toggle-extended-table", "value"), Input("toggle-sort-by-roh-first", "value"), ], [ State("selected-files", "value"), State("selected-filters-all", "value"), State("selected-filters-any", "value"), State("num-of-results", "value"), ], ) def switch_tab( at, extended, sort_by_roh_first, files, filters_all, filters_any, num_of_results ): cur_hash = selection2hash( files, filters_all, filters_any, num_of_results, extended, sort_by_roh_first, ) if at == "tab-files": return ("", "", "", "", "", "") elif at == "tab-filters": return ("", "", "", "", "", "") elif at == "tab-columns": if cur_hash in _CACHE["columns"]: return (_CACHE["columns"][cur_hash], "", "", "", "", "") else: figures = [] for column in COLUMNS[1:]: files2plot = get_files2plot( results, files, filters_all, filters_any, column, ) prefix = get_prefix(files2plot) if num_of_results != 0 and num_of_results is not None: table, new_file2plot = make_table( files2plot, prefix, num_of_results ) files2plot = [ (file_, df) for file_, df in files2plot if file_ in new_file2plot ] prefix = get_prefix(files2plot) figures.append( dcc.Graph( figure=make_line_figures( files2plot, prefix, title=column, column=column ) ) ) figures.append(html.Hr()) _CACHE["columns"][cur_hash] = figures return (figures, "", "", "", "", "") elif
# Copyright 2002-2011 <NAME>. See LICENSE for licensing information. """mixminion.server.ServerQueue Facilities for retriable delivery queues, and for mix pools. """ import cPickle import math import os import operator import time import stat import sys import threading import mixminion.Filestore from mixminion.Common import MixError, MixFatalError, secureDelete, LOG, \ createPrivateDir, readPickled, writePickled, formatTime, readFile, \ ceilDiv from mixminion.Crypto import getCommonPRNG from mixminion.Filestore import CorruptedFile __all__ = [ 'DeliveryQueue', 'TimedMixPool', 'CottrellMixPool', 'BinomialCottrellMixPool', 'PerAddressDeliveryQueue' ] def _calculateNext(lastAttempt, firstAttempt, retrySchedule, canDrop, now): """DOCDOC""" # If we've never tried to deliver the message, it's ready to # go immediately. if lastAttempt is None: return now # Otherwise, we count from the time the message was first queued, # until we find a scheduled delivery that falls after the last # attempted delivery. # # This scheduled delivery may be in the past. That's okay: it only # means that we've missed a scheduled delivery, and we can try again # immediately. attempt = firstAttempt for interval in retrySchedule: attempt += interval if attempt > lastAttempt: return attempt # Oops: there are no scheduled deliveries after the last delivery. # Time to drop this message, or go into holding mode. if canDrop: return None else: if not retrySchedule or retrySchedule[-1]<5: #DOCDOC retrySchedule = [3600] attempt += (ceilDiv(lastAttempt-attempt+60,retrySchedule[-1]) * retrySchedule[-1]) return attempt class _DeliveryState: """Helper class: holds the state needed to schedule delivery or eventual abandonment of a message in a DeliveryQueue.""" ## Fields: # queuedTime: time at which the corresponding message was first # inserted into the queue. # lastAttempt: The most recent time at which we attempted to # deliver the message. (None means 'never'). # address: Pickleable object holding address information. Delivery # code uses this field to group messages by address before loading # them all from disk. Must be usable as hash key. # pendingAt: None (if we're not sending this message), or a time # at which we begain sending this message. # nextAttempt: None, or the time at which we'll next try to send # this message. This field is invalid until someone calls # setNextAttempt. If the time is in the past, delivery can # be tried now. If None, the message may be removable. def __init__(self, queuedTime=None, lastAttempt=None, address=None): """Create a new _DeliveryState for a message received at queuedTime (default now), whose last delivery attempt was at lastAttempt (default never).""" if queuedTime is None: queuedTime = time.time() self.queuedTime = queuedTime self.lastAttempt = lastAttempt self.address = address self.pending = None self.nextAttempt = None self.remove = 0 def isPending(self): """Return true iff we are currently trying to deliver this message.""" return self.pending is not None def setPending(self, now=None): """Note that we are now trying to deliver this message, so that we don't try to deliver it twice at the same time.""" if now is None: now = time.time() self.pending = now def setNonPending(self): """Note that we are no longer trying to deliver this message, so that we can try it again later.""" self.pending = None def isRemovable(self): """Return true iff this message is old enough to be removed.""" return self.remove def __getstate__(self): # For pickling. All future versions of deliverystate will pickle # to a tuple, whose first element will be a version string. return ("V1", self.queuedTime, self.lastAttempt, self.address) def __setstate__(self, state): # For pickling. if state[0] == "V1": self.queuedTime = state[1] self.lastAttempt = state[2] self.address = state[3] else: #XXXX008 This is way too extreme. raise MixFatalError("Unrecognized delivery state") self.pending = None self.nextAttempt = None self.remove = 0 def setNextAttempt(self, retrySchedule, now=None): """Return the next time when we should try to deliver this message according to the provided retrySchedule. If the time returned is in the past, then immediate delivery is okay. If the time returned is None, this message has expired and should be forgotten. """ if not now: now = time.time() self.remove = 0 self.nextAttempt = _calculateNext(self.lastAttempt, self.queuedTime, retrySchedule, canDrop=1, now=now) if self.nextAttempt is None: self.remove = 1 def setLastAttempt(self, when): """Update time of the last attempted delivery.""" self.lastAttempt = when class PendingMessage: """PendingMessage represents a message in a DeliveryQueue, for delivery to a specific address. See DeliveryQueue._deliverMessages for more information about the interface.""" ## # queue: the deliveryqueue holding this message # handle: the handle for this message in the queue # address: The address passed to queueDeliveryMessage for this message, # or None # message: The object queued as this message, or None if the object # has not yet been loaded. def __init__(self, handle, queue, address, message=None): self.handle = handle self.queue = queue self.address = address self.message = message def getAddress(self): return self.address def getHandle(self): return self.handle def succeeded(self,now=None): """Mark this message as having been successfully deleted, removing it from the queue.""" self.queue.deliverySucceeded(self.handle,now=now) self.queue = self.message = None def failed(self, retriable=0, now=None): """Mark this message as has having failed delivery, either rescheduling it or removing it from the queue.""" self.queue.deliveryFailed(self.handle, retriable, now=now) self.queue = self.message = None def getMessage(self): """Return the underlying object stored in the delivery queue, loading it from disk if necessary. May raise CorruptedFile.""" assert self.handle is not None if self.message is None: self.message = self.queue.store.getObject(self.handle) return self.message class DeliveryQueue: """A DeliveryQueue implements a queue that greedily sends messages to outgoing streams that occasionally fail. All underlying messages are pickled objects. Additionally, we store metadata about attempted deliveries in the past, so we know when to schedule the next delivery. This class is abstract. Implementors of this class should subclass it to add a _deliverMessages method. Multiple invocations of this method may be active at a given time. Upon success or failure, this method should cause deliverySucceeded or deliveryFailed to be called as appropriate. Users of this class will probably only want to call the queueDeliveryMessage, sendReadyMessages, and nextMessageReadyAt methods. This class caches information about the directory state; it won't play nice if multiple instances are looking at the same directory. """ ### # Fields: # store -- An ObjectMetadataStore to back this queue. The objects # are instances of whatever deliverable object this queue contains; # the metadata are instances of _DeliveryState. # retrySchedule -- a list of intervals at which delivery of messages # should be reattempted, as described in "setRetrySchedule". # _lock -- a reference to the RLock used to control access to the # store. def __init__(self, location, retrySchedule=None, now=None, name=None): """Create a new DeliveryQueue object that stores its files in <location>. If retrySchedule is provided, it is interpreted as in setRetrySchedule. Name, if present, is a human-readable name used in log messages.""" self.store = mixminion.Filestore.ObjectMetadataStore( location,create=1,scrub=1) self._lock = self.store._lock if name is None: self.qname = os.path.split(location)[1] else: self.qname = name self.retrySchedule = None self._rescan() if retrySchedule is not None: self.setRetrySchedule(retrySchedule, now) else: self.setRetrySchedule([0], now) self._repOK() def setRetrySchedule(self, schedule, now=None): """Set the retry schedule for this queue. A retry schedule is a list of integers, each representing a number of seconds. For example, a schedule of [ 120, 120, 3600, 3600 ] will cause undeliverable messages to be retried after 2 minutes, then 2 minutes later, then 1 hour later, then 1 hour later. Retry schedules are not strictly guaranteed, for two reasons: 1) Message delivery can fail _unretriably_, in which case no further attempts are made. 2) Retries are only actually attempted when sendReadyMessages is called. If the schedule specifies retry attempts at 10-second intervals, but sendReadyMessages is invoked only every 30 minutes, messages will only me retried once every 30 minutes. """ try: self._lock.acquire() self.retrySchedule = schedule[:] self._rebuildNextAttempt(now) finally: self._lock.release() def _rescan(self, now=None): """Helper: Rebuild the internal state of this queue from the underlying directory. After calling 'rescan', _rebuildNextAttempt must be called to recalculate our delivery schedule.""" try: self._lock.acquire() self.store.loadAllMetadata(lambda h: _DeliveryState()) self._rebuildNextAttempt(now) self._repOK() finally: self._lock.release() def getAllMessages(self): """Return handles for all messages in the store.""" return self.store.getAllMessages() def count(self): """Return the number of messages in the store.""" return self.store.count() def _rebuildNextAttempt(self, now=None): """Helper: Reconstruct self.nextAttempt
<gh_stars>1-10 import urllib import urllib2 from util import hook import re from lxml import etree import types administrators = ["bluesoul", "macky", "toxicdick"] # Multiple nicks are separated by commas and delimited with quotes. def db_init(db): print "In db_init function." try: db.execute("create table if not exists searches" "(search_string UNIQUE PRIMARY KEY,link)") except db.Error as e: print "Error in db_init: " + str(e) return db def get_link(db, inp): print "In get_link function." inp = urllib.quote_plus(inp) try: row = db.execute("select link from searches where" " search_string=lower(?) limit 1", (inp.lower(),)).fetchone() print "Printing row in get_link" print row print "Contents of inp.lower():" + str(inp) return row except db.Error as e: print "Error in get_link: " + str(e) def store_link(db, stub, search): print "In store_link function." try: db.execute("insert into searches (search_string, link) VALUES (?, ?)", (search.lower(), stub)) db.commit() except db.Error as e: print "Error in store_link: " + str(e) return stub def remove_link(db, search): print "In remove_link function." try: db.execute("delete from searches where search_string = ?", (search.lower(),)) db.commit() return True except db.Error as e: print "Error in remove_link: " + str(e) return False def get_stats(stub, year, per, playoffs): print "In get_stats function." stub = ''.join(stub) url = 'http://www.basketball-reference.com/players/' + stub agent = 'Shaqtus/1.0' req = urllib2.Request(url, headers={'User-Agent': agent}) handle = urllib2.urlopen(req) read = handle.read() read = read.replace("<!--", "") # Everything but per-game is commented out read = read.replace("-->", "") # for some stupid reason as of November 2016 read = read.replace("></td>", ">N/A</td>") # new behavior of blank entries when no 3s taken, for example results = etree.HTML(read) name = results.xpath('.//h1') namefield = [] if not name: # Sometimes the name isn't where we expect it to be. name = results.xpath('.//*[@id="info_box"]/div[3]/h1') # Usually that means it's here. for x in name[0].iter(): namefield.insert(len(namefield), x.text) if playoffs is True: if per == "per36": if year is None: stats2 = results.xpath('.//*[@id="playoffs_per_minute"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="playoffs_per_minute"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="playoffs_per_minute.' + year + '"]') elif per == "per100": if year is None: stats2 = results.xpath('.//*[@id="playoffs_per_poss"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="playoffs_per_poss"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="playoffs_per_poss.' + year + '"]') elif per == "advanced": if year is None: stats2 = results.xpath('.//*[@id="playoffs_advanced"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="playoffs_advanced"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="playoffs_advanced.' + year + '"]') else: if year is None: stats2 = results.xpath('.//*[@id="playoffs_per_game"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="playoffs_per_game"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="playoffs_per_game.' + year + '"]') else: if per == "per36": if year is None: stats2 = results.xpath('.//*[@id="per_minute"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="per_minute"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="per_minute.' + year + '"]') elif per == "per100": if year is None: stats2 = results.xpath('.//*[@id="per_poss"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="per_poss"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="per_poss.' + year + '"]') elif per == "advanced": if year is None: stats2 = results.xpath('.//*[@id="advanced"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="advanced"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="advanced.' + year + '"]') else: if year is None: stats2 = results.xpath('.//*[@id="per_game"]//tr[@class="full_table"][last()]') elif year == "career": stats2 = results.xpath('.//*[@id="per_game"]/tfoot/tr[1]') else: stats2 = results.xpath('.//*[@id="per_game.' + year + '"]') statlist = [] print stats2 for i in stats2[0].iter(): statlist.insert(len(statlist), i.text) try: statlist.remove(u'\xa0\u2605') # Remove all-star designation except ValueError: pass try: statlist.remove(u'\xa0\u274d') # Remove championship designation except ValueError: pass if statlist[4] == "TOT": # If a player played for more than 1 team statlist[5] = "Multiple Teams" # Indicate as such in the proper spot statlist.insert(6, None) # And add a blank entry to match the rest of the players. statlist = filter(None, statlist) # Remove all blanks. print statlist if per == "advanced": if year == "career": formatted = (namefield[0] + " | " + str(statlist[0]) + " | " + str(statlist[7]) + " PER | " + str(statlist[8]) + " TS% | " + str(statlist[9]) + " 3PAr | " + str(statlist[10]) + " FTr | " + str(statlist[11]) + " ORB% | " + str(statlist[12]) + " DRB% | " + str(statlist[13]) + " TRB% | " + str(statlist[14]) + " AST% | " + str(statlist[15]) + " STL% | " + str(statlist[16]) + " BLK% | " + str(statlist[17]) + " TOV% | " + str(statlist[18]) + " USG% | " + str(statlist[20]) + " OWS | " + str(statlist[21]) + " DWS | " + str(statlist[22]) + " WS | " + str(statlist[23]) + " WS/48 | " + str(statlist[25]) + " OBPM | " + str(statlist[26]) + " DBPM | " + str(statlist[27]) + " BPM | " + str(statlist[28]) + " VORP") else: formatted = (namefield[0] + " | Age " + str(statlist[1]) + " | " + str(statlist[7]) + " PER | " + str(statlist[8]) + " TS% | " + str(statlist[9]) + " 3PAr | " + str(statlist[10]) + " FTr | " + str(statlist[11]) + " ORB% | " + str(statlist[12]) + " DRB% | " + str(statlist[13]) + " TRB% | " + str(statlist[14]) + " AST% | " + str(statlist[15]) + " STL% | " + str(statlist[16]) + " BLK% | " + str(statlist[17]) + " TOV% | " + str(statlist[18]) + " USG% | " + str(statlist[20]) + " OWS | " + str(statlist[21]) + " DWS | " + str(statlist[22]) + " WS | " + str(statlist[23]) + " WS/48 | " + str(statlist[25]) + " OBPM | " + str(statlist[26]) + " DBPM | " + str(statlist[27]) + " BPM | " + str(statlist[28]) + " VORP") elif per == "per100": if year == "career": formatted = (namefield[0] + " | " + str(statlist[0]) + " | " + str(statlist[5]) + " GP | " + str(statlist[6]) + " GS | " + str(statlist[7]) + " MP | " + str(statlist[8]) + " FGM | " + str(statlist[9]) + " FGA | " + str(statlist[10]) + " FG% | " + str(statlist[11]) + " 3PM | " + str(statlist[12]) + " 3PA | " + str(statlist[13]) + " 3P% | " + str(statlist[17]) + " FTM | " + str(statlist[18]) + " FTA | " + str(statlist[19]) + " FT% | " + str(statlist[20]) + " ORB | " + str(statlist[21]) + " DRB | " + str(statlist[22]) + " TRB | " + str(statlist[23]) + " AST | " + str(statlist[24]) + " STL | " + str(statlist[25]) + " BLK | " + str(statlist[26]) + " TOV | " + str(statlist[27]) + " PF | " + str(statlist[28]) + " PTS | " + str(statlist[30]) + " ORtg | " + str(statlist[31]) + " DRtg") else: formatted = (namefield[0] + " | " + str(statlist[0]) + " | " + str(statlist[5]) + " GP | " + str(statlist[6]) + " GS | " + str(statlist[7]) + " MP | " + str(statlist[8]) + " FGM | " + str(statlist[9]) + " FGA | " + str(statlist[10]) + " FG% | " + str(statlist[11]) + " 3PM | " + str(statlist[12]) + " 3PA | " + str(statlist[13]) + " 3P% | " + str(statlist[17]) + " FTM | " + str(statlist[18]) + " FTA | " + str(statlist[19]) + " FT% | " + str(statlist[20]) + " ORB | " + str(statlist[21]) + " DRB | " + str(statlist[22]) + " TRB | " + str(statlist[23]) + " AST | " + str(statlist[24]) + " STL | " + str(statlist[25]) + " BLK | " + str(statlist[26]) + " TOV | " + str(statlist[27]) + " PF | " + str(statlist[28]) + " PTS | " + str(statlist[30]) + " ORtg | " + str(statlist[31]) + " DRtg") elif per == "per36": if year == "career": formatted = (namefield[0] + " | " + str(statlist[0]) + " | " + str(statlist[5]) + " GP | " + str(statlist[6]) + " GS | " + str(statlist[7]) + " MP | " + str(statlist[8]) + " FGM | " + str(statlist[9]) + " FGA
in elem: # treat as enum val = 0 for k, v in elem['values'].items(): elem['values'][k] = elem['values'][k] or OrderedDict() elem['values'][k]['name'] = k val = elem['values'][k].get('value', val) elem['values'][k]['value'] = val val += 1 enums[path] = elem elem['is_enum'] = True return elem def resolve_interface(scope, name, typeargs): """ Resolves a type name (i.e. interface name or value type name) given as a string to an interface object. The innermost scope is searched first. At every scope level, if no matching interface is found, it is checked if a matching value type exists. If so, the interface type fibre.Property<value_type> is returned. """ if not isinstance(name, str): return name if 'fibre.Property.type' in typeargs: typeargs['fibre.Property.type'] = resolve_valuetype(scope, typeargs['fibre.Property.type']) scope = scope.split('.') for probe_scope in [join_name(*scope[:(len(scope)-i)]) for i in range(len(scope)+1)]: probe_name = join_name(probe_scope, name) #print('probing ' + probe_name) if probe_name in interfaces: return interfaces[probe_name] elif probe_name in value_types: typeargs['fibre.Property.type'] = value_types[probe_name] return make_property_type(typeargs) elif probe_name in generics: return generics[probe_name](typeargs) raise Exception('could not resolve type {} in {}. Known interfaces are: {}. Known value types are: {}'.format(name, join_name(*scope), list(interfaces.keys()), list(value_types.keys()))) def resolve_valuetype(scope, name): """ Resolves a type name given as a string to the type object. The innermost scope is searched first. """ if not isinstance(name, str): return name scope = scope.split('.') for probe_scope in [join_name(*scope[:(len(scope)-i)]) for i in range(len(scope)+1)]: probe_name = join_name(probe_scope, name) if probe_name in value_types: return value_types[probe_name] raise Exception('could not resolve type {} in {}. Known value types are: {}'.format(name, join_name(*scope), list(value_types.keys()))) def map_to_fibre01_type(t): if t.get('is_enum', False): return 'int32' elif t['fullname'] == 'float32': return 'float' return t['fullname'] def generate_endpoint_for_property(prop, attr_bindto, idx): prop_intf = interfaces[prop['type']['fullname']] endpoint = { 'id': idx, 'function': prop_intf['functions']['read' if prop['type']['mode'] == 'readonly' else 'exchange'], 'in_bindings': OrderedDict([('obj', attr_bindto)]), 'out_bindings': OrderedDict() } endpoint_definition = { 'name': prop['name'], 'id': idx, 'type': map_to_fibre01_type(prop['type']['value_type']), 'access': 'r' if prop['type']['mode'] == 'readonly' else 'rw', } return endpoint, endpoint_definition def generate_endpoint_table(intf, bindto, idx): """ Generates a Fibre v0.1 endpoint table for a given interface. This will probably be deprecated in the future. The object must have no circular property types (i.e. A.b has type B and B.a has type A). """ endpoints = [] endpoint_definitions = [] cnt = 0 for k, prop in intf['attributes'].items(): property_value_type = re.findall('^fibre\.Property<([^>]*), (readonly|readwrite)>$', prop['type']['fullname']) #attr_bindto = join_name(bindto, bindings_map.get(join_name(intf['fullname'], k), k + ('_' if len(intf['functions']) or (intf['fullname'] in treat_as_classes) else ''))) attr_bindto = intf['c_name'] + '::get_' + prop['name'] + '(' + bindto + ')' if len(property_value_type): # Special handling for Property<...> attributes: they resolve to one single endpoint endpoint, endpoint_definition = generate_endpoint_for_property(prop, attr_bindto, idx + cnt) endpoints.append(endpoint) endpoint_definitions.append(endpoint_definition) cnt += 1 else: inner_endpoints, inner_endpoint_definitions, inner_cnt = generate_endpoint_table(prop['type'], attr_bindto, idx + cnt) endpoints += inner_endpoints endpoint_definitions.append({ 'name': k, 'type': 'object', 'members': inner_endpoint_definitions }) cnt += inner_cnt for k, func in intf['functions'].items(): endpoints.append({ 'id': idx + cnt, 'function': func, 'in_bindings': OrderedDict([('obj', bindto), *[(k_arg, '(' + bindto + ')->' + func['name'] + '_in_' + k_arg + '_') for k_arg in list(func['in'].keys())[1:]]]), 'out_bindings': OrderedDict((k_arg, '&(' + bindto + ')->' + func['name'] + '_out_' + k_arg + '_') for k_arg in func['out'].keys()), }) in_def = [] out_def = [] for i, (k_arg, arg) in enumerate(list(func['in'].items())[1:]): endpoint, endpoint_definition = generate_endpoint_for_property({ 'name': arg['name'], 'type': make_property_type({'fibre.Property.type': arg['type'], 'fibre.Property.mode': 'readwrite'}) }, intf['c_name'] + '::get_' + func['name'] + '_in_' + k_arg + '_' + '(' + bindto + ')', idx + cnt + 1 + i) endpoints.append(endpoint) in_def.append(endpoint_definition) for i, (k_arg, arg) in enumerate(func['out'].items()): endpoint, endpoint_definition = generate_endpoint_for_property({ 'name': arg['name'], 'type': make_property_type({'fibre.Property.type': arg['type'], 'fibre.Property.mode': 'readonly'}) }, intf['c_name'] + '::get_' + func['name'] + '_out_' + k_arg + '_' + '(' + bindto + ')', idx + cnt + len(func['in']) + i) endpoints.append(endpoint) out_def.append(endpoint_definition) endpoint_definitions.append({ 'name': k, 'id': idx + cnt, 'type': 'function', 'inputs': in_def, 'outputs': out_def }) cnt += len(func['in']) + len(func['out']) return endpoints, endpoint_definitions, cnt # Parse arguments parser = argparse.ArgumentParser(description="Gernerate code from YAML interface definitions") parser.add_argument("--version", action="store_true", help="print version information") parser.add_argument("-v", "--verbose", action="store_true", help="print debug information (on stderr)") parser.add_argument("-d", "--definitions", type=argparse.FileType('r', encoding='utf-8'), nargs='+', help="the YAML interface definition file(s) used to generate the code") parser.add_argument("-t", "--template", type=argparse.FileType('r', encoding='utf-8'), help="the code template") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-o", "--output", type=argparse.FileType('w', encoding='utf-8'), help="path of the generated output") group.add_argument("--outputs", type=str, help="path pattern for the generated outputs. One output is generated for each interface. Use # as placeholder for the interface name.") parser.add_argument("--generate-endpoints", type=str, nargs='?', help="if specified, an endpoint table will be generated and passed to the template for the specified interface") args = parser.parse_args() if args.version: print("0.0.1") sys.exit(0) definition_files = args.definitions template_file = args.template # Load definition files for definition_file in definition_files: try: file_content = yaml.load(definition_file, Loader=SafeLineLoader) except yaml.scanner.ScannerError as ex: print("YAML parsing error: " + str(ex), file=sys.stderr) sys.exit(1) for err in validator.iter_errors(file_content): if '__line__' in err.absolute_path: continue if '__column__' in err.absolute_path: continue #instance = err.instance.get(re.findall("([^']*)' (?:was|were) unexpected\)", err.message)[0], err.instance) # TODO: print line number raise Exception(err.message + '\nat ' + str(list(err.absolute_path))) interfaces.update(get_dict(file_content, 'interfaces')) value_types.update(get_dict(file_content, 'valuetypes')) dictionary += file_content.get('dictionary', None) or [] # Preprocess definitions # Regularize everything into a wellknown form for k, item in list(interfaces.items()): regularize_interface('', k, item) for k, item in list(value_types.items()): regularize_valuetype('', k, item) if args.verbose: print('Known interfaces: ' + ''.join([('\n ' + k) for k in interfaces.keys()])) print('Known value types: ' + ''.join([('\n ' + k) for k in value_types.keys()])) clashing_names = list(set(value_types.keys()).intersection(set(interfaces.keys()))) if len(clashing_names): print("**Error**: Found both an interface and a value type with the name {}. This is not allowed, interfaces and value types (such as enums) share the same namespace.".format(clashing_names[0]), file=sys.stderr) sys.exit(1) # Resolve all types into references for _, item in list(interfaces.items()): for _, prop in item['attributes'].items(): prop['type'] = resolve_interface(item['fullname'], prop['type'], prop['typeargs']) for _, func in item['functions'].items(): for _, arg in func['in'].items(): arg['type'] = resolve_valuetype(item['fullname'], arg['type']) for _, arg in func['out'].items(): arg['type'] = resolve_valuetype(item['fullname'], arg['type']) # Attach interfaces to their parents toplevel_interfaces = [] for k, item in list(interfaces.items()): k = split_name(k) if len(k) == 1: toplevel_interfaces.append(item) else: if k[:-1] != ['fibre']: # TODO: remove special handling parent = interfaces[join_name(*k[:-1])] parent['interfaces'].append(item) item['parent'] = parent toplevel_enums = [] for k, item in list(enums.items()): k = split_name(k) if len(k) == 1: toplevel_enums.append(item) else: if k[:-1] != ['fibre']: # TODO: remove special handling parent = interfaces[join_name(*k[:-1])] parent['enums'].append(item) item['parent'] = parent if args.generate_endpoints: endpoints, embedded_endpoint_definitions, _ = generate_endpoint_table(interfaces[args.generate_endpoints], '&ep_root', 1) # TODO: make user-configurable embedded_endpoint_definitions = [{'name': '', 'id': 0, 'type': 'json', 'access': 'r'}] + embedded_endpoint_definitions endpoints = [{'id': 0, 'function': {'fullname': 'endpoint0_handler', 'in': {}, 'out': {}}, 'bindings': {}}] + endpoints else: embedded_endpoint_definitions = None endpoints = None # Render template env = jinja2.Environment( comment_start_string='[#', comment_end_string='#]', block_start_string='[%', block_end_string='%]', variable_start_string='[[', variable_end_string=']]' ) def tokenize(text, interface, interface_transform, value_type_transform, attribute_transform): """ Looks for referencable tokens (interface names, value type names or attribute names) in a documentation text and runs them through the provided processing functions. Tokens are detected by enclosing back-ticks (`). interface: The interface type object that defines the scope in which the tokens should be detected. interface_transform: A function that takes an interface object as an argument and returns a string. value_type_transform: A function that takes a value type object as an argument and returns a string. attribute_transform: A function that takes the token strin and an attribute object as arguments and returns a string. """ if text is None or isinstance(text, jinja2.runtime.Undefined): return text def token_transform(token): token = token.groups()[0] token_list = split_name(token) # Check if this is an attribute reference scope = interface attr = None while attr is None and not scope is None: attr_intf = scope for name in token_list: if not name in attr_intf['attributes']: attr = None break attr = attr_intf['attributes'][name] attr_intf = attr['type'] scope = scope.get('parent', None) if not attr is None: return attribute_transform(token, attr) print('Warning: cannot resolve "{}" in {}'.format(token, interface['fullname'])) return "`" + token + "`" return re.sub(r'`([A-Za-z\._]+)`', token_transform, text) env.filters['to_pascal_case'] = to_pascal_case env.filters['to_camel_case'] = to_camel_case env.filters['to_macro_case'] = to_macro_case env.filters['to_snake_case'] = to_snake_case env.filters['to_kebab_case'] = to_kebab_case env.filters['first'] = lambda x: next(iter(x)) env.filters['skip_first'] = lambda x: list(x)[1:] env.filters['to_c_string'] = lambda x: '\n'.join(('"' + line.replace('"', '\\"') + '"') for line in json.dumps(x, separators=(',', ':')).replace('{"name"', '\n{"name"').split('\n')) env.filters['tokenize'] = tokenize env.filters['diagonalize'] = lambda lst: [lst[:i + 1] for i in range(len(lst))] template = env.from_string(template_file.read()) template_args = { 'interfaces': interfaces, 'value_types': value_types, 'toplevel_interfaces': toplevel_interfaces, 'endpoints': endpoints, 'embedded_endpoint_definitions': embedded_endpoint_definitions } if not args.output is None: output =
np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&19': np.array([0.4964962439921071, 0.3798215458387346]), 'virginica&1&20': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&21': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&22': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&23': np.array([0.22125635302655813, 0.2925832702358638]), 'virginica&1&24': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&25': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&26': np.array([0.10063786451829529, 0.4085974066833644]), 'virginica&1&27': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&28': np.array([0.8441748651745272, -0.6057436494968107]), 'virginica&1&29': np.array([0.6453274192140858, -0.6334259878992301]), 'virginica&1&30': np.array([-0.32199975656257646, 0.7482293552463756]), 'virginica&1&31': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&32': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&33': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&34': np.array([0.2619265016777598, 0.33491141590339474]), 'virginica&1&35': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&36': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&37': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&38': np.array([-0.2562642052727569, 0.6920266972283227]), 'virginica&1&39': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&40': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&41': np.array([-0.34479806250338163, 0.7789143553916729]), 'virginica&1&42': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&43': np.array([0.6253066100206679, -0.5612970743228719]), 'virginica&1&44': np.array([0.4159041613345079, -0.5802838287107943]), 'virginica&1&45': np.array([-0.7749499208750119, 0.8147189440804429]), 'virginica&1&46': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&47': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&48': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&49': np.array([-0.4079256832347186, 0.038455640985860955]), 'virginica&1&50': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&51': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&52': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&53': np.array([-0.6964303997553315, 0.7444536452136676]), 'virginica&1&54': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&55': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&56': np.array([-0.7213651642695392, 0.7718874443854203]), 'virginica&1&57': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&58': np.array([-0.5538416840542331, 0.2026191723113616]), 'virginica&1&59': np.array([-0.3472412936248763, -0.1219322389673262]), 'virginica&1&60': np.array([0.4933316375690332, 0.5272416708629276]), 'virginica&1&61': np.array([0.5041830043657418, 0.5392782673950876]), 'virginica&1&62': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&63': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&64': np.array([0.3093950298647913, 0.1140298206733954]), 'virginica&1&65': np.array([0.5041830043657418, 0.5392782673950876]), 'virginica&1&66': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&67': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&68': np.array([0.40694846236352233, 0.5109051764198169]), 'virginica&1&69': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&70': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&71': np.array([0.415695226122737, 0.5230815102377903]), 'virginica&1&72': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&73': np.array([0.28313251310829024, -0.10978015869508362]), 'virginica&1&74': np.array([0.20013484983664692, -0.3483612449300506]), 'virginica&1&75': np.array([0.0, 0.4756207622944677]), 'virginica&1&76': np.array([0.0, 0.4854334805210761]), 'virginica&1&77': np.array([0.0, -0.16885577975809632]), 'virginica&1&78': np.array([0.0, -0.39580588553855395]), 'virginica&1&79': np.array([0.0, 0.2538072707138344]), 'virginica&1&80': np.array([0.0, 0.4854334805210761]), 'virginica&1&81': np.array([0.0, -0.16885577975809632]), 'virginica&1&82': np.array([0.0, -0.39580588553855395]), 'virginica&1&83': np.array([0.0, 0.4904755652105692]), 'virginica&1&84': np.array([0.0, -0.16885577975809632]), 'virginica&1&85': np.array([0.0, -0.39580588553855395]), 'virginica&1&86': np.array([0.0, 0.5008471974438506]), 'virginica&1&87': np.array([0.0, -0.39580588553855395]), 'virginica&1&88': np.array([0.0, -0.14423919730424817]), 'virginica&1&89': np.array([0.0, -0.3847817540585927]), 'virginica&1&90': np.array([0.37157553889555184, 0.1221600832023858]), 'virginica&1&91': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&92': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&93': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&94': np.array([0.4964962439921071, 0.3798215458387346]), 'virginica&1&95': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&96': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&97': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&98': np.array([0.22125635302655813, 0.2925832702358638]), 'virginica&1&99': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&100': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&101': np.array([0.10063786451829529, 0.4085974066833644]), 'virginica&1&102': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&103': np.array([0.8441748651745272, -0.6057436494968107]), 'virginica&1&104': np.array([0.6453274192140858, -0.6334259878992301]), 'virginica&1&105': np.array([-0.32199975656257646, 0.7482293552463756]), 'virginica&1&106': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&107': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&108': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&109': np.array([0.2619265016777598, 0.33491141590339474]), 'virginica&1&110': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&111': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&112': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&113': np.array([-0.2562642052727569, 0.6920266972283227]), 'virginica&1&114': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&115': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&116': np.array([-0.34479806250338163, 0.7789143553916729]), 'virginica&1&117': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&118': np.array([0.6253066100206679, -0.5612970743228719]), 'virginica&1&119': np.array([0.4159041613345079, -0.5802838287107943]), 'virginica&1&120': np.array([-0.7749499208750119, 0.8147189440804429]), 'virginica&1&121': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&122': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&123': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&124': np.array([-0.4079256832347186, 0.038455640985860955]), 'virginica&1&125': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&126': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&127': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&128': np.array([-0.6964303997553315, 0.7444536452136676]), 'virginica&1&129': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&130': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&131': np.array([-0.7213651642695392, 0.7718874443854203]), 'virginica&1&132': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&133': np.array([-0.5538416840542331, 0.2026191723113616]), 'virginica&1&134': np.array([-0.3472412936248763, -0.1219322389673262]), 'virginica&1&135': np.array([0.5188109114552927, 0.03638964581864269]), 'virginica&1&136': np.array([0.5131478569192371, 0.04203387599862816]), 'virginica&1&137': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&138': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&139': np.array([0.5436097000280874, 0.1461891067488832]), 'virginica&1&140': np.array([0.5131478569192371, 0.04203387599862816]), 'virginica&1&141': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&142': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&143': np.array([0.4788153032824012, 0.08625929936974323]), 'virginica&1&144': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&145': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&146': np.array([0.46583127837967303, 0.09875847161509169]), 'virginica&1&147': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&148': np.array([0.7419884013108898, -0.4595742931114029]), 'virginica&1&149': np.array([0.6092194175719845, -0.5086479426935605]), 'virginica&1&150': np.array([0.37157553889555184, 0.1221600832023858]), 'virginica&1&151': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&152': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&153': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&154': np.array([0.4964962439921071, 0.3798215458387346]), 'virginica&1&155': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&156': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&157': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&158': np.array([0.22125635302655813, 0.2925832702358638]), 'virginica&1&159': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&160': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&161': np.array([0.10063786451829529, 0.4085974066833644]), 'virginica&1&162': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&163': np.array([0.8441748651745272, -0.6057436494968107]), 'virginica&1&164': np.array([0.6453274192140858, -0.6334259878992301]), 'virginica&1&165': np.array([-0.32199975656257646, 0.7482293552463756]), 'virginica&1&166': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&167': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&168': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&169': np.array([0.2619265016777598, 0.33491141590339474]), 'virginica&1&170': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&171': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&172': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&173': np.array([-0.2562642052727569, 0.6920266972283227]), 'virginica&1&174': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&175': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&176': np.array([-0.34479806250338163, 0.7789143553916729]), 'virginica&1&177': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&178': np.array([0.6253066100206679, -0.5612970743228719]), 'virginica&1&179': np.array([0.4159041613345079, -0.5802838287107943]), 'virginica&1&180': np.array([-0.7749499208750119, 0.8147189440804429]), 'virginica&1&181': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&182': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&183': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&184': np.array([-0.4079256832347186, 0.038455640985860955]), 'virginica&1&185': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&186': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&187': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&188': np.array([-0.6964303997553315, 0.7444536452136676]), 'virginica&1&189': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&190': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&191': np.array([-0.7213651642695392, 0.7718874443854203]), 'virginica&1&192': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&193': np.array([-0.5538416840542331, 0.2026191723113616]), 'virginica&1&194': np.array([-0.3472412936248763, -0.1219322389673262]), 'virginica&1&195': np.array([0.5188109114552927, 0.03638964581864269]), 'virginica&1&196': np.array([0.5131478569192371, 0.04203387599862816]), 'virginica&1&197': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&198': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&199': np.array([0.5436097000280874, 0.1461891067488832]), 'virginica&1&200': np.array([0.5131478569192371, 0.04203387599862816]), 'virginica&1&201': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&202': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&203': np.array([0.4788153032824012, 0.08625929936974323]), 'virginica&1&204': np.array([0.7329462736700701, -0.4610490766898857]), 'virginica&1&205': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&206': np.array([0.46583127837967303, 0.09875847161509169]), 'virginica&1&207': np.array([0.5965042032375719, -0.48856644624972617]), 'virginica&1&208': np.array([0.7419884013108898, -0.4595742931114029]), 'virginica&1&209': np.array([0.6092194175719845, -0.5086479426935605]), 'virginica&1&210': np.array([0.37157553889555184, 0.1221600832023858]), 'virginica&1&211': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&212': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&213': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&214': np.array([0.4964962439921071, 0.3798215458387346]), 'virginica&1&215': np.array([0.2463036871609408, 0.24630368716093934]), 'virginica&1&216': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&217': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&218': np.array([0.22125635302655813, 0.2925832702358638]), 'virginica&1&219': np.array([0.9105775730167809, -0.6842162738602727]), 'virginica&1&220': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&221': np.array([0.10063786451829529, 0.4085974066833644]), 'virginica&1&222': np.array([0.6718337295341265, -0.6620422637360074]), 'virginica&1&223': np.array([0.8441748651745272, -0.6057436494968107]), 'virginica&1&224': np.array([0.6453274192140858, -0.6334259878992301]), 'virginica&1&225': np.array([-0.7749499208750119, 0.8147189440804429]), 'virginica&1&226': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&227': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&228': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&229': np.array([-0.4079256832347186, 0.038455640985860955]), 'virginica&1&230': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&231': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&232': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&233': np.array([-0.6964303997553315, 0.7444536452136676]), 'virginica&1&234': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&235': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&236': np.array([-0.7213651642695392, 0.7718874443854203]), 'virginica&1&237': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&238': np.array([-0.5538416840542331, 0.2026191723113616]), 'virginica&1&239': np.array([-0.3472412936248763, -0.1219322389673262]), 'virginica&1&240': np.array([0.056623968925773045, 0.43360725859686644]), 'virginica&1&241': np.array([0.020169511418752378, 0.47015948158260334]), 'virginica&1&242': np.array([0.5806365328450952, -0.4726270680771261]), 'virginica&1&243': np.array([0.41462901544715686, -0.4964318942067897]), 'virginica&1&244': np.array([0.3351719071445682, 0.20616862401308342]), 'virginica&1&245': np.array([0.020169511418752378, 0.47015948158260334]), 'virginica&1&246': np.array([0.5806365328450952, -0.4726270680771261]), 'virginica&1&247': np.array([0.41462901544715686, -0.4964318942067897]), 'virginica&1&248': np.array([0.024556360933646205, 0.4723948285969902]), 'virginica&1&249': np.array([0.5806365328450952, -0.4726270680771261]), 'virginica&1&250': np.array([0.41462901544715686, -0.4964318942067897]), 'virginica&1&251': np.array([-0.0164329511444131, 0.5132208276383963]), 'virginica&1&252': np.array([0.41462901544715686, -0.4964318942067897]), 'virginica&1&253': np.array([0.581569928198426, -0.46134543884925855]), 'virginica&1&254': np.array([0.42361197252581306, -0.5068181610814407]), 'virginica&1&255': np.array([-0.32199975656257646, 0.7482293552463756]), 'virginica&1&256': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&257': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&258': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&259': np.array([0.2619265016777598, 0.33491141590339474]), 'virginica&1&260': np.array([-0.43843349141088417, 0.8642740701867917]), 'virginica&1&261': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&262': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&263': np.array([-0.2562642052727569, 0.6920266972283227]), 'virginica&1&264': np.array([0.7141739659554729, -0.661981914015288]), 'virginica&1&265': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&266': np.array([-0.34479806250338163, 0.7789143553916729]), 'virginica&1&267': np.array([0.4446001433508151, -0.6107546840046901]), 'virginica&1&268': np.array([0.6253066100206679, -0.5612970743228719]), 'virginica&1&269': np.array([0.4159041613345079, -0.5802838287107943]), 'virginica&1&270': np.array([-0.6288817118959938, 0.6849987400957501]), 'virginica&1&271': np.array([-0.6491819158994796, 0.7060292771859485]), 'virginica&1&272': np.array([-0.36354251586275393, 0.01503732165107865]), 'virginica&1&273': np.array([-0.2224264339516076, -0.2751400010362469]), 'virginica&1&274': np.array([-0.3507937472799825, 0.22709708691079003]), 'virginica&1&275': np.array([-0.6491819158994796, 0.7060292771859485]), 'virginica&1&276': np.array([-0.36354251586275393, 0.01503732165107865]), 'virginica&1&277': np.array([-0.2224264339516076, -0.2751400010362469]), 'virginica&1&278': np.array([-0.6219129029345898, 0.6860569455333333]), 'virginica&1&279': np.array([-0.36354251586275393, 0.01503732165107865]), 'virginica&1&280': np.array([-0.2224264339516076, -0.2751400010362469]), 'virginica&1&281': np.array([-0.6423063482710314, 0.7078274136226649]), 'virginica&1&282': np.array([-0.2224264339516076, -0.2751400010362469]), 'virginica&1&283': np.array([-0.38798262782075055, 0.05152547330256509]), 'virginica&1&284': np.array([-0.23804537254556749, -0.24790919248823104]), 'virginica&1&285': np.array([-0.7749499208750119, 0.8147189440804429]), 'virginica&1&286': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&287': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&288': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&289': np.array([-0.4079256832347186, 0.038455640985860955]), 'virginica&1&290': np.array([-0.8040309195416899, 0.8445152504134819]), 'virginica&1&291': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&292': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&293': np.array([-0.6964303997553315, 0.7444536452136676]), 'virginica&1&294': np.array([-0.582650696375085, 0.22335655671229132]), 'virginica&1&295': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&296': np.array([-0.7213651642695392, 0.7718874443854203]), 'virginica&1&297': np.array([-0.33108168891715994, -0.1364781674635115]), 'virginica&1&298': np.array([-0.5538416840542331, 0.2026191723113616]), 'virginica&1&299': np.array([-0.3472412936248763, -0.1219322389673262]), 'virginica&1&300': np.array([0.4933316375690332, 0.5272416708629276]), 'virginica&1&301': np.array([0.5041830043657418, 0.5392782673950876]), 'virginica&1&302': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&303': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&304': np.array([0.3093950298647913, 0.1140298206733954]), 'virginica&1&305': np.array([0.5041830043657418, 0.5392782673950876]), 'virginica&1&306': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&307': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&308': np.array([0.40694846236352233, 0.5109051764198169]), 'virginica&1&309': np.array([0.25657760110071476, -0.12592645350389117]), 'virginica&1&310': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&311': np.array([0.415695226122737, 0.5230815102377903]), 'virginica&1&312': np.array([0.13717260713320115, -0.36277799079016637]), 'virginica&1&313': np.array([0.28313251310829024, -0.10978015869508362]), 'virginica&1&314': np.array([0.20013484983664692, -0.3483612449300506]), 'virginica&2&0': np.array([0.37157691321004915, 0.12216227283618836]), 'virginica&2&1': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&2': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&3': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&4': np.array([0.4741571944522723, -0.3872697414416878]), 'virginica&2&5': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&6': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&7': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&8': np.array([0.6273836195848199, -0.15720981251964872]), 'virginica&2&9': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&10': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&11': np.array([0.6863652799597699, -0.21335694415409426]), 'virginica&2&12': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&13': np.array([0.11274898124253621, 0.6292927079496371]), 'virginica&2&14': np.array([0.32240464148521225, 0.645858545382009]), 'virginica&2&15': np.array([0.37157691321004915, 0.12216227283618836]), 'virginica&2&16': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&17': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&18': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&19': np.array([0.4741571944522723, -0.3872697414416878]), 'virginica&2&20': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&21': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&22': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&23': np.array([0.6273836195848199, -0.15720981251964872]), 'virginica&2&24': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&25': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&26': np.array([0.6863652799597699, -0.21335694415409426]), 'virginica&2&27': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&28': np.array([0.11274898124253621, 0.6292927079496371]), 'virginica&2&29': np.array([0.32240464148521225, 0.645858545382009]), 'virginica&2&30': np.array([0.5188517506916897, 0.036358567813067386]), 'virginica&2&31': np.array([0.5131939273945454, 0.04199748266790813]), 'virginica&2&32': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&33': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&34': np.array([0.5354807894355184, -0.3418054346754283]), 'virginica&2&35': np.array([0.5131939273945454, 0.04199748266790813]), 'virginica&2&36': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&37': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&38': np.array([0.5917672401610737, -0.061499563231173816]), 'virginica&2&39': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&40': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&41': np.array([0.5967658480721675, -0.06546963852548916]), 'virginica&2&42': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&43': np.array([0.15466782862660866, 0.5877736906472755]), 'virginica&2&44': np.array([0.37833006296225374, 0.5922410451071548]), 'virginica&2&45': np.array([0.8252668830593566, 0.11450866713130668]), 'virginica&2&46': np.array([0.8211795643076095, 0.11869650771610692]), 'virginica&2&47': np.array([0.644166410268985, 0.30120464260998964]), 'virginica&2&48': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&49': np.array([0.8735738195653328, -0.046438180466149094]), 'virginica&2&50': np.array([0.8211795643076095, 0.11869650771610692]), 'virginica&2&51': np.array([0.644166410268985, 0.30120464260998964]), 'virginica&2&52': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&53': np.array([0.8388485924434891, 0.09800790238640067]), 'virginica&2&54': np.array([0.644166410268985, 0.30120464260998964]), 'virginica&2&55': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&56': np.array([0.835455914569297, 0.10189258327760495]), 'virginica&2&57': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&58': np.array([0.6958244586699014, 0.2551528503043789]), 'virginica&2&59': np.array([0.7857855057542923, 0.17526869720012267]), 'virginica&2&60': np.array([-0.5227340800279543, 0.4209267574088147]), 'virginica&2&61': np.array([-0.5140708637198534, 0.4305361238057349]), 'virginica&2&62': np.array([-0.2661726847443776, 0.6902916602462779]), 'virginica&2&63': np.array([-0.2741128763380603, 0.7260889090887469]), 'virginica&2&64': np.array([-0.6188410763351541, -0.22803625884668638]), 'virginica&2&65': np.array([-0.5140708637198534, 0.4305361238057349]), 'virginica&2&66': np.array([-0.2661726847443776, 0.6902916602462779]), 'virginica&2&67': np.array([-0.2741128763380603, 0.7260889090887469]), 'virginica&2&68': np.array([-0.596973015481227, 0.37395461795328944]), 'virginica&2&69': np.array([-0.2661726847443776, 0.6902916602462779]), 'virginica&2&70': np.array([-0.2741128763380603, 0.7260889090887469]), 'virginica&2&71': np.array([-0.5903420131350324, 0.384224764046184]), 'virginica&2&72': np.array([-0.2741128763380603, 0.7260889090887469]), 'virginica&2&73': np.array([-0.3951343262323671, 0.6428414057947632]), 'virginica&2&74': np.array([-0.4001176958439725, 0.6972674869002595]), 'virginica&2&75': np.array([0.0, 0.47562425924289314]), 'virginica&2&76': np.array([0.0, 0.4854368956593117]), 'virginica&2&77': np.array([0.0, 0.7348263896003954]), 'virginica&2&78': np.array([0.0, 0.7920887571493729]), 'virginica&2&79': np.array([0.0, -0.507614207038711]), 'virginica&2&80': np.array([0.0, 0.4854368956593117]), 'virginica&2&81': np.array([0.0, 0.7348263896003954]), 'virginica&2&82': np.array([0.0, 0.7920887571493729]), 'virginica&2&83': np.array([0.0, 0.4039238345412103]), 'virginica&2&84': np.array([0.0, 0.7348263896003954]), 'virginica&2&85': np.array([0.0, 0.7920887571493729]), 'virginica&2&86': np.array([0.0, 0.41580041887839214]), 'virginica&2&87': np.array([0.0, 0.7920887571493729]), 'virginica&2&88': np.array([0.0, 0.6909317817603084]), 'virginica&2&89': np.array([0.0, 0.7700808435239105]), 'virginica&2&90': np.array([0.37157691321004915, 0.12216227283618836]), 'virginica&2&91': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&92': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&93': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&94': np.array([0.4741571944522723, -0.3872697414416878]), 'virginica&2&95': np.array([0.24630541996506908, 0.24630541996506994]), 'virginica&2&96': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&97': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&98': np.array([0.6273836195848199, -0.15720981251964872]), 'virginica&2&99': np.array([0.04449246321056297, 0.7096449459722027]), 'virginica&2&100': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&101': np.array([0.6863652799597699, -0.21335694415409426]), 'virginica&2&102': np.array([0.2953784217387408, 0.6750352694420284]), 'virginica&2&103': np.array([0.11274898124253621, 0.6292927079496371]), 'virginica&2&104': np.array([0.32240464148521225, 0.645858545382009]), 'virginica&2&105': np.array([0.5188517506916897, 0.036358567813067386]), 'virginica&2&106': np.array([0.5131939273945454, 0.04199748266790813]), 'virginica&2&107': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&108': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&109': np.array([0.5354807894355184, -0.3418054346754283]), 'virginica&2&110': np.array([0.5131939273945454, 0.04199748266790813]), 'virginica&2&111': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&112': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&113': np.array([0.5917672401610737, -0.061499563231173816]), 'virginica&2&114': np.array([0.06285591932387397, 0.6914253444924359]), 'virginica&2&115': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&116': np.array([0.5967658480721675, -0.06546963852548916]), 'virginica&2&117': np.array([0.34904320225465857, 0.6233384360811872]), 'virginica&2&118': np.array([0.15466782862660866, 0.5877736906472755]), 'virginica&2&119': np.array([0.37833006296225374, 0.5922410451071548]), 'virginica&2&120': np.array([0.8252668830593566, 0.11450866713130668]), 'virginica&2&121': np.array([0.8211795643076095, 0.11869650771610692]), 'virginica&2&122': np.array([0.644166410268985, 0.30120464260998964]), 'virginica&2&123': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&124': np.array([0.8735738195653328, -0.046438180466149094]), 'virginica&2&125': np.array([0.8211795643076095, 0.11869650771610692]), 'virginica&2&126': np.array([0.644166410268985, 0.30120464260998964]), 'virginica&2&127': np.array([0.7640280271176497, 0.19364537761420375]), 'virginica&2&128': np.array([0.8388485924434891, 0.09800790238640067]), 'virginica&2&129': np.array([0.644166410268985, 0.30120464260998964]),
<gh_stars>10-100 # pylint: disable=E1101 import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset import numpy as np from physionet import PhysioNet, get_data_min_max, variable_time_collate_fn2 from sklearn import model_selection from sklearn import metrics from person_activity import PersonActivity def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) def log_normal_pdf(x, mean, logvar, mask): const = torch.from_numpy(np.array([2. * np.pi])).float().to(x.device) const = torch.log(const) return -.5 * (const + logvar + (x - mean) ** 2. / torch.exp(logvar)) * mask def normal_kl(mu1, lv1, mu2, lv2): v1 = torch.exp(lv1) v2 = torch.exp(lv2) lstd1 = lv1 / 2. lstd2 = lv2 / 2. kl = lstd2 - lstd1 + ((v1 + (mu1 - mu2) ** 2.) / (2. * v2)) - .5 return kl def mean_squared_error(orig, pred, mask): error = (orig - pred) ** 2 error = error * mask return error.sum() / mask.sum() def normalize_masked_data(data, mask, att_min, att_max): # we don't want to divide by zero att_max[att_max == 0.] = 1. if (att_max != 0.).all(): data_norm = (data - att_min) / att_max else: raise Exception("Zero!") if torch.isnan(data_norm).any(): raise Exception("nans!") # set masked out elements back to zero data_norm[mask == 0] = 0 return data_norm, att_min, att_max def evaluate(dim, rec, dec, test_loader, args, num_sample=10, device="cuda"): mse, test_n = 0.0, 0.0 with torch.no_grad(): for test_batch in test_loader: test_batch = test_batch.to(device) observed_data, observed_mask, observed_tp = ( test_batch[:, :, :dim], test_batch[:, :, dim: 2 * dim], test_batch[:, :, -1], ) if args.sample_tp and args.sample_tp < 1: subsampled_data, subsampled_tp, subsampled_mask = subsample_timepoints( observed_data.clone(), observed_tp.clone(), observed_mask.clone(), args.sample_tp) else: subsampled_data, subsampled_tp, subsampled_mask = \ observed_data, observed_tp, observed_mask out = rec(torch.cat((subsampled_data, subsampled_mask), 2), subsampled_tp) qz0_mean, qz0_logvar = ( out[:, :, : args.latent_dim], out[:, :, args.latent_dim:], ) epsilon = torch.randn( num_sample, qz0_mean.shape[0], qz0_mean.shape[1], qz0_mean.shape[2] ).to(device) z0 = epsilon * torch.exp(0.5 * qz0_logvar) + qz0_mean z0 = z0.view(-1, qz0_mean.shape[1], qz0_mean.shape[2]) batch, seqlen = observed_tp.size() time_steps = ( observed_tp[None, :, :].repeat(num_sample, 1, 1).view(-1, seqlen) ) pred_x = dec(z0, time_steps) pred_x = pred_x.view(num_sample, -1, pred_x.shape[1], pred_x.shape[2]) pred_x = pred_x.mean(0) mse += mean_squared_error(observed_data, pred_x, observed_mask) * batch test_n += batch return mse / test_n def compute_losses(dim, dec_train_batch, qz0_mean, qz0_logvar, pred_x, args, device): observed_data, observed_mask \ = dec_train_batch[:, :, :dim], dec_train_batch[:, :, dim:2*dim] noise_std = args.std # default 0.1 noise_std_ = torch.zeros(pred_x.size()).to(device) + noise_std noise_logvar = 2. * torch.log(noise_std_).to(device) logpx = log_normal_pdf(observed_data, pred_x, noise_logvar, observed_mask).sum(-1).sum(-1) pz0_mean = pz0_logvar = torch.zeros(qz0_mean.size()).to(device) analytic_kl = normal_kl(qz0_mean, qz0_logvar, pz0_mean, pz0_logvar).sum(-1).sum(-1) if args.norm: logpx /= observed_mask.sum(-1).sum(-1) analytic_kl /= observed_mask.sum(-1).sum(-1) return logpx, analytic_kl def evaluate_classifier(model, test_loader, dec=None, args=None, classifier=None, dim=41, device='cuda', reconst=False, num_sample=1): pred = [] true = [] test_loss = 0 for test_batch, label in test_loader: test_batch, label = test_batch.to(device), label.to(device) batch_len = test_batch.shape[0] observed_data, observed_mask, observed_tp \ = test_batch[:, :, :dim], test_batch[:, :, dim:2*dim], test_batch[:, :, -1] with torch.no_grad(): out = model( torch.cat((observed_data, observed_mask), 2), observed_tp) if reconst: qz0_mean, qz0_logvar = out[:, :, :args.latent_dim], out[:, :, args.latent_dim:] epsilon = torch.randn( num_sample, qz0_mean.shape[0], qz0_mean.shape[1], qz0_mean.shape[2]).to(device) z0 = epsilon * torch.exp(.5 * qz0_logvar) + qz0_mean z0 = z0.view(-1, qz0_mean.shape[1], qz0_mean.shape[2]) if args.classify_pertp: pred_x = dec(z0, observed_tp[None, :, :].repeat( num_sample, 1, 1).view(-1, observed_tp.shape[1])) #pred_x = pred_x.view(num_sample, batch_len, pred_x.shape[1], pred_x.shape[2]) out = classifier(pred_x) else: out = classifier(z0) if args.classify_pertp: N = label.size(-1) out = out.view(-1, N) label = label.view(-1, N) _, label = label.max(-1) test_loss += nn.CrossEntropyLoss()(out, label.long()).item() * batch_len * 50. else: label = label.unsqueeze(0).repeat_interleave( num_sample, 0).view(-1) test_loss += nn.CrossEntropyLoss()(out, label).item() * batch_len * num_sample pred.append(out.cpu().numpy()) true.append(label.cpu().numpy()) pred = np.concatenate(pred, 0) true = np.concatenate(true, 0) acc = np.mean(pred.argmax(1) == true) auc = metrics.roc_auc_score( true, pred[:, 1]) if not args.classify_pertp else 0. return test_loss/pred.shape[0], acc, auc def get_mimiciii_data(args): input_dim = 12 x = np.load('../../../neuraltimeseries/Dataset/final_input3.npy') y = np.load('../../../neuraltimeseries/Dataset/final_output3.npy') x = x[:, :25] x = np.transpose(x, (0, 2, 1)) # normalize values and time observed_vals, observed_mask, observed_tp = x[:, :, :input_dim], x[:, :, input_dim:2*input_dim], x[:, :, -1] if np.max(observed_tp) != 0.: observed_tp = observed_tp / np.max(observed_tp) if not args.nonormalize: for k in range(input_dim): data_min, data_max = float('inf'), 0. for i in range(observed_vals.shape[0]): for j in range(observed_vals.shape[1]): if observed_mask[i, j, k]: data_min = min(data_min, observed_vals[i, j, k]) data_max = max(data_max, observed_vals[i, j, k]) #print(data_min, data_max) if data_max == 0: data_max = 1 observed_vals[:, :, k] = ( observed_vals[:, :, k] - data_min)/data_max # set masked out elements back to zero observed_vals[observed_mask == 0] = 0 print(observed_vals[0], observed_tp[0]) print(x.shape, y.shape) kfold = model_selection.StratifiedKFold( n_splits=5, shuffle=True, random_state=0) splits = [(train_inds, test_inds) for train_inds, test_inds in kfold.split(np.zeros(len(y)), y)] x_train, y_train = x[splits[args.split][0]], y[splits[args.split][0]] test_data_x, test_data_y = x[splits[args.split] [1]], y[splits[args.split][1]] if not args.old_split: train_data_x, val_data_x, train_data_y, val_data_y = \ model_selection.train_test_split( x_train, y_train, stratify=y_train, test_size=0.2, random_state=0) else: frac = int(0.8*x_train.shape[0]) train_data_x, val_data_x = x_train[:frac], x_train[frac:] train_data_y, val_data_y = y_train[:frac], y_train[frac:] print(train_data_x.shape, train_data_y.shape, val_data_x.shape, val_data_y.shape, test_data_x.shape, test_data_y.shape) print(np.sum(test_data_y)) train_data_combined = TensorDataset(torch.from_numpy(train_data_x).float(), torch.from_numpy(train_data_y).long().squeeze()) val_data_combined = TensorDataset(torch.from_numpy(val_data_x).float(), torch.from_numpy(val_data_y).long().squeeze()) test_data_combined = TensorDataset(torch.from_numpy(test_data_x).float(), torch.from_numpy(test_data_y).long().squeeze()) train_dataloader = DataLoader( train_data_combined, batch_size=args.batch_size, shuffle=False) test_dataloader = DataLoader( test_data_combined, batch_size=args.batch_size, shuffle=False) val_dataloader = DataLoader( val_data_combined, batch_size=args.batch_size, shuffle=False) data_objects = {"train_dataloader": train_dataloader, "test_dataloader": test_dataloader, "val_dataloader": val_dataloader, "input_dim": input_dim} return data_objects def get_physionet_data(args, device, q, flag=1): train_dataset_obj = PhysioNet('data/physionet', train=True, quantization=q, download=True, n_samples=min(10000, args.n), device=device) # Use custom collate_fn to combine samples with arbitrary time observations. # Returns the dataset along with mask and time steps test_dataset_obj = PhysioNet('data/physionet', train=False, quantization=q, download=True, n_samples=min(10000, args.n), device=device) # Combine and shuffle samples from physionet Train and physionet Test total_dataset = train_dataset_obj[:len(train_dataset_obj)] if not args.classif: # Concatenate samples from original Train and Test sets # Only 'training' physionet samples are have labels. # Therefore, if we do classifiction task, we don't need physionet 'test' samples. total_dataset = total_dataset + \ test_dataset_obj[:len(test_dataset_obj)] print(len(total_dataset)) # Shuffle and split train_data, test_data = model_selection.train_test_split(total_dataset, train_size=0.8, random_state=42, shuffle=True) record_id, tt, vals, mask, labels = train_data[0] # n_samples = len(total_dataset) input_dim = vals.size(-1) data_min, data_max = get_data_min_max(total_dataset, device) batch_size = min(min(len(train_dataset_obj), args.batch_size), args.n) if flag: test_data_combined = variable_time_collate_fn(test_data, device, classify=args.classif, data_min=data_min, data_max=data_max) if args.classif: train_data, val_data = model_selection.train_test_split(train_data, train_size=0.8, random_state=11, shuffle=True) train_data_combined = variable_time_collate_fn( train_data, device, classify=args.classif, data_min=data_min, data_max=data_max) val_data_combined = variable_time_collate_fn( val_data, device, classify=args.classif, data_min=data_min, data_max=data_max) print(train_data_combined[1].sum( ), val_data_combined[1].sum(), test_data_combined[1].sum()) print(train_data_combined[0].size(), train_data_combined[1].size(), val_data_combined[0].size(), val_data_combined[1].size(), test_data_combined[0].size(), test_data_combined[1].size()) train_data_combined = TensorDataset( train_data_combined[0], train_data_combined[1].long().squeeze()) val_data_combined = TensorDataset( val_data_combined[0], val_data_combined[1].long().squeeze()) test_data_combined = TensorDataset( test_data_combined[0], test_data_combined[1].long().squeeze()) else: train_data_combined = variable_time_collate_fn( train_data, device, classify=args.classif, data_min=data_min, data_max=data_max) print(train_data_combined.size(), test_data_combined.size()) train_dataloader = DataLoader( train_data_combined, batch_size=batch_size, shuffle=False) test_dataloader = DataLoader( test_data_combined, batch_size=batch_size, shuffle=False) else: train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=False, collate_fn=lambda batch: variable_time_collate_fn2(batch, args, device, data_type="train", data_min=data_min, data_max=data_max)) test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=False, collate_fn=lambda batch: variable_time_collate_fn2(batch, args, device, data_type="test", data_min=data_min, data_max=data_max)) attr_names = train_dataset_obj.params data_objects = {"dataset_obj": train_dataset_obj, "train_dataloader": train_dataloader, "test_dataloader": test_dataloader, "input_dim": input_dim, "n_train_batches": len(train_dataloader), "n_test_batches": len(test_dataloader), "attr": attr_names, # optional "classif_per_tp": False, # optional "n_labels": 1} # optional if args.classif: val_dataloader = DataLoader( val_data_combined, batch_size=batch_size, shuffle=False) data_objects["val_dataloader"] = val_dataloader return data_objects def variable_time_collate_fn(batch, device=torch.device("cpu"), classify=False, activity=False, data_min=None, data_max=None): """ Expects a batch of time series data in the form of (record_id, tt, vals, mask, labels) where - record_id is a patient id - tt is a 1-dimensional tensor containing T time values of observations. - vals is a (T, D) tensor containing observed values for D variables. - mask is a (T, D) tensor containing 1 where values were observed and 0 otherwise. - labels is a list of labels for the current patient, if labels are available. Otherwise None. Returns: combined_tt: The union of all time observations. combined_vals: (M, T, D) tensor containing the observed values. combined_mask: (M, T, D) tensor containing 1 where values were observed and 0 otherwise. """ D = batch[0][2].shape[1] # number of labels N = batch[0][-1].shape[1] if activity else 1 len_tt = [ex[1].size(0) for ex in batch] maxlen = np.max(len_tt) enc_combined_tt = torch.zeros([len(batch), maxlen]).to(device) enc_combined_vals = torch.zeros([len(batch), maxlen, D]).to(device) enc_combined_mask = torch.zeros([len(batch), maxlen, D]).to(device) if classify: if activity: combined_labels = torch.zeros([len(batch), maxlen, N]).to(device) else: combined_labels = torch.zeros([len(batch), N]).to(device) for b, (record_id, tt, vals, mask, labels) in enumerate(batch): currlen = tt.size(0) enc_combined_tt[b, :currlen] = tt.to(device) enc_combined_vals[b, :currlen] = vals.to(device) enc_combined_mask[b, :currlen] = mask.to(device) if classify: if activity: combined_labels[b, :currlen] = labels.to(device) else: combined_labels[b] = labels.to(device) if not activity:
<reponame>usegalaxy-no/usegalaxy #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_redis_instance description: - A Google Cloud Redis instance. short_description: Creates a GCP Instance author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present type: str alternative_location_id: description: - Only applicable to STANDARD_HA tier which protects the instance against zonal failures by provisioning it across two zones. - If provided, it must be a different zone from the one provided in [locationId]. required: false type: str auth_enabled: description: - Optional. Indicates whether OSS Redis AUTH is enabled for the instance. If set to "true" AUTH is enabled on the instance. - Default value is "false" meaning AUTH is disabled. required: false default: 'false' type: bool authorized_network: description: - The full name of the Google Compute Engine network to which the instance is connected. If left unspecified, the default network will be used. required: false type: str connect_mode: description: - The connection mode of the Redis instance. - 'Some valid choices include: "DIRECT_PEERING", "PRIVATE_SERVICE_ACCESS"' required: false default: DIRECT_PEERING type: str display_name: description: - An arbitrary and optional user-provided name for the instance. required: false type: str labels: description: - Resource labels to represent user provided metadata. required: false type: dict redis_configs: description: - Redis configuration parameters, according to U(http://redis.io/topics/config). - 'Please check Memorystore documentation for the list of supported parameters: U(https://cloud.google.com/memorystore/docs/redis/reference/rest/v1/projects.locations.instances#Instance.FIELDS.redis_configs) .' required: false type: dict location_id: description: - The zone where the instance will be provisioned. If not provided, the service will choose a zone for the instance. For STANDARD_HA tier, instances will be created across two zones for protection against zonal failures. If [alternativeLocationId] is also provided, it must be different from [locationId]. required: false type: str name: description: - The ID of the instance or a fully qualified identifier for the instance. required: true type: str memory_size_gb: description: - Redis memory size in GiB. required: true type: int redis_version: description: - 'The version of Redis software. If not provided, latest supported version will be used. Currently, the supported values are: - REDIS_5_0 for Redis 5.0 compatibility - REDIS_4_0 for Redis 4.0 compatibility - REDIS_3_2 for Redis 3.2 compatibility .' required: false type: str reserved_ip_range: description: - The CIDR range of internal addresses that are reserved for this instance. If not provided, the service will choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. Ranges must be unique and non-overlapping with existing subnets in an authorized network. required: false type: str tier: description: - 'The service tier of the instance. Must be one of these values: - BASIC: standalone instance - STANDARD_HA: highly available primary/replica instances .' - 'Some valid choices include: "BASIC", "STANDARD_HA"' required: false default: BASIC type: str region: description: - The name of the Redis region of the instance. required: true type: str project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list elements: str env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - 'API Reference: U(https://cloud.google.com/memorystore/docs/redis/reference/rest/)' - 'Official Documentation: U(https://cloud.google.com/memorystore/docs/redis/)' - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: create a network google.cloud.gcp_compute_network: name: network-instance project: "{{ gcp_project }}" auth_kind: "{{ gcp_cred_kind }}" service_account_file: "{{ gcp_cred_file }}" state: present register: network - name: create a instance google.cloud.gcp_redis_instance: name: instance37 tier: STANDARD_HA memory_size_gb: 1 region: us-central1 location_id: us-central1-a redis_version: REDIS_3_2 display_name: Ansible Test Instance reserved_ip_range: 192.168.0.0/29 labels: my_key: my_val other_key: other_val project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" state: present ''' RETURN = ''' alternativeLocationId: description: - Only applicable to STANDARD_HA tier which protects the instance against zonal failures by provisioning it across two zones. - If provided, it must be a different zone from the one provided in [locationId]. returned: success type: str authEnabled: description: - Optional. Indicates whether OSS Redis AUTH is enabled for the instance. If set to "true" AUTH is enabled on the instance. - Default value is "false" meaning AUTH is disabled. returned: success type: bool authorizedNetwork: description: - The full name of the Google Compute Engine network to which the instance is connected. If left unspecified, the default network will be used. returned: success type: str connectMode: description: - The connection mode of the Redis instance. returned: success type: str createTime: description: - The time the instance was created in RFC3339 UTC "Zulu" format, accurate to nanoseconds. returned: success type: str currentLocationId: description: - The current zone where the Redis endpoint is placed. - For Basic Tier instances, this will always be the same as the [locationId] provided by the user at creation time. For Standard Tier instances, this can be either [locationId] or [alternativeLocationId] and can change after a failover event. returned: success type: str displayName: description: - An arbitrary and optional user-provided name for the instance. returned: success type: str host: description: - Hostname or IP address of the exposed Redis endpoint used by clients to connect to the service. returned: success type: str labels: description: - Resource labels to represent user provided metadata. returned: success type: dict redisConfigs: description: - Redis configuration parameters, according to U(http://redis.io/topics/config). - 'Please check Memorystore documentation for the list of supported parameters: U(https://cloud.google.com/memorystore/docs/redis/reference/rest/v1/projects.locations.instances#Instance.FIELDS.redis_configs) .' returned: success type: dict locationId: description: - The zone where the instance will be provisioned. If not provided, the service will choose a zone for the instance. For STANDARD_HA tier, instances will be created across two zones for protection against zonal failures. If [alternativeLocationId] is also provided, it must be different from [locationId]. returned: success type: str name: description: - The ID of the instance or a fully qualified identifier for the instance. returned: success type: str memorySizeGb: description: - Redis memory size in GiB. returned: success type: int port: description: - The port number of the exposed Redis endpoint. returned: success type: int persistenceIamIdentity: description: - Output only. Cloud IAM identity used by import / export operations to transfer data to/from Cloud Storage. Format is "serviceAccount:". - The value may change over time for a given instance so should be checked before each import/export operation. returned: success type: str redisVersion: description: - 'The version of Redis software. If not provided, latest supported version will be used. Currently, the supported values are: - REDIS_5_0 for Redis 5.0 compatibility - REDIS_4_0 for Redis 4.0
<gh_stars>1-10 from unittest.mock import PropertyMock from django.db.models import Q from unittest import mock, skip import datetime from django.core.management import call_command from django.test import tag, TestCase, SimpleTestCase from django.urls import reverse from django.utils.text import slugify from django.utils.timezone import get_current_timezone from freezegun import freeze_time from jmespath import search as s from fixturedb.factories.win import create_win_factory from mi.views.team_type_views import BaseTeamTypeMIView from mi.views.ukregion_views import UKRegionWinsFilterMixin, UKRegionTeamTypeNameMixin, UKRegionValidOptionsMixin from wins.constants import HQ_TEAM_REGION_OR_POST, UK_REGIONS, UK_SUPER_REGIONS from wins.factories import AdvisorFactory from mi.tests.base_test_case import MiApiViewsWithWinsBaseTestCase from mi.tests.utils import GenericTopNonHvcWinsTestMixin, GenericWinTableTestMixin, GenericDetailsTestMixin, \ GenericCampaignsViewTestCase, GenericMonthlyViewTestCase @freeze_time(MiApiViewsWithWinsBaseTestCase.frozen_date_17) class TeamTypeBaseViewTestCase(MiApiViewsWithWinsBaseTestCase): TEST_TEAM = 'post:Albania - Tirana' TEAM_TYPE = 'post' TEST_TEAM_NAME = TEST_TEAM.lstrip(f'{TEAM_TYPE}:') TEST_TEAM_SLUG = slugify(TEST_TEAM_NAME) export_value = 100000 win_date_2017 = datetime.datetime( 2017, 4, 25, tzinfo=get_current_timezone()) win_date_2016 = datetime.datetime( 2016, 5, 25, tzinfo=get_current_timezone()) fy_2016_last_date = datetime.datetime( 2017, 3, 31, tzinfo=get_current_timezone()) @classmethod def setUpClass(cls): super().setUpClass() call_command('create_missing_hvcs', verbose=False) def get_url_for_year(self, year, base_url=None): if not base_url: base_url = self.view_base_url return '{base}?year={year}'.format(base=base_url, year=year) class PostTopNonHVCViewTestCase(TeamTypeBaseViewTestCase, GenericTopNonHvcWinsTestMixin): export_value = 9992 post_top_nonhvc_url = reverse('mi:posts_top_nonhvc', kwargs={ "team_slug": "albania-tirana"}) post_topnonhvc_url_invalid = reverse( 'mi:posts_top_nonhvc', kwargs={"team_slug": "ABC"}) post_topnonhvc_url_missing_post_kwarg = reverse( 'mi:posts_top_nonhvc', kwargs={"team_slug": None}) fin_years = [2016, 2017] def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='post', default_hq_team='post:Albania - Tirana' ) self.view_base_url = self.post_top_nonhvc_url def test_fake_post_404(self): self.view_base_url = self.post_topnonhvc_url_invalid self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_missing_post_404(self): self.view_base_url = self.post_topnonhvc_url_missing_post_kwarg self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) class PostWinTableTestCase(TeamTypeBaseViewTestCase, GenericWinTableTestMixin): TEST_COUNTRY_CODE = 'IE' fin_years = [2016, 2017] expected_response = { "post": { "id": "albania-tirana", "name": "Albania - Tirana", }, "avg_time_to_confirm": 0.0, "wins": { "hvc": [], } } def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='post', default_hq_team='post:Albania - Tirana' ) self.post_win_table_url = reverse('mi:post_win_table', kwargs={ 'team_slug': 'albania-tirana' }) self.post_win_table_url_invalid = reverse('mi:post_win_table', kwargs={ 'team_slug': 'notalbania-tirana' }) self.view_base_url = self.post_win_table_url class PostListViewTestCase(TeamTypeBaseViewTestCase): view_base_url = reverse('mi:post') def test_list_of_posts(self): self.url = self.get_url_for_year(2016) response_data = self._api_response_data # must be a subset of the full HQ_TEAM_REGION_OR_POST self.assertTrue(len(response_data) <= len(HQ_TEAM_REGION_OR_POST)) # must be same length as the HQ_TEAM_REGION_OR_POST list filtered by team type self.assertEqual( len(response_data), len({k: v for k, v in HQ_TEAM_REGION_OR_POST if k.startswith('post')}) ) self.assertEqual(set(response_data[0].keys()), {'id', 'name'}) # year doesn't matter self.expected_response = response_data self.url = self.get_url_for_year(2017) self.assertResponse() class PostDetailViewTestCase(TeamTypeBaseViewTestCase, GenericDetailsTestMixin): TEST_TEAM = 'post:Albania - Tirana' TEAM_TYPE = 'post' TEST_TEAM_NAME = TEST_TEAM.lstrip(f'{TEAM_TYPE}:') TEST_TEAM_SLUG = slugify(TEST_TEAM_NAME) def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='post', default_hq_team=self.TEST_TEAM ) self.post_detail_url = reverse('mi:post_detail', kwargs={ 'team_slug': self.TEST_TEAM_SLUG }) self.post_detail_url_invalid = reverse('mi:post_detail', kwargs={ 'team_slug': 'notalbania-tirana' }) self.post_detail_url_missing_post_kwarg = reverse( 'mi:post_detail', kwargs={"team_slug": None}) self.view_base_url = self.post_detail_url self.expected_response = dict( id=self.TEST_TEAM_SLUG, name='Albania - Tirana', **self.expected_response ) def test_fake_post_detail_404(self): self.view_base_url = self.post_detail_url_invalid self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_missing_post_detail_404(self): self.view_base_url = self.post_detail_url_missing_post_kwarg self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_detail_wrong_post_doesnt_appear_in_albania(self): self._create_hvc_win( hvc_code=self.TEST_CAMPAIGN_ID, win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE, hq_team="post:Austria - Vienna" ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data self.assert_top_level_keys(api_response) self.assert_no_wins_no_values(api_response) def assert_top_level_keys(self, response_data): subset = { 'name': self.TEST_TEAM_NAME, 'id': self.TEST_TEAM_SLUG } self.assertDictContainsSubset(subset, response_data) class PostCampaignsViewTestCase(TeamTypeBaseViewTestCase, GenericCampaignsViewTestCase): TEST_TEAM = 'post:Albania - Tirana' TEAM_TYPE = 'post' TEST_TEAM_NAME = TEST_TEAM.lstrip(f'{TEAM_TYPE}:') TEST_TEAM_SLUG = slugify(TEST_TEAM_NAME) CEN_16_HVCS = ["E045", "E046", "E047", "E048", "E214"] CEN_17_HVCS = ["E045", "E046", "E047", "E054", "E119", "E225"] TEST_CAMPAIGN_ID = "E045" TARGET_E017 = 10000000 PRORATED_TARGET = 833333 # target based on the frozen date view_base_url = reverse('mi:posts_campaigns', kwargs={ 'team_slug': TEST_TEAM_SLUG}) expected_response = { "campaigns": [], "name": TEST_TEAM_NAME, "id": TEST_TEAM_SLUG, "hvcs": { "campaigns": [], "target": 0 }, "avg_time_to_confirm": 0.0 } def setUp(self): self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='post', default_hq_team=self.TEST_TEAM ) def test_campaigns_count_no_wins(self): """ In Posts view the campaigns are generated from the wins themselves. So if there are no wins there should be no campaigns """ for year in self.fin_years: with self.subTest(year=year): self.url = self.get_url_for_year(year) api_response = self._api_response_data self.assertEqual(len(api_response["campaigns"]), 0) def test_campaign_progress_colour_1_win(self): """ Given the 'Frozen datetime', progress colour will be zero if there is 1 win. For the posts view it'll always be 'zero' """ self._create_hvc_win( win_date=self.win_date_2017, hvc_code=self.TEST_CAMPAIGN_ID, confirm=True, fin_year=2017, export_value=1, country=self.TEST_COUNTRY_CODE ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data e017_status = s(f"campaigns[?campaign_id=='{self.TEST_CAMPAIGN_ID}'].totals.progress.status", api_response)[0] self.assertEqual(e017_status, "zero") def test_campaign_progress_colour_10_wins(self): """ Given the 'Frozen datetime', progress colour will be zero if there are no wins. For the posts view it'll always be 'zero' """ for _ in range(10): self._create_hvc_win( win_date=self.win_date_2017, hvc_code=self.TEST_CAMPAIGN_ID, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data e017_status = s(f"campaigns[?campaign_id=='{self.TEST_CAMPAIGN_ID}'].totals.progress.status", api_response)[0] self.assertEqual(e017_status, "zero") def test_campaign_progress_percent_confirmed_wins_1(self): """ Test simple progress percent """ for year in self.fin_years: with self.subTest(year=year): win_date = getattr(self, f'win_date_{year}') self.url = self.get_url_for_year(year) self._create_hvc_win( hvc_code=self.TEST_CAMPAIGN_ID, win_date=win_date, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE ) api_response = self._api_response_data # progress should always be 0 self.assertEqual(s("campaigns[?campaign_id=='{}'].totals.progress.confirmed_percent" .format(self.TEST_CAMPAIGN_ID), api_response)[0], 0.0) self.assertEqual(s("campaigns[?campaign_id=='{}'].totals.progress.unconfirmed_percent" .format(self.TEST_CAMPAIGN_ID), api_response)[0], 0.0) class PostMonthsViewTestCase(TeamTypeBaseViewTestCase, GenericMonthlyViewTestCase): TEST_TEAM = 'post:Albania - Tirana' TEAM_TYPE = 'post' TEST_TEAM_NAME = TEST_TEAM.lstrip(f'{TEAM_TYPE}:') TEST_TEAM_SLUG = slugify(TEST_TEAM_NAME) view_base_url = reverse('mi:posts_months', kwargs={ 'team_slug': TEST_TEAM_SLUG}) expected_response = { "campaigns": [], "name": TEST_TEAM_NAME, "id": TEST_TEAM_SLUG, "hvcs": { "campaigns": [], "target": 0 }, "avg_time_to_confirm": 0.0 } def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type=self.TEAM_TYPE, default_hq_team=self.TEST_TEAM ) @tag('uk_region') class UKRegionTopNonHVCViewTestCase(TeamTypeBaseViewTestCase, GenericTopNonHvcWinsTestMixin): export_value = 9992 uk_region_top_nonhvc_url = reverse('mi:uk_regions_top_nonhvc', kwargs={ "team_slug": "south-west"}) uk_region_topnonhvc_url_invalid = reverse( 'mi:uk_regions_top_nonhvc', kwargs={"team_slug": "ABC"}) uk_region_topnonhvc_url_missing_uk_region_kwarg = reverse( 'mi:uk_regions_top_nonhvc', kwargs={"team_slug": None}) fin_years = [2016, 2017] def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='itt', default_hq_team='itt:DIT South West' ) self.view_base_url = self.uk_region_top_nonhvc_url def test_fake_post_404(self): self.view_base_url = self.uk_region_topnonhvc_url_invalid self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_missing_post_404(self): self.view_base_url = self.uk_region_topnonhvc_url_missing_uk_region_kwarg self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) @tag('uk_region') class UKRegionWinTableTestCase(TeamTypeBaseViewTestCase, GenericWinTableTestMixin): TEST_COUNTRY_CODE = 'IE' fin_years = [2016, 2017] expected_response = { "uk_region": { "id": "south-west", "name": "South West", }, "avg_time_to_confirm": 0.0, "wins": { "hvc": [], } } def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='itt', default_hq_team='itt:DIT South West' ) self.uk_region_win_table_url = reverse('mi:uk_regions_win_table', kwargs={ 'team_slug': 'south-west' }) self.uk_region_win_table_url_invalid = reverse('mi:uk_regions_win_table', kwargs={ 'team_slug': 'notsouth-west' }) self.view_base_url = self.uk_region_win_table_url @tag('uk_region') class UKRegionListViewTestCase(TeamTypeBaseViewTestCase): view_base_url = reverse('mi:uk_regions') def test_list_of_uk_regions(self): self.url = self.get_url_for_year(2016) response_data = self._api_response_data # must be same length as the UK_SUPER_REGIONS self.assertEqual( len(response_data['region_groups']), len(UK_SUPER_REGIONS) ) # year doesn't matter self.expected_response = { "region_groups": [ { "name": "Northern Powerhouse", "regions": [ { "id": "north-west", "name": "North West", }, { "id": "north-east", "name": "North East", }, { "id": "yorkshire-and-the-humber", "name": "Yorkshire and The Humber", } ], "devolved": False, }, { "name": "Midlands Engine", "regions": [ { "id": "east-midlands", "name": "East Midlands", }, { "id": "west-midlands", "name": "West Midlands", } ], "devolved": False, }, { "name": "London", "regions": [ { "id": "london", "name": "London", } ], "devolved": False, }, { "name": "South", "regions": [ { "id": "east-of-england", "name": "East of England", }, { "id": "south-east", "name": "South East", }, { "id": "south-west", "name": "South West", } ], "devolved": False, }, { "name": "Devolved Administrations", "regions": [ { "id": "northern-ireland", "name": "Northern Ireland", }, { "id": "scotland", "name": "Scotland", }, { "id": "wales", "name": "Wales", } ], "devolved": True, } ] } self.url = self.get_url_for_year(2017) self.assertResponse() @tag('uk_region') class UKRegionDetailViewTestCase(TeamTypeBaseViewTestCase, GenericDetailsTestMixin): TEST_TEAM = 'south-west' TEAM_TYPE = 'uk_region' TEST_TEAM_NAME = "South West" TEST_TEAM_SLUG = slugify(TEST_TEAM_NAME) expected_response = { **GenericDetailsTestMixin.expected_response, "name": TEST_TEAM_NAME, "id": TEST_TEAM_SLUG, 'target': None, "avg_time_to_confirm": 0.0, 'export_experience': {'total': {'number': {'confirmed': 0, 'total': 0, 'unconfirmed': 0}, 'value': {'confirmed': 0, 'total': 0, 'unconfirmed': 0}}}, } def setUp(self): super().setUp() self._win_factory_function = create_win_factory( self.user, sector_choices=self.TEAM_1_SECTORS, default_team_type='itt', default_hq_team='itt:DIT South West' ) self.uk_region_detail_url = reverse('mi:uk_regions_detail', kwargs={ 'team_slug': self.TEST_TEAM_SLUG }) self.uk_region_detail_url_invalid = reverse('mi:uk_regions_detail', kwargs={ 'team_slug': 'notsouth-west' }) self.uk_region_detail_url_missing_uk_region_kwarg = reverse( 'mi:uk_regions_detail', kwargs={"team_slug": None}) self.view_base_url = self.uk_region_detail_url self.expected_response = dict( **self.expected_response ) def test_fake_uk_region_detail_404(self): self.view_base_url = self.uk_region_detail_url_invalid self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_missing_uk_region_detail_404(self): self.view_base_url = self.uk_region_detail_url_missing_uk_region_kwarg self.url = self.get_url_for_year(2017) self._get_api_response(self.url, status_code=404) def test_detail_wrong_uk_region_doesnt_appear_in_south_west(self): self._create_hvc_win( hvc_code=self.TEST_CAMPAIGN_ID, win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE, hq_team="itt:DIT Team East" ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data self.assert_top_level_keys(api_response) self.assert_no_wins_no_values(api_response) def assert_top_level_keys(self, response_data): subset = { 'name': self.TEST_TEAM_NAME, 'id': self.TEST_TEAM_SLUG } self.assertDictContainsSubset(subset, response_data) def test_detail_hvc_win_appear_in_south_west(self): self._create_hvc_win( hvc_code=self.TEST_CAMPAIGN_ID, win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE, hq_team="itt:DIT South West" ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data self.assert_top_level_keys(api_response) self.assertEqual(api_response["wins"]["export"] ["hvc"]["number"]["confirmed"], 1) def test_detail_non_hvc_win_appear_in_south_west(self): win = self._create_non_hvc_win( win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE, ) win.team_type = 'itt' win.hq_team = "itt:DIT South West" win.save() self.url = self.get_url_for_year(2017) api_response = self._api_response_data self.assert_top_level_keys(api_response) self.assertEqual(api_response["wins"]["export"] ["non_hvc"]["number"]["confirmed"], 1) def test_detail_non_hvc_win_appear_in_south_west_even_with_diff_contributor(self): win = self._create_non_hvc_win( win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE, ) win.team_type = 'itt' win.hq_team = "itt:DIT South West" win.save() AdvisorFactory( win=win, name='<NAME>', team_type='itt', hq_team="itt:DIT North West" ) self.url = self.get_url_for_year(2017) api_response = self._api_response_data self.assert_top_level_keys(api_response) self.assertEqual(api_response["wins"]["export"] ["non_hvc"]["number"]["confirmed"], 1) @skip('until contributing wins is implemented') def test_non_hvc_win_by_north_west_but_contributed_by_south_west_appear_in_south_west(self): win = self._create_non_hvc_win( win_date=self.win_date_2017, confirm=True, fin_year=2017, export_value=self.export_value, country=self.TEST_COUNTRY_CODE ) win.team_type = 'itt'
""" Base class for tensor-product style meshes """ import numpy as np import scipy.sparse as sp import properties from discretize.base.base_mesh import BaseMesh from discretize.utils import ( is_scalar, as_array_n_by_dim, unpack_widths, mkvc, ndgrid, spzeros, sdiag, sdinv, TensorType, interpolation_matrix, ) from discretize.utils.code_utils import deprecate_method, deprecate_property import warnings class BaseTensorMesh(BaseMesh): """ Base class for tensor-product style meshes This class contains properites and methods that are common to cartesian and cylindrical meshes defined by tensor-produts of vectors describing cell spacings. Do not use this class directly, instead, inherit it if you plan to develop a tensor-style mesh (e.g. a spherical mesh) or use the :meth:`discretize.TensorMesh` class to create a cartesian tensor mesh. """ _meshType = "BASETENSOR" _aliases = { **BaseMesh._aliases, **{ "gridCC": "cell_centers", "gridN": "nodes", "gridFx": "faces_x", "gridFy": "faces_y", "gridFz": "faces_z", "gridEx": "edges_x", "gridEy": "edges_y", "gridEz": "edges_z", }, } _unitDimensions = [1, 1, 1] # properties h = properties.Tuple( "h is a list containing the cell widths of the tensor mesh in each " "dimension.", properties.Array( "widths of the tensor mesh in a single dimension", dtype=float, shape=("*",), ), min_length=1, max_length=3, coerce=True, required=True, ) def __init__(self, h=None, origin=None, **kwargs): h_in = h if "x0" in kwargs: origin = kwargs.pop('x0') origin_in = origin # Sanity Checks if not isinstance(h_in, (list, tuple)): raise TypeError("h_in must be a list, not {}".format(type(h_in))) if len(h_in) not in [1, 2, 3]: raise ValueError( "h_in must be of dimension 1, 2, or 3 not {}".format(len(h_in)) ) # build h h = list(range(len(h_in))) for i, h_i in enumerate(h_in): if is_scalar(h_i) and not isinstance(h_i, np.ndarray): # This gives you something over the unit cube. h_i = self._unitDimensions[i] * np.ones(int(h_i)) / int(h_i) elif isinstance(h_i, (list, tuple)): h_i = unpack_widths(h_i) if not isinstance(h_i, np.ndarray): raise TypeError("h[{0:d}] is not a numpy array.".format(i)) if len(h_i.shape) != 1: raise ValueError("h[{0:d}] must be a 1D numpy array.".format(i)) h[i] = h_i[:] # make a copy. # Origin of the mesh origin = np.zeros(len(h)) if origin_in is not None: if len(h) != len(origin_in): raise ValueError("Dimension mismatch. origin != len(h)") for i in range(len(h)): x_i, h_i = origin_in[i], h[i] if is_scalar(x_i): origin[i] = x_i elif x_i == "0": origin[i] = 0.0 elif x_i == "C": origin[i] = -h_i.sum() * 0.5 elif x_i == "N": origin[i] = -h_i.sum() else: raise Exception( "origin[{0:d}] must be a scalar or '0' to be zero, " "'C' to center, or 'N' to be negative. The input value" " {1} {2} is invalid".format(i, x_i, type(x_i)) ) if "n" in kwargs.keys(): n = kwargs.pop("n") if np.any(n != np.array([x.size for x in h])): raise ValueError("Dimension mismatch. The provided n doesn't h") else: n = np.array([x.size for x in h]) super(BaseTensorMesh, self).__init__(n, origin=origin, **kwargs) # Ensure h contains 1D vectors self.h = [mkvc(x.astype(float)) for x in h] @property def nodes_x(self): """Nodal grid vector (1D) in the x direction.""" return np.r_[self.origin[0], self.h[0]].cumsum() @property def nodes_y(self): """Nodal grid vector (1D) in the y direction.""" return None if self.dim < 2 else np.r_[self.origin[1], self.h[1]].cumsum() @property def nodes_z(self): """Nodal grid vector (1D) in the z direction.""" return None if self.dim < 3 else np.r_[self.origin[2], self.h[2]].cumsum() @property def cell_centers_x(self): """Cell-centered grid vector (1D) in the x direction.""" nodes = self.nodes_x return (nodes[1:] + nodes[:-1]) / 2 @property def cell_centers_y(self): """Cell-centered grid vector (1D) in the y direction.""" if self.dim < 2: return None nodes = self.nodes_y return (nodes[1:] + nodes[:-1]) / 2 @property def cell_centers_z(self): """Cell-centered grid vector (1D) in the z direction.""" if self.dim < 3: return None nodes = self.nodes_z return (nodes[1:] + nodes[:-1]) / 2 @property def cell_centers(self): """Cell-centered grid.""" return self._getTensorGrid("cell_centers") @property def nodes(self): """Nodal grid.""" return self._getTensorGrid("nodes") @property def h_gridded(self): """ Returns an (nC, dim) numpy array with the widths of all cells in order """ if self.dim == 1: return self.h[0][:, None] return ndgrid(*self.h) @property def faces_x(self): """Face staggered grid in the x direction.""" if self.nFx == 0: return return self._getTensorGrid("faces_x") @property def faces_y(self): """Face staggered grid in the y direction.""" if self.nFy == 0 or self.dim < 2: return return self._getTensorGrid("faces_y") @property def faces_z(self): """Face staggered grid in the z direction.""" if self.nFz == 0 or self.dim < 3: return return self._getTensorGrid("faces_z") @property def edges_x(self): """Edge staggered grid in the x direction.""" if self.nEx == 0: return return self._getTensorGrid("edges_x") @property def edges_y(self): """Edge staggered grid in the y direction.""" if self.nEy == 0 or self.dim < 2: return return self._getTensorGrid("edges_y") @property def edges_z(self): """Edge staggered grid in the z direction.""" if self.nEz == 0 or self.dim < 3: return return self._getTensorGrid("edges_z") def _getTensorGrid(self, key): if getattr(self, "_" + key, None) is None: setattr(self, "_" + key, ndgrid(self.get_tensor(key))) return getattr(self, "_" + key) def get_tensor(self, key): """Returns a tensor list. Parameters ---------- key : str Which tensor (see below) key can be:: 'CC', 'cell_centers' -> location of cell centers 'N', 'nodes' -> location of nodes 'Fx', 'faces_x' -> location of faces with an x normal 'Fy', 'faces_y' -> location of faces with an y normal 'Fz', 'faces_z' -> location of faces with an z normal 'Ex', 'edges_x' -> location of edges with an x tangent 'Ey', 'edges_y' -> location of edges with an y tangent 'Ez', 'edges_z' -> location of edges with an z tangent Returns ------- list list of the tensors that make up the mesh. """ key = self._parse_location_type(key) if key == "faces_x": ten = [ self.nodes_x, self.cell_centers_y, self.cell_centers_z, ] elif key == "faces_y": ten = [ self.cell_centers_x, self.nodes_y, self.cell_centers_z, ] elif key == "faces_z": ten = [ self.cell_centers_x, self.cell_centers_y, self.nodes_z, ] elif key == "edges_x": ten = [self.cell_centers_x, self.nodes_y, self.nodes_z] elif key == "edges_y": ten = [self.nodes_x, self.cell_centers_y, self.nodes_z] elif key == "edges_z": ten = [self.nodes_x, self.nodes_y, self.cell_centers_z] elif key == "cell_centers": ten = [ self.cell_centers_x, self.cell_centers_y, self.cell_centers_z, ] elif key == "nodes": ten = [self.nodes_x, self.nodes_y, self.nodes_z] else: raise KeyError(r"Unrecognized key {key}") return [t for t in ten if t is not None] # --------------- Methods --------------------- def is_inside(self, pts, location_type="nodes", **kwargs): """ Determines if a set of points are inside a mesh. :param numpy.ndarray pts: Location of points to test :rtype: numpy.ndarray :return: inside, numpy array of booleans """ if "locType" in kwargs: warnings.warn( "The locType keyword argument has been deprecated, please use location_type. " "This will be removed in discretize 1.0.0", DeprecationWarning, ) location_type = kwargs["locType"] pts = as_array_n_by_dim(pts, self.dim) tensors = self.get_tensor(location_type) if location_type[0].lower() == "n" and self._meshType == "CYL": # NOTE: for a CYL mesh we add a node to check if we are inside in # the radial direction! tensors[0] = np.r_[0.0, tensors[0]] tensors[1] = np.r_[tensors[1], 2.0 * np.pi] inside = np.ones(pts.shape[0], dtype=bool) for i, tensor in enumerate(tensors): TOL = np.diff(tensor).min() * 1.0e-10 inside = ( inside & (pts[:, i] >= tensor.min() - TOL) & (pts[:, i] <= tensor.max() + TOL) ) return inside def _getInterpolationMat(self, loc, location_type="cell_centers", zeros_outside=False): """Produces interpolation matrix Parameters ---------- loc : numpy.ndarray Location of points to interpolate to location_type: stc What to interpolate location_type can be:: 'Ex', 'edges_x' -> x-component of field defined on x edges 'Ey', 'edges_y' -> y-component of field defined on y edges 'Ez', 'edges_z' -> z-component of field defined on z edges 'Fx', 'faces_x' -> x-component of field defined on x faces 'Fy', 'faces_y' -> y-component of field defined on y faces 'Fz', 'faces_z' -> z-component of field defined on z faces 'N', 'nodes' -> scalar field defined on nodes 'CC', 'cell_centers' -> scalar field defined on cell centers 'CCVx', 'cell_centers_x' -> x-component of vector field defined on cell centers 'CCVy', 'cell_centers_y' -> y-component of vector field defined on cell centers 'CCVz', 'cell_centers_z' -> z-component of vector field defined on cell centers Returns ------- scipy.sparse.csr_matrix M, the interpolation matrix """ loc = as_array_n_by_dim(loc, self.dim) if not zeros_outside: if not np.all(self.is_inside(loc)): raise ValueError("Points outside of mesh") else: indZeros = np.logical_not(self.is_inside(loc)) loc[indZeros, :] = np.array([v.mean() for v in self.get_tensor("CC")]) location_type = self._parse_location_type(location_type) if location_type in ["faces_x", "faces_y", "faces_z", "edges_x", "edges_y", "edges_z"]: ind = {"x": 0, "y": 1,
<filename>sklearn/metrics/pairwise.py # -*- coding: utf-8 -*- # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> # <NAME> <<EMAIL>> # License: BSD 3 clause import itertools from functools import partial import warnings import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix from scipy.sparse import issparse from joblib import Parallel, effective_n_jobs from ..utils.validation import _num_samples from ..utils.validation import check_non_negative from ..utils import check_array from ..utils import gen_even_slices from ..utils import gen_batches, get_chunk_n_rows from ..utils import is_scalar_nan from ..utils.extmath import row_norms, safe_sparse_dot from ..preprocessing import normalize from ..utils._mask import _get_mask from ..utils.fixes import delayed from ..utils.fixes import sp_version, parse_version from ._pairwise_fast import _chi2_kernel_fast, _sparse_manhattan from ..exceptions import DataConversionWarning # Utility Functions def _return_float_dtype(X, Y): """ 1. If dtype of X and Y is float32, then dtype float32 is returned. 2. Else dtype float is returned. """ if not issparse(X) and not isinstance(X, np.ndarray): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and not isinstance(Y, np.ndarray): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = float return X, Y, dtype def check_pairwise_arrays( X, Y, *, precomputed=False, dtype=None, accept_sparse="csr", force_all_finite=True, copy=False, ): """Set X and Y appropriately and checks inputs. If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats (or dtype if provided). Finally, the function checks that the size of the second dimension of the two arrays is equal, or the equivalent check for a precomputed distance matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) precomputed : bool, default=False True if X is to be treated as precomputed distances to the samples in Y. dtype : str, type, list of type, default=None Data type required for X and Y. If None, the dtype will be an appropriate float type selected by _return_float_dtype. .. versionadded:: 0.18 accept_sparse : str, bool or list/tuple of str, default='csr' String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.22 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan`. copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. .. versionadded:: 0.22 Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y, dtype_float = _return_float_dtype(X, Y) estimator = "check_pairwise_arrays" if dtype is None: dtype = dtype_float if Y is X or Y is None: X = Y = check_array( X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator, ) else: X = check_array( X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator, ) Y = check_array( Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator, ) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError( "Precomputed metric requires shape " "(n_queries, n_indexed). Got (%d, %d) " "for %d indexed." % (X.shape[0], X.shape[1], Y.shape[0]) ) elif X.shape[1] != Y.shape[1]: raise ValueError( "Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % (X.shape[1], Y.shape[1]) ) return X, Y def check_paired_arrays(X, Y): """Set X and Y appropriately and checks inputs for paired distances. All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y = check_pairwise_arrays(X, Y) if X.shape != Y.shape: raise ValueError( "X and Y should be of same shape. They were respectively %r and %r long." % (X.shape, Y.shape) ) return X, Y # Pairwise distances def euclidean_distances( X, Y=None, *, Y_norm_squared=None, squared=False, X_norm_squared=None ): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. For efficiency reasons, the euclidean distance between a pair of row vector x and y is computed as:: dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) This formulation has two advantages over other ways of computing distances. First, it is computationally efficient when dealing with sparse data. Second, if one argument varies but the other remains unchanged, then `dot(x, x)` and/or `dot(y, y)` can be pre-computed. However, this is not the most precise way of doing this computation, because this equation potentially suffers from "catastrophic cancellation". Also, the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ default=None If `None`, uses `Y=X`. Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) \ or (1, n_samples_Y), default=None Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) May be ignored in some cases, see the note below. squared : bool, default=False Return squared Euclidean distances. X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) \ or (1, n_samples_X), default=None Pre-computed dot-products of vectors in X (e.g., ``(X**2).sum(axis=1)``) May be ignored in some cases, see the note below. Notes ----- To achieve better accuracy, `X_norm_squared` and `Y_norm_squared` may be unused if they are passed as ``float32``. Returns ------- distances : ndarray of shape (n_samples_X, n_samples_Y) See Also -------- paired_distances : Distances betweens pairs of elements of X and Y. Examples -------- >>> from sklearn.metrics.pairwise import euclidean_distances >>> X = [[0, 1], [1, 1]] >>> # distance between rows of X >>> euclidean_distances(X, X) array([[0., 1.], [1., 0.]]) >>> # get distance to origin >>> euclidean_distances(X, [[0, 0]]) array([[1. ], [1.41421356]]) """ X, Y = check_pairwise_arrays(X, Y) if X_norm_squared is not None: X_norm_squared = check_array(X_norm_squared, ensure_2d=False) original_shape = X_norm_squared.shape if X_norm_squared.shape == (X.shape[0],): X_norm_squared = X_norm_squared.reshape(-1, 1) if X_norm_squared.shape == (1, X.shape[0]): X_norm_squared = X_norm_squared.T if X_norm_squared.shape != (X.shape[0], 1): raise ValueError( f"Incompatible dimensions for X of shape {X.shape} and " f"X_norm_squared of shape {original_shape}." ) if Y_norm_squared is not None: Y_norm_squared = check_array(Y_norm_squared, ensure_2d=False) original_shape = Y_norm_squared.shape if Y_norm_squared.shape == (Y.shape[0],): Y_norm_squared = Y_norm_squared.reshape(1, -1) if Y_norm_squared.shape == (Y.shape[0], 1): Y_norm_squared = Y_norm_squared.T if Y_norm_squared.shape != (1, Y.shape[0]): raise
inputs['day_start'] = combined['start_days'] inputs['nday'] = combined['Nsim_days'] inputs['avg_ppamult'] = combined['avg_ppa'] inputs['group_weight'] = combined['weights'] inputs['avg_sfadjust'] = combined['avg_sfadj'] Ng = len(inputs['day_start']) # Number of simulations # Run simulations steps_per_day = wf_steps_per_hour*24 s = {} hourly_results_keys = ['generation', 'pricing_mult', 'sf_thermal_gen', 'disp_qsfprod_expected', 'disp_wpb_expected'] for key in hourly_results_keys: s[key] = [0.0 for i in range(nrec)] # Array of yearly generation # Run full annual simulation with dispatch enabled only on selected days if inputs['run_continuous_with_dispatch_days']: select_dispatch_series = [0 for v in range(365)] for g in range(Ng): # Number of simulation groupings d1 = inputs['day_start'][g] - Nprev # First day to be included in simulation group g for j in range(inputs['nday'][g] + Nprev ): if (d1+j)>=0 and (d1+j)<365: select_dispatch_series[d1 + j] = 1 vd['select_dispatch_series'] = select_dispatch_series # Set up array of cluster-average solar field availability sf_adjust_hourly = list(sf_adjust_tot) # Hourly adjustment factors from previous calculation if inputs['avg_sfadjust'] is not None: sf_adjust_hourly = dni_clustering.create_annual_array_with_cluster_average_values(sf_adjust_hourly, inputs['avg_ppamult'], inputs['day_start'], inputs['nday'], Nprev = inputs['nprev'], Nnext = Nnext, overwrite_surrounding_days = True) vd['sf_adjust:hourly'] = [100.*(1.-v) for v in sf_adjust_hourly] sgroup = pysdk.run_simulation(vd, design) # Run continuous simulation for g in range(Ng): # Run simulation only for group g if not inputs['run_continuous_with_dispatch_days']: # Run simulation for group g d1 = inputs['day_start'][g] - Nprev # First day to be included in simulation group g Nprev_sim = inputs['day_start'][g] - max(0,d1) # Number of previous days actually allowed in the simulation Ndays_tot = inputs['nday'][g] + Nprev + Nnext # Number of days to be simulated tstart = int(max(0, d1*24.*3600.)) tend = int(min(8760.*3600., (d1+Ndays_tot)*24.*3600.)) vd['time_start'] = tstart vd['time_stop'] = tend vd['vacuum_arrays'] = True vd['time_steps_per_hour'] = wf_steps_per_hour # Update solar field hourly adjustment factors to reflect cluster-average values if inputs['avg_sfadjust'] is not None: sf_adjust_hourly_new = list(sf_adjust_tot) Nsim = inputs['nday'][g] + Nprev + Nnext for h in range(Nsim*steps_per_day): time_pt = (inputs['day_start'][g] - Nprev)*steps_per_day+ h if h>=0 and h<8760*wf_steps_per_hour: sf_adjust_hourly_new[time_pt] = inputs['avg_sfadjust'][g][h] vd['sf_adjust:hourly'] = [100.*(1.-v) for v in sf_adjust_hourly_new] else: vd['sf_adjust:hourly'] = [100.*(1.-v) for v in sf_adjust_tot] sgroup = pysdk.run_simulation(vd, design) # Run simulation for selected set of days # Collect simulation results in full annual array for d in range(inputs['nday'][g]): # Days counted in simulation grouping day_of_year = inputs['day_start'][g] + d if inputs['run_continuous_with_dispatch_days']: # Simulation output contains full annual array i = day_of_year * steps_per_day else: # Simulation output contains only simulated subset of days i = (Nprev_sim+d)*steps_per_day for key in hourly_results_keys: for h in range(steps_per_day): # Hours in day d s[key][day_of_year*steps_per_day + h] = sgroup[key][i+h] clusters = {'exemplars':inputs['exemplars'], 'partition_matrix':inputs['partition_matrix']} for key in hourly_results_keys: s[key] = dni_clustering.compute_annual_array_from_clusters(s[key], clusters, Ndays, adjust_wt = True, k1 = inputs['first_pt_cluster'], k2 = inputs['last_pt_cluster']) s['pricing_mult'] = self.params.dispatch_factors_ts s['total_installed_cost'] = sgroup['total_installed_cost'] s['system_capacity'] = sgroup['system_capacity'] s['annual_generation'] = 0.0 s['revenue_units'] = 0.0 for h in range(len(s['generation'])): s['annual_generation'] += s['generation'][h] / float(wf_steps_per_hour) s['revenue_units'] += s['generation'][h] * s['pricing_mult'][h] / float(wf_steps_per_hour) # Run full simulation else: s = pysdk.run_simulation(vd, design) #lifetime revenue rev = s['revenue_units'] s['sales'] = self.calc_real_dollars(rev * pysdk.F['ppa_price_input'], is_revenue=True) #Calculating number of receiver starts s['rec_starts'] = 0 for i in range(1, len(s['sf_thermal_gen'])): if s['sf_thermal_gen'][i] > 0. and s['sf_thermal_gen'][i-1] <= 0.: s['rec_starts'] += 1 #Calculating number of cycle starts and cycle ramping s['cycle_starts'] = 0 s['cycle_ramp'] = 0.0 for i in range(1, len(s['generation'])): if s['generation'][i] > 0. and s['generation'][i-1] <= 0.: s['cycle_starts'] += 1 if s['generation'][i] > s['generation'][i-1] and s['generation'][i] > 0.: s['cycle_ramp'] += (s['generation'][i] - s['generation'][i-1]) # 'generation' has units of kWe s['cycle_ramp_index'] = s['cycle_ramp']/(max(s['generation'])*365.) # Dispatched results for comparison #--initialize s['disp_rec_starts'] = 0 s['disp_cycle_starts'] = 0 s['disp_cycle_ramp'] = 0.0 s['disp_cycle_ramp_index'] = 0.0 if self.params.is_dispatch: #Calculating number of receiver starts DISPATCHED gen = s['disp_qsfprod_expected'] for i in range(1, len(gen)): if gen[i] > 0. and gen[i-1] <= 0.: s['disp_rec_starts'] += 1 #Calculating number of cycle starts and cycle ramping DISPATCHED gen = s['disp_wpb_expected'] for i in range(1, len(gen)): if gen[i] > 0. and gen[i-1] <= 0.: s['disp_cycle_starts'] += 1 if gen[i] > gen[i-1] and gen[i] > 0.: s['disp_cycle_ramp'] += (gen[i] - gen[i-1]) s['disp_cycle_ramp_index'] = s['disp_cycle_ramp']/(max(gen)*365.) s['disp_cycle_ramp'] *= 1000. #convert MW to kW # Receiver and cycle start up cost s['rec_start_cost_y1'] = self.params.disp_rsu_cost*s['rec_starts'] s['cycle_start_cost_y1'] = self.params.disp_csu_cost*s['cycle_starts'] s['cycle_ramp_cost_y1'] = self.params.disp_pen_delta_w*s['cycle_ramp'] # Lifetime cost s['rec_start_cost'] = self.calc_real_dollars(s['rec_start_cost_y1']) s['cycle_start_cost'] = self.calc_real_dollars(s['cycle_start_cost_y1']) s['cycle_ramp_cost'] = self.calc_real_dollars(s['cycle_ramp_cost_y1']) if rev < 0: s['sales'] = float('nan') #return not a number if simulation is invalid s['avg_degradation'] = degr_mult s['avg_soil'] = avg_soil s['avg_avail'] = avg_avail return s def E(self, variables): """ The explicit terms """ print "Running explicit terms E()" #receiver cost arec = variables.D_rec.value*pi*variables.rec_height.value erec = self.params.rec_ref_cost*(arec/self.params.rec_ref_area)**0.7 #Tower cost etower = self.params.tower_fixed_cost * exp(self.params.tower_exp * variables.h_tower.value) #Plant Cost del_eff = variables.design_eff.value - 0.412 effscale = 0. for i,c in enumerate(self.params.c_ces): effscale += c*del_eff**i eplant = (self.params.c_cps0 + self.params.c_cps1 * variables.P_ref.value * 1000.) * (1. + effscale) #TES cost eTES = self.params.tes_spec_cost * variables.P_ref.value * 1000. \ / variables.design_eff.value \ * variables.tshours.value #OM labor costs heliostat_om_labor_y1 = self.params.om_staff_cost * variables.om_staff.value * self.params.om_staff_max_hours_week*52. #annual heliostat_om_labor = self.calc_real_dollars(heliostat_om_labor_y1, is_labor = True) #lifetime #Washing labor costs heliostat_wash_cost_y1 = variables.n_wash_crews.value * self.params.wash_crew_cost * self.params.wash_crew_max_hours_week*52. #annual heliostat_wash_cost = self.calc_real_dollars(heliostat_wash_cost_y1, is_labor=True) #lifetime d = {'cost_receiver':erec, 'cost_tower':etower, 'cost_plant':eplant, 'cost_TES':eTES, } for k,v in d.items(): d[k] = self.calc_real_dollars(v) d.update({ 'heliostat_om_labor_y1':heliostat_om_labor_y1, 'heliostat_om_labor':heliostat_om_labor, 'heliostat_wash_cost_y1':heliostat_wash_cost_y1, 'heliostat_wash_cost':heliostat_wash_cost, }) return d def dE(self, variables): """ return derivatives of E """ de = {} #dictionary containing derivatives by variable key return de def F(self, variables, S, om_cost): #total_installed_cost, generation, pricing_mult): """ Financial model run """ print "Running financial model F()" vd = variables.as_dict() vd.update(self.params.as_dict()) f = pysdk.run_financial(vd, S['total_installed_cost'], S['generation'], S['pricing_mult'], om_cost, S['system_capacity']) return f def Z(self, variables, **kwargs): """ The whole objective function """ # if not self.design: # raise PySDKError("Attempting to run objective function without a valid design.") vd = variables.as_dict() vd.update(self.params.as_dict()) #user can provide keyword arguments to use existing S or P results if "S" in kwargs and not "D" in kwargs: raise PySDKError("When providing simulation results 'S' to the objective function, you must also "+ "provide design results 'D'.") #Design if "D" in kwargs: D = kwargs["D"] else: #run the design module D = self.D(variables) #updates self.design #Heliostat availability and OM if "M" in kwargs: M = kwargs["M"] else: M = self.M(variables, D['design']) #Heliostat soiling and degradation if "O" in kwargs: O = kwargs["O"] else: O = self.O(variables, D['design']) #Performance simulation - revenue model if "S" in kwargs: S = kwargs["S"] else: if "cluster_inputs" in kwargs: cluster_inputs = kwargs["cluster_inputs"] S = self.S(D['design'], variables, M['avail_sched'], O['soiling_sched'], O['degradation_sched'], cluster_inputs = cluster_inputs) elif "Nclusters" in kwargs: Nclusters = kwargs["Nclusters"] S = self.S(D['design'], variables, M['avail_sched'], O['soiling_sched'], O['degradation_sched'], Nclusters = Nclusters) else: S = self.S(D['design'], variables, M['avail_sched'], O['soiling_sched'], O['degradation_sched']) #Explicit (cost) terms if "E" in kwargs: E = kwargs["E"] else: E = self.E(variables) #----- the objective function ----- z = {} z['cost_receiver'] = E['cost_receiver'] z['cost_tower'] = E['cost_tower'] z['cost_plant'] = E['cost_plant'] z['cost_TES'] = E['cost_TES'] z['cost_land'] = D['cost_land'] z['cost_heliostats'] = D['cost_heliostats'] cap_cost = sum( [v for v in z.itervalues()] ) z['rec_start_cost'] = S['rec_start_cost'] z['cycle_start_cost'] = S['cycle_start_cost'] z['cycle_ramp_cost'] = S['cycle_ramp_cost'] z['heliostat_repair_cost'] = M['heliostat_repair_cost'] #structural, mechanical, electrical repair costs z['heliostat_om_labor'] = E['heliostat_om_labor'] #OM labor on heliostat field z['heliostat_wash_cost'] = E['heliostat_wash_cost'] #costs due to labor and materials for mirror washing z['heliostat_refurbish_cost'] = O['heliostat_refurbish_cost'] #Mirror replacement cost om_cost_lifetime = sum( [v for v in z.itervalues()] ) - cap_cost om_cost = ( M['heliostat_repair_cost_y1'] + E['heliostat_om_labor_y1'] + E['heliostat_wash_cost_y1'] + O['heliostat_refurbish_cost_y1'] + S['rec_start_cost_y1'] + S['cycle_start_cost_y1'] + S['cycle_ramp_cost_y1'] ) z['sales'] = -S['sales'] #electricity sales zobj = sum( [v for v in z.itervalues()] ) #--- financial model f = self.F(variables, S, om_cost) z['ppa'] = f['ppa'] z['lcoe_nom'] = f['lcoe_nom'] z['lcoe_real'] = f['lcoe_real'] #------ if "printout" in kwargs: if kwargs["printout"]: fmtf = "{:30s}{:^5s}{: 11.1f}" fmtd = "{:30s}{:^5s}{: 11d}" print "="*20 + " PERF TABLE " + "="*20 print fmtf.format("Mirror replacements per year","1/yr",O['n_repairs']) print fmtf.format("Heliostat repairs per year","1/yr",M['n_repairs']) print fmtf.format("Average degradation loss", "%", S['avg_degradation']*100.) print fmtf.format("Average soiling loss", "%", S['avg_soil']*100.)
that are substantially faster than a for loop. First, in the case of a single (n,n) density matrix, we package the entire array as a single-element array whose entry is the array. In the case of multiple density matrices a (k,n,n) Array, we package everything as a (k,1) Array whose [j,0] entry is the [j,:,:] density matrix. In calculating the left- and right-mult contributions, we package H+L and H-L as (1) object arrays whose single entry stores the relevant sparse matrix. We can then multiply our packaged density matrix and [H\pm L]. Using numpy broadcasting rules, [H\pm L] will be broadcast to a (k,1) Array for elementwise multiplication with our packaged density matrices. After this, elementwise multiplication is applied. This in turn references each object's __mul__ function, which–for our csr_matrix components means matrix multiplication. In calculating the left-right-multiplication part, we use our (m)-shape object arrays holding the dissipator operators to perform multiplication. We can take an elementwise product with our packaged density matrix, at which point our dissipator operators are broadcast as (m) -> (1,m) -> (k,m) shaped, and our packaged density matrix as (k,1) -> (k,m). Elementwise multiplication is then applied, which is interpreted as matrix multiplication. This yields an array where entry [i,j] is an object storing the results of s_jL_j\rho_i L_j^\dagger. We can then sum over j and unpackage our object array to get our desired result. """ hamiltonian_matrix = None if self._static_hamiltonian is not None or self._hamiltonian_operators is not None: hamiltonian_matrix = -1j * self.evaluate_hamiltonian(ham_sig_vals) # B matrix # package (n,n) Arrays as (1) # Arrays of dtype object, or (k,n,n) Arrays as (k,1) Arrays of dtype object y = package_density_matrices(y) # if dissipators present (includes both hamiltonian is None and is not None) if self._dissipator_operators is not None or self._static_dissipators is not None: # A matrix if self._static_dissipators is None: dissipators_matrix = np.sum( -0.5 * dis_sig_vals * self._dissipator_products, axis=-1 ) elif self._dissipator_operators is None: dissipators_matrix = self._static_dissipators_product_sum else: dissipators_matrix = self._static_dissipators_product_sum + np.sum( -0.5 * dis_sig_vals * self._dissipator_products, axis=-1 ) if hamiltonian_matrix is not None: left_mult_contribution = np.squeeze([hamiltonian_matrix + dissipators_matrix] * y) right_mult_contribution = np.squeeze(y * [dissipators_matrix - hamiltonian_matrix]) else: left_mult_contribution = np.squeeze([dissipators_matrix] * y) right_mult_contribution = np.squeeze(y * [dissipators_matrix]) # both_mult_contribution[i] = \gamma_i L_i\rho L_i^\dagger performed in array language if self._static_dissipators is None: both_mult_contribution = np.sum( (dis_sig_vals * self._dissipator_operators) * y * self._dissipator_operators_adj, axis=-1, ) elif self._dissipator_operators is None: both_mult_contribution = np.sum( self._static_dissipators * y * self._static_dissipators_adj, axis=-1 ) else: both_mult_contribution = ( np.sum( (dis_sig_vals * self._dissipator_operators) * y * self._dissipator_operators_adj, axis=-1, ) + np.sum(self._static_dissipators * y * self._static_dissipators_adj, axis=-1) ) out = left_mult_contribution + right_mult_contribution + both_mult_contribution elif hamiltonian_matrix is not None: out = (([hamiltonian_matrix] * y) - (y * [hamiltonian_matrix]))[0] else: raise QiskitError( "SparseLindbladCollection with None for static_hamiltonian, " "hamiltonian_operators, and dissipator_operators, cannot evaluate rhs." ) if len(y.shape) == 2: # Very slow; avoid if not necessary (or if better implementation found). Needs to # map a (k) Array of dtype object with j^{th} entry a (n,n) Array -> (k,n,n) Array. out = unpackage_density_matrices(out.reshape(y.shape[0], 1)) return out class JAXSparseLindbladCollection(BaseLindbladOperatorCollection): r"""Object for computing the right hand side of the Lindblad equation with using jax.experimental.sparse.BCOO arrays. """ @property def static_hamiltonian(self) -> "BCOO": return self._static_hamiltonian @static_hamiltonian.setter def static_hamiltonian(self, new_static_hamiltonian: Union["BCOO", None]): self._static_hamiltonian = to_BCOO(new_static_hamiltonian) @property def hamiltonian_operators(self) -> Union["BCOO", None]: return self._hamiltonian_operators @hamiltonian_operators.setter def hamiltonian_operators(self, new_hamiltonian_operators: Union["BCOO", None]): self._hamiltonian_operators = to_BCOO(new_hamiltonian_operators) @property def static_dissipators(self) -> Union["BCOO", None]: return self._static_dissipators @static_dissipators.setter def static_dissipators(self, new_static_dissipators: Union["BCOO", None]): """Operators constructed using dense operations.""" self._static_dissipators = to_array(new_static_dissipators) if self._static_dissipators is not None: self._static_dissipators_adj = np.conjugate( np.transpose(self._static_dissipators, [0, 2, 1]) ).copy() self._static_dissipators_product_sum = -0.5 * np.sum( np.matmul(self._static_dissipators_adj, self._static_dissipators), axis=0 ) self._static_dissipators = jsparse.BCOO.fromdense( self._static_dissipators.data, n_batch=1 ) self._static_dissipators_adj = jsparse.BCOO.fromdense( self._static_dissipators_adj.data, n_batch=1 ) self._static_dissipators_product_sum = jsparse.BCOO.fromdense( self._static_dissipators_product_sum.data ) @property def dissipator_operators(self) -> Union["BCOO", None]: return self._dissipator_operators @dissipator_operators.setter def dissipator_operators(self, new_dissipator_operators: Union["BCOO", None]): """Operators constructed using dense operations.""" self._dissipator_operators = to_array(new_dissipator_operators) if self._dissipator_operators is not None: self._dissipator_operators_adj = np.conjugate( np.transpose(self._dissipator_operators, [0, 2, 1]) ).copy() self._dissipator_products = np.matmul( self._dissipator_operators_adj, self._dissipator_operators ) self._dissipator_operators = jsparse.BCOO.fromdense( self._dissipator_operators.data, n_batch=1 ) self._dissipator_operators_adj = jsparse.BCOO.fromdense( self._dissipator_operators_adj.data, n_batch=1 ) self._dissipator_products = -0.5 * jsparse.BCOO.fromdense( self._dissipator_products.data, n_batch=1 ) def evaluate(self, ham_sig_vals: Array, dis_sig_vals: Array) -> Array: raise ValueError("Non-vectorized Lindblad collections cannot be evaluated without a state.") def evaluate_hamiltonian(self, ham_sig_vals: Union["BCOO", None]) -> "BCOO": r"""Compute the Hamiltonian. Args: ham_sig_vals: [Real] values of :math:`s_j` in :math:`H = \sum_j s_j(t) H_j + H_d`. Returns: Hamiltonian matrix. Raises: QiskitError: If collection not sufficiently specified. """ if isinstance(ham_sig_vals, Array): ham_sig_vals = ham_sig_vals.data if self._static_hamiltonian is not None and self._hamiltonian_operators is not None: return ( jsparse_linear_combo(ham_sig_vals, self._hamiltonian_operators) + self._static_hamiltonian ) elif self._static_hamiltonian is None and self._hamiltonian_operators is not None: return jsparse_linear_combo(ham_sig_vals, self._hamiltonian_operators) elif self._static_hamiltonian is not None: return self._static_hamiltonian else: raise QiskitError( self.__class__.__name__ + """ with None for both static_hamiltonian and hamiltonian_operators cannot evaluate Hamiltonian.""" ) @wrap def evaluate_rhs( self, ham_sig_vals: Union[None, Array], dis_sig_vals: Union[None, Array], y: Array ) -> Array: r"""Evaluates Lindblad equation RHS given a pair of signal values for the hamiltonian terms and the dissipator terms. Expresses the RHS of the Lindblad equation as :math:`(A+B)y + y(A-B) + C`, where .. math:: A = (-1/2)*\sum_jD_j^\dagger D_j + (-1/2)*\sum_j\gamma_j(t) L_j^\dagger L_j, B = -iH, C = \sum_j \gamma_j(t) L_j y L_j^\dagger. Args: ham_sig_vals: hamiltonian coefficient values, :math:`s_j(t)`. dis_sig_vals: dissipator signal values, :math:`\gamma_j(t)`. y: density matrix as (n,n) Array representing the state at time :math:`t`. Returns: RHS of Lindblad equation .. math:: -i[H,y] + \sum_j\gamma_j(t)(L_j y L_j^\dagger - (1/2) * {L_j^\daggerL_j,y}). Raises: QiskitError: If operator collection is underspecified. """ hamiltonian_matrix = None if self._static_hamiltonian is not None or self._hamiltonian_operators is not None: hamiltonian_matrix = -1j * self.evaluate_hamiltonian(ham_sig_vals) # B matrix # if dissipators present (includes both hamiltonian is None and is not None) if self._dissipator_operators is not None or self._static_dissipators is not None: # A matrix if self._static_dissipators is None: dissipators_matrix = jsparse_linear_combo(dis_sig_vals, self._dissipator_products) elif self._dissipator_operators is None: dissipators_matrix = self._static_dissipators_product_sum else: dissipators_matrix = self._static_dissipators_product_sum + jsparse_linear_combo( dis_sig_vals, self._dissipator_products ) if hamiltonian_matrix is not None: left_mult_contribution = jsparse_matmul(hamiltonian_matrix + dissipators_matrix, y) right_mult_contribution = jsparse_matmul( y, dissipators_matrix + (-1 * hamiltonian_matrix) ) else: left_mult_contribution = jsparse_matmul(dissipators_matrix, y) right_mult_contribution = jsparse_matmul(y, dissipators_matrix) if len(y.shape) == 3: # Must do array broadcasting and transposition to ensure vectorization works y = jnp.broadcast_to(y, (1, y.shape[0], y.shape[1], y.shape[2])).transpose( [1, 0, 2, 3] ) if self._static_dissipators is None: both_mult_contribution = jnp.tensordot( dis_sig_vals, jsparse_triple_product( self._dissipator_operators, y, self._dissipator_operators_adj ), axes=(-1, -3), ) elif self._dissipator_operators is None: both_mult_contribution = jnp.sum( jsparse_triple_product( self._static_dissipators, y, self._static_dissipators_adj ), axis=-3, ) else: both_mult_contribution = jnp.sum( jsparse_triple_product( self._static_dissipators, y, self._static_dissipators_adj ), axis=-3, ) + jnp.tensordot( dis_sig_vals, jsparse_triple_product( self._dissipator_operators, y, self._dissipator_operators_adj ), axes=(-1, -3), ) out = left_mult_contribution + right_mult_contribution + both_mult_contribution return out # if just hamiltonian elif hamiltonian_matrix is not None: return jsparse_matmul(hamiltonian_matrix, y) - jsparse_matmul(y, hamiltonian_matrix) else: raise QiskitError( """JAXSparseLindbladCollection with None for static_hamiltonian, hamiltonian_operators, static_dissipators, and dissipator_operators, cannot evaluate rhs.""" ) class BaseVectorizedLindbladCollection(BaseLindbladOperatorCollection, BaseOperatorCollection): """Base class for Vectorized Lindblad collections. The vectorized Lindblad equation represents the Lindblad master equation in the structure of a linear matrix differential equation in standard form. Hence, this class inherits from both ``BaseLindbladOperatorCollection`` and ``BaseOperatorCollection``. This class manages the general property handling of converting operators in a Lindblad collection to the correct type, constructing vectorized versions, and combining for use in a BaseOperatorCollection. Requires implementation of: - ``convert_to_internal_type``: Convert operators to the required internal type, e.g. csr or Array. - ``evaluation_class``: Class property that returns the subclass of BaseOperatorCollection to be used when evaluating the model, e.g. DenseOperatorCollection or SparseOperatorCollection. """ def __init__( self, static_hamiltonian: Optional[Array] = None, hamiltonian_operators: Optional[Array] = None, static_dissipators: Optional[Array] = None, dissipator_operators: Optional[Array] = None, ): r"""Initialize collection. Args: static_hamiltonian: Constant term :math:`H_d` to be added to the Hamiltonian of the system. hamiltonian_operators: Specifies breakdown of Hamiltonian as :math:`H(t) = \sum_j s(t) H_j+H_d` by specifying H_j. (k,n,n) array. static_dissipators:
b5f==''\ and board.s8c+board.s7d+board.s6e=='': moves = '9b5f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9b)and b4g==''\ and board.s8c+board.s7d+board.s6e+board.s5f=='': moves = '9b4g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9b)and b3h==''\ and board.s8c+board.s7d+board.s6e+board.s5f+board.s4g=='': moves = '9b3h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b9b)and b2i==''\ and board.s8c+board.s7d+board.s6e+board.s5f+board.s4g+board.s3h=='': moves = '9b2i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b1c !='': if re.match(r'[SGK+]', Bboard.b1c)and b1b=='': moves = '1c1b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGK+]', Bboard.b1c)and b2b=='': moves = '1c2b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]', Bboard.b1c)and b2c=='': moves = '1c2c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]', Bboard.b1c)and b1d=='': moves = '1c1d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|S|K',Bboard.b1c)and b2d=='': moves = '1c2d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[PLSR]', Bboard.b1c)and b1b=='': moves = '1c1b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b1c)and b2b=='': moves = '1c2b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b2c=='': moves = '1c2c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1d=='': moves = '1c1d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b1c)and b2d=='': moves = '1c2d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b1c)and b2a=='': moves = '1c2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1a==''\ and board.s1b=='': moves = '1c1a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b1c)and b1a==''\ and board.s1b=='': moves = '1c1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1e==''\ and board.s1d=='': moves = '1c1e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1e==''\ and board.s1d=='': moves = '1c1e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1f==''\ and board.s1d+board.s1e=='': moves = '1c1f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1f==''\ and board.s1d+board.s1e=='': moves = '1c1f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1g==''\ and board.s1d+board.s1e+board.s1f=='': moves = '1c1g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1g==''\ and board.s1d+board.s1e+board.s1f=='': moves = '1c1g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1h==''\ and board.s1d+board.s1e+board.s1f+board.s1g=='': moves = '1c1h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1h==''\ and board.s1d+board.s1e+board.s1f+board.s1g=='': moves = '1c1h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b1i==''\ and board.s1d+board.s1e+board.s1f+board.s1g+board.s1h=='': moves = '1c1i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b1i==''\ and board.s1d+board.s1e+board.s1f+board.s1g+board.s1h=='': moves = '1c1i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b3c==''\ and board.s2c=='': moves = '1c3c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b3c==''\ and board.s2c=='': moves = '1c3c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b4c==''\ and board.s2c+board.s3c=='': moves = '1c4c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b4c==''\ and board.s2c+board.s3c=='': moves = '1c4c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b5c==''\ and board.s2c+board.s3c+board.s4c=='': moves = '1c5c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b5c==''\ and board.s2c+board.s3c+board.s4c=='': moves = '1c5c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b6c==''\ and board.s2c+board.s3c+board.s4c+board.s5c=='': moves = '1c6c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b6c==''\ and board.s2c+board.s3c+board.s4c+board.s5c=='': moves = '1c6c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b7c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c=='': moves = '1c7c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b7c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c=='': moves = '1c7c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b8c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c+board.s7c=='': moves = '1c8c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b8c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c+board.s7c=='': moves = '1c8c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b1c)and b9c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c+board.s7c+board.s8c=='': moves = '1c9c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b1c)and b9c==''\ and board.s2c+board.s3c+board.s4c+board.s5c+board.s6c+board.s7c+board.s8c=='': moves = '1c9c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b3a==''\ and board.s2b=='': moves = '1c3a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b3e==''\ and board.s2d=='': moves = '1c3e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b4f==''\ and board.s2d+board.s3e=='': moves = '1c4f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b5g==''\ and board.s2d+board.s3e+board.s4f=='': moves = '1c5g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b6h==''\ and board.s2d+board.s3e+board.s4f+board.s5g=='': moves = '1c6h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('B',Bboard.b1c)and b7i==''\ and board.s2d+board.s3e+board.s4f+board.s5g+board.s6h=='': moves = '1c7i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b3a==''\ and board.s2b=='': moves = '1c3a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b3e==''\ and board.s2d=='': moves = '1c3e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b4f==''\ and board.s2d+board.s3e=='': moves = '1c4f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b5g==''\ and board.s2d+board.s3e+board.s4f=='': moves = '1c5g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b6h==''\ and board.s2d+board.s3e+board.s4f+board.s5g=='': moves = '1c6h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+B', Bboard.b1c)and b7i==''\ and board.s2d+board.s3e+board.s4f+board.s5g+board.s6h=='': moves = '1c7i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if Bboard.b2c !='': if re.match(r'[SGK+]', Bboard.b2c)and b2b=='': moves = '2c2b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGK+]', Bboard.b2c)and b1b=='': moves = '2c1b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[SGK+]', Bboard.b2c)and b3b=='': moves = '2c3b' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]', Bboard.b2c)and b1c=='': moves = '2c1c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]', Bboard.b2c)and b3c=='': moves = '2c3c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[GK+]', Bboard.b2c)and b2d=='': moves = '2c2d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|S|K',Bboard.b2c)and b1d=='': moves = '2c1d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'\+R|\+B|S|K',Bboard.b2c)and b3d=='': moves = '2c3d' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[PLSR]', Bboard.b2c)and b2b=='': moves = '2c2b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b2c)and b1b=='': moves = '2c1b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b2c)and b3b=='': moves = '2c3b+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b1c=='': moves = '2c1c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b3c=='': moves = '2c3c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2d=='': moves = '2c2d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b2c)and b1d=='': moves = '2c1d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'[BS]', Bboard.b2c)and b3d=='': moves = '2c3d+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b2c)and b1a=='': moves = '2c1a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('N', Bboard.b2c)and b3a=='': moves = '2c3a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2a==''\ and board.s2b=='': moves = '2c2a' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match(r'R|L', Bboard.b2c)and b2a==''\ and board.s2b=='': moves = '2c2a+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2e==''\ and board.s2d=='': moves = '2c2e' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2e==''\ and board.s2d=='': moves = '2c2e+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2f==''\ and board.s2d+board.s2e=='': moves = '2c2f' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2f==''\ and board.s2d+board.s2e=='': moves = '2c2f+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2g==''\ and board.s2d+board.s2e+board.s2f=='': moves = '2c2g' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2g==''\ and board.s2d+board.s2e+board.s2f=='': moves = '2c2g+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2h==''\ and board.s2d+board.s2e+board.s2f+board.s2g=='': moves = '2c2h' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2h==''\ and board.s2d+board.s2e+board.s2f+board.s2g=='': moves = '2c2h+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b2i==''\ and board.s2d+board.s2e+board.s2f+board.s2g+board.s2h=='': moves = '2c2i' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b2i==''\ and board.s2d+board.s2e+board.s2f+board.s2g+board.s2h=='': moves = '2c2i+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b4c==''\ and board.s3c=='': moves = '2c4c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b4c==''\ and board.s3c=='': moves = '2c4c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b5c==''\ and board.s3c+board.s4c=='': moves = '2c5c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b5c==''\ and board.s3c+board.s4c=='': moves = '2c5c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b6c==''\ and board.s3c+board.s4c+board.s5c=='': moves = '2c6c' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('R', Bboard.b2c)and b6c==''\ and board.s3c+board.s4c+board.s5c=='': moves = '2c6c+' kaihimore(moves) if oute.oute == 0: depth1.append(moves) if re.match('\+R', Bboard.b2c)and b7c==''\ and board.s3c+board.s4c+board.s5c+board.s6c=='':
''' Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' from django.conf import settings from django.core.exceptions import ObjectDoesNotExist import orm_settings from utilities import get_current_year d = {'DATABASES': orm_settings.get_db_dict()} settings.configure(**d) import models from django.db.models import Q HANDLE_EXC = True MEMBER_PHS = ['home_ph', 'bus_ph', 'cell_ph', 'fax'] PREV_TITLES = (('PID','International Director'), ('PCC', 'Council Chairperson'), ('PDG', 'District Governor')) def get_member_data(member_id, overrides={}): ''' Return formatted member data for the given id, in a dict: {'name': string of the members name {'id': member id 'prev_title': the previous title, if they have one. '' otherwise 'partner': string of the partners name, or '' 'partner_lion': Boolean if partner is a Lion or not 'resigned': Boolean 'join_date': int of the joining year 'deceased': Boolean 'country': string of country or '' 'phone': list of phone numbers: [home, work, cell, fax] - '' for empty ones 'email': string of email or '' 'club': string of club name or ''} This allows a caller to pad blanks if it uses the result in columns 'overrides' is a dict of fields which can override the members base field. This can have keys: email office home_ph fax 'use_prev_title' governs whether to prepend (I)PID, (I)PCC or (I)PDG if applicable return None if the id isn't found ''' try: m = models.Member.objects.get(pk=int(member_id)) except: if not HANDLE_EXC: raise return None # look up previous title, if they have one prev_title = '' # get immediate_past year imm_year = get_current_year() - 1 # look up any previous titles the member may hold prev_titles = models.StructOfficer.objects.filter(member__id=member_id) # loop over possible past titles, selecting the first that matches for abbrev, title in PREV_TITLES: try: item = prev_titles.filter(office__title=title) if item: item = item[0] if (item.year <= imm_year): # found match. Check if it is Immediate Past if item.year == imm_year: prev_title += 'I' prev_title += abbrev break except ObjectDoesNotExist: # could not find item, move to next title pass d = {} d['id'] = member_id d['prev_title'] = prev_title # got a valid member, build some info d['name'] = '%s %s' % (m.first_name, m.last_name) d['partner'] = m.partner.strip() or '' d['partner_lion'] = m.partner_lion_b d['resigned'] = m.resigned_b d['deceased'] = m.deceased_b d['join_date'] = m.join_date d['phone'] = [] for p in MEMBER_PHS: if p in overrides: num = overrides[p] else: num = getattr(m, p) if num: # Append a phone number, using the first initial of its attr name as a label d['phone'].append('%s' % num) else: d['phone'].append('') d['email'] = overrides.get('email', '') or (m.email or '') try: club = m.club d['club'] = club.__unicode__() except: d['club'] = None return d def get_md(name=None): ''' Return the MD Struct object specified by name. Return None if that name does not match an MD. If no name is specified, return the first MD in the db, sorted by id. If there aren't any, return None ''' try: if name: # find the matching MD md = models.Struct.objects.get(name=name) if md.type.id != 1: # this is not an MD, raise a ValueError to let the exception dump us out raise ValueError return md else: # get the first md in the list return models.Struct.objects.filter(type=1)[0] except: # No match, return None if not HANDLE_EXC: raise return None def get_struct_details(struct_id): ''' Return details of an struct and children within it, in a dict of: {'struct': struct dict for struct, 'children': A list of struct dicts for each child in the struct} A struct dict is defined as: {'id': ID, 'struct': The struct object, 'name': Name, 'website': Website, 'type': Struct type 'parent': 'id of parent, or None if there isn't one' } ''' try: struct = models.Struct.objects.get(id=struct_id) except Exception: if not HANDLE_EXC: raise return None out = {} structs = [struct] + [d for d in models.Struct.objects.filter(parent=struct) if d.in_use_b] for s in structs: item = {'id': s.id, 'struct': s, 'name': s.__unicode__(), 'website': s.website, 'type': s.type, 'parent': s.parent } if s.type.id == 1: out['struct'] = item else: l = out.get('children', []) l.append(item) out['children'] = l return out def get_struct_officers(offices, struct_id): ''' For the passed in list of office titles in 'offices', return a list of member dicts in the same order, for officers of the struct from 'struct_id'. Each item of 'offices' may be a title string, or a tuple of (title, year of service). If just a string, the current year is used. Use None if any office doesn't find a match ''' out = [] override = {} officers = models.StructOfficer.objects for off in offices: # Check if off is a string if hasattr(off, 'upper'): year = get_current_year() else: off, year = off[0], off[1] try: o = officers.filter(struct__id=struct_id).filter(year=year).get(office__title=off) if o: if o.email: override['email'] = o.email o = get_member_data(o.member.id, override) else: o = None except: if not HANDLE_EXC: raise o = None out.append(o) return out def get_past_struct_officers(office, struct_id, other_structs=False, prev_structs=False, year=None): ''' Return a dict of {'local': (year served, end month, member dict, struct name) for members who served in the specified struct 'other': (year served, end month, member dict, struct name) for members who served in other structs 'prev': (year served, end month, member dict, struct name) for members who served in pre-merged structs if not 'other_strucs', the 'other' key is [] for everyone who held 'office' for the struct before 'year'. Return [] if no matches ''' if not year: year = get_current_year() local_struct = models.Struct.objects.get(pk=struct_id) out = {} # A list of Q objects to filter on, the key to store them in items = [] if prev_structs: prev_structs = [sm.previous_struct for sm in models.StructMerge.objects.filter(current_struct=struct_id)] items.append(((Q(struct__in=prev_structs),), 'prev')) else: prev_structs = [local_struct] out['prev'] = [] items.append(((Q(struct__id=struct_id),), 'local')) if other_structs: items.append(([~Q(struct__id=struct_id),~Q(struct__in=prev_structs), Q(member__club__struct=local_struct, member__deceased_b=False, member__resigned_b=False)], 'other')) else: out['other'] = [] for qs, key in items: l = [] offs = models.StructOfficer.objects.filter(*qs).filter(year__lt=year) offs = offs.filter(office__title=office).order_by('year', 'end_month', 'struct__name') for off in offs: l.append((off.year, off.end_month, off.member and get_member_data(off.member.id, {'email':off.email} if off.email else {}), off.struct.__unicode__())) out[key] = l return out def get_struct_chairs(year, struct_id): ''' Return a list of struct chairs for a given struct and year, ordered by alphabetical name. Return tuples of (chair title, member dict) ''' out = [] chairs = models.StructChair.objects.filter(struct__id=struct_id).filter(year=year).filter(member__isnull=False) for c in chairs: out.append((c.office, get_member_data(c.member.id))) return out def get_merch_centres(struct_id): ''' Get merch centre info for a given struct. Return a list of dicts of: {'manager': member dict or None, 'fin_advisor': member dict or None, 'contact_person': name of contact person, 'add1' to 'add5': address lines, 'po_code': po code, 'tel', 'fax': phones # strings, 'email': email, 'website': website string} Return an empty list if no matches ''' out = [] mcs = models.MerchCentre.objects.filter(struct__id=struct_id) for mc in mcs: out.append({'manager': mc.manager and get_member_data(mc.manager.id), 'fin_advisor': mc.fin_advisor and get_member_data(mc.fin_advisor.id), }) for k in ['contact_person', 'po_code', 'tel', 'fax', 'email', 'website'] + ['add%d' % i for i in range(1,6)]: out[-1][k] = getattr(mc, k) return out def get_brightsight_offices(struct_id): ''' Get brightsight office info for a given struct. Return a list of dicts of: {'manager': name of manager, 'manager_cell_ph': manager cell phone, 'manager_email': manager email, 'contact_person': name of contact person, 'add1' to 'add5': address
sai_thrift_create_nhop(self.client, addr_family, ip_addr1, rif1) nhop2 = sai_thrift_create_nhop(self.client, addr_family, ip_addr1, rif2) nhop_group1 = sai_thrift_create_next_hop_group(self.client) nhop_gmember1 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop1) nhop_gmember2 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop2) sai_thrift_create_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) # send the test packet(s) try: pkt = simple_tcpv6_packet(eth_dst=router_mac, eth_src='00:22:22:22:22:22', ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1234, ipv6_hlim=64) exp_pkt1 = simple_tcpv6_packet(eth_dst='00:11:22:33:44:55', eth_src=router_mac, ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1234, ipv6_hlim=63) exp_pkt2 = simple_tcpv6_packet(eth_dst='00:11:22:33:44:56', eth_src=router_mac, ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1234, ipv6_hlim=63) send_packet(self, 2, str(pkt)) verify_any_packet_any_port(self, [exp_pkt1, exp_pkt2], [0, 1]) pkt = simple_tcpv6_packet(eth_dst=router_mac, eth_src='00:22:22:22:22:45', ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1248, ipv6_hlim=64) exp_pkt1 = simple_tcpv6_packet(eth_dst='00:11:22:33:44:55', eth_src=router_mac, ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1248, ipv6_hlim=63) exp_pkt2 = simple_tcpv6_packet(eth_dst='00:11:22:33:44:56', eth_src=router_mac, ipv6_dst='fdf8:f53e:61e4::18', ipv6_src='fc00:e968:6179::de52:7100', tcp_sport=0x1248, ipv6_hlim=63) send_packet(self, 2, str(pkt)) verify_any_packet_any_port(self, [exp_pkt1, exp_pkt2], [0, 1]) finally: sai_thrift_remove_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember1) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember2) self.client.sai_thrift_remove_next_hop_group(nhop_group1) self.client.sai_thrift_remove_next_hop(nhop1) self.client.sai_thrift_remove_next_hop(nhop2) sai_thrift_remove_neighbor(self.client, addr_family, rif1, ip_addr1, dmac1) sai_thrift_remove_neighbor(self.client, addr_family, rif2, ip_addr1, dmac2) self.client.sai_thrift_remove_router_interface(rif1) self.client.sai_thrift_remove_router_interface(rif2) self.client.sai_thrift_remove_router_interface(rif3) self.client.sai_thrift_remove_virtual_router(vr1) @group('l3') @group('ecmp') class L3IPv4EcmpLpmTest(sai_base_test.ThriftInterfaceDataPlane): def runTest(self): print print "Sending packet port 3 -> port [0,1,2] (192.168.0.1 -> 10.10.10.1 [id = 101])" switch_init(self.client) port1 = port_list[0] port2 = port_list[1] port3 = port_list[2] port4 = port_list[3] v4_enabled = 1 v6_enabled = 1 mac = '' addr_family = SAI_IP_ADDR_FAMILY_IPV4 ip_addr1 = '10.10.0.0' ip_mask1 = '255.255.0.0' ip_mask2 = '255.255.255.0' nhop_ip1 = '11.11.11.11' nhop_ip1_subnet = '11.11.11.0' nhop_ip2 = '22.22.22.22' nhop_ip2_subnet = '22.22.22.0' nhop_ip3 = '33.33.33.33' nhop_ip3_subnet = '33.33.33.0' dmac1 = '00:11:22:33:44:55' dmac2 = '00:11:22:33:44:56' dmac3 = '00:11:22:33:44:57' vr1 = sai_thrift_create_virtual_router(self.client, v4_enabled, v6_enabled) rif1 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port1, 0, v4_enabled, v6_enabled, mac) rif2 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port2, 0, v4_enabled, v6_enabled, mac) rif3 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port3, 0, v4_enabled, v6_enabled, mac) rif4 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port4, 0, v4_enabled, v6_enabled, mac) sai_thrift_create_neighbor(self.client, addr_family, rif1, nhop_ip1, dmac1) sai_thrift_create_neighbor(self.client, addr_family, rif2, nhop_ip2, dmac2) sai_thrift_create_neighbor(self.client, addr_family, rif3, nhop_ip3, dmac3) nhop1 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip1, rif1) nhop2 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip2, rif2) nhop3 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip3, rif3) nhop_group1 = sai_thrift_create_next_hop_group(self.client) nhop_gmember1 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop1) nhop_gmember2 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop2) nhop_gmember3 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop3) sai_thrift_create_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) sai_thrift_create_route(self.client, vr1, addr_family, nhop_ip1_subnet, ip_mask2, rif1) sai_thrift_create_route(self.client, vr1, addr_family, nhop_ip2_subnet, ip_mask2, rif2) sai_thrift_create_route(self.client, vr1, addr_family, nhop_ip3_subnet, ip_mask2, rif3) # send the test packet(s) try: count = [0, 0, 0] dst_ip = int(socket.inet_aton('10.10.10.1').encode('hex'),16) max_itrs = 200 src_mac_start = '00:22:22:22:22:' for i in range(0, max_itrs): dst_ip_addr = socket.inet_ntoa(hex(dst_ip)[2:].zfill(8).decode('hex')) src_mac = src_mac_start + str(i%99).zfill(2) pkt = simple_tcp_packet(eth_dst=router_mac, eth_src=src_mac, ip_dst=dst_ip_addr, ip_src='192.168.8.1', ip_id=106, ip_ttl=64) exp_pkt1 = simple_tcp_packet(eth_dst='00:11:22:33:44:55', eth_src=router_mac, ip_dst=dst_ip_addr, ip_src='192.168.8.1', ip_id=106, ip_ttl=63) exp_pkt2 = simple_tcp_packet(eth_dst='00:11:22:33:44:56', eth_src=router_mac, ip_dst=dst_ip_addr, ip_src='192.168.8.1', ip_id=106, ip_ttl=63) exp_pkt3 = simple_tcp_packet(eth_dst='00:11:22:33:44:57', eth_src=router_mac, ip_dst=dst_ip_addr, ip_src='192.168.8.1', ip_id=106, ip_ttl=63) send_packet(self, 3, str(pkt)) rcv_idx = verify_any_packet_any_port(self, [exp_pkt1, exp_pkt2, exp_pkt3], [0, 1, 2]) count[rcv_idx] += 1 dst_ip += 1 for i in range(0, 3): self.assertTrue((count[i] >= ((max_itrs / 3) * 0.8)), "Not all paths are equally balanced, %s" % count) finally: sai_thrift_remove_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) sai_thrift_remove_route(self.client, vr1, addr_family, nhop_ip1_subnet, ip_mask2, rif1) sai_thrift_remove_route(self.client, vr1, addr_family, nhop_ip2_subnet, ip_mask2, rif2) sai_thrift_remove_route(self.client, vr1, addr_family, nhop_ip3_subnet, ip_mask2, rif3) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember1) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember2) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember3) self.client.sai_thrift_remove_next_hop_group(nhop_group1) self.client.sai_thrift_remove_next_hop(nhop1) self.client.sai_thrift_remove_next_hop(nhop2) self.client.sai_thrift_remove_next_hop(nhop3) sai_thrift_remove_neighbor(self.client, addr_family, rif1, nhop_ip1, dmac1) sai_thrift_remove_neighbor(self.client, addr_family, rif2, nhop_ip2, dmac2) sai_thrift_remove_neighbor(self.client, addr_family, rif3, nhop_ip3, dmac3) self.client.sai_thrift_remove_router_interface(rif1) self.client.sai_thrift_remove_router_interface(rif2) self.client.sai_thrift_remove_router_interface(rif3) self.client.sai_thrift_remove_router_interface(rif4) self.client.sai_thrift_remove_virtual_router(vr1) @group('l3') @group('ecmp') class L3IPv6EcmpLpmTest(sai_base_test.ThriftInterfaceDataPlane): def runTest(self): print print "Sending packet port 1 -> port 2 (192.168.0.1 -> 10.10.10.1 [id = 101])" switch_init(self.client) port1 = port_list[0] port2 = port_list[1] port3 = port_list[2] port4 = port_list[3] v4_enabled = 1 v6_enabled = 1 mac = '' addr_family = SAI_IP_ADDR_FAMILY_IPV6 ip_addr1 = 'fc00:e968:6179::de52:7100' ip_mask1 = 'fc00:e968:6179::de52:7100' nhop_ip1 = 'fc00:e968:6179::de52:7100' nhop_ip2 = 'fdf8:f53e:61e4::18' nhop_ip3 = 'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b' dmac1 = '00:11:22:33:44:55' dmac2 = '00:11:22:33:44:56' dmac3 = '00:11:22:33:44:57' vr1 = sai_thrift_create_virtual_router(self.client, v4_enabled, v6_enabled) rif1 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port1, 0, v4_enabled, v6_enabled, mac) rif2 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port2, 0, v4_enabled, v6_enabled, mac) rif3 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port3, 0, v4_enabled, v6_enabled, mac) rif4 = sai_thrift_create_router_interface(self.client, vr1, SAI_ROUTER_INTERFACE_TYPE_PORT, port4, 0, v4_enabled, v6_enabled, mac) sai_thrift_create_neighbor(self.client, addr_family, rif1, nhop_ip1, dmac1) sai_thrift_create_neighbor(self.client, addr_family, rif2, nhop_ip2, dmac2) sai_thrift_create_neighbor(self.client, addr_family, rif3, nhop_ip3, dmac3) nhop1 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip1, rif1) nhop2 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip2, rif2) nhop3 = sai_thrift_create_nhop(self.client, addr_family, nhop_ip3, rif3) nhop_group1 = sai_thrift_create_next_hop_group(self.client) nhop_gmember1 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop1) nhop_gmember2 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop2) nhop_gmember3 = sai_thrift_create_next_hop_group_member(self.client, nhop_group1, nhop3) sai_thrift_create_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) # send the test packet(s) try: count = [0, 0, 0] dst_ip = socket.inet_pton(socket.AF_INET6, 'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b') dst_ip_arr = list(dst_ip) src_mac_start = '00:22:22:22:22:' max_itrs = 200 sport = 0x1234 dport = 0x50 for i in range(0, max_itrs): dst_ip_addr = socket.inet_ntop(socket.AF_INET6, dst_ip) src_mac = src_mac_start + str(i%99).zfill(2) #HACK: sport is a hack for hashing since the ecmp hash does not #include ipv6 sa and da. pkt = simple_tcpv6_packet( eth_dst=router_mac, eth_src=src_mac, ipv6_dst=dst_ip_addr, ipv6_src='fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', tcp_sport=sport, tcp_dport=dport, ipv6_hlim=64) exp_pkt1 = simple_tcpv6_packet( eth_dst='00:11:22:33:44:55', eth_src=router_mac, ipv6_dst=dst_ip_addr, ipv6_src='fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', tcp_sport=sport, tcp_dport=dport, ipv6_hlim=63) exp_pkt2 = simple_tcpv6_packet( eth_dst='00:11:22:33:44:56', eth_src=router_mac, ipv6_dst=dst_ip_addr, ipv6_src='fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', tcp_sport=sport, tcp_dport=dport, ipv6_hlim=63) exp_pkt3 = simple_tcpv6_packet( eth_dst='00:11:22:33:44:57', eth_src=router_mac, ipv6_dst=dst_ip_addr, ipv6_src='fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', tcp_sport=sport, tcp_dport=dport, ipv6_hlim=63) exp_pkt4 = simple_tcpv6_packet( eth_dst='00:11:22:33:44:58', eth_src=router_mac, ipv6_dst=dst_ip_addr, ipv6_src='fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', tcp_sport=sport, tcp_dport=dport, ipv6_hlim=63) send_packet(self, 3, str(pkt)) rcv_idx = verify_any_packet_any_port(self, [exp_pkt1, exp_pkt2, exp_pkt3], [0, 1, 2]) count[rcv_idx] += 1 dst_ip_arr[15] = chr(ord(dst_ip_arr[15]) + 1) dst_ip = ''.join(dst_ip_arr) sport += 15 dport += 20 print "Count = %s" % str(count) for i in range(0, 3): self.assertTrue((count[i] >= ((max_itrs / 3) * 0.75)), "Not all paths are equally balanced") finally: sai_thrift_remove_route(self.client, vr1, addr_family, ip_addr1, ip_mask1, nhop_group1) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember1) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember2) self.client.sai_thrift_remove_next_hop_group_member(nhop_gmember3) self.client.sai_thrift_remove_next_hop_group(nhop_group1) self.client.sai_thrift_remove_next_hop(nhop1) self.client.sai_thrift_remove_next_hop(nhop2) self.client.sai_thrift_remove_next_hop(nhop3) sai_thrift_remove_neighbor(self.client, addr_family, rif1, nhop_ip1, dmac1) sai_thrift_remove_neighbor(self.client, addr_family, rif2, nhop_ip2, dmac2) sai_thrift_remove_neighbor(self.client, addr_family, rif3, nhop_ip3, dmac3) self.client.sai_thrift_remove_router_interface(rif1) self.client.sai_thrift_remove_router_interface(rif2) self.client.sai_thrift_remove_router_interface(rif3) self.client.sai_thrift_remove_router_interface(rif4) self.client.sai_thrift_remove_virtual_router(vr1) @group('l3') @group('ecmp') class L3IPv4EcmpHashSeedTest(sai_base_test.ThriftInterfaceDataPlane): def runTest(self): ''' Create a VRF with IPv4 and IPv6 enabled. Create 4 router interfaces in the same VRF. Create a route (/24 mask) with nhop and neighbor entry in three router interfaces. Send 100 streams with varying 5-tuple combinations to the destination IP on one port and verify distribution on the three router interfaces for which the nhops are present. Change the ECMP hash seed value to 10 and verify distribution. ''' print "Sending packet port4 -> port1,port2,port3 (192.168.6.1 to 10.10.10.1) " switch_init(self.client) port1 = port_list[0] port2 = port_list[1] port3 = port_list[2] port4 = port_list[3] v4_enabled = 1 v6_enabled = 1 mac = '' hash_seed = 10 addr_family = SAI_IP_ADDR_FAMILY_IPV4 ip_addr1 = '192.168.1.1' ip_addr2 = '192.168.2.1' ip_addr3 = '192.168.3.1' ip_addr4 = '10.10.10.0' ip_addr1_subnet = '192.168.1.0' ip_addr2_subnet = '192.168.2.0' ip_addr3_subnet = '192.168.3.0' ip_mask = '255.255.255.0' destmac1 = '00:11:22:33:44:51' destmac2 = '00:11:22:33:44:52' destmac3 = '00:11:22:33:44:53' virtual_router = sai_thrift_create_virtual_router(self.client, v4_enabled, v6_enabled) router_interface1 = sai_thrift_create_router_interface(self.client, virtual_router, SAI_ROUTER_INTERFACE_TYPE_PORT, port1, 0, v4_enabled, v6_enabled, mac) router_interface2 = sai_thrift_create_router_interface(self.client, virtual_router, SAI_ROUTER_INTERFACE_TYPE_PORT, port2, 0, v4_enabled, v6_enabled, mac) router_interface3 = sai_thrift_create_router_interface(self.client, virtual_router, SAI_ROUTER_INTERFACE_TYPE_PORT, port3, 0, v4_enabled, v6_enabled, mac) router_interface4 = sai_thrift_create_router_interface(self.client, virtual_router, SAI_ROUTER_INTERFACE_TYPE_PORT, port4, 0, v4_enabled, v6_enabled, mac) sai_thrift_create_neighbor(self.client, addr_family, router_interface1, ip_addr1, destmac1) sai_thrift_create_neighbor(self.client, addr_family, router_interface2, ip_addr2, destmac2) sai_thrift_create_neighbor(self.client, addr_family, router_interface3, ip_addr3, destmac3) next_hop1 = sai_thrift_create_nhop(self.client, addr_family, ip_addr1, router_interface1) next_hop2 = sai_thrift_create_nhop(self.client, addr_family, ip_addr2, router_interface2) next_hop3 = sai_thrift_create_nhop(self.client, addr_family, ip_addr3, router_interface3) nexthop_group = sai_thrift_create_next_hop_group(self.client) nexthop_gmember1 = sai_thrift_create_next_hop_group_member(self.client, nexthop_group, next_hop1) nexthop_gmember2 = sai_thrift_create_next_hop_group_member(self.client, nexthop_group, next_hop2) nexthop_gmember3 = sai_thrift_create_next_hop_group_member(self.client, nexthop_group, next_hop3) sai_thrift_create_route(self.client, virtual_router, addr_family, ip_addr4, ip_mask, nexthop_group) try: count = [0, 0, 0] maximum_packets = 101 src_mac_start = '00:22:22:22:22:' ip_src_start = '192.168.6.' ip_dst_start = '10.10.10.' destination_port = 0x80 source_port = 0x1234 for i in range(1, maximum_packets): src_mac = src_mac_start + str(i % 99).zfill(2) ip_source = ip_src_start + str(i % 99).zfill(3) ip_destination= ip_dst_start + str(i % 99).zfill(3) if (i%100) == 0: print " %s packets are sent ...." % (i) packet = simple_tcp_packet(eth_dst=router_mac, eth_src=src_mac, ip_dst=ip_destination, ip_src=ip_source, tcp_sport=source_port, tcp_dport=destination_port, ip_id=106, ip_ttl=64) #expected packet at port1 expected_packet1 = simple_tcp_packet(eth_dst='00:11:22:33:44:51', eth_src=router_mac, ip_dst= ip_destination, ip_src=ip_source, tcp_sport=source_port, tcp_dport=destination_port, ip_id=106, ip_ttl=63) #expected packet at port2 expected_packet2 = simple_tcp_packet(eth_dst='00:11:22:33:44:52', eth_src = router_mac, ip_dst= ip_destination, ip_src=ip_source, tcp_sport=source_port, tcp_dport=destination_port, ip_id =106, ip_ttl=63) #expected packet at port3 expected_packet3 = simple_tcp_packet(eth_dst='00:11:22:33:44:53', eth_src = router_mac, ip_dst= ip_destination, ip_src=ip_source, tcp_sport=source_port, tcp_dport=destination_port, ip_id =106, ip_ttl=63) send_packet(self, 3, str(packet)) rcv_idx = verify_any_packet_any_port(self, [expected_packet1, expected_packet2, expected_packet3], [0, 1, 2]) count[rcv_idx] += 1 source_port += 1 destination_port += 1 print "Packet distribution With default HashSeed value" for i in range(0,3): print "packets received at port interface : " + i
cwave, cscale, cscale_type, segments, copy=False): if copy: smod = np.copy(smod) if cscale is None: return smod for il in segments: if cscale[il] is not None and not np.all(cscale[il] == 0): if cscale_type in ["spline", "spline+mask"]: if len(cscale[il]) != len(smod[il]): cs = np.interp(wave[il], cwave[il], cscale[il]) else: cs = cscale[il] smod[il] *= cs else: x = wave[il] - wave[il][0] smod[il] *= np.polyval(cscale[il], x) return smod def apply_radial_velocity_and_continuum( wave, wmod, smod, vrad, cscale, cscale_type, segments, copy=False ): """ Apply the radial velocity and continuum corrections to a syntheic spectrum to match the observation Parameters ---------- wave : array final wavelength array of the observation wmod : array wavelength array of the synthethic spectrum smod : array flux array of the synthetic spectrum vrad : array, None radial velocities in km/s for each segment cscale : array, None continnum scales for each segment, exact meaning depends on cscale_type cscale_type : str defines the continuum correction behaviour segments : array the segments to apply the correction to Returns ------- smod : array the corrected synthetic spectrum """ smod = apply_radial_velocity(wave, wmod, smod, vrad, segments, copy=copy) # The radial velocity shift also interpolates onto the wavelength grid smod = apply_continuum(wave, smod, wave, cscale, cscale_type, segments, copy=copy) return smod def null_result(nseg, ndeg=0, ctype=None): vrad, vrad_unc = np.zeros(nseg), np.zeros((nseg, 2)) if ctype in ["spline", "spline+mask"]: cscale = [np.ones(ndeg[i]) for i in range(nseg)] cscale = Iliffe_vector(values=cscale) cscale_unc = [np.zeros(ndeg[i]) for i in range(nseg)] cscale_unc = Iliffe_vector(values=cscale_unc) else: cscale, cscale_unc = np.zeros((nseg, ndeg + 1)), np.zeros((nseg, ndeg + 1, 2)) cscale[:, -1] = 1 return vrad, vrad_unc, cscale, cscale_unc def cross_correlate_segment(x_obs, y_obs, x_syn, y_syn, mask, rv_bounds): # Interpolate synthetic observation onto the observation wavelength grid y_tmp = np.interp(x_obs, x_syn, y_syn) # Normalize both spectra y_obs_tmp = y_obs - np.min(y_obs) y_obs_tmp /= np.nanpercentile(y_obs_tmp, 95) y_obs_tmp -= 1 y_tmp_tmp = y_tmp - np.min(y_tmp) y_tmp_tmp /= np.nanpercentile(y_tmp_tmp, 95) y_tmp_tmp -= 1 # Perform cross correaltion between normalized spectra corr = correlate(y_obs_tmp, y_tmp_tmp, mode="same") # Determine the radial velocity offset # and only retain the area within the bounds x_mid = x_obs[len(x_obs) // 2] x_shift = c_light * (1 - x_mid / x_obs) idx = (x_shift >= rv_bounds[0]) & (x_shift <= rv_bounds[1]) x_shift = x_shift[idx] corr = corr[idx] return x_shift, corr def determine_radial_velocity( sme, x_syn, y_syn, segment, cscale=None, only_mask=False, rv_bounds=(-100, 100), whole=False, ): """ Calculate radial velocity by using cross correlation and least-squares between observation and synthetic spectrum Parameters ---------- sme : SME_Struct sme structure with observed spectrum and flags segment : int which wavelength segment to handle, -1 if its using the whole spectrum cscale : array of size (ndeg,) continuum coefficients, as determined by e.g. determine_continuum x_syn : array of size (n,) wavelength of the synthetic spectrum y_syn : array of size (n,) intensity of the synthetic spectrum Raises ------ ValueError if sme.vrad_flag is not recognized Returns ------- rvel : float best fit radial velocity for this segment/whole spectrum or None if no observation is present """ if "spec" not in sme or "wave" not in sme: # No observation no radial velocity warnings.warn("Missing data for radial velocity determination") rvel = 0 elif sme.vrad_flag == "none": # vrad_flag says don't determine radial velocity rvel = sme.vrad[segment] elif sme.vrad_flag == "whole" and not whole: # We are inside a segment, but only want to determine rv at the end rvel = 0 elif sme.vrad_flag == "fix": rvel = sme.vrad[segment] else: # Fit radial velocity # Extract data x, y = sme.wave, sme.spec if "mask" in sme: m = sme.mask else: m = sme.spec.copy() m[:] = sme.mask_values["line"] if "uncs" in sme: u = sme.uncs else: u = sme.spec.copy() u[:] = 1 # Only this one segment x_obs = x[segment] y_obs = y[segment].copy() u_obs = u[segment] mask = m[segment] if sme.telluric is not None: tell = sme.telluric[segment] else: tell = 1 if sme.vrad_flag == "each": # apply continuum y_syn = apply_continuum( {segment: x_syn}, {segment: y_syn}, sme.wave, {segment: cscale}, sme.cscale_type, [segment], )[segment] elif sme.vrad_flag == "whole": # All segments y_syn = apply_continuum( x_syn, y_syn, sme.wave, cscale, sme.cscale_type, range(len(y_obs)), ) else: raise ValueError( f"Radial velocity flag {sme.vrad_flag} not recognised, expected one of 'each', 'whole', 'none'" ) if only_mask: mask = mask == sme.mask_values["continuum"] else: mask = mask == sme.mask_values["line"] mask |= mask == sme.mask_values["continuum"] # x_obs = x_obs[mask] # y_obs = y_obs[mask] # u_obs = u_obs[mask] # y_tmp = np.interp(x_obs, x_syn, y_syn) # if sme.telluric is not None: # tell = tell[mask] # else: # tell = 1 # Get a first rough estimate from cross correlation if sme.vrad_flag == "each": x_shift, corr = cross_correlate_segment( x_obs, y_obs, x_syn, y_syn, mask, rv_bounds ) else: # If using several segments we run the cross correlation for each # segment seperately and then sum the results nseg = len(segment) shift = [None for _ in range(nseg)] corr = [None for _ in range(nseg)] for i in range(len(x_obs)): shift[i], corr[i] = cross_correlate_segment( x_obs[i], y_obs[i], x_syn[i], y_syn[i], mask[i], rv_bounds ) n_min = min([len(s) for s in shift]) x_shift = np.linspace(rv_bounds[0], rv_bounds[1], n_min) corrs_interp = [np.interp(x_shift, s, c) for s, c in zip(shift, corr)] corrs_interp = np.array(corrs_interp) corr = np.sum(corrs_interp, axis=0) mask = np.concatenate(mask) x_obs = np.concatenate(x_obs)[mask] y_obs = np.concatenate(y_obs)[mask] u_obs = np.concatenate(u_obs)[mask] x_syn = np.concatenate(x_syn) y_syn = np.concatenate(y_syn) if sme.telluric is not None: tell = np.concatenate(tell)[mask] # Retrieve the initial cross correlation guess offset = np.argmax(corr) rvel = x_shift[offset] # Then minimize the least squares for a better fit # as cross correlation can only find def func(rv): rv_factor = np.sqrt((1 - rv / c_light) / (1 + rv / c_light)) shifted = interpolator(x_obs * rv_factor) resid = (y_obs - shifted * tell) / u_obs resid = np.nan_to_num(resid, copy=False) return resid interpolator = lambda x: np.interp(x, x_syn, y_syn) res = least_squares(func, x0=rvel, loss="soft_l1", bounds=rv_bounds) rvel = res.x[0] return rvel def match_rv_continuum(sme, segments, x_syn, y_syn): """ Match both the continuum and the radial velocity of observed/synthetic spectrum Note that the parameterization of the continuum is different to old SME !!! Parameters ---------- sme : SME_Struct input sme structure with all the parameters segment : int index of the wavelength segment to match, or -1 when dealing with the whole spectrum x_syn : array of size (n,) wavelength of the synthetic spectrum y_syn : array of size (n,) intensitz of the synthetic spectrum Returns ------- rvel : float new radial velocity cscale : array of size (ndeg + 1,) new continuum coefficients """ cont_func = { "mask": ContinuumNormalizationMask, "match": ContinuumNormalizationMatch, "match+mask": ContinuumNormalizationMatchMask, "spline": ContinuumNormalizationSpline, "spline+mask": ContinuumNormalizationSplineMask, "mcmc": ContinuumNormalizationMCMC, } vrad, vrad_unc, cscale, cscale_unc = null_result( sme.nseg, sme.cscale_degree, sme.cscale_type ) if sme.cscale_flag == "none" and sme.vrad_flag == "none": return cscale, cscale_unc, vrad, vrad_unc if np.isscalar(segments): segments = [segments] if not callable(sme.vrad_flag): radial_velocity = determine_radial_velocity else: radial_velocity = sme.vrad_flag if not callable(sme.cscale_type): continuum_normalization = cont_func[sme.cscale_type]() else: continuum_normalization = sme.cscale_type if sme.vrad_flag == "none": pass elif sme.vrad_flag == "fix": vrad[segments] = sme.vrad[segments] elif sme.vrad_flag == "each": for s in segments: # We only use the continuum mask for the continuum fit, # we need the lines for the radial velocity vrad[s] = radial_velocity(sme, x_syn[s], y_syn[s], s, cscale[s]) elif sme.vrad_flag == "whole": s = segments vrad[s] = radial_velocity( sme, [x_syn[s] for s in s], [y_syn[s] for s in s], s, cscale[s], whole=True, ) else: raise ValueError if sme.cscale_flag == "none": pass elif sme.cscale_flag == "fix": if sme.cscale is not None: cscale[segments] = sme.cscale[segments] else: pass else: if sme.cscale_type == "mcmc": for s in segments: ( vrad[s], vrad_unc[s], cscale[s], cscale_unc[s], ) = continuum_normalization(sme, x_syn[s], y_syn[s], s, rvel=vrad[s]) else: for s in segments: cscale[s] = continuum_normalization( sme, x_syn[s], y_syn[s], s, rvel=vrad[s] ) # Keep values from unused segments select = np.arange(sme.nseg) mask = np.full(select.shape, True) for seg in segments: mask &= select != seg vrad[mask] = sme.vrad[mask] if sme.cscale_type in ["spline", "spline+mask"]: for i in range(len(mask)): if ( mask[i] and sme.cscale is not None and len(cscale[i]) ==
self.__tokenText() try: n = self.__iparse(text) except: self.__error() t = self.__tokenPop() self.__renumber(n,t) if isPy38: self._transfer_end_attributes([n]) return n def __from(self): return self.__import(stmt='from') def __assert(self): return self.__import(stmt='assert') def __script(self,mode='script'): end = 'end'+mode self.__tokenPop() if self._tokens[self._tokenX].kind==end: self.__tokenPop() return [] dcoffs, text = dedent(self.__tokenText(strip=0,colonRemove=False)) scriptMode = 'script'==mode if text: try: n = self.__rparse(text) except: self.__error() t = self.__tokenPop() try: assert self._tokens[self._tokenX].kind==end self.__tokenPop() except: self.__error(end+' expected') if not text: return [] if mode=='eval': n = ast.Expr(value=ast.Call(func=ast.Name(id='__swrite__',ctx=ast.Load()),args=n,keywords=[],starargs=None,kwargs=None)) self.__renumber(n,t,dcoffs=dcoffs) return n def __eval(self): return self.__script(mode='eval') def __if(self): tokens = self._tokens k = 'elif' I = None while k=='elif': try: t = self._tokenX text = self.__tokenText(forceColonPass=1) if text.startswith('elif'): text = 'if '+text[4:] n = self.__iparse(text) except: self.__error() self.__tokenPop() self.__renumber(n,tokens[t]) n.body = self.__preppy(followers=['endif','elif','else'],fixEmpty=True) if I: p.orelse = [n] else: I = n p = n k = tokens[self._tokenX-1].kind #we consumed the terminal in __preppy if k=='elif': self._tokenX -= 1 if k=='else': p.orelse = self.__preppy(followers=['endif']) if isPy38: self._transfer_end_attributes([I]) return I def __const(self): try: n = ast.Expr(value=ast.Call(func=ast.Name(id='__write__',ctx=ast.Load()),args=[ast.Str(s=self.__tokenText(strip=0))],keywords=[],starargs=None,kwargs=None)) except: self.__error('bad constant') t = self.__tokenPop() self.__renumber(n,t) return n def __expr(self): t = self.__tokenText() try: n = ast.Expr(value=ast.Call(func=ast.Name(id='__swrite__',ctx=ast.Load()),args=[self.__rparse(t)[0].value],keywords=[],starargs=None,kwargs=None)) except: self.__error('bad expression') t = self.__tokenPop() self.__renumber(n,t) if isPy38: self._transfer_end_attributes([n]) return n def __error(self,msg='invalid syntax'): pos = self._tokens[self._tokenX].start f = StringIO() traceback.print_exc(file=f) f = f.getvalue() m = 'File "<string>", line ' i = f.rfind('File "<string>", line ') if i<0: t, v = map(str,sys.exc_info()[:2]) self.__lexerror('%s %s(%s)' % (msg, t, v),pos) else: i += len(m) f = f[i:].split('\n') n = int(f[0].strip())+self.source[:pos].count('\n') raise SyntaxError(' File %s, line %d\n%s' % (self.filename,n,'\n'.join(f[1:]))) def __serror(self,msg='invalid syntax'): self.__lexerror(msg,self._tokens[self._tokenX].start) def __parse(self,text=None): if text: self.source = text self.__tokenize() return self.__preppy() @staticmethod def dump(node,annotate_fields=False,include_attributes=True): return ('[%s]' % ', '.join(PreppyParser.dump(x,annotate_fields=annotate_fields,include_attributes=include_attributes) for x in node) if isinstance(node,list) else ast.dump(node,annotate_fields=annotate_fields, include_attributes=include_attributes)) def __get_pre_preamble(self): return ('from preppy import include, __preppy__vlhs__, __get_conv__, __wsscontroller__\n' if self._defSeen==1 else 'from preppy import include, rl_exec as __rl_exec__, __preppy__vlhs__, __get_conv__, __wsscontroller__\n') def __get_ast(self): preppyNodes = self.__parse() flno = (AbsLineNo(1),0) if isPy38: flno = flno+flno llno = (AbsLineNo(self.__lineno(self._tokens[-1].end)),0) #last line number information if isPy38: llno = llno + llno if self._defSeen==1: t, F = self._fnc_defn args = F.args if args.kwarg: kwargName = args.kwarg.arg if isPy34 else args.kwarg CKWA = [] else: if isPy3: argNames = [a.arg for a in args.args] + [a.arg for a in args.kwonlyargs] if args.vararg: argNames += [args.vararg.arg if isPy34 else args.vararg] else: argNames = [a.id for a in args.args] if args.vararg: argNames += [args.vararg] #choose a kwargName not in existing names kwargName = '__kwds__' while kwargName in argNames: kwargName = kwargname.replace('s_','ss_') if isPy34: args.kwarg = ast.arg(kwargName,None) args.kwarg.lineno = F.lineno args.kwarg.col_offset = F.col_offset else: args.kwarg = kwargName CKWA = ["if %s: raise TypeError('get: unexpected keyword arguments %%r' %% %s)" % (kwargName,kwargName)] leadNodes=self.__rparse('\n'.join([ "__lquoteFunc__=%s.setdefault('__lquoteFunc__',None)" % kwargName, "%s.pop('__lquoteFunc__')" % kwargName, "__quoteFunc__=%s.setdefault('__quoteFunc__',None)" % kwargName, "%s.pop('__quoteFunc__')" % kwargName, '__qFunc__,__lqFunc__=__get_conv__(__quoteFunc__,__lquoteFunc__,%s)' % self._isBytes ] + CKWA + [ "__append__=[].append", "__wss__=__wsscontroller__()", "__write__=lambda x:__append__(__lqFunc__(__wss__.c(x)))", "__swrite__=lambda x:__append__(__qFunc__(__wss__.x(x)))", ])) trailNodes = self.__rparse("return ''.join(__append__.__self__)") self.__renumber(F,t) self.__renumber(leadNodes,flno) self.__renumber(trailNodes,llno) preppyNodes = leadNodes + preppyNodes + trailNodes global _newPreambleAst if not _newPreambleAst: _newPreambleAst = self.__rparse(self.__get_pre_preamble()+_newPreamble) self.__renumber(_newPreambleAst,llno) F.body = preppyNodes extraAst = [F]+_newPreambleAst else: global _preambleAst, _preamble if not _preambleAst: #_preamble = 'from unparse import Unparser\n'+_preamble.replace('NS = {}\n','NS = {};Unparser(M,__save_sys_stdout__)\n') _preambleAst = self.__rparse(self.__get_pre_preamble()+(_preamble.replace('__isbytes__',str(self._isBytes)))) self.__renumber(_preambleAst,llno) M = ast.parse("def __code__(dictionary, outputfile, __write__,__swrite__,__save_sys_stdout__,__wss__): pass",self.filename,mode='exec') self.__renumber(M,flno) M.body[0].body = preppyNodes extraAst = self.__rparse('__preppy_nodes__=%r\n__preppy_filename__=%r\n' % (pickle.dumps(M),self.filename))+_preambleAst M = ast.parse('__checksum__=%r' % self.sourcechecksum,self.filename,mode='exec') M.body += extraAst return M _preambleAst=None _preamble='''import ast, pickle def run(dictionary, __write__=None, quoteFunc=None, outputfile=None, lquoteFunc=None): ### begin standard prologue import sys, os __preppyOverrideStdout__ = dictionary.get('__preppyOverrideStdout__',None) if __preppyOverrideStdout__ is None: __preppyOverrideStdout__ = os.environ.get('PREPPY_OVERRIDE_STDOUT','0')=='1' __save_sys_stdout__ = sys.stdout try: # compiled logic below # make sure quoteFunc is defined: qFunc, lconv = __get_conv__(quoteFunc,lquoteFunc,__isbytes__) globals()['__quoteFunc__'] = qFunc globals()['__lquoteFunc__'] = lconv # make sure __write__ is defined class dummyfile: pass if __write__: if outputfile is not None: raise ValueError("do not define both outputfile (%r) and __write__ (%r)." %(outputfile, __write__)) outputfile = dummyfile() outputfile.write = __write__ else: if not outputfile: outputfile = sys.stdout __write__ = outputfile.write __wss__=__wsscontroller__() __swrite__ = lambda x: __write__(qFunc(__wss__.x(x))) __lwrite__ = lambda x: __write__(lconv(__wss__.c(x))) if __preppyOverrideStdout__: sys.stdout = dummyfile() sys.stdout.write = __swrite__ M = pickle.loads(__preppy_nodes__) b = M.body[0].body for k in dictionary: try: if k not in ('dictionary','__write__', '__swrite__','outputfile','__save_sys_stdout__','__wss__') and __preppy__vlhs__(k): b.insert(0,ast.parse('%s=dictionary[%r]' % (k,k),'???',mode='exec').body[0]) except: pass NS = {} NS['include'] = include __rl_exec__(compile(M,__preppy_filename__,'exec'),NS) NS['__code__'](dictionary,outputfile,__lwrite__,__swrite__,__save_sys_stdout__,__wss__) finally: #### end of compiled logic, standard cleanup if __preppyOverrideStdout__: sys.stdout = __save_sys_stdout__ def getOutputFromKeywords(quoteFunc=None, lquoteFunc=None, **kwds): buf=[] run(kwds,__write__=buf.append, quoteFunc=quoteFunc, lquoteFunc=lquoteFunc) if quoteFunc is None: quoteFunc = __get_conv__(None,None,__isbytes__)[0] return quoteFunc('')[0:0].join(buf) def getOutput(dictionary, quoteFunc=None, lquoteFunc=None): return getOutputFromKeywords(quoteFunc=quoteFunc, lquoteFunc=lquoteFunc, **dictionary) if __name__=='__main__': run() ''' _newPreambleAst=None _newPreamble='''def run(*args,**kwds): raise ValueError('Wrong kind of prep file') def getOutput(*args,**kwds): run() if __name__=='__main__': run() ''' def testgetOutput(name="testoutput"): mod = getModule(name,'.',savePyc=1,sourcetext=teststring,importModule=1) pel(mod.getOutput({})) def testgetmodule(name="testoutput"): #name = "testpreppy" pel("trying to load"+name) result = getPreppyModule(name, verbose=1) pel( "load successful! running result") pel("=" * 100) result.run({}) if isPy34: from importlib import util as importlib_util from types import ModuleType as preppy_new_module MAGIC_NUMBER = importlib_util.MAGIC_NUMBER def __rl_get_module__(name,dir): for ext in ('.py','.pyw','.pyo','.pyc','.pyd'): path = os.path.join(dir,name+ext) if os.path.isfile(path): spec = importlib_util.spec_from_file_location(name,path) return spec.loader.load_module() raise ImportError('no suitable file found') else: import imp MAGIC_NUMBER = imp.get_magic() preppy_new_module = imp.new_module def __rl_get_module__(name,dir): f, p, desc= imp.find_module(name,[dir]) try: return imp.load_module(name,f,p,desc) finally: if f: f.close() def rl_get_module(name,dir): if name in sys.modules: om = sys.modules[name] del sys.modules[name] else: om = None try: try: m = __rl_get_module__(name,dir) t = getTimeStamp(m) if t<preppyTime: return None return m except: raise ImportError('%s[%s]' % (name,dir)) finally: if om: sys.modules[name] = om def getTimeStamp(m,default=float('Inf')): try: with open(m.__file__,'rb') as f: f.seek(4,os.SEEK_SET) return struct.unpack('<L', f.read(4))[0] except: return default def preppyTime(): try: import preppy fn = preppy.__file__ if fn.endswith('.py'): return os.stat(fn)[8] return getTimeStamp(preppy) except: return float('Inf') preppyTime = preppyTime() # cache found modules by source file name FILE_MODULES = {} SOURCE_MODULES = {} def getModule(name, directory=".", source_extension=".prep", verbose=None, savefile=None, sourcetext=None, savePy=0, force=0, savePyc=1, importModule=1, _globals=None, _existing_module=None): """Returns a python module implementing the template, compiling if needed. force: ignore up-to-date checks and always recompile. """ verbose = verbose or _verbose if isinstance(name,bytesT): name = name.decode('utf8') if isinstance(directory,bytesT): directory = directory.decode('utf8') if isinstance(source_extension,bytesT): source_extension = source_extension.decode('utf8') if isinstance(sourcetext,bytesT): sourcetext = sourcetext.decode('utf8') if hasattr(name,'read'): sourcetext = name.read() name = getattr(name,'name',None) if not name: name = '_preppy_'+getMd5(sourcetext) else: # it's possible that someone could ask for # name "subdir/spam.prep" in directory "/mydir", instead of # "spam.prep" in directory "/mydir/subdir". Failing to get # this right means getModule can fail to find it and recompile # every time. This is common during batch compilation of directories. extraDir, name = os.path.split(name) if extraDir: if os.path.isabs(extraDir): directory = extraDir else: directory = directory + os.sep + extraDir dir = os.path.abspath(os.path.normpath(directory)) # they may ask for 'spam.prep' instead of just 'spam'. Trim off # any extension name = os.path.splitext(name)[0] if verbose: pnl(' checking %s... ' % os.path.join(dir, name)) # savefile is deprecated but kept for safety. savePy and savePyc are more # explicit and are the preferred. By default it generates a pyc and no .py # file to reduce clutter. if savefile and savePyc == 0: savePyc = 1 if sourcetext is not None: # they fed us the source explicitly sourcechecksum = getMd5(sourcetext) if not name: name = '_preppy_'+sourcechecksum if verbose: pnl(" sourcetext provided... ") sourcefilename = "<input text %s>" % name nosourcefile = 1 module = SOURCE_MODULES.get(sourcetext,None) if module: return module else: nosourcefile = 0 # see if the module exists as a python file sourcefilename = os.path.join(dir, name+source_extension) module = FILE_MODULES.get(sourcefilename,None) try: module = rl_get_module(name,dir) checksum = module.__checksum__ if verbose: pnl(" found... ") except: # ImportError: #catch ALL Errors importing the module (eg name="") module = checksum = None if verbose: if verbose>2: traceback.print_exc() pnl(" pyc %s[%s] not found... " % (name,dir)) # check against source file try: sourcefile = open(sourcefilename, "r") except: if verbose: pnl(" no source file, reuse... ") if module is None: raise ValueError("couldn't find source %s or module %s" % (sourcefilename, name)) # use the existing module??? (NO SOURCE PRESENT) FILE_MODULES[sourcefilename] = module return module else: sourcetext = sourcefile.read() # NOTE: force recompile on each new version of this module. sourcechecksum = getMd5(sourcetext) if sourcechecksum==checksum: if force==0: # use the existing module. it matches if verbose: pnl("
<filename>src/plugins/brokers/kibbleES.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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. import json import elasticsearch import elasticsearch.helpers import threading import sys KIBBLE_DB_VERSION = 2 # Current DB struct version ACCEPTED_DB_VERSIONS = [1,2] # Versions we know how to work with. class KibbleESWrapper(object): """ Class for rewriting old-style queries to the new ones, where doc_type is an integral part of the DB name """ def __init__(self, ES): self.ES = ES self.indices = self.indicesClass(ES) def get(self, index, doc_type, id): return self.ES.get(index = index+'_'+doc_type, doc_type = '_doc', id = id) def exists(self, index, doc_type, id): return self.ES.exists(index = index+'_'+doc_type, doc_type = '_doc', id = id) def delete(self, index, doc_type, id): return self.ES.delete(index = index+'_'+doc_type, doc_type = '_doc', id = id) def index(self, index, doc_type, id, body): return self.ES.index(index = index+'_'+doc_type, doc_type = '_doc', id = id, body = body) def update(self, index, doc_type, id, body): return self.ES.update(index = index+'_'+doc_type, doc_type = '_doc', id = id, body = body) def search(self, index, doc_type, size = 100, _source_include = None, body = None): return self.ES.search( index = index+'_'+doc_type, doc_type = '_doc', size = size, _source_include = _source_include, body = body ) def count(self, index, doc_type, body = None): return self.ES.count( index = index+'_'+doc_type, doc_type = '_doc', body = body ) class indicesClass(object): """ Indices helper class """ def __init__(self, ES): self.ES = ES def exists(self, index): return self.ES.indices.exists(index = index) class KibbleESWrapperSeven(object): """ Class for rewriting old-style queries to the new ones, where doc_type is an integral part of the DB name and NOT USED (>= 7.x) """ def __init__(self, ES): self.ES = ES self.indices = self.indicesClass(ES) def get(self, index, doc_type, id): return self.ES.get(index = index+'_'+doc_type, id = id) def exists(self, index, doc_type, id): return self.ES.exists(index = index+'_'+doc_type, id = id) def delete(self, index, doc_type, id): return self.ES.delete(index = index+'_'+doc_type, id = id) def index(self, index, doc_type, id, body): return self.ES.index(index = index+'_'+doc_type, id = id, body = body) def update(self, index, doc_type, id, body): return self.ES.update(index = index+'_'+doc_type, id = id, body = body) def search(self, index, doc_type, size = 100, _source_includes = None, body = None): return self.ES.search( index = index+'_'+doc_type, size = size, _source_includes = _source_includes, body = body ) def count(self, index, doc_type, body = None): return self.ES.count( index = index+'_'+doc_type, body = body ) class indicesClass(object): """ Indices helper class """ def __init__(self, ES): self.ES = ES def exists(self, index): return self.ES.indices.exists(index = index) # This is redundant, refactor later? def pprint(string, err = False): line = "[core]: %s" % (string) if err: sys.stderr.write(line + "\n") else: print(line) class KibbleBit: """ KibbleBit class with direct ElasticSearch access """ def __init__(self, broker, organisation, tid): self.config = broker.config self.organisation = organisation self.broker = broker self.json_queue = [] self.queueMax = 1000 # Entries to keep before bulk pushing self.pluginname = "" self.tid = tid self.dbname = self.broker.config['elasticsearch']['database'] def __del__(self): """ On unload/delete, push the last chunks of data to ES """ if self.json_queue: print("Pushing stragglers") self.bulk() def pprint(self, string, err = False): line = "[thread#%i:%s]: %s" % (self.tid, self.pluginname, string) if err: sys.stderr.write(line + "\n") else: print(line) def updateSource(self, source): """ Updates a source document, usually with a status update """ self.broker.DB.index(index=self.broker.config['elasticsearch']['database'], doc_type="source", id=source['sourceID'], body = source ) def get(self, doctype, docid): """ Fetches a document from the DB """ doc = self.broker.DB.get(index=self.broker.config['elasticsearch']['database'], doc_type=doctype, id = docid) if doc: return doc['_source'] return None def exists(self, doctype, docid): """ Checks whether a document already exists or not """ return self.broker.DB.exists(index=self.broker.config['elasticsearch']['database'], doc_type=doctype, id = docid) def index(self, doctype, docid, document): """ Adds a new document to the index """ dbname = self.broker.config['elasticsearch']['database'] self.broker.DB.index(index=dbname, doc_type = doctype, id = docid, body = document) def append(self, t, doc): """ Append a document to the bulk push queue """ if not 'id' in doc: sys.stderr.write("No doc ID specified!\n") return doc['doctype'] = t self.json_queue.append(doc) # If we've crossed the bulk limit, do a push if len(self.json_queue) > self.queueMax: pprint("Bulk push forced") self.bulk() def bulk(self): """ Push pending JSON objects in the queue to ES""" xjson = self.json_queue js_arr = [] self.json_queue = [] for entry in xjson: js = entry doc = js js['@version'] = 1 dbname = self.broker.config['elasticsearch']['database'] if self.broker.noTypes: dbname += "_%s" % js['doctype'] js_arr.append({ '_op_type': 'update' if js.get('upsert') else 'index', '_index': dbname, '_type': '_doc', '_id': js['id'], 'doc' if js.get('upsert') else '_source': doc, 'doc_as_upsert': True, }) else: js_arr.append({ '_op_type': 'update' if js.get('upsert') else 'index', '_index': dbname, '_type': js['doctype'], '_id': js['id'], 'doc' if js.get('upsert') else '_source': doc, 'doc_as_upsert': True, }) try: elasticsearch.helpers.bulk(self.broker.oDB, js_arr) except Exception as err: pprint("Warning: Could not bulk insert: %s" % err) class KibbleOrganisation: """ KibbleOrg with direct ElasticSearch access """ def __init__(self, broker, org): """ Init an org, set up ElasticSearch for KibbleBits later on """ self.broker = broker self.id = org def sources(self, sourceType = None, view = None): """ Get all sources or sources of a specific type for an org """ s = [] # Search for all sources of this organisation mustArray = [{ 'term': { 'organisation': self.id } } ] if view: res = self.broker.DB.get( index=self.broker.config['elasticsearch']['database'], doc_type="view", id = view ) if res: mustArray.append({ 'terms': { 'sourceID': res['_source']['sourceList'] } }) # If we want a specific source type, amend the search criteria if sourceType: mustArray.append({ 'term': { 'type': sourceType } }) # Run the search, fetch all results, 9999 max. TODO: Scroll??? res = self.broker.DB.search( index=self.broker.config['elasticsearch']['database'], doc_type="source", size = 9999, body = { 'query': { 'bool': { 'must': mustArray } }, 'sort': { 'sourceURL': 'asc' } } ) for hit in res['hits']['hits']: if sourceType == None or hit['_source']['type'] == sourceType: s.append(hit['_source']) return s """ Master Kibble Broker Class for direct ElasticSearch access """ class Broker: def __init__(self, config): es_config = config['elasticsearch'] auth = None if 'user' in es_config: auth = (es_config['user'], es_config['password']) pprint("Connecting to ElasticSearch database at %s:%i..." % (es_config['hostname'], es_config.get('port', 9200))) es = elasticsearch.Elasticsearch([{ 'host': es_config['hostname'], 'port': int(es_config.get('port', 9200)), 'use_ssl': es_config.get('ssl', False), 'verify_certs': False, 'url_prefix': es_config.get('uri', ''), 'http_auth': auth }], max_retries=5, retry_on_timeout=True ) es_info = es.info() pprint("Connected!") self.DB = es self.oDB = es # Original ES class, always. the .DB may change self.config = config self.bitClass = KibbleBit # This bit is required since ES 6.x and above don't like document types self.noTypes = True if int(es_info['version']['number'].split('.')[0]) >= 6 else False self.seven = True if int(es_info['version']['number'].split('.')[0]) >= 7 else False if self.noTypes: pprint("This is a type-less DB, expanding database names instead.") if self.seven: pprint("We're using ES >= 7.x, NO DOC_TYPE!") es = KibbleESWrapperSeven(es) else: es = KibbleESWrapper(es) self.DB = es if not es.indices.exists(index = es_config['database'] + "_api"): sys.stderr.write("Could not find database group %s_* in ElasticSearch!\n" % es_config['database']) sys.exit(-1) else: pprint("This DB supports types, utilizing..") if not es.indices.exists(index = es_config['database']): sys.stderr.write("Could not find database %s in ElasticSearch!\n" % es_config['database']) sys.exit(-1) try: apidoc = es.get(index=es_config['database'], doc_type='api', id = 'current')['_source'] # We currently accept and know how to use DB versions 1 and 2. if apidoc['dbversion'] not in ACCEPTED_DB_VERSIONS: if apidoc['dbversion'] > KIBBLE_DB_VERSION: sys.stderr.write("The database '%s' uses a newer structure format (version %u) than the scanners (version %u). Please upgrade your scanners.\n" % (es_config['database'], apidoc['dbversion'], KIBBLE_DB_VERSION)) sys.exit(-1) if apidoc['dbversion'] < KIBBLE_DB_VERSION: sys.stderr.write("The database '%s' uses an older structure format (version %u) than the scanners (version %u). Please upgrade your main Kibble server.\n" % (es_config['database'], apidoc['dbversion'], KIBBLE_DB_VERSION)) sys.exit(-1) except: sys.stderr.write("Invalid
<reponame>zhuweiDark/fangzi #!/usr/bin/python # -*- coding: UTF-8 -*- import urllib import urllib2 import re import requests from lxml import etree #from bs4 import BeautifulSoup import chardet import xlwt #from xlwt import * import sys import os import traceback reload(sys) sys.setdefaultencoding( "utf-8" ) import requests imageDir = "/Users/zhuwei/房天下/" #filepath = '/Users/zhuwei/Documents/testpachong/text.txt' excelFilePath = "/Users/zhuwei/fangtianxia.xls" #url = "http://www.baidu.com" excelFile = xlwt.Workbook(encoding ='utf-8') excelSheet = excelFile.add_sheet(u"房天下") def getRequestUrlText(url,user_agent): try : headers = { 'User-Agent' : user_agent , 'Content-Encoding':'gzip, deflate, sdch', 'Vary':'Accept-Encoding', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Connection':'keep-alive'} response = requests.get(url,headers = headers) response.raise_for_status() response.encoding = 'gb2312' except requests.RequestException as e: print( str(e)) return None else: return response.text # 爬单个网页的内容 def getSinglePageContent(headerElement,allRowDataLists,titleStr,nowFenStr,cityStr,addressStr,urlStr): title = "" nowfenData = "" totalfen = "" zixundianhua = "" junjia = "" xiangmudizhi = "" zhulihuxing = "" jinqikaipan = "" tmpHeaderElement = headerElement[0] #名称 if titleStr == None : titleElement = tmpHeaderElement.find("./div/div/h1/strong") if len(titleElement.text) >0 : title = titleElement.text.encode('utf-8') else : print("title is not get !!!") else: title = titleStr.encode('utf-8') nowFenElement = None if nowFenStr == None : # 当前评分 nowFenElement = tmpHeaderElement.find("./div/div/a") if nowFenElement.get('target') == '_blank' : if nowFenElement != None and nowFenElement.text != None and len(nowFenElement.text) > 0 : nowfenData = nowFenElement.text.encode('utf-8') else: print("now fen is not get!!!") else : nowfenData = nowFenStr.encode("utf-8") # 总分 if nowFenElement == None : totalfen = "5分".encode('utf-8') else : totalElement = nowFenElement.find("./span") if totalElement != None and totalElement.text != None and len(totalElement.text) > 0 : tmpzongfen = totalElement.text totalfen = tmpzongfen.replace('/',"").encode('utf-8') else: print("totalelemnt is not get !!!!") # 均价 junjiaElement = tmpHeaderElement.xpath('//div/*[@class="inf_left fl "]') if isinstance(junjiaElement,list) : for tmpJunJia in junjiaElement : if tmpJunJia.get("class") == 'inf_left fl ' : tmpjunjiaData = tmpJunJia.find("./span") if tmpjunjiaData != None and tmpjunjiaData.get('class') == 'prib cn_ff' : if len(tmpjunjiaData.text) >0 : nextJunJiaStr = tmpjunjiaData.tail nextJunJiaStr = nextJunJiaStr.replace("\t","") nextJunJiaStr = nextJunJiaStr.replace("\n","") junjia = tmpjunjiaData.text.encode('utf-8') if len(nextJunJiaStr) > 0 : junjia += nextJunJiaStr.encode('utf-8') break else : tmpjunjiaData = tmpJunJia.find("./p/span") if tmpjunjiaData != None and tmpjunjiaData.get('class') == 'prib cn_ff' : if len(tmpjunjiaData.text) >0 : nextJunJiaStr = tmpjunjiaData.tail nextJunJiaStr = nextJunJiaStr.replace("\t","") nextJunJiaStr = nextJunJiaStr.replace("\n","") junjia = tmpjunjiaData.text.encode('utf-8') if len(nextJunJiaStr) > 0 : junjia += nextJunJiaStr.encode('utf-8') break else: print("junjia element is not get!!!") # 咨询电话 zixundianhuanElement = tmpHeaderElement.xpath('//*[@class="advice_left"]/p/span') #tmpHeaderElement.findall("./div/div/p/span") if isinstance(zixundianhuanElement,list) : for tmpzixunText in zixundianhuanElement : if len(tmpzixunText.text) >0 : zixundianhua += tmpzixunText.text.encode('utf-8') else : print("tmpzixunText is not found!!!") else: print("zixundianhuanElement is not list ,zixundianhua not get!!!") # 项目地址//*[@id="xfdsxq_B04_12"] xiangmudizhiElement = tmpHeaderElement.xpath('//div/*[@class="inf_left fl"]') if isinstance(xiangmudizhiElement,list) : for tmpxiangmuText in xiangmudizhiElement : if tmpxiangmuText != None and tmpxiangmuText.get('class') == 'inf_left fl' \ and (tmpxiangmuText.get('id') == 'xfdsxq_B04_12' or tmpxiangmuText.get('id') == 'xfptxq_B04_12'): tmpSpanEle = tmpxiangmuText.find("./span") if tmpSpanEle != None : tmpxiangmuTitle = tmpSpanEle.get("title") if tmpxiangmuTitle != None and len(tmpxiangmuTitle) > 0 : xiangmudizhi = tmpxiangmuTitle.encode('utf-8') break else : tmpSpanEle = tmpxiangmuText.find("./p/span") if tmpSpanEle != None : tmpxiangmuTitle = tmpSpanEle.get("title") if tmpxiangmuTitle != None and len(tmpxiangmuTitle) > 0 : xiangmudizhi = tmpxiangmuTitle.encode('utf-8') break else: print("xiangmudizhiElement is not get!!!") # 主力户型 zhulihuxingElement = tmpHeaderElement.findall("./div/div/div/a") if isinstance(zhulihuxingElement,list) and len(zhulihuxingElement) > 0: for tmpzhuliText in zhulihuxingElement : if tmpzhuliText.get("target") == '_blank': #此处需要转换转换成utf-8编码不然m2显示成乱码 tmppingfangmi = '㎡' tes11 = tmppingfangmi.encode('utf-8') tmpzhuliTextStr = tmpzhuliText.text.encode('utf-8').replace('�',tmppingfangmi).strip() if len(zhulihuxing) > 0 : zhulihuxing += (" | " + tmpzhuliTextStr.encode('utf-8')) else: zhulihuxing += tmpzhuliTextStr.encode('utf-8') else: zhulihuxingElement = tmpHeaderElement.xpath('//*[@id="xfdsxq_B04_13"][@class="inf_left fl"]/div/a') if zhulihuxingElement == None or len(zhulihuxingElement) == 0 : zhulihuxingElement = tmpHeaderElement.xpath('//*[@id="xfptxq_B04_13"][@class="inf_left fl"]/p/a') if isinstance(zhulihuxingElement,list) and len(zhulihuxingElement) > 0: for tmpzhuliText in zhulihuxingElement : if tmpzhuliText.get("target") == '_blank': #此处需要转换转换成utf-8编码不然m2显示成乱码 tmppingfangmi = '㎡' tes11 = tmppingfangmi.encode('utf-8') tmpzhuliTextStr = tmpzhuliText.text.encode('utf-8').replace('�',tmppingfangmi).strip() if len(zhulihuxing) > 0 : zhulihuxing += (" | " + tmpzhuliTextStr.encode('utf-8')) else: zhulihuxing += tmpzhuliTextStr.encode('utf-8') # 近期开盘 jinqikaipanElement = tmpHeaderElement.xpath('//div/*[@class="inf_left fl"]') if isinstance(jinqikaipanElement,list) : for subjinQiElement in jinqikaipanElement: if subjinQiElement != None and subjinQiElement.get("class") == 'inf_left fl' \ and subjinQiElement.get("id") == None : tmpKaiPanElement = subjinQiElement.find("a") tmpH3Element = subjinQiElement.find("h3") tmpPElement = subjinQiElement.find("p") if tmpKaiPanElement == None and tmpH3Element != None : tmptailText = tmpH3Element.tail if tmptailText != None : tmptailText = tmptailText.replace("\n","") tmptailText = tmptailText.replace("\t","") tmptailText = tmptailText.replace('  ',"") if len(tmptailText) > 0: jinqikaipan = tmptailText.encode('utf-8') break elif tmpKaiPanElement != None: if tmpKaiPanElement.get("class") == 'kaipan' : jinqikaipan = tmpKaiPanElement.get("title").encode('utf-8') break elif tmpKaiPanElement == None and tmpH3Element == None and tmpPElement != None : tmpAElement = tmpPElement.find("a") if tmpAElement!= None and tmpAElement.get("target") =="_blank" : jinqikaipan = tmpAElement.get("title") if len(jinqikaipan) == 0 : jinqikaipan = tmpAElement.text jinqikaipan = jinqikaipan.encode("utf-8") break elif subjinQiElement != None and subjinQiElement.get("class") == 'inf_left fl' \ and subjinQiElement.get("id") == "xfptxq_B04_12" : tmpKaiPanElement = subjinQiElement.find("span") if tmpKaiPanElement != None and len(tmpKaiPanElement.text) >0 : tmpKaiPanContent = tmpKaiPanElement.text.encode('utf-8') if tmpKaiPanContent != xiangmudizhi : jinqikaipan = tmpKaiPanContent break else: print("jinqikaipanElement is not get!!!!") rowDataList = [] rowDataList.append(title) rowDataList.append(nowfenData) rowDataList.append(totalfen) rowDataList.append(junjia) rowDataList.append(zixundianhua) rowDataList.append(zhulihuxing) rowDataList.append(xiangmudizhi) rowDataList.append(jinqikaipan) rowDataList.append(cityStr) rowDataList.append(addressStr) rowDataList.append(urlStr) allRowDataLists.append(rowDataList) #写入excel columIndexData = 0 rowIndexData = len(allRowDataLists) for tmpNameStrRow in rowDataList : tmpNameData = tmpNameStrRow if isinstance(tmpNameData,str) == False or len(tmpNameData) == 0 : tmpNameData = "None".encode("utf-8") print("rowIndex:" + str(rowIndexData)) print("columIndex:"+str(columIndexData)) print("tmpName:" +tmpNameData) excelSheet.write(rowIndexData,columIndexData,tmpNameData) columIndexData += 1 print("getSinglePageContent is done!!") def getSingleImageDownload(url,imageTitle,filePathStr,user_agent): print(url) # 开始下载单个图片 try: headers = { 'User-Agent' : user_agent , 'Content-Encoding':'gzip, deflate, sdch', 'Vary':'Accept-Encoding', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Connection':'keep-alive'} resText= requests.get(url,headers = headers, timeout=30) except requests.exceptions.RequestException as e: print ("当前图片无法下载:"+ str(e)) return False fileDstPath = filePathStr +"/"+ imageTitle +".jpg" fp = open(fileDstPath,'wb') try: fp.write(resText.content) except Exception as e: print("e:"+ str(e)) fp.close() return False fp.close() return True def getImageDownloads(url,title,user_agent) : #判断目录在不在,不再创建 if (os.path.exists(imageDir) == False) : os.mkdir(imageDir,) #判断要下载的文件在不在,不在的话创建 fileDirStr = imageDir +title if (os.path.exists(fileDirStr) == False ) : #发现文件夹没有创建,创建该文件夹 os.mkdir(fileDirStr,) resText = getRequestUrlText(url,user_agent) if resText == None : print("妈妈的获取图片失败了:"+url) return False #解析成dom树 html = etree.HTML(resText) bigImages = html.xpath('//*[@id="imageShowBig"]/li') print ("images cout: " + str(len(bigImages))) for tmpImage in bigImages : tmpImageStr = tmpImage.find("./div/a/img") if tmpImageStr == None : tmpImageStr = tmpImage.find("./div/div/a/img") imageStr = tmpImageStr.get("src") imageTile = tmpImageStr.get("alt") if len(imageStr) : if imageStr.startswith("http://"): #开始下载图片 res = getSingleImageDownload(imageStr,imageTile,fileDirStr,user_agent) if res == False : print("妈妈告诉我图片下载失败了!!") continue else: continue else: continue # 获取单页面数据 def getSinglePageContentDownloads(url,user_agent,allRowDataLists) : print("getSinglePageContentDownloads:"+url) resText = getRequestUrlText(url,user_agent) if resText == None : print("获取单页数据失败了:"+url) return False #解析dom树 html = etree.HTML(resText) links = html.xpath('//*[@id="bx1"]/div/div[1]/div[1]/div/div/ul/li') listUrl = [] for tmpChild in links : children = tmpChild.getchildren() for secondChild in children: if secondChild.get("class") == "clearfix": jumUrlattri = secondChild.find("./div/div/div/a") urlJump = jumUrlattri.get("href") if len(urlJump) : #开始撸啊撸了 if urlJump.startswith("http://"): listUrl.append(urlJump) break else : continue else : continue else : continue print ("list len is :" +str(len(listUrl))) #开始爬正文内容了哈 for urlStr in listUrl: print("contentUrl:"+urlStr) resText = getRequestUrlText(urlStr,user_agent) if resText == None : print("正文解析失败了:"+urlStr) continue html = etree.HTML(resText) headerElement = html.xpath('/html/body/div[3]/div[3]/div[2]/div[1]') titleStr = None nowFenStr = None cityStr = None addressStr = None # 还有两个需要爬,一个city 一个address #获取 city pattern = re.compile(ur'var city = \W*;') resultCity = re.search(pattern,resText) if resultCity != None and resultCity.group() != None : tmpCityStr = resultCity.group() tmpCityStr = tmpCityStr.replace('var city =',"") tmpCityStr = tmpCityStr.replace(';',"") tmpCityStr = tmpCityStr.replace('"',"") if len(tmpCityStr) > 0 : cityStr = tmpCityStr.encode('utf-8') #获取 address pattern = re.compile(ur'address=\W*;') resultAddress = re.search(pattern,resText) if resultAddress != None and resultAddress.group() != None : tmpAddressStr = resultAddress.group() tmpAddressStr = tmpAddressStr.replace('address=',"") tmpAddressStr = tmpAddressStr.replace(';',"") tmpAddressStr = tmpAddressStr.replace('"',"") tmpAddressStr = tmpAddressStr.replace('\'',"") if len(tmpAddressStr) > 0 : addressStr = tmpAddressStr.encode('utf-8') if len(headerElement) >0 : getSinglePageContent(headerElement,allRowDataLists,titleStr,nowFenStr,cityStr,addressStr,urlStr) else: # 先获取标题啊 titleElement = html.xpath('//*[@id="xfptxq_B03_01"]') if isinstance(titleElement,list) : for titleTmpElement in titleElement : if titleTmpElement.get('class') == 'ts_linear' and titleTmpElement.get('id') == 'xfptxq_B03_01' \ and len(titleTmpElement.get('title')) > 0: titleStr = titleTmpElement.get('title').encode('utf-8') break # 获取当前评分 #var score_array_total = "4.23" pattern = re.compile(ur'var score_array_total = "[0-9].*[0-9]";') resultNowFen = re.search(pattern,resText) if resultNowFen != None and resultNowFen.group() != None : groupNowFen = resultNowFen.group() groupNowFen = groupNowFen.replace('var score_array_total = ',"") groupNowFen = groupNowFen.replace(';',"") groupNowFen = groupNowFen.replace('"',"") if len(groupNowFen) > 0 : nowFenStr = groupNowFen.encode('utf-8') # 妈的一个网站多种样式,我日了狗了 # 重试另一种爬法 headerElement = html.xpath('/html/body/div[9]/div[10]/div[2]/div[1]') if len(headerElement) > 0 : getSinglePageContent(headerElement,allRowDataLists,titleStr,nowFenStr,cityStr,addressStr,urlStr) else: headerElement = html.xpath('/html/body/div[7]/div[10]/div[2]/div[1]') if len(headerElement) > 0 : getSinglePageContent(headerElement,allRowDataLists,titleStr,nowFenStr,cityStr,addressStr,urlStr) #爬图片了 currentRowDataIndex = len(allRowDataLists) -1 currentRowDataList = allRowDataLists[currentRowDataIndex] titleData = currentRowDataList[0] getImageDownloads(urlStr,titleData,user_agent) return True def main() : url = "http://newhouse.hz.fang.com/house/s" # user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' user_agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/545.1 (KHTML, like Gecko) Chrome/14.0.810.0 Safari/545.1" allRowDataLists = [] indexValue = 0 listColums = [u"标题",u"当前评分",u"总分",u"均价",u"咨询电话",u"主力户型",u"项目地址",u"近期开盘",u"城市",u"具体区",u"网站地址"] columIndex = 0 for tmpName in listColums : excelSheet.write(0,columIndex,tmpName) columIndex += 1 rowIndexData = 1 #获取内容
_simbody.Rotation_convertThreeAxesRotationToThreeAngles(self, bodyOrSpace, axis1, axis2, axis3) def convertRotationToQuaternion(self): """ convertRotationToQuaternion(Rotation self) -> SimTK::Quaternion Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_convertRotationToQuaternion(self) def convertRotationToAngleAxis(self): """ convertRotationToAngleAxis(Rotation self) -> Vec4 Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_convertRotationToAngleAxis(self) def convertRotationToBodyFixedXY(self): """ convertRotationToBodyFixedXY(Rotation self) -> Vec2 Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_convertRotationToBodyFixedXY(self) def convertRotationToBodyFixedXYZ(self): """ convertRotationToBodyFixedXYZ(Rotation self) -> Vec3 Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_convertRotationToBodyFixedXYZ(self) def isSameRotationToWithinAngle(self, R, okPointingAngleErrorRads): """ isSameRotationToWithinAngle(Rotation self, Rotation R, double okPointingAngleErrorRads) -> bool Parameters ---------- R: SimTK::Rotation_< double > const & okPointingAngleErrorRads: double """ return _simbody.Rotation_isSameRotationToWithinAngle(self, R, okPointingAngleErrorRads) def isSameRotationToWithinAngleOfMachinePrecision(self, R): """ isSameRotationToWithinAngleOfMachinePrecision(Rotation self, Rotation R) -> bool Parameters ---------- R: SimTK::Rotation_< double > const & """ return _simbody.Rotation_isSameRotationToWithinAngleOfMachinePrecision(self, R) def getMaxAbsDifferenceInRotationElements(self, R): """ getMaxAbsDifferenceInRotationElements(Rotation self, Rotation R) -> double Parameters ---------- R: SimTK::Rotation_< double > const & """ return _simbody.Rotation_getMaxAbsDifferenceInRotationElements(self, R) def areAllRotationElementsSameToEpsilon(self, R, epsilon): """ areAllRotationElementsSameToEpsilon(Rotation self, Rotation R, double epsilon) -> bool Parameters ---------- R: SimTK::Rotation_< double > const & epsilon: double """ return _simbody.Rotation_areAllRotationElementsSameToEpsilon(self, R, epsilon) def areAllRotationElementsSameToMachinePrecision(self, R): """ areAllRotationElementsSameToMachinePrecision(Rotation self, Rotation R) -> bool Parameters ---------- R: SimTK::Rotation_< double > const & """ return _simbody.Rotation_areAllRotationElementsSameToMachinePrecision(self, R) def __init__(self, *args): """ __init__(SimTK::Rotation_<(double)> self) -> Rotation __init__(SimTK::Rotation_<(double)> self, Rotation R) -> Rotation Parameters ---------- R: SimTK::Rotation_< double > const & __init__(SimTK::Rotation_<(double)> self, double angle, CoordinateAxis axis) -> Rotation Parameters ---------- angle: double axis: SimTK::CoordinateAxis const & __init__(SimTK::Rotation_<(double)> self, double angle, Vec3 nonUnitVector) -> Rotation Parameters ---------- angle: double nonUnitVector: SimTK::Vec3 const & __init__(SimTK::Rotation_<(double)> self, SimTK::BodyOrSpaceType bodyOrSpace, double angle1, CoordinateAxis axis1, double angle2, CoordinateAxis axis2) -> Rotation Parameters ---------- bodyOrSpace: enum SimTK::BodyOrSpaceType angle1: double axis1: SimTK::CoordinateAxis const & angle2: double axis2: SimTK::CoordinateAxis const & __init__(SimTK::Rotation_<(double)> self, SimTK::BodyOrSpaceType bodyOrSpace, double angle1, CoordinateAxis axis1, double angle2, CoordinateAxis axis2, double angle3, CoordinateAxis axis3) -> Rotation Parameters ---------- bodyOrSpace: enum SimTK::BodyOrSpaceType angle1: double axis1: SimTK::CoordinateAxis const & angle2: double axis2: SimTK::CoordinateAxis const & angle3: double axis3: SimTK::CoordinateAxis const & __init__(SimTK::Rotation_<(double)> self, Quaternion q) -> Rotation Parameters ---------- q: SimTK::Quaternion_< double > const & __init__(SimTK::Rotation_<(double)> self, Mat33 m, bool arg3) -> Rotation Parameters ---------- m: SimTK::Mat33 const & arg3: bool __init__(SimTK::Rotation_<(double)> self, Mat33 m) -> Rotation Parameters ---------- m: SimTK::Mat33 const & __init__(SimTK::Rotation_<(double)> self, UnitVec3 uvec, CoordinateAxis axis) -> Rotation Parameters ---------- uvec: SimTK::UnitVec3 const & axis: SimTK::CoordinateAxis const __init__(SimTK::Rotation_<(double)> self, UnitVec3 uveci, CoordinateAxis axisi, Vec3 vecjApprox, CoordinateAxis axisjApprox) -> Rotation Parameters ---------- uveci: SimTK::UnitVec3 const & axisi: SimTK::CoordinateAxis const & vecjApprox: SimTK::Vec3 const & axisjApprox: SimTK::CoordinateAxis const & __init__(SimTK::Rotation_<(double)> self, InverseRotation arg2) -> Rotation Parameters ---------- arg2: SimTK::InverseRotation_< double > const & """ this = _simbody.new_Rotation(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def invert(self): """ invert(Rotation self) -> InverseRotation Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_invert(self) def transpose(self): """ transpose(Rotation self) -> InverseRotation Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_transpose(self) def __invert__(self, *args): """ __invert__(Rotation self) -> InverseRotation __invert__(Rotation self) -> InverseRotation Parameters ---------- self: SimTK::Rotation_< double > * """ return _simbody.Rotation___invert__(self, *args) def __imul__(self, *args): """ __imul__(Rotation self, Rotation R) -> Rotation Parameters ---------- R: SimTK::Rotation_< double > const & __imul__(Rotation self, InverseRotation arg2) -> Rotation Parameters ---------- arg2: SimTK::InverseRotation_< double > const & """ return _simbody.Rotation___imul__(self, *args) def __itruediv__(self, *args): return _simbody.Rotation___itruediv__(self, *args) __idiv__ = __itruediv__ def asMat33(self): """ asMat33(Rotation self) -> Mat33 Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_asMat33(self) def toMat33(self): """ toMat33(Rotation self) -> Mat33 Parameters ---------- self: SimTK::Rotation_< double > const * """ return _simbody.Rotation_toMat33(self) def setRotationToBodyFixedXYZ(self, *args): """ setRotationToBodyFixedXYZ(Rotation self, Vec3 v) Parameters ---------- v: SimTK::Vec3 const & setRotationToBodyFixedXYZ(Rotation self, Vec3 c, Vec3 s) Parameters ---------- c: SimTK::Vec3 const & s: SimTK::Vec3 const & """ return _simbody.Rotation_setRotationToBodyFixedXYZ(self, *args) def convertAngVelToBodyFixed321Dot(q, w_PB_B): """ convertAngVelToBodyFixed321Dot(Vec3 q, Vec3 w_PB_B) -> Vec3 Parameters ---------- q: SimTK::Vec3 const & w_PB_B: SimTK::Vec3 const & """ return _simbody.Rotation_convertAngVelToBodyFixed321Dot(q, w_PB_B) convertAngVelToBodyFixed321Dot = staticmethod(convertAngVelToBodyFixed321Dot) def convertBodyFixed321DotToAngVel(q, qd): """ convertBodyFixed321DotToAngVel(Vec3 q, Vec3 qd) -> Vec3 Parameters ---------- q: SimTK::Vec3 const & qd: SimTK::Vec3 const & """ return _simbody.Rotation_convertBodyFixed321DotToAngVel(q, qd) convertBodyFixed321DotToAngVel = staticmethod(convertBodyFixed321DotToAngVel) def convertAngVelDotToBodyFixed321DotDot(q, w_PB_B, wdot_PB_B): """ convertAngVelDotToBodyFixed321DotDot(Vec3 q, Vec3 w_PB_B, Vec3 wdot_PB_B) -> Vec3 Parameters ---------- q: SimTK::Vec3 const & w_PB_B: SimTK::Vec3 const & wdot_PB_B: SimTK::Vec3 const & """ return _simbody.Rotation_convertAngVelDotToBodyFixed321DotDot(q, w_PB_B, wdot_PB_B) convertAngVelDotToBodyFixed321DotDot = staticmethod(convertAngVelDotToBodyFixed321DotDot) def calcNForBodyXYZInBodyFrame(*args): """ calcNForBodyXYZInBodyFrame(Vec3 q) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & calcNForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & """ return _simbody.Rotation_calcNForBodyXYZInBodyFrame(*args) calcNForBodyXYZInBodyFrame = staticmethod(calcNForBodyXYZInBodyFrame) def calcNForBodyXYZInParentFrame(*args): """ calcNForBodyXYZInParentFrame(Vec3 q) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & calcNForBodyXYZInParentFrame(Vec3 cq, Vec3 sq) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & """ return _simbody.Rotation_calcNForBodyXYZInParentFrame(*args) calcNForBodyXYZInParentFrame = staticmethod(calcNForBodyXYZInParentFrame) def multiplyByBodyXYZ_N_P(cosxy, sinxy, oocosy, w_PB): """ multiplyByBodyXYZ_N_P(Vec2 cosxy, Vec2 sinxy, double oocosy, Vec3 w_PB) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & oocosy: double w_PB: SimTK::Vec3 const & """ return _simbody.Rotation_multiplyByBodyXYZ_N_P(cosxy, sinxy, oocosy, w_PB) multiplyByBodyXYZ_N_P = staticmethod(multiplyByBodyXYZ_N_P) def multiplyByBodyXYZ_NT_P(cosxy, sinxy, oocosy, q): """ multiplyByBodyXYZ_NT_P(Vec2 cosxy, Vec2 sinxy, double oocosy, Vec3 q) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & oocosy: double q: SimTK::Vec3 const & """ return _simbody.Rotation_multiplyByBodyXYZ_NT_P(cosxy, sinxy, oocosy, q) multiplyByBodyXYZ_NT_P = staticmethod(multiplyByBodyXYZ_NT_P) def convertAngVelInParentToBodyXYZDot(cosxy, sinxy, oocosy, w_PB): """ convertAngVelInParentToBodyXYZDot(Vec2 cosxy, Vec2 sinxy, double oocosy, Vec3 w_PB) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & oocosy: double w_PB: SimTK::Vec3 const & """ return _simbody.Rotation_convertAngVelInParentToBodyXYZDot(cosxy, sinxy, oocosy, w_PB) convertAngVelInParentToBodyXYZDot = staticmethod(convertAngVelInParentToBodyXYZDot) def convertAngAccInParentToBodyXYZDotDot(cosxy, sinxy, oocosy, qdot, b_PB): """ convertAngAccInParentToBodyXYZDotDot(Vec2 cosxy, Vec2 sinxy, double oocosy, Vec3 qdot, Vec3 b_PB) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & oocosy: double qdot: SimTK::Vec3 const & b_PB: SimTK::Vec3 const & """ return _simbody.Rotation_convertAngAccInParentToBodyXYZDotDot(cosxy, sinxy, oocosy, qdot, b_PB) convertAngAccInParentToBodyXYZDotDot = staticmethod(convertAngAccInParentToBodyXYZDotDot) def multiplyByBodyXYZ_NInv_P(cosxy, sinxy, qdot): """ multiplyByBodyXYZ_NInv_P(Vec2 cosxy, Vec2 sinxy, Vec3 qdot) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & qdot: SimTK::Vec3 const & """ return _simbody.Rotation_multiplyByBodyXYZ_NInv_P(cosxy, sinxy, qdot) multiplyByBodyXYZ_NInv_P = staticmethod(multiplyByBodyXYZ_NInv_P) def multiplyByBodyXYZ_NInvT_P(cosxy, sinxy, v_P): """ multiplyByBodyXYZ_NInvT_P(Vec2 cosxy, Vec2 sinxy, Vec3 v_P) -> Vec3 Parameters ---------- cosxy: SimTK::Vec2 const & sinxy: SimTK::Vec2 const & v_P: SimTK::Vec3 const & """ return _simbody.Rotation_multiplyByBodyXYZ_NInvT_P(cosxy, sinxy, v_P) multiplyByBodyXYZ_NInvT_P = staticmethod(multiplyByBodyXYZ_NInvT_P) def calcNDotForBodyXYZInBodyFrame(*args): """ calcNDotForBodyXYZInBodyFrame(Vec3 q, Vec3 qdot) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & qdot: SimTK::Vec3 const & calcNDotForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq, Vec3 qdot) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & qdot: SimTK::Vec3 const & """ return _simbody.Rotation_calcNDotForBodyXYZInBodyFrame(*args) calcNDotForBodyXYZInBodyFrame = staticmethod(calcNDotForBodyXYZInBodyFrame) def calcNDotForBodyXYZInParentFrame(*args): """ calcNDotForBodyXYZInParentFrame(Vec3 q, Vec3 qdot) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & qdot: SimTK::Vec3 const & calcNDotForBodyXYZInParentFrame(Vec2 cq, Vec2 sq, double ooc1, Vec3 qdot) -> Mat33 Parameters ---------- cq: SimTK::Vec2 const & sq: SimTK::Vec2 const & ooc1: double qdot: SimTK::Vec3 const & """ return _simbody.Rotation_calcNDotForBodyXYZInParentFrame(*args) calcNDotForBodyXYZInParentFrame = staticmethod(calcNDotForBodyXYZInParentFrame) def calcNInvForBodyXYZInBodyFrame(*args): """ calcNInvForBodyXYZInBodyFrame(Vec3 q) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & calcNInvForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & """ return _simbody.Rotation_calcNInvForBodyXYZInBodyFrame(*args) calcNInvForBodyXYZInBodyFrame = staticmethod(calcNInvForBodyXYZInBodyFrame) def calcNInvForBodyXYZInParentFrame(*args): """ calcNInvForBodyXYZInParentFrame(Vec3 q) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & calcNInvForBodyXYZInParentFrame(Vec3 cq, Vec3 sq) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & """ return _simbody.Rotation_calcNInvForBodyXYZInParentFrame(*args) calcNInvForBodyXYZInParentFrame = staticmethod(calcNInvForBodyXYZInParentFrame) def convertAngVelInBodyFrameToBodyXYZDot(*args): """ convertAngVelInBodyFrameToBodyXYZDot(Vec3 q, Vec3 w_PB_B) -> Vec3 Parameters ---------- q: SimTK::Vec3 const & w_PB_B: SimTK::Vec3 const & convertAngVelInBodyFrameToBodyXYZDot(Vec3 cq, Vec3 sq, Vec3 w_PB_B) -> Vec3 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & w_PB_B: SimTK::Vec3 const & """ return _simbody.Rotation_convertAngVelInBodyFrameToBodyXYZDot(*args) convertAngVelInBodyFrameToBodyXYZDot = staticmethod(convertAngVelInBodyFrameToBodyXYZDot) def convertBodyXYZDotToAngVelInBodyFrame(*args): """ convertBodyXYZDotToAngVelInBodyFrame(Vec3 q, Vec3 qdot) -> Vec3 Parameters ---------- q: SimTK::Vec3 const & qdot: SimTK::Vec3 const & convertBodyXYZDotToAngVelInBodyFrame(Vec3 cq, Vec3 sq, Vec3 qdot) -> Vec3 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & qdot: SimTK::Vec3 const & """ return _simbody.Rotation_convertBodyXYZDotToAngVelInBodyFrame(*args) convertBodyXYZDotToAngVelInBodyFrame = staticmethod(convertBodyXYZDotToAngVelInBodyFrame) def convertAngVelDotInBodyFrameToBodyXYZDotDot(*args): """ convertAngVelDotInBodyFrameToBodyXYZDotDot(Vec3
None, execution_role_arn: Optional[pulumi.Input[str]] = None, kms_key: Optional[pulumi.Input[str]] = None, logging_configuration: Optional[pulumi.Input[pulumi.InputType['EnvironmentLoggingConfigurationArgs']]] = None, max_workers: Optional[pulumi.Input[int]] = None, min_workers: Optional[pulumi.Input[int]] = None, name: Optional[pulumi.Input[str]] = None, network_configuration: Optional[pulumi.Input[pulumi.InputType['EnvironmentNetworkConfigurationArgs']]] = None, plugins_s3_object_version: Optional[pulumi.Input[str]] = None, plugins_s3_path: Optional[pulumi.Input[str]] = None, requirements_s3_object_version: Optional[pulumi.Input[str]] = None, requirements_s3_path: Optional[pulumi.Input[str]] = None, source_bucket_arn: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, webserver_access_mode: Optional[pulumi.Input[str]] = None, weekly_maintenance_window_start: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['airflow_configuration_options'] = airflow_configuration_options __props__['airflow_version'] = airflow_version if dag_s3_path is None and not opts.urn: raise TypeError("Missing required property 'dag_s3_path'") __props__['dag_s3_path'] = dag_s3_path __props__['environment_class'] = environment_class if execution_role_arn is None and not opts.urn: raise TypeError("Missing required property 'execution_role_arn'") __props__['execution_role_arn'] = execution_role_arn __props__['kms_key'] = kms_key __props__['logging_configuration'] = logging_configuration __props__['max_workers'] = max_workers __props__['min_workers'] = min_workers __props__['name'] = name if network_configuration is None and not opts.urn: raise TypeError("Missing required property 'network_configuration'") __props__['network_configuration'] = network_configuration __props__['plugins_s3_object_version'] = plugins_s3_object_version __props__['plugins_s3_path'] = plugins_s3_path __props__['requirements_s3_object_version'] = requirements_s3_object_version __props__['requirements_s3_path'] = requirements_s3_path if source_bucket_arn is None and not opts.urn: raise TypeError("Missing required property 'source_bucket_arn'") __props__['source_bucket_arn'] = source_bucket_arn __props__['tags'] = tags __props__['webserver_access_mode'] = webserver_access_mode __props__['weekly_maintenance_window_start'] = weekly_maintenance_window_start __props__['arn'] = None __props__['created_at'] = None __props__['last_updateds'] = None __props__['service_role_arn'] = None __props__['status'] = None __props__['webserver_url'] = None super(Environment, __self__).__init__( 'aws:mwaa/environment:Environment', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, airflow_configuration_options: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, airflow_version: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, created_at: Optional[pulumi.Input[str]] = None, dag_s3_path: Optional[pulumi.Input[str]] = None, environment_class: Optional[pulumi.Input[str]] = None, execution_role_arn: Optional[pulumi.Input[str]] = None, kms_key: Optional[pulumi.Input[str]] = None, last_updateds: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EnvironmentLastUpdatedArgs']]]]] = None, logging_configuration: Optional[pulumi.Input[pulumi.InputType['EnvironmentLoggingConfigurationArgs']]] = None, max_workers: Optional[pulumi.Input[int]] = None, min_workers: Optional[pulumi.Input[int]] = None, name: Optional[pulumi.Input[str]] = None, network_configuration: Optional[pulumi.Input[pulumi.InputType['EnvironmentNetworkConfigurationArgs']]] = None, plugins_s3_object_version: Optional[pulumi.Input[str]] = None, plugins_s3_path: Optional[pulumi.Input[str]] = None, requirements_s3_object_version: Optional[pulumi.Input[str]] = None, requirements_s3_path: Optional[pulumi.Input[str]] = None, service_role_arn: Optional[pulumi.Input[str]] = None, source_bucket_arn: Optional[pulumi.Input[str]] = None, status: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, webserver_access_mode: Optional[pulumi.Input[str]] = None, webserver_url: Optional[pulumi.Input[str]] = None, weekly_maintenance_window_start: Optional[pulumi.Input[str]] = None) -> 'Environment': """ Get an existing Environment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] airflow_configuration_options: The `airflow_configuration_options` parameter specifies airflow override options. Check the [Official documentation](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html#configuring-env-variables-reference) for all possible configuration options. :param pulumi.Input[str] airflow_version: Airflow version of your environment, will be set by default to the latest version that MWAA supports. :param pulumi.Input[str] arn: The ARN of the MWAA Environment :param pulumi.Input[str] created_at: The Created At date of the MWAA Environment * `logging_configuration.<LOG_TYPE>.cloud_watch_log_group_arn` - Provides the ARN for the CloudWatch group where the logs will be published :param pulumi.Input[str] dag_s3_path: The relative path to the DAG folder on your Amazon S3 storage bucket. For example, dags. For more information, see [Importing DAGs on Amazon MWAA](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html). :param pulumi.Input[str] environment_class: Environment class for the cluster. Possible options are `mw1.small`, `mw1.medium`, `mw1.large`. Will be set by default to `mw1.small`. Please check the [AWS Pricing](https://aws.amazon.com/de/managed-workflows-for-apache-airflow/pricing/) for more information about the environment classes. :param pulumi.Input[str] execution_role_arn: The Amazon Resource Name (ARN) of the task execution role that the Amazon MWAA and its environment can assume. Check the [official AWS documentation](https://docs.aws.amazon.com/mwaa/latest/userguide/mwaa-create-role.html) for the detailed role specification. :param pulumi.Input[str] kms_key: The Amazon Resource Name (ARN) of your KMS key that you want to use for encryption. Will be set to the ARN of the managed KMS key `aws/airflow` by default. Please check the [Official Documentation](https://docs.aws.amazon.com/mwaa/latest/userguide/custom-keys-certs.html) for more information. :param pulumi.Input[pulumi.InputType['EnvironmentLoggingConfigurationArgs']] logging_configuration: The Apache Airflow logs you want to send to Amazon CloudWatch Logs. :param pulumi.Input[int] max_workers: The maximum number of workers that can be automatically scaled up. Value need to be between `1` and `25`. Will be `10` by default. :param pulumi.Input[int] min_workers: The minimum number of workers that you want to run in your environment. Will be `1` by default. :param pulumi.Input[str] name: The name of the Apache Airflow Environment :param pulumi.Input[pulumi.InputType['EnvironmentNetworkConfigurationArgs']] network_configuration: Specifies the network configuration for your Apache Airflow Environment. This includes two private subnets as well as security groups for the Airflow environment. Each subnet requires internet connection, otherwise the deployment will fail. See Network configuration below for details. :param pulumi.Input[str] plugins_s3_object_version: The plugins.zip file version you want to use. :param pulumi.Input[str] plugins_s3_path: The relative path to the plugins.zip file on your Amazon S3 storage bucket. For example, plugins.zip. If a relative path is provided in the request, then plugins_s3_object_version is required. For more information, see [Importing DAGs on Amazon MWAA](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html). :param pulumi.Input[str] requirements_s3_object_version: The requirements.txt file version you want to use. :param pulumi.Input[str] requirements_s3_path: The relative path to the requirements.txt file on your Amazon S3 storage bucket. For example, requirements.txt. If a relative path is provided in the request, then requirements_s3_object_version is required. For more information, see [Importing DAGs on Amazon MWAA](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html). :param pulumi.Input[str] service_role_arn: The Service Role ARN of the Amazon MWAA Environment :param pulumi.Input[str] source_bucket_arn: The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, arn:aws:s3:::airflow-mybucketname. :param pulumi.Input[str] status: The status of the Amazon MWAA Environment :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: An array of key:value pairs to associate with the resource. :param pulumi.Input[str] webserver_access_mode: Specifies whether the webserver should be accessible over the internet or via your specified VPC. Possible options: `PRIVATE_ONLY` (default) and `PUBLIC_ONLY`. :param pulumi.Input[str] webserver_url: The webserver URL of the MWAA Environment :param pulumi.Input[str] weekly_maintenance_window_start: Specifies the start date for the weekly maintenance window. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["airflow_configuration_options"] = airflow_configuration_options __props__["airflow_version"] = airflow_version __props__["arn"] = arn __props__["created_at"] = created_at __props__["dag_s3_path"] = dag_s3_path __props__["environment_class"] = environment_class __props__["execution_role_arn"] = execution_role_arn __props__["kms_key"] = kms_key __props__["last_updateds"] = last_updateds __props__["logging_configuration"] = logging_configuration __props__["max_workers"] = max_workers __props__["min_workers"] = min_workers __props__["name"] = name __props__["network_configuration"] = network_configuration __props__["plugins_s3_object_version"] = plugins_s3_object_version __props__["plugins_s3_path"] = plugins_s3_path __props__["requirements_s3_object_version"] = requirements_s3_object_version __props__["requirements_s3_path"] = requirements_s3_path __props__["service_role_arn"] = service_role_arn __props__["source_bucket_arn"] = source_bucket_arn __props__["status"] = status __props__["tags"] = tags __props__["webserver_access_mode"] = webserver_access_mode __props__["webserver_url"] = webserver_url __props__["weekly_maintenance_window_start"] = weekly_maintenance_window_start return Environment(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="airflowConfigurationOptions") def airflow_configuration_options(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ The `airflow_configuration_options` parameter specifies airflow override options. Check the [Official documentation](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html#configuring-env-variables-reference) for all possible configuration options. """ return pulumi.get(self, "airflow_configuration_options") @property @pulumi.getter(name="airflowVersion") def airflow_version(self) -> pulumi.Output[str]: """ Airflow version of your environment, will be set by default to the latest version that MWAA supports. """ return pulumi.get(self, "airflow_version") @property @pulumi.getter def arn(self) -> pulumi.Output[str]: """ The ARN of the MWAA Environment """ return pulumi.get(self, "arn") @property @pulumi.getter(name="createdAt") def created_at(self) -> pulumi.Output[str]: """ The Created At date of the MWAA Environment * `logging_configuration.<LOG_TYPE>.cloud_watch_log_group_arn` - Provides the ARN for the CloudWatch group where the logs will be published """ return pulumi.get(self, "created_at") @property @pulumi.getter(name="dagS3Path") def dag_s3_path(self) -> pulumi.Output[str]: """ The relative path to the DAG folder on your Amazon S3 storage bucket. For example, dags. For more information, see [Importing DAGs on Amazon MWAA](https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html). """ return pulumi.get(self, "dag_s3_path") @property @pulumi.getter(name="environmentClass") def environment_class(self) -> pulumi.Output[str]: """ Environment class for the cluster. Possible options are `mw1.small`, `mw1.medium`, `mw1.large`. Will be set by default to `mw1.small`. Please check the [AWS Pricing](https://aws.amazon.com/de/managed-workflows-for-apache-airflow/pricing/) for more information about the environment classes. """ return pulumi.get(self, "environment_class") @property @pulumi.getter(name="executionRoleArn") def execution_role_arn(self) -> pulumi.Output[str]: """ The Amazon Resource Name (ARN) of the task execution role that the Amazon MWAA and its environment can assume. Check the [official AWS documentation](https://docs.aws.amazon.com/mwaa/latest/userguide/mwaa-create-role.html) for
"""Gets the location terms. :return: the location terms :rtype: ``osid.mapping.LocationQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.mapping.LocationQueryInspector location_terms = property(fget=get_location_terms) @abc.abstractmethod def get_total_duration_terms(self): """Gets the total duration terms. :return: the duration terms :rtype: ``osid.search.terms.DurationRangeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DurationRangeTerm total_duration_terms = property(fget=get_total_duration_terms) @abc.abstractmethod def get_calendar_id_terms(self): """Gets the calendar ``Id`` terms. :return: the calendar ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm calendar_id_terms = property(fget=get_calendar_id_terms) @abc.abstractmethod def get_calendar_terms(self): """Gets the calendar terms. :return: the calendar terms :rtype: ``osid.calendaring.CalendarQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.CalendarQueryInspector calendar_terms = property(fget=get_calendar_terms) @abc.abstractmethod def get_schedule_query_inspector_record(self, schedule_record_type): """Gets the schedule query inspector record corresponding to the given ``Schedule`` record ``Type``. :param schedule_record_type: a schedule query record type :type schedule_record_type: ``osid.type.Type`` :return: the schedule query inspector record :rtype: ``osid.calendaring.records.ScheduleQueryInspectorRecord`` :raise: ``NullArgument`` -- ``schedule_record_type`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unsupported`` -- ``has_record_type(schedule_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.records.ScheduleQueryInspectorRecord class ScheduleSlotQueryInspector: """This is the query inspector for examining schedule queries.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_schedule_slot_id_terms(self): """Gets the schedule slot ``Id`` terms. :return: the schedule ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm schedule_slot_id_terms = property(fget=get_schedule_slot_id_terms) @abc.abstractmethod def get_schedule_slot_terms(self): """Gets the schedule slot terms. :return: the schedule slot terms :rtype: ``osid.calendaring.ScheduleSlotQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.ScheduleSlotQueryInspector schedule_slot_terms = property(fget=get_schedule_slot_terms) @abc.abstractmethod def get_weekday_terms(self): """Gets the weekday terms. :return: the weekday terms :rtype: ``osid.search.terms.CardinalTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.CardinalTerm weekday_terms = property(fget=get_weekday_terms) @abc.abstractmethod def get_weekly_interval_terms(self): """Gets the weekly interval terms. :return: the weekly interval terms :rtype: ``osid.search.terms.IntegerTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IntegerTerm weekly_interval_terms = property(fget=get_weekly_interval_terms) @abc.abstractmethod def get_week_of_month_terms(self): """Gets the week of month terms. :return: the week of month terms :rtype: ``osid.search.terms.IntegerTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IntegerTerm week_of_month_terms = property(fget=get_week_of_month_terms) @abc.abstractmethod def get_weekday_time_terms(self): """Gets the weekday time terms. :return: the fixed interval terms :rtype: ``osid.search.terms.TimeRangeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.TimeRangeTerm weekday_time_terms = property(fget=get_weekday_time_terms) @abc.abstractmethod def get_fixed_interval_terms(self): """Gets the fixed interval terms. :return: the fixed interval terms :rtype: ``osid.search.terms.DurationRangeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DurationRangeTerm fixed_interval_terms = property(fget=get_fixed_interval_terms) @abc.abstractmethod def get_duration_terms(self): """Gets the duration terms. :return: the duration terms :rtype: ``osid.search.terms.DurationTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DurationTerm duration_terms = property(fget=get_duration_terms) @abc.abstractmethod def get_calendar_id_terms(self): """Gets the calendar ``Id`` terms. :return: the calendar ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm calendar_id_terms = property(fget=get_calendar_id_terms) @abc.abstractmethod def get_calendar_terms(self): """Gets the calendar terms. :return: the calendar terms :rtype: ``osid.calendaring.CalendarQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.CalendarQueryInspector calendar_terms = property(fget=get_calendar_terms) @abc.abstractmethod def get_schedule_slot_query_inspector_record(self, schedule_slot_record_type): """Gets the schedule slot query inspector record corresponding to the given ``ScheduleSlot`` record ``Type``. :param schedule_slot_record_type: a schedule slot query record type :type schedule_slot_record_type: ``osid.type.Type`` :return: the schedule slot query inspector record :rtype: ``osid.calendaring.records.ScheduleSlotQueryInspectorRecord`` :raise: ``NullArgument`` -- ``schedule_slot_record_type`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unsupported`` -- ``has_record_type(schedule_slot_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.records.ScheduleSlotQueryInspectorRecord class TimePeriodQueryInspector: """This is the query inspector for examining time period queries.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_start_terms(self): """Gets the start terms. :return: the start terms :rtype: ``osid.search.terms.DateTimeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DateTimeTerm start_terms = property(fget=get_start_terms) @abc.abstractmethod def get_end_terms(self): """Gets the end terms. :return: the end terms :rtype: ``osid.search.terms.DateTimeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DateTimeTerm end_terms = property(fget=get_end_terms) @abc.abstractmethod def get_time_terms(self): """Gets the time terms. :return: the time terms :rtype: ``osid.search.terms.DateTimeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DateTimeTerm time_terms = property(fget=get_time_terms) @abc.abstractmethod def get_time_inclusive_terms(self): """Gets the inclusive time terms. :return: the time range terms :rtype: ``osid.search.terms.DateTimeRangeTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DateTimeRangeTerm time_inclusive_terms = property(fget=get_time_inclusive_terms) @abc.abstractmethod def get_duration_terms(self): """Gets the duration terms. :return: the duration terms :rtype: ``osid.search.terms.DurationTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.DurationTerm duration_terms = property(fget=get_duration_terms) @abc.abstractmethod def get_exception_id_terms(self): """Gets the exception event ``Id`` terms. :return: the exception event ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm exception_id_terms = property(fget=get_exception_id_terms) @abc.abstractmethod def get_exception_terms(self): """Gets the exception event terms. :return: the exception event terms :rtype: ``osid.calendaring.EventQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.EventQueryInspector exception_terms = property(fget=get_exception_terms) @abc.abstractmethod def get_event_id_terms(self): """Gets the event ``Id`` terms. :return: the event ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm event_id_terms = property(fget=get_event_id_terms) @abc.abstractmethod def get_event_terms(self): """Gets the event terms. :return: the event terms :rtype: ``osid.calendaring.EventQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.EventQueryInspector event_terms = property(fget=get_event_terms) @abc.abstractmethod def get_calendar_id_terms(self): """Gets the calendar ``Id`` terms. :return: the calendar ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm calendar_id_terms = property(fget=get_calendar_id_terms) @abc.abstractmethod def get_calendar_terms(self): """Gets the calendar terms. :return: the calendar terms :rtype: ``osid.calendaring.CalendarQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.CalendarQueryInspector calendar_terms = property(fget=get_calendar_terms) @abc.abstractmethod def get_time_period_query_inspector_record(self, time_period_record_type): """Gets the time period query record interface corresponding to the given ``TimePeriod`` record ``Type``. :param time_period_record_type: a time period query record type :type time_period_record_type: ``osid.type.Type`` :return: the time period query inspector record :rtype: ``osid.calendaring.records.TimePeriodQueryInspectorRecord`` :raise: ``NullArgument`` -- ``time_period_record_type`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unsupported`` -- ``has_record_type(time_period_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.records.TimePeriodQueryInspectorRecord class CommitmentQueryInspector: """This is the query inspector for examining commitment queries.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_event_id_terms(self): """Gets the event ``Id`` terms. :return: the event ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm event_id_terms = property(fget=get_event_id_terms) @abc.abstractmethod def get_event_terms(self): """Gets the event terms. :return: the event terms :rtype: ``osid.calendaring.EventQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.EventQueryInspector event_terms = property(fget=get_event_terms) @abc.abstractmethod def get_resource_id_terms(self): """Gets the resource ``Id`` terms. :return: the resource ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm resource_id_terms = property(fget=get_resource_id_terms) @abc.abstractmethod def get_resource_terms(self): """Gets the resource terms. :return: the resource terms :rtype: ``osid.resource.ResourceQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.resource.ResourceQueryInspector resource_terms = property(fget=get_resource_terms) @abc.abstractmethod def get_calendar_id_terms(self): """Gets the calendar ``Id`` terms. :return: the calendar ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm calendar_id_terms = property(fget=get_calendar_id_terms) @abc.abstractmethod def get_calendar_terms(self): """Gets the calendar terms. :return: the calendar terms :rtype: ``osid.calendaring.CalendarQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.CalendarQueryInspector calendar_terms = property(fget=get_calendar_terms) @abc.abstractmethod def get_commitment_query_inspector_record(self, commitment_record_type): """Gets the commitment query inspector record corresponding to the given ``Commitment`` record ``Type``. :param commitment_record_type: a commitment query record type :type commitment_record_type: ``osid.type.Type`` :return: the commitment query inspector record :rtype: ``osid.calendaring.records.CommitmentQueryInspectorRecord`` :raise: ``NullArgument`` -- ``commitment_record_type`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unsupported`` -- ``has_record_type(commitment_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return # osid.calendaring.records.CommitmentQueryInspectorRecord class CalendarQueryInspector: """This is the query inspector for examining calendar queries.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_event_id_terms(self): """Gets the event ``Id`` terms. :return: the event ``Id`` terms :rtype: ``osid.search.terms.IdTerm`` *compliance: mandatory -- This method must be implemented.* """ return # osid.search.terms.IdTerm event_id_terms = property(fget=get_event_id_terms) @abc.abstractmethod def get_event_terms(self): """Gets the event terms. :return: the event terms :rtype: ``osid.calendaring.EventQueryInspector`` *compliance: mandatory -- This method must be implemented.* """ return #
from typing import Dict, Tuple from aiohttp import BasicAuth, ClientResponse from .core import OAuth1Client, OAuth2Client, UserInfo __author__ = "<NAME>" __copyright__ = "Copyright 2017, <NAME>" __credits__ = ["<NAME>"] __license__ = "MIT" __version__ = "0.5.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" class NaverClient(OAuth2Client): """Support Naver. * Dashboard: https://developers.naver.com/apps/#/list * Docs: https://developers.naver.com/docs/login/overview/ * API reference: https://developers.naver.com/docs/login/api/ * API tutorial: https://developers.naver.com/docs/login/web/ """ access_token_url = "https://nid.naver.com/oauth2.0/token" authorize_url = "https://nid.naver.com/oauth2.0/authorize" base_url = None name = "naver" user_info_url = "https://openapi.naver.com/v1/nid/me" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" return UserInfo( id=data.get("sub", data.get("id")), email=data.get("email"), verified_email=data.get("verified_email"), first_name=data.get("given_name"), last_name=data.get("family_name"), picture=data.get("picture"), ) class GoogleClient(OAuth2Client): """Support Google. * Dashboard: https://console.developers.google.com/project * Docs: https://developers.google.com/accounts/docs/OAuth2 * API reference: https://developers.google.com/gdata/docs/directory * API explorer: https://developers.google.com/oauthplayground/ """ access_token_url = "https://accounts.google.com/o/oauth2/token" authorize_url = "https://accounts.google.com/o/oauth2/auth" base_url = "https://www.googleapis.com/plus/v1/" name = "google" user_info_url = "https://www.googleapis.com/userinfo/v2/me" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" return UserInfo( id=data.get("id"), nickname=data.get("nickname"), name=data.get("name"), email=data.get("email"), gender=data.get("gender"), age=data.get("age"), birthday=data.get("birthday"), profile_image=data.get("profile_image"), ) class GitlabClient(OAuth2Client): """Support Gitlab * Dashboard: https://gitlab.com/profile/applications * Docs: https://docs.gitlab.com/ce/api/oauth2.html * API reference: https://docs.gitlab.com/ee/api/README.html """ access_token_url = "https://gitlab.com/oauth/token" authorize_url = "https://gitlab.com/oauth/authorize" base_url = "https://gitlab.com/api/v4" name = "gitlab" user_info_url = "https://gitlab.com/api/v4/user" @classmethod def user_parse(cls, data) -> UserInfo: return UserInfo( id=data.get("id"), email=data.get("email"), picture=data.get("avatar_url"), username=data.get("username"), link=data.get("web_url"), ) class BitbucketClient(OAuth1Client): """Support Bitbucket. * Dashboard: https://bitbucket.org/account/user/peterhudec/api * Docs: https://confluence.atlassian.com/display/BITBUCKET/oauth+Endpoint * API refer: https://confluence.atlassian.com/display/BITBUCKET/Using+the+Bitbucket+REST+APIs """ access_token_url = "https://bitbucket.org/!api/1.0/oauth/access_token" authorize_url = "https://bitbucket.org/!api/1.0/oauth/authenticate" base_url = "https://api.bitbucket.org/1.0/" name = "bitbucket" request_token_url = "https://bitbucket.org/!api/1.0/oauth/request_token" user_info_url = "https://api.bitbucket.org/1.0/user" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" user_ = data.get("user") return UserInfo( id=user_.get("username"), username=user_.get("username"), first_name=user_.get("first_name"), last_name=user_.get("last_name"), picture=user_.get("avatar"), link=user_.get("resource_url"), ) class Bitbucket2Client(OAuth2Client): """Support Bitbucket API 2.0. * Dashboard: https://bitbucket.org/account/user/peterhudec/api * Docs:https://confluence.atlassian.com/display/BITBUCKET/OAuth+on+Bitbucket+Cloud * API refer: https://confluence.atlassian.com/display/BITBUCKET/Using+the+Bitbucket+REST+APIs """ access_token_url = "https://bitbucket.org/site/oauth2/access_token" authorize_url = "https://bitbucket.org/site/oauth2/authorize" base_url = "https://api.bitbucket.org/2.0/" name = "bitbucket" user_info_url = "https://api.bitbucket.org/2.0/user" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" links = data.get("links", {}) return UserInfo( id=data.get("uuid"), username=data.get("username"), last_name=data.get("display_name"), picture=links.get("avatar", {}).get("href"), link=links.get("html", {}).get("href"), ) async def request( self, method: str, url: str, params: Dict[str, str] = None, headers: Dict[str, str] = None, **aio_kwargs, ) -> ClientResponse: """Request OAuth2 resource.""" url = self._get_url(url) if self.access_token: headers = headers or {"Accept": "application/json"} headers["Authorization"] = "Bearer {}".format(self.access_token) auth = None else: auth = BasicAuth(self.client_id, self.client_secret) headers = headers or { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", } return await self.aiohttp_session.request( method, url, params=params, headers=headers, auth=auth, **aio_kwargs ) class Flickr(OAuth1Client): """Support Flickr. * Dashboard: https://www.flickr.com/services/apps/ * Docs: https://www.flickr.com/services/api/auth.oauth.html * API reference: https://www.flickr.com/services/api/ """ access_token_url = "http://www.flickr.com/services/oauth/request_token" authorize_url = "http://www.flickr.com/services/oauth/authorize" base_url = "https://api.flickr.com/" name = "flickr" request_token_url = "http://www.flickr.com/services/oauth/request_token" user_info_url = "http://api.flickr.com/services/rest?method=flickr.test.login&format=json&nojsoncallback=1" # noqa @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" user_ = data.get("user", {}) first_name, _, last_name = ( data.get("fullname", {}).get("_content", "").partition(" ") ) return UserInfo( id=data.get("user_nsid") or user_.get("id"), username=user_.get("username", {}).get("_content"), first_name=first_name, last_name=last_name, ) class Meetup(OAuth1Client): """Support Meetup. * Dashboard: http://www.meetup.com/meetup_api/oauth_consumers/ * Docs: http://www.meetup.com/meetup_api/auth/#oauth * API: http://www.meetup.com/meetup_api/docs/ """ access_token_url = "https://api.meetup.com/oauth/access/" authorize_url = "http://www.meetup.com/authorize/" base_url = "https://api.meetup.com/2/" name = "meetup" request_token_url = "https://api.meetup.com/oauth/request/" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" return UserInfo( id=data.get("id") or data.get("member_id"), locale=data.get("lang"), picture=data.get("photo", {}).get("photo_link"), ) class Plurk(OAuth1Client): """Support Plurk. * Dashboard: http://www.plurk.com/PlurkApp/ * API: http://www.plurk.com/API * API explorer: http://www.plurk.com/OAuth/test/ """ access_token_url = "http://www.plurk.com/OAuth/access_token" authorize_url = "http://www.plurk.com/OAuth/authorize" base_url = "http://www.plurk.com/APP/" name = "plurk" request_token_url = "http://www.plurk.com/OAuth/request_token" user_info_url = "http://www.plurk.com/APP/Profile/getOwnProfile" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" _user = data.get("user_info", {}) _id = _user.get("id") or _user.get("uid") first_name, _, last_name = _user.get("full_name", "").partition(" ") city, country = map(lambda s: s.strip(), _user.get("location", ",").split(",")) return UserInfo( id=_id, locale=_user.get("default_lang"), username=_user.get("display_name"), first_name=first_name, last_name=last_name, picture="http://avatars.plurk.com/{0}-big2.jpg".format(_id), city=city, country=country, ) class TwitterClient(OAuth1Client): """Support Twitter. * Dashboard: https://dev.twitter.com/apps * Docs: https://dev.twitter.com/docs * API reference: https://dev.twitter.com/docs/api """ access_token_url = "https://api.twitter.com/oauth/access_token" authorize_url = "https://api.twitter.com/oauth/authorize" base_url = "https://api.twitter.com/1.1/" name = "twitter" request_token_url = "https://api.twitter.com/oauth/request_token" user_info_url = "https://api.twitter.com/1.1/account/verify_credentials.json" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" first_name, _, last_name = data["name"].partition(" ") city, _, country = map( lambda s: s.strip(), data.get("location", "").partition(",") ) return UserInfo( id=data.get("id") or data.get("user_id"), first_name=first_name, last_name=last_name, picture=data.get("profile_image_url"), locale=data.get("lang"), link=data.get("url"), username=data.get("screen_name"), city=city, country=country, ) class TumblrClient(OAuth1Client): """Support Tumblr. * Dashboard: http://www.tumblr.com/oauth/apps * Docs: http://www.tumblr.com/docs/en/api/v2#auth * API reference: http://www.tumblr.com/docs/en/api/v2 """ access_token_url = "http://www.tumblr.com/oauth/access_token" authorize_url = "http://www.tumblr.com/oauth/authorize" base_url = "https://api.tumblr.com/v2/" name = "tumblr" request_token_url = "http://www.tumblr.com/oauth/request_token" user_info_url = "http://api.tumblr.com/v2/user/info" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" _user = data.get("response", {}).get("user", {}) return UserInfo( id=_user.get("name"), username=_user.get("name"), link=_user.get("blogs", [{}])[0].get("url"), ) class VimeoClient(OAuth1Client): """Support Vimeo.""" access_token_url = "https://vimeo.com/oauth/access_token" authorize_url = "https://vimeo.com/oauth/authorize" base_url = "https://vimeo.com/api/rest/v2/" name = "vimeo" request_token_url = "https://vimeo.com/oauth/request_token" user_info_url = ( "http://vimeo.com/api/rest/v2?format=json&method=vimeo.oauth.checkAccessToken" ) @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" _user = data.get("oauth", {}).get("user", {}) first_name, _, last_name = _user.get("display_name").partition(" ") return UserInfo( id=_user.get("id"), username=_user.get("username"), first_name=first_name, last_name=last_name, ) class YahooClient(OAuth1Client): """Support Yahoo. * Dashboard: https://developer.vimeo.com/apps * Docs: https://developer.vimeo.com/apis/advanced#oauth-endpoints * API reference: https://developer.vimeo.com/apis """ access_token_url = "https://api.login.yahoo.com/oauth/v2/get_token" authorize_url = "https://api.login.yahoo.com/oauth/v2/request_auth" base_url = "https://query.yahooapis.com/v1/" name = "yahoo" request_token_url = "https://api.login.yahoo.com/oauth/v2/get_request_token" user_info_url = ( "https://query.yahooapis.com/v1/yql?q=select%20*%20from%20" "social.profile%20where%20guid%3Dme%3B&format=json" ) @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" _user = data.get("query", {}).get("results", {}).get("profile", {}) city, country = map(lambda s: s.strip(), _user.get("location", ",").split(",")) emails = _user.get("emails") main_email = "" if isinstance(emails, list): for email in emails: if "primary" in list(email.keys()): main_email = email.get("handle") elif isinstance(emails, dict): main_email = emails.get("handle") return UserInfo( id=_user.get("guid"), username=_user.get("username"), link=_user.get("profileUrl"), picture=_user.get("image", {}).get("imageUrl"), city=city, country=country, email=main_email, ) class AmazonClient(OAuth2Client): """Support Amazon. * Dashboard: https://developer.amazon.com/lwa/sp/overview.html * Docs: https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/conceptual_overview.html # noqa * API reference: https://developer.amazon.com/public/apis """ access_token_url = "https://api.amazon.com/auth/o2/token" authorize_url = "https://www.amazon.com/ap/oa" base_url = "https://api.amazon.com/" name = "amazon" user_info_url = "https://api.amazon.com/user/profile" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" return UserInfo(id=data.get("user_id")) class EventbriteClient(OAuth2Client): """Support Eventbrite. * Dashboard: http://www.eventbrite.com/myaccount/apps/ * Docs: https://developer.eventbrite.com/docs/auth/ * API: http://developer.eventbrite.com/docs/ """ access_token_url = "https://www.eventbrite.com/oauth/token" authorize_url = "https://www.eventbrite.com/oauth/authorize" base_url = "https://www.eventbriteapi.com/v3/" name = "eventbrite" user_info_url = "https://www.eventbriteapi.com/v3/users/me" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" for email in data.get("emails", []): if email.get("primary"): return UserInfo(id=email.get("email"), email=email.get("email")) return UserInfo() class FacebookClient(OAuth2Client): """Support Facebook. * Dashboard: https://developers.facebook.com/apps * Docs: http://developers.facebook.com/docs/howtos/login/server-side-login/ * API reference: http://developers.facebook.com/docs/reference/api/ * API explorer: http://developers.facebook.com/tools/explorer """ access_token_url = "https://graph.facebook.com/oauth/access_token" authorize_url = "https://www.facebook.com/dialog/oauth" base_url = "https://graph.facebook.com/v2.4" name = "facebook" user_info_url = "https://graph.facebook.com/me" async def user_info(self, **kwargs) -> Tuple[UserInfo, Dict]: """Facebook required fields-param.""" params = kwargs.get("params", {}) params[ "fields" ] = "id,email,first_name,last_name,name,link,locale,gender,location" return await super(FacebookClient, self).user_info(params=params, **kwargs) @staticmethod def user_parse(data): """Parse information from provider.""" id_ = data.get("id") location = data.get("location", {}).get("name") city, country = "", "" if location: split_location = location.split(", ") city = split_location[0].strip() if len(split_location) > 1: country = split_location[1].strip() return UserInfo( id=id_, email=data.get("email"), first_name=data.get("first_name"), last_name=data.get("last_name"), username=data.get("name"), picture="http://graph.facebook.com/{0}/picture?type=large".format(id_), link=data.get("link"), locale=data.get("locale"), gender=data.get("gender"), city=city, country=country, ) class FoursquareClient(OAuth2Client): """Support Foursquare. * Dashboard: https://foursquare.com/developers/apps * Docs: https://developer.foursquare.com/overview/auth.html * API reference: https://developer.foursquare.com/docs/ """ access_token_url = "https://foursquare.com/oauth2/access_token" authorize_url = "https://foursquare.com/oauth2/authenticate" base_url = "https://api.foursquare.com/v2/" name = "foursquare" user_info_url = "https://api.foursquare.com/v2/users/self" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from the provider.""" user = data.get("response", {}).get("user", {}) city, country = user.get("homeCity", ", ").split(", ") return UserInfo( id=user.get("id"), email=user.get("contact", {}).get("email"), first_name=user.get("firstName"), last_name=user.get("lastName"), city=city, country=country, ) class GithubClient(OAuth2Client): """Support Github. * Dashboard: https://github.com/settings/applications/ * Docs: http://developer.github.com/v3/#authentication * API reference: http://developer.github.com/v3/ """ access_token_url = "https://github.com/login/oauth/access_token" authorize_url = "https://github.com/login/oauth/authorize" base_url = "https://api.github.com" name = "github" user_info_url = "https://api.github.com/user" @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" first_name, _, last_name = (data.get("name") or "").partition(" ") location = data.get("location", "") city, country = "", "" if location: split_location = location.split(",") country = split_location[0].strip() if len(split_location) > 1: city = split_location[1].strip() return UserInfo( id=data.get("id"), email=data.get("email"), first_name=first_name, last_name=last_name, username=data.get("login"), picture=data.get("avatar_url"), link=data.get("html_url"), city=city, country=country, ) class VKClient(OAuth2Client): """Support vk.com. * Dashboard: http://vk.com/editapp?id={consumer_key} * Docs: http://vk.com/developers.php?oid=-17680044&p=Authorizing_Sites * API reference: http://vk.com/developers.php?oid=-17680044&p=API_Method_Description """ authorize_url = "http://api.vk.com/oauth/authorize" access_token_url = "https://api.vk.com/oauth/access_token" user_info_url = "https://api.vk.com/method/getProfiles?fields=uid,first_name,last_name,nickname,sex,bdate,city,country,timezone,photo_big" # noqa name = "vk" base_url = "https://api.vk.com" def __init__(self, *args, **kwargs): """Set default scope.""" super(VKClient, self).__init__(*args, **kwargs) self.params.setdefault("scope", "offline") @classmethod def user_parse(cls, data) -> UserInfo: """Parse information from provider.""" resp = data.get("response", [{}])[0] return UserInfo( id=resp.get("uid"), first_name=resp.get("first_name"), last_name=resp.get("last_name"), username=resp.get("nickname"), city=resp.get("city"), country=resp.get("country"), picture=resp.get("photo_big"), ) class OdnoklassnikiClient(OAuth2Client): """Support ok.ru. * Dashboard: http://ok.ru/dk?st.cmd=appsInfoMyDevList * Docs: https://apiok.ru/wiki/display/api/Authorization+OAuth+2.0 * API reference: https://apiok.ru/wiki/pages/viewpage.action?pageId=49381398 """ authorize_url = "https://connect.ok.ru/oauth/authorize" access_token_url = "https://api.odnoklassniki.ru/oauth/token.do" user_info_url = "http://api.ok.ru/api/users/getCurrentUser?fields=uid,first_name,last_name,gender,city,country,pic128max" # noqa name = "odnoklassniki" base_url = "https://api.ok.ru" def __init__(self, *args, **kwargs): """Set
# Copyright 2019 by <NAME>. All rights reserved. # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """Per residue backbone and sidechain hedra and dihedra definitions. Listed in order of output for internal coordinates (.pic) output file. Require sufficient overlap to link all defined dihedra. Entries in these tables without corresponding atom coordinates are ignored. <http://www.imgt.org/IMGTeducation/Aide-memoire/_UK/aminoacids/formuleAA/> for naming of individual atoms """ # Backbone hedra and dihedra - within residue, no next or prev. ic_data_backbone = ( ("N", "CA", "C", "O"), # locate backbone O ("O", "C", "CA", "CB"), # locate CB ("CA", "C", "O"), ("CB", "CA", "C"), ("CA", "C", "OXT"), # OXT if present ("N", "CA", "C", "OXT"), ("H", "N", "CA"), # amide proton if present ("C", "CA", "N", "H"), ("HA", "CA", "C"), # CA proton ("O", "C", "CA", "HA"), ("HA2", "CA", "C"), # gly CA proton ("O", "C", "CA", "HA2"), ("HA3", "CA", "C"), # gly CA proton ("O", "C", "CA", "HA3"), ("N", "CA", "CB"), ("N", "CA", "CB", "HB"), # CB protons ("N", "CA", "CB", "HB1"), ("N", "CA", "CB", "HB2"), ("N", "CA", "CB", "HB3"), ("CA", "CB", "HB"), ("CA", "CB", "HB1"), ("CA", "CB", "HB2"), ("CA", "CB", "HB3"), ("H1", "N", "CA"), # chain start protons ("H2", "N", "CA"), ("H3", "N", "CA"), ("C", "CA", "N", "H1"), ("C", "CA", "N", "H2"), ("C", "CA", "N", "H3"), ) # Sidechain hedra and dihedra. ic_data_sidechains = { "V": ( ("CA", "CB", "CG1"), ("N", "CA", "CB", "CG1", "chi1"), # chi1 ("CA", "CB", "CG2"), ("N", "CA", "CB", "CG2"), ("CB", "CG1", "HG11"), ("CB", "CG1", "HG12"), ("CB", "CG1", "HG13"), ("CB", "CG2", "HG21"), ("CB", "CG2", "HG22"), ("CB", "CG2", "HG23"), ("CA", "CB", "CG1", "HG11"), ("CA", "CB", "CG1", "HG12"), ("CA", "CB", "CG1", "HG13"), ("CA", "CB", "CG2", "HG21"), ("CA", "CB", "CG2", "HG22"), ("CA", "CB", "CG2", "HG23"), ), "L": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD1"), ("CA", "CB", "CG", "CD1", "chi2"), # chi2 ("CB", "CG", "CD2"), ("CA", "CB", "CG", "CD2"), ("CB", "CG", "HG"), ("CA", "CB", "CG", "HG"), ("CG", "CD1", "HD11"), ("CG", "CD1", "HD12"), ("CG", "CD1", "HD13"), ("CG", "CD2", "HD21"), ("CG", "CD2", "HD22"), ("CG", "CD2", "HD23"), ("CB", "CG", "CD1", "HD11"), ("CB", "CG", "CD1", "HD12"), ("CB", "CG", "CD1", "HD13"), ("CB", "CG", "CD2", "HD21"), ("CB", "CG", "CD2", "HD22"), ("CB", "CG", "CD2", "HD23"), ), "I": ( ("CA", "CB", "CG1"), ("N", "CA", "CB", "CG1", "chi1"), # chi1 ("CB", "CG1", "CD1"), ("CA", "CB", "CG1", "CD1", "chi2"), # chi2 ("CA", "CB", "CG2"), ("N", "CA", "CB", "CG2"), ("CB", "CG1", "HG12"), ("CB", "CG1", "HG13"), ("CB", "CG2", "HG21"), ("CB", "CG2", "HG22"), ("CB", "CG2", "HG23"), ("CA", "CB", "CG1", "HG12"), ("CA", "CB", "CG1", "HG13"), ("CA", "CB", "CG2", "HG21"), ("CA", "CB", "CG2", "HG22"), ("CA", "CB", "CG2", "HG23"), ("CG1", "CD1", "HD11"), ("CG1", "CD1", "HD12"), ("CG1", "CD1", "HD13"), ("CB", "CG1", "CD1", "HD11"), ("CB", "CG1", "CD1", "HD12"), ("CB", "CG1", "CD1", "HD13"), ), "M": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "SD"), ("CA", "CB", "CG", "SD", "chi2"), # chi2 ("CG", "SD", "CE"), ("CB", "CG", "SD", "CE", "chi3"), # chi3 ("CB", "CG", "HG2"), ("CB", "CG", "HG3"), ("CA", "CB", "CG", "HG2"), ("CA", "CB", "CG", "HG3"), ("SD", "CE", "HE1"), ("SD", "CE", "HE2"), ("SD", "CE", "HE3"), ("CG", "SD", "CE", "HE1"), ("CG", "SD", "CE", "HE2"), ("CG", "SD", "CE", "HE3"), ), "F": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD1"), ("CA", "CB", "CG", "CD1", "chi2"), # chi2 ("CG", "CD1", "CE1"), ("CB", "CG", "CD1", "CE1"), ("CD1", "CE1", "CZ"), ("CG", "CD1", "CE1", "CZ"), ("CB", "CG", "CD2"), ("CA", "CB", "CG", "CD2"), ("CG", "CD2", "CE2"), ("CB", "CG", "CD2", "CE2"), ("CG", "CD1", "HD1"), ("CB", "CG", "CD1", "HD1"), ("CG", "CD2", "HD2"), ("CB", "CG", "CD2", "HD2"), ("CD1", "CE1", "HE1"), ("CG", "CD1", "CE1", "HE1"), ("CD2", "CE2", "HE2"), ("CG", "CD2", "CE2", "HE2"), ("CE1", "CZ", "HZ"), ("CD1", "CE1", "CZ", "HZ"), ), "P": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD"), ("CA", "CB", "CG", "CD", "chi2"), # chi2 ("CB", "CG", "HG2"), ("CB", "CG", "HG3"), ("CA", "CB", "CG", "HG2"), ("CA", "CB", "CG", "HG3"), ("CG", "CD", "HD2"), ("CG", "CD", "HD3"), ("CB", "CG", "CD", "HD2"), ("CB", "CG", "CD", "HD3"), ), "S": ( ("CA", "CB", "OG"), ("N", "CA", "CB", "OG", "chi1"), # chi1 ("CB", "OG", "HG"), ("CA", "CB", "OG", "HG"), ), "T": ( ("CA", "CB", "OG1"), ("N", "CA", "CB", "OG1", "chi1"), # chi1 ("CA", "CB", "CG2"), ("N", "CA", "CB", "CG2"), ("CB", "OG1", "HG1"), ("CA", "CB", "OG1", "HG1"), ("CB", "CG2", "HG21"), ("CB", "CG2", "HG22"), ("CB", "CG2", "HG23"), ("CA", "CB", "CG2", "HG21"), ("CA", "CB", "CG2", "HG22"), ("CA", "CB", "CG2", "HG23"), ), "C": ( ("CA", "CB", "SG"), ("N", "CA", "CB", "SG", "chi1"), # chi1 ("CB", "SG", "HG"), ("CA", "CB", "SG", "HG"), ), "N": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "OD1"), ("CA", "CB", "CG", "OD1", "chi2"), # chi2 ("CB", "CG", "ND2"), ("CA", "CB", "CG", "ND2"), ("CG", "ND2", "HD21"), ("CG", "ND2", "HD22"), ("CB", "CG", "ND2", "HD21"), ("CB", "CG", "ND2", "HD22"), ), "Q": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD"), ("CA", "CB", "CG", "CD", "chi2"), # chi2 ("CG", "CD", "OE1"), ("CB", "CG", "CD", "OE1", "chi3"), # chi3 ("CG", "CD", "NE2"), ("CB", "CG", "CD", "NE2"), ("CB", "CG", "HG2"), ("CB", "CG", "HG3"), ("CA", "CB", "CG", "HG2"), ("CA", "CB", "CG", "HG3"), ("CD", "NE2", "HE21"), ("CD", "NE2", "HE22"), ("CG", "CD", "NE2", "HE21"), ("CG", "CD", "NE2", "HE22"), ), "Y": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD1"), ("CA", "CB", "CG", "CD1", "chi2"), # chi2 ("CG", "CD1", "CE1"), ("CB", "CG", "CD1", "CE1"), ("CD1", "CE1", "CZ"), ("CG", "CD1", "CE1", "CZ"), ("CE1", "CZ", "OH"), ("CD1", "CE1", "CZ", "OH"), ("CB", "CG", "CD2"), ("CA", "CB", "CG", "CD2"), ("CG", "CD2", "CE2"), ("CB", "CG", "CD2", "CE2"), ("CG", "CD1", "HD1"), ("CB", "CG", "CD1", "HD1"), ("CG", "CD2", "HD2"), ("CB", "CG", "CD2", "HD2"), ("CD1", "CE1", "HE1"), ("CG", "CD1", "CE1", "HE1"), ("CD2", "CE2", "HE2"), ("CG", "CD2", "CE2", "HE2"), ("CZ", "OH", "HH"), ("CE1", "CZ", "OH", "HH"), ), "W": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD1"), ("CA", "CB", "CG", "CD1", "chi2"), # chi2 ("CG", "CD1", "NE1"), ("CB", "CG", "CD1", "NE1"), ("CB", "CG", "CD2"), ("CA", "CB", "CG", "CD2"), ("CG", "CD2", "CE2"), ("CB", "CG", "CD2", "CE2"), ("CD2", "CE2", "CZ2"), ("CG", "CD2", "CE2", "CZ2"), ("CE2", "CZ2", "CH2"), ("CD2", "CE2", "CZ2", "CH2"), ("CE2", "CZ2", "HZ2"), ("CD2", "CE2", "CZ2", "HZ2"), ("CG", "CD2", "CE3"), ("CB", "CG", "CD2", "CE3"), ("CZ2", "CH2", "CZ3"), ("CE2", "CZ2", "CH2", "CZ3"), ("CG", "CD1", "HD1"), ("CB", "CG", "CD1", "HD1"), ("CD1", "NE1", "HE1"), ("CG", "CD1", "NE1", "HE1"), ("CD2", "CE3", "HE3"), ("CG", "CD2", "CE3", "HE3"), ("CH2", "CZ3", "HZ3"), ("CZ2", "CH2", "CZ3", "HZ3"), ("CZ2", "CH2", "HH2"), ("CE2", "CZ2", "CH2", "HH2"), ), "D": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "OD1"), ("CA", "CB", "CG", "OD1", "chi2"), # chi2 ("CB", "CG", "OD2"), ("CA", "CB", "CG", "OD2"), ), "E": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD"), ("CA", "CB", "CG", "CD", "chi2"), # chi2 ("CG", "CD", "OE1"), ("CB", "CG", "CD", "OE1", "chi3"), # chi3 ("CG", "CD", "OE2"), ("CB", "CG", "CD", "OE2"), ("CB", "CG", "HG2"), ("CB", "CG", "HG3"), ("CA", "CB", "CG", "HG2"), ("CA", "CB", "CG", "HG3"), ), "H": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "ND1"), ("CA", "CB", "CG", "ND1", "chi2"), # chi2 ("CG", "ND1", "CE1"), ("CB", "CG", "ND1", "CE1"), ("CB", "CG", "CD2"), ("CA", "CB", "CG", "CD2"), ("CG", "CD2", "NE2"), ("CB", "CG", "CD2", "NE2"), ("CG", "ND1", "HD1"), ("CB", "CG", "ND1", "HD1"), ("CG", "CD2", "HD2"), ("CB", "CG", "CD2", "HD2"), ("ND1", "CE1", "HE1"), ("CG", "ND1", "CE1", "HE1"), ("CD2", "NE2", "HE2"), ("CG", "CD2", "NE2", "HE2"), ), "K": ( ("CA", "CB", "CG"), ("N", "CA", "CB", "CG", "chi1"), # chi1 ("CB", "CG", "CD"), ("CA", "CB", "CG", "CD", "chi2"), # chi2 ("CG", "CD", "CE"), ("CB", "CG", "CD", "CE", "chi3"), # chi3 ("CD", "CE", "NZ"), ("CG", "CD", "CE", "NZ", "chi4"), # chi4 ("CB", "CG", "HG2"), ("CB", "CG",
= 1) def doit2() : dataz = datax variable1 = str(data_var1.get()) variable2 = str(data_var2.get()) variable3 = str(data_var3.get()) variable4 = str(data_var4.get()) variable5 = str(data_var5.get()) variable_array = [variable1,variable2,variable3,variable4,variable5] variable_array.append ("Patient Condition") dataz = dataz[variable_array].dropna(axis=0,how='any') #split dataset train, test = train_test_split(dataz, test_size=0.6, random_state=int(4)) gnb = GaussianNB() newarr = [] newarr.extend(variable_array) newarr.remove("Patient Condition") gnb.fit(train[newarr].values, train["Patient Condition"]) result = gnb.predict(test[newarr]) # Print Performance Indicator data_accuracy = ("Number of mislabeled points out of a total {} points : {}, performance {:05.2f}%" .format( test.shape[0], (test["Patient Condition"] != result).sum(), 100*(1-(test["Patient Condition"] != result).sum()/test.shape[0]) )) test_data = pd.concat([test[newarr], test["Patient Condition"]], axis=1) test_data["Patient Condition"] = result test_data["Data Accuracy"] = data_accuracy #excel writer writer = pd.ExcelWriter('Output.xlsx', engine = 'xlsxwriter') test_data.to_excel(writer,sheet_name='Sheet1') writer.save() window.destroy() si("","Output Created! Check it out!") enter2 = Button(window.frame_header,text="Enter",width=25,command=doit2).grid(row=13, column = 1) elif i == 6 : #entry number 1 ttk.Label(window.frame_header, text = "Data Variable number 1").grid(row = 8, column = 0) data_var1 = StringVar() entry_var1 = Entry(window.frame_header,textvariable=data_var1,width=30,bg="Light Grey").grid(row = 8,column = 1) #entry number 2 ttk.Label(window.frame_header, text = "Data Variable number 2").grid(row = 9, column = 0) data_var2 = StringVar() entry_var2 = Entry(window.frame_header,textvariable=data_var2,width=30,bg="Light Grey").grid(row = 9,column = 1) #entry number 3 ttk.Label(window.frame_header, text = "Data Variable number 3").grid(row = 10, column = 0) data_var3 = StringVar() entry_var3 = Entry(window.frame_header,textvariable=data_var3,width=30,bg="Light Grey").grid(row = 10,column = 1) #entry number 4 ttk.Label(window.frame_header, text = "Data Variable number 4").grid(row = 11, column = 0) data_var4 = StringVar() entry_var4 = Entry(window.frame_header,textvariable=data_var4,width=30,bg="Light Grey").grid(row = 11,column = 1) #entry number 5 ttk.Label(window.frame_header, text = "Data Variable number 5").grid(row = 12, column = 0) data_var5 = StringVar() entry_var5 = Entry(window.frame_header,textvariable=data_var5,width=30,bg="Light Grey").grid(row = 12,column = 1) #entry number 6 ttk.Label(window.frame_header, text = "Data Variable number 6").grid(row = 13, column = 0) data_var6 = StringVar() entry_var6 = Entry(window.frame_header,textvariable=data_var6,width=30,bg="Light Grey").grid(row = 13,column = 1) def doit2() : dataz = datax variable1 = str(data_var1.get()) variable2 = str(data_var2.get()) variable3 = str(data_var3.get()) variable4 = str(data_var4.get()) variable5 = str(data_var5.get()) variable6 = str(data_var6.get()) variable_array = [variable1,variable2,variable3,variable4,variable5,variable6] variable_array.append ("Patient Condition") dataz = dataz[variable_array].dropna(axis=0,how='any') #split dataset train, test = train_test_split(dataz, test_size=0.6, random_state=int(4)) gnb = GaussianNB() newarr = [] newarr.extend(variable_array) newarr.remove("Patient Condition") gnb.fit(train[newarr].values, train["Patient Condition"]) result = gnb.predict(test[newarr]) # Print Performance Indicator data_accuracy = ("Number of mislabeled points out of a total {} points : {}, performance {:05.2f}%" .format( test.shape[0], (test["Patient Condition"] != result).sum(), 100*(1-(test["Patient Condition"] != result).sum()/test.shape[0]) )) test_data = pd.concat([test[newarr], test["Patient Condition"]], axis=1) test_data["Patient Condition"] = result test_data["Data Accuracy"] = data_accuracy #excel writer writer = pd.ExcelWriter('Output.xlsx', engine = 'xlsxwriter') test_data.to_excel(writer,sheet_name='Sheet1') writer.save() window.destroy() si("","Output Created! Check it out!") enter2 = Button(window.frame_header,text="Enter",width=25,command=doit2).grid(row=14, column = 1) elif i == 7 : #entry number 1 ttk.Label(window.frame_header, text = "Data Variable number 1").grid(row = 8, column = 0) data_var1 = StringVar() entry_var1 = Entry(window.frame_header,textvariable=data_var1,width=30,bg="Light Grey").grid(row = 8,column = 1) #entry number 2 ttk.Label(window.frame_header, text = "Data Variable number 2").grid(row = 9, column = 0) data_var2 = StringVar() entry_var2 = Entry(window.frame_header,textvariable=data_var2,width=30,bg="Light Grey").grid(row = 9,column = 1) #entry number 3 ttk.Label(window.frame_header, text = "Data Variable number 3").grid(row = 10, column = 0) data_var3 = StringVar() entry_var3 = Entry(window.frame_header,textvariable=data_var3,width=30,bg="Light Grey").grid(row = 10,column = 1) #entry number 4 ttk.Label(window.frame_header, text = "Data Variable number 4").grid(row = 11, column = 0) data_var4 = StringVar() entry_var4 = Entry(window.frame_header,textvariable=data_var4,width=30,bg="Light Grey").grid(row = 11,column = 1) #entry number 5 ttk.Label(window.frame_header, text = "Data Variable number 5").grid(row = 12, column = 0) data_var5 = StringVar() entry_var5 = Entry(window.frame_header,textvariable=data_var5,width=30,bg="Light Grey").grid(row = 12,column = 1) #entry number 6 ttk.Label(window.frame_header, text = "Data Variable number 6").grid(row = 13, column = 0) data_var6 = StringVar() entry_var6 = Entry(window.frame_header,textvariable=data_var6,width=30,bg="Light Grey").grid(row = 13,column = 1) #entry number 7 ttk.Label(window.frame_header, text = "Data Variable number 7").grid(row = 14, column = 0) data_var7 = StringVar() entry_var7 = Entry(window.frame_header,textvariable=data_var7,width=30,bg="Light Grey").grid(row = 14,column = 1) def doit2() : dataz = datax variable1 = str(data_var1.get()) variable2 = str(data_var2.get()) variable3 = str(data_var3.get()) variable4 = str(data_var4.get()) variable5 = str(data_var5.get()) variable6 = str(data_var6.get()) variable7 = str(data_var7.get()) variable_array = [variable1,variable2,variable3,variable4,variable5,variable6,variable7] variable_array.append ("Patient Condition") dataz = dataz[variable_array].dropna(axis=0,how='any') #split dataset train, test = train_test_split(dataz, test_size=0.6, random_state=int(4)) gnb = GaussianNB() newarr = [] newarr.extend(variable_array) newarr.remove("Patient Condition") gnb.fit(train[newarr].values, train["Patient Condition"]) result = gnb.predict(test[newarr]) # Print Performance Indicator data_accuracy = ("Number of mislabeled points out of a total {} points : {}, performance {:05.2f}%" .format( test.shape[0], (test["Patient Condition"] != result).sum(), 100*(1-(test["Patient Condition"] != result).sum()/test.shape[0]) )) test_data = pd.concat([test[newarr], test["Patient Condition"]], axis=1) test_data["Patient Condition"] = result test_data["Data Accuracy"] = data_accuracy #excel writer writer = pd.ExcelWriter('Output.xlsx', engine = 'xlsxwriter') test_data.to_excel(writer,sheet_name='Sheet1') writer.save() window.destroy() si("","Output Created! Check it out!") enter2 = Button(window.frame_header,text="Enter",width=25,command=doit2).grid(row=15, column = 1) elif i == 8 : #entry number 1 ttk.Label(window.frame_header, text = "Data Variable number 1").grid(row = 8, column = 0) data_var1 = StringVar() entry_var1 = Entry(window.frame_header,textvariable=data_var1,width=30,bg="Light Grey").grid(row = 8,column = 1) #entry number 2 ttk.Label(window.frame_header, text = "Data Variable number 2").grid(row = 9, column = 0) data_var2 = StringVar() entry_var2 = Entry(window.frame_header,textvariable=data_var2,width=30,bg="Light Grey").grid(row = 9,column = 1) #entry number 3 ttk.Label(window.frame_header, text = "Data Variable number 3").grid(row = 10, column = 0) data_var3 = StringVar() entry_var3 = Entry(window.frame_header,textvariable=data_var3,width=30,bg="Light Grey").grid(row = 10,column = 1) #entry number 4 ttk.Label(window.frame_header, text = "Data Variable number 4").grid(row = 11, column = 0) data_var4 = StringVar() entry_var4 = Entry(window.frame_header,textvariable=data_var4,width=30,bg="Light Grey").grid(row = 11,column = 1) #entry number 5 ttk.Label(window.frame_header, text = "Data Variable number 5").grid(row = 12, column = 0) data_var5 = StringVar() entry_var5 = Entry(window.frame_header,textvariable=data_var5,width=30,bg="Light Grey").grid(row = 12,column = 1) #entry number 6 ttk.Label(window.frame_header, text = "Data Variable number 6").grid(row = 13, column = 0) data_var6 = StringVar() entry_var6 = Entry(window.frame_header,textvariable=data_var6,width=30,bg="Light Grey").grid(row = 13,column = 1) #entry number 7 ttk.Label(window.frame_header, text = "Data Variable number 7").grid(row = 14, column = 0) data_var7 = StringVar() entry_var7 = Entry(window.frame_header,textvariable=data_var7,width=30,bg="Light Grey").grid(row = 14,column = 1) #entry number 8 ttk.Label(window.frame_header, text = "Data Variable number 8").grid(row = 15, column = 0) data_var8 = StringVar() entry_var8 = Entry(window.frame_header,textvariable=data_var8,width=30,bg="Light Grey").grid(row = 15,column = 1) def doit2() : dataz = datax variable1 = str(data_var1.get()) variable2 = str(data_var2.get()) variable3 = str(data_var3.get()) variable4 = str(data_var4.get()) variable5 = str(data_var5.get()) variable6 = str(data_var6.get()) variable7 = str(data_var7.get()) variable7 = str(data_var8.get()) variable_array = [variable1,variable2,variable3,variable4,variable5,variable6,variable7,variable8] variable_array.append ("Patient Condition") dataz = dataz[variable_array].dropna(axis=0,how='any') #split dataset train, test = train_test_split(dataz, test_size=0.6, random_state=int(4)) gnb = GaussianNB() newarr = [] newarr.extend(variable_array) newarr.remove("Patient Condition") gnb.fit(train[newarr].values, train["Patient Condition"]) result = gnb.predict(test[newarr]) # Print Performance Indicator data_accuracy = ("Number of mislabeled points out of a total {} points : {}, performance {:05.2f}%" .format( test.shape[0], (test["Patient Condition"] != result).sum(), 100*(1-(test["Patient Condition"] != result).sum()/test.shape[0]) )) test_data = pd.concat([test[newarr], test["Patient Condition"]], axis=1) test_data["Patient Condition"] = result test_data["Data Accuracy"] = data_accuracy #excel writer writer = pd.ExcelWriter('Output.xlsx', engine = 'xlsxwriter') test_data.to_excel(writer,sheet_name='Sheet1') writer.save() window.destroy() si("","Output Created! Check it out!") enter2 = Button(window.frame_header,text="Enter",width=25,command=doit2).grid(row=16, column = 1) elif i == 9 : #entry number 1 ttk.Label(window.frame_header, text = "Data Variable number 1").grid(row = 8, column = 0) data_var1 = StringVar() entry_var1 = Entry(window.frame_header,textvariable=data_var1,width=30,bg="Light Grey").grid(row = 8,column = 1) #entry number 2 ttk.Label(window.frame_header, text = "Data Variable number 2").grid(row = 9, column = 0) data_var2 = StringVar() entry_var2 = Entry(window.frame_header,textvariable=data_var2,width=30,bg="Light Grey").grid(row = 9,column = 1) #entry number 3 ttk.Label(window.frame_header, text = "Data Variable number 3").grid(row = 10, column = 0) data_var3 = StringVar() entry_var3 = Entry(window.frame_header,textvariable=data_var3,width=30,bg="Light Grey").grid(row = 10,column = 1) #entry number 4 ttk.Label(window.frame_header, text = "Data Variable number 4").grid(row = 11, column = 0) data_var4 = StringVar() entry_var4 = Entry(window.frame_header,textvariable=data_var4,width=30,bg="Light Grey").grid(row = 11,column = 1) #entry number 5 ttk.Label(window.frame_header, text = "Data Variable number 5").grid(row = 12, column = 0) data_var5 = StringVar() entry_var5 = Entry(window.frame_header,textvariable=data_var5,width=30,bg="Light Grey").grid(row = 12,column = 1) #entry number 6 ttk.Label(window.frame_header, text = "Data Variable number 6").grid(row = 13, column = 0) data_var6 = StringVar() entry_var6 = Entry(window.frame_header,textvariable=data_var6,width=30,bg="Light Grey").grid(row = 13,column = 1) #entry number 7 ttk.Label(window.frame_header, text = "Data Variable number 7").grid(row = 14, column = 0) data_var7 = StringVar() entry_var7 = Entry(window.frame_header,textvariable=data_var7,width=30,bg="Light Grey").grid(row = 14,column = 1) #entry number 8 ttk.Label(window.frame_header, text = "Data Variable number 8").grid(row = 15, column = 0) data_var8 = StringVar() entry_var8 = Entry(window.frame_header,textvariable=data_var8,width=30,bg="Light Grey").grid(row = 15,column = 1) #entry number 9 ttk.Label(window.frame_header, text =
enumerate(group_ids): yoff = ix * voff groupname = self.controller.file_groups[str(checked)] dgroup = self.controller.get_group(groupname) plot_yarrays = [(yarray_name, PLOTOPTS_1, dgroup.filename)] if dgroup is not None: dgroup.plot_extras = [] self.plot(dgroup, title='', new=newplot, multi=True, yoff=yoff, plot_yarrays=plot_yarrays, with_extras=False, delay_draw=True) newplot = False ppanel = self.controller.get_display(stacked=False).panel ppanel.conf.show_legend=True ppanel.conf.draw_legend() ppanel.unzoom_all() def onAutoNorm(self, evt=None): dgroup = self.controller.get_group() try: norm2 = max(dgroup.energy) - dgroup.e0 norm1 = 5.0*int(norm2/15.0) nnorm = 2 if (norm2-norm1 < 350): nnorm = 1 if (norm2-norm1 < 50): nnorm = 0 except: nnorm = None self.wids['auto_step'].SetValue(1) self.wids['auto_e0'].SetValue(1) self.wids['nvict'].SetSelection(0) self.wids['pre1'].SetValue(0) self.wids['pre2'].SetValue(0) self.wids['norm1'].SetValue(0) self.wids['norm2'].SetValue(0) if nnorm is not None: self.set_nnorm_widget(nnorm) self.wids['norm_method'].SetSelection(0) self.onReprocess() def onCopyAuto(self, evt=None): opts = dict(pre1=0, pre2=0, nvict=0, norm1=0, norm2=0, norm_method='polynomial', nnorm=2, auto_e0=1, auto_step=1) for checked in self.controller.filelist.GetCheckedStrings(): groupname = self.controller.file_groups[str(checked)] grp = self.controller.get_group(groupname) if grp != self.controller.group and not grp.is_frozen: self.update_config(opts, dgroup=grp) self.fill_form(grp) self.process(grp, force=True) def onSaveConfigBtn(self, evt=None): conf = self.get_config() conf.update(self.read_form()) self.set_defaultconfig(conf) def onCopyParam(self, name=None, evt=None): conf = self.get_config() form = self.read_form() conf.update(form) dgroup = self.controller.get_group() self.update_config(conf) self.fill_form(dgroup) opts = {} name = str(name) def copy_attrs(*args): for a in args: opts[a] = conf[a] if name == 'xas_e0': copy_attrs('e0', 'show_e0', 'auto_e0') elif name == 'xas_step': copy_attrs('edge_step', 'auto_step') elif name == 'xas_pre': copy_attrs('pre1', 'pre2', 'nvict') elif name == 'atsym': copy_attrs('atsym', 'edge') elif name == 'xas_norm': copy_attrs('norm_method', 'nnorm', 'norm1', 'norm2') elif name == 'energy_ref': copy_attrs('energy_ref') for checked in self.controller.filelist.GetCheckedStrings(): groupname = self.controller.file_groups[str(checked)] grp = self.controller.get_group(groupname) if grp != self.controller.group and not grp.is_frozen: self.update_config(opts, dgroup=grp) self.fill_form(grp) self.process(grp, force=True) def onSet_XASE0(self, evt=None, value=None): "handle setting auto e0 / show e0" auto_e0 = self.wids['auto_e0'].GetValue() self.update_config({'e0': self.wids['e0'].GetValue(), 'auto_e0':self.wids['auto_e0'].GetValue()}) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onSet_XASE0Val(self, evt=None, value=None): "handle setting e0" self.wids['auto_e0'].SetValue(0) self.update_config({'e0': self.wids['e0'].GetValue(), 'auto_e0':self.wids['auto_e0'].GetValue()}) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onSet_XASStep(self, evt=None, value=None): "handle setting edge step" edge_step = self.wids['step'].GetValue() if edge_step < 0: self.wids['step'].SetValue(abs(edge_step)) self.wids['auto_step'].SetValue(0) self.update_config({'edge_step': abs(edge_step), 'auto_step': False}) autoset_fs_increment(self.wids['step'], abs(edge_step)) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onSet_Scale(self, evt=None, value=None): "handle setting non-XAFS scale value" self.update_config({'scale': self.wids['scale'].GetValue()}) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onSet_Ranges(self, evt=None, **kws): conf = {} for attr in ('pre1', 'pre2', 'norm1', 'norm2'): conf[attr] = self.wids[attr].GetValue() self.update_config(conf) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onSelPoint(self, evt=None, opt='__', relative_e0=True, win=None): """ get last selected point from a specified plot window and fill in the value for the widget defined by `opt`. by default it finds the latest cursor position from the cursor history of the first 20 plot windows. """ if opt not in self.wids: return None _x, _y = last_cursor_pos(win=win, _larch=self.larch) if _x is None: return e0 = self.wids['e0'].GetValue() if opt == 'e0': self.wids['e0'].SetValue(_x) self.wids['auto_e0'].SetValue(0) elif opt in ('pre1', 'pre2', 'norm1', 'norm2'): self.wids[opt].SetValue(_x-e0) time.sleep(0.01) wx.CallAfter(self.onReprocess) def onReprocess(self, evt=None, value=None, **kws): "handle request reprocess" if self.skip_process: return try: dgroup = self.controller.get_group() except TypeError: return if not hasattr(dgroup, self.configname): return form = self.read_form() self.process(dgroup=dgroup) self.onPlotEither() def make_dnormde(self, dgroup): form = dict(group=dgroup.groupname) self.larch_eval("{group:s}.dnormde={group:s}.dmude/{group:s}.edge_step".format(**form)) self.larch_eval("{group:s}.d2normde={group:s}.d2mude/{group:s}.edge_step".format(**form)) def process(self, dgroup=None, force_mback=False, force=False, **kws): """ handle process (pre-edge/normalize) of XAS data from XAS form """ if self.skip_process and not force: return if dgroup is None: dgroup = self.controller.get_group() if dgroup is None: return self.skip_process = True conf = self.get_config(dgroup) dgroup.custom_plotopts = {} form = self.read_form() form['group'] = dgroup.groupname groupnames = list(self.controller.file_groups.keys()) self.wids['energy_ref'].SetChoices(groupnames) eref = conf.get('energy_ref', dgroup.groupname) for key, val in self.controller.file_groups.items(): if eref in (val, key): self.wids['energy_ref'].SetStringSelection(key) if not is_xasgroup(dgroup): self.skip_process = False dgroup.mu = dgroup.ydat * 1.0 opts = {'group': dgroup.groupname, 'scale': conf.get('scale', 1.0)} self.larch_eval("{group:s}.scale = {scale:.8f}".format(**opts)) self.larch_eval("{group:s}.norm = {scale:.8f}*{group:s}.ydat".format(**opts)) return en_units = getattr(dgroup, 'energy_units', None) if en_units is None: en_units = guess_energy_units(dgroup.energy) if en_units != 'eV': mono_dspace = getattr(dgroup, 'mono_dspace', 1) dlg = EnergyUnitsDialog(self.parent, dgroup.energy, unitname=en_units, dspace=mono_dspace) res = dlg.GetResponse() dlg.Destroy() if res.ok: en_units = res.units dgroup.mono_dspace = res.dspace dgroup.xdat = dgroup.energy = res.energy dgroup.energy_units = en_units e0 = form['e0'] edge_step = form['edge_step'] copts = [dgroup.groupname] if not form['auto_e0']: if e0 < max(dgroup.energy) and e0 > min(dgroup.energy): copts.append("e0=%.4f" % float(e0)) if not form['auto_step']: copts.append("step=%s" % gformat(float(edge_step))) for attr in ('pre1', 'pre2', 'nvict', 'nnorm', 'norm1', 'norm2'): if form[attr] is None: copts.append("%s=None" % attr) else: copts.append("%s=%.2f" % (attr, form[attr])) self.larch_eval("pre_edge(%s)" % (', '.join(copts))) self.larch_eval("{group:s}.norm_poly = 1.0*{group:s}.norm".format(**form)) norm_method = form['norm_method'].lower() form['normmeth'] = 'poly' if force_mback or norm_method.startswith('mback'): form['normmeth'] = 'mback' copts = [dgroup.groupname] copts.append("z=%d" % atomic_number(form['atsym'])) copts.append("edge='%s'" % form['edge']) for attr in ('pre1', 'pre2', 'nvict', 'nnorm', 'norm1', 'norm2'): if form[attr] is None: copts.append("%s=None" % attr) else: copts.append("%s=%.2f" % (attr, form[attr])) self.larch_eval("mback_norm(%s)" % (', '.join(copts))) if form['auto_step']: norm_expr = """{group:s}.norm = 1.0*{group:s}.norm_{normmeth:s} {group:s}.edge_step = 1.0*{group:s}.edge_step_{normmeth:s}""" self.larch_eval(norm_expr.format(**form)) else: norm_expr = """{group:s}.norm = 1.0*{group:s}.norm_{normmeth:s} {group:s}.norm *= {group:s}.edge_step_{normmeth:s}/{edge_step:.8f}""" self.larch_eval(norm_expr.format(**form)) if norm_method.startswith('area'): form['normmeth'] = 'area' expr = """{group:s}.norm = 1.0*{group:s}.norm_{normmeth:s} {group:s}.edge_step = 1.0*{group:s}.edge_step_{normmeth:s}""" self.larch_eval(expr.format(**form)) self.make_dnormde(dgroup) if form['auto_e0']: self.wids['e0'].SetValue(dgroup.e0) if form['auto_step']: self.wids['step'].SetValue(dgroup.edge_step) autoset_fs_increment(self.wids['step'], dgroup.edge_step) self.wids['atsym'].SetStringSelection(dgroup.atsym) self.wids['edge'].SetStringSelection(dgroup.edge) self.set_nnorm_widget(dgroup.pre_edge_details.nnorm) for attr in ('e0', 'edge_step'): conf[attr] = getattr(dgroup, attr) for attr in ('pre1', 'pre2', 'norm1', 'norm2'): conf[attr] = val = getattr(dgroup.pre_edge_details, attr, None) if val is not None: self.wids[attr].SetValue(val) if hasattr(dgroup, 'mback_params'): # from mback conf['atsym'] = getattr(dgroup.mback_params, 'atsym') conf['edge'] = getattr(dgroup.mback_params, 'edge') self.update_config(conf, dgroup=dgroup) wx.CallAfter(self.unset_skip_process) def get_plot_arrays(self, dgroup): lab = plotlabels.norm if dgroup is None: return dgroup.plot_y2label = None dgroup.plot_xlabel = plotlabels.energy dgroup.plot_yarrays = [('norm', PLOTOPTS_1, lab)] if not is_xasgroup(dgroup): pchoice = PlotOne_Choices_nonxas[self.plotone_op.GetStringSelection()] dgroup.plot_xlabel = 'x' dgroup.plot_ylabel = 'y' dgroup.plot_yarrays = [('ydat', PLOTOPTS_1, 'ydat')] dgroup.dmude = np.gradient(dgroup.ydat)/np.gradient(dgroup.xdat) dgroup.d2mude = np.gradient(dgroup.dmude)/np.gradient(dgroup.xdat) if not hasattr(dgroup, 'scale'): dgroup.scale = 1.0 dgroup.norm = dgroup.ydat*dgroup.scale if pchoice == 'dmude': dgroup.plot_ylabel = 'dy/dx' dgroup.plot_yarrays = [('dmude', PLOTOPTS_1, 'dy/dx')] elif pchoice == 'd2mude': dgroup.plot_ylabel = 'd2y/dx2' dgroup.plot_yarrays = [('d2mude', PLOTOPTS_1, 'd2y/dx')] elif pchoice == 'norm': dgroup.plot_ylabel = 'scaled y' dgroup.plot_yarrays = [('norm', PLOTOPTS_1, 'y/scale')] elif pchoice == 'norm+dnormde': lab = plotlabels.norm dgroup.plot_y2label = 'dy/dx' dgroup.plot_yarrays = [('ydat', PLOTOPTS_1, 'y'), ('dnormde', PLOTOPTS_D, 'dy/dx')] elif pchoice == 'norm+d2normde': lab = plotlabels.norm dgroup.plot_y2label = 'd2y/dx2' dgroup.plot_yarrays = [('ydat', PLOTOPTS_1, 'y'), ('d2normde', PLOTOPTS_D, 'd2y/dx')] return req_attrs = ['e0', 'norm', 'dmude', 'd2mude', 'pre_edge'] pchoice = PlotOne_Choices[self.plotone_op.GetStringSelection()] if pchoice in ('mu', 'norm', 'flat', 'dmude', 'd2mude'): lab = getattr(plotlabels, pchoice) dgroup.plot_yarrays = [(pchoice, PLOTOPTS_1, lab)] elif pchoice == 'prelines': dgroup.plot_yarrays = [('mu', PLOTOPTS_1, plotlabels.mu), ('pre_edge', PLOTOPTS_2, 'pre edge'), ('post_edge', PLOTOPTS_2, 'post edge')] elif pchoice == 'preedge': lab = r'pre-edge subtracted $\mu$' dgroup.pre_edge_sub = dgroup.norm * dgroup.edge_step dgroup.plot_yarrays = [('pre_edge_sub', PLOTOPTS_1, lab)] elif pchoice == 'mu+dmude': lab = plotlabels.mu lab2 = plotlabels.dmude dgroup.plot_yarrays = [('mu', PLOTOPTS_1, lab), ('dmude', PLOTOPTS_D, lab2)] dgroup.plot_y2label = lab2 elif pchoice == 'mu+d2mude': lab = plotlabels.mu lab2 = plotlabels.d2mude dgroup.plot_yarrays = [('mu', PLOTOPTS_1, lab), ('d2mude', PLOTOPTS_D, lab2)] dgroup.plot_y2label = lab2 elif pchoice == 'norm+dnormde': lab = plotlabels.norm lab2 = plotlabels.dmude + ' (normalized)' dgroup.plot_yarrays = [('norm', PLOTOPTS_1, lab), ('dnormde', PLOTOPTS_D, lab2)] dgroup.plot_y2label = lab2 elif pchoice == 'norm+d2normde': lab = plotlabels.norm lab2 = plotlabels.d2mude + ' (normalized)' dgroup.plot_yarrays = [('norm', PLOTOPTS_1, lab), ('d2normde', PLOTOPTS_D, lab2)] dgroup.plot_y2label = lab2 elif pchoice == 'mback_norm': req_attrs.append('mback_norm') lab = r'$\mu$' if not hasattr(dgroup, 'mback_mu'): self.process(dgroup=dgroup, force_mback=True) dgroup.plot_yarrays = [('mu', PLOTOPTS_1, lab), ('mback_mu', PLOTOPTS_2, r'tabulated $\mu(E)$')] elif pchoice == 'mback_poly': req_attrs.append('mback_norm') lab = plotlabels.norm if not hasattr(dgroup, 'mback_mu'): self.process(dgroup=dgroup, force_mback=True) dgroup.plot_yarrays = [('norm_mback', PLOTOPTS_1, 'mback'), ('norm_poly', PLOTOPTS_2, 'polynomial')] elif pchoice == 'area_norm': dgroup.plot_yarrays = [('norm_area', PLOTOPTS_1, 'area'), ('norm_poly', PLOTOPTS_2, 'polynomial')] dgroup.plot_ylabel = lab needs_proc = False for attr in req_attrs: needs_proc = needs_proc or (not hasattr(dgroup, attr)) if needs_proc: self.process(dgroup=dgroup, force=True) y4e0 = dgroup.ydat = getattr(dgroup, dgroup.plot_yarrays[0][0], dgroup.mu) dgroup.plot_extras = [] if self.wids['showe0'].IsChecked(): ie0 = index_of(dgroup.energy, dgroup.e0) dgroup.plot_extras.append(('marker', dgroup.e0, y4e0[ie0], {})) def plot(self, dgroup, title=None, plot_yarrays=None, yoff=0, delay_draw=False, multi=False, new=True, zoom_out=True, with_extras=True, **kws): if self.skip_plotting: return ppanel = self.controller.get_display(stacked=False).panel viewlims = ppanel.get_viewlimits() plotcmd = ppanel.oplot if new: plotcmd = ppanel.plot erange = Plot_EnergyRanges[self.plot_erange.GetStringSelection()] self.controller.set_plot_erange(erange) groupname = getattr(dgroup, 'groupname', None) if groupname is None: return if not hasattr(dgroup, 'xdat'): print("Cannot plot group ", groupname) if ((getattr(dgroup, 'plot_yarrays', None) is None or getattr(dgroup, 'energy', None) is None or getattr(dgroup, 'mu', None) is None or getattr(dgroup, 'e0', None) is None or getattr(dgroup, 'dmude', None) is None or getattr(dgroup, 'd2mude', None) is None or getattr(dgroup, 'norm', None) is None)): self.process(dgroup=dgroup) self.get_plot_arrays(dgroup) if plot_yarrays is None and hasattr(dgroup, 'plot_yarrays'): plot_yarrays = dgroup.plot_yarrays popts = kws path, fname = os.path.split(dgroup.filename) if 'label' not in popts: popts['label'] = dgroup.plot_ylabel zoom_out = (zoom_out or min(dgroup.xdat) >= viewlims[1]
import collections import copy import datetime import json import logging import os import sys import typing import unittest import uuid COMMON_PRIMITIVES_DIR = os.path.join(os.path.dirname(__file__), 'common-primitives') # NOTE: This insertion should appear before any code attempting to resolve or load primitives, # so the git submodule version of `common-primitives` is looked at first. sys.path.insert(0, COMMON_PRIMITIVES_DIR) TEST_PRIMITIVES_DIR = os.path.join(os.path.dirname(__file__), 'data', 'primitives') sys.path.insert(0, TEST_PRIMITIVES_DIR) from common_primitives.dataset_to_dataframe import DatasetToDataFramePrimitive from common_primitives.column_parser import ColumnParserPrimitive from common_primitives.random_forest import RandomForestClassifierPrimitive from test_primitives.monomial import MonomialPrimitive from test_primitives.random import RandomPrimitive from test_primitives.sum import SumPrimitive from test_primitives.increment import IncrementPrimitive from d3m import container, exceptions, index, utils from d3m.metadata import base as metadata_base, hyperparams, params, pipeline from d3m.primitive_interfaces import base, transformer, supervised_learning TEST_PIPELINE_1 = """ { "id": "2b50a7db-c5e2-434c-b02d-9e595bd56788", "digest": "b87dbbd5b8bcc1470050a756cf22d6def2662a61482debf55c09948225372411", "schema": "https://metadata.datadrivendiscovery.org/schemas/v0/pipeline.json", "source": { "name": "<NAME>", "contact": "mailto:<EMAIL>" }, "created": "2018-02-28T09:42:27.443844Z", "name": "Test pipeline", "description": "Just a test pipeline", "users": [ { "id": "f32467bc-698c-4ab6-a489-2e8f73fcfdaa", "reason": "User was making a test", "rationale": "I made a test" } ], "inputs": [ { "name": "dataframe inputs" }, { "name": "dataframe outputs" }, { "name": "extra data" } ], "outputs": [ { "name": "dataframe predictions", "data": "steps.6.main" } ], "steps": [ { "type": "PRIMITIVE", "primitive": { "id": "efa24fae-49c4-4482-b49f-ceb351c0d916", "version": "0.1.0", "python_path": "d3m.primitives.test.LossPrimitive", "name": "Loss Primitive" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" }, "outputs": { "type": "CONTAINER", "data": "inputs.1" } }, "outputs": [ { "id": "produce" } ] }, { "type": "PRIMITIVE", "primitive": { "id": "00c3a435-a87c-405b-bed9-3a8c402d4431", "version": "0.1.0", "python_path": "d3m.primitives.test.Model1Primitive", "name": "Model 1 Primitive" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" }, "outputs": { "type": "CONTAINER", "data": "inputs.1" } }, "outputs": [ { "id": "produce" } ] }, { "type": "PRIMITIVE", "primitive": { "id": "4987c4b0-cf4c-4f7f-9bcc-557a6d72589d", "version": "0.1.0", "python_path": "d3m.primitives.test.Model2Primitive", "name": "Model 2 Primitive" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" }, "outputs": { "type": "CONTAINER", "data": "inputs.1" } }, "outputs": [ { "id": "produce" } ] }, { "type": "PRIMITIVE", "primitive": { "id": "9c00d42d-382d-4177-a0e7-082da88a29c8", "version": "0.1.0", "python_path": "d3m.primitives.operator.sum.Test", "name": "Sum Values", "digest": "__SUM_DIGEST__" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" } }, "outputs": [ { "id": "produce" } ] }, { "type": "PRIMITIVE", "primitive": { "id": "e42e6f17-77cc-4611-8cca-bba36a46e806", "version": "0.1.0", "python_path": "d3m.primitives.test.PipelineTestPrimitive", "name": "Pipeline Test Primitive" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" }, "extra_data": { "type": "CONTAINER", "data": "inputs.2" }, "offset": { "type": "DATA", "data": "steps.3.produce" } }, "outputs": [ { "id": "produce" }, { "id": "produce_score" } ], "hyperparams": { "loss": { "type": "PRIMITIVE", "data": 0 }, "column_to_operate_on": { "type": "VALUE", "data": 5 }, "ensemble": { "type": "PRIMITIVE", "data": [ 1, 2 ] }, "columns_to_operate_on": { "type": "VALUE", "data": [3, 6, 7] } }, "users": [ { "id": "<PASSWORD>", "reason": "User clicked on a button", "rationale": "I dragged an icon" } ] }, { "type": "SUBPIPELINE", "pipeline": { "id": "0113b91f-3010-4a47-bd56-a50c4e28a4a4", "digest": "83430addfcb9430ad02fd59f114ac7c723806058ca90d6b0f226d1031826ac8d" }, "inputs": [ { "data": "steps.4.produce" } ], "outputs": [ { "id": "pipeline_output" } ] }, { "type": "PLACEHOLDER", "inputs": [ { "data": "steps.5.pipeline_output" }, { "data": "steps.4.produce_score" } ], "outputs": [ { "id": "main" } ] } ] } """.replace('__SUM_DIGEST__', SumPrimitive.metadata.query()['digest']) TEST_PIPELINE_2 = """ { "id": "0113b91f-3010-4a47-bd56-a50c4e28a4a4", "digest": "83430addfcb9430ad02fd59f114ac7c723806058ca90d6b0f226d1031826ac8d", "schema": "https://metadata.datadrivendiscovery.org/schemas/v0/pipeline.json", "created": "2018-02-28T09:42:27.443844Z", "name": "Test pipeline", "description": "Just a test pipeline", "inputs": [ {} ], "outputs": [ { "data": "steps.0.produce" } ], "steps": [ { "type": "PRIMITIVE", "primitive": { "id": "4987c4b0-cf4c-4f7f-9bcc-557a6d72589d", "version": "0.1.0", "python_path": "d3m.primitives.test.Model2Primitive", "name": "Model 2 Primitive" }, "arguments": { "inputs": { "type": "CONTAINER", "data": "inputs.0" }, "outputs": { "type": "CONTAINER", "data": "inputs.0" } }, "outputs": [ { "id": "produce" } ] } ] } """ class MockPrimitiveBuilder: """ This class helps build mock primitives from scratch without checking. """ def __init__(self, inputs, hyperparams, primitive_id=None, version='0.0.0', name='mock_primitive_name', python_path='d3m.primitives.mock.foobar', digest='f' * 64): """ inputs : Dict It will be used to fill the 'arguments' field. outputs : List List of output names """ self.primitive_dict = { 'type': 'PRIMITIVE', 'primitive': { 'id': primitive_id if primitive_id is not None else str(uuid.uuid4()), 'version': version, 'python_path': python_path, 'name': name, 'digest': digest, }, 'arguments': inputs, 'hyperparams': hyperparams, 'outputs': None, } def build(self, **inputs_data): primitive_dict = copy.deepcopy(self.primitive_dict) primitive_dict['arguments'] = copy.deepcopy({name: self.primitive_dict['arguments'][name] for name in inputs_data.keys() if name in self.primitive_dict['arguments']}) primitive_dict['hyperparams'] = copy.deepcopy({name: self.primitive_dict['hyperparams'][name] for name in inputs_data.keys() if name in self.primitive_dict['hyperparams']}) for name, data in inputs_data.items(): if name in primitive_dict['arguments']: primitive_dict['arguments'][name]['data'] = data elif name in primitive_dict['hyperparams']: primitive_dict['hyperparams'][name]['data'] = data else: raise IndexError("No match name found for '{name}' in primitive {primitive_name}".format(name=name, primitive_name=self.primitive_dict['primitive']['name'])) return primitive_dict class MockPipelineBuilder: """ This class helps build pipelines for testing from scratch without checking. """ def __init__(self, input_names, pipeline_id=None, name='mock_name', description='mock_description'): self._increase_counter = 0 self.pipeline_dict = { 'id': pipeline_id if pipeline_id is not None else str(uuid.uuid4()), 'schema': 'https://metadata.datadrivendiscovery.org/schemas/v0/pipeline.json', 'source': {'name': 'Test author'}, 'created': datetime.datetime.now(tz=datetime.timezone.utc).isoformat(), 'name': name, 'description': description, 'inputs': [{'name': n} for n in input_names], 'outputs': [], 'steps': [] } self._subpipelines = {} def add_primitive(self, primitive_dict, outputs): """ Add primitives. """ primitive_dict['outputs'] = [{'id': o} for o in outputs] self.pipeline_dict['steps'].append(primitive_dict) def add_placeholder(self, inputs, outputs): placeholder_dict = { 'type': 'PLACEHOLDER', 'inputs': [{'data': input_data_ref} for input_data_ref in inputs], 'outputs': [{'id': output_id for output_id in outputs}] } self.pipeline_dict['steps'].append(placeholder_dict) def add_subpipeline(self, pipeline: pipeline.Pipeline, inputs, outputs): self._subpipelines[pipeline.id] = pipeline subpipeline_dict = { 'type': 'SUBPIPELINE', 'pipeline': {'id': pipeline.id}, 'inputs': [{'data': input_data_ref} for input_data_ref in inputs], 'outputs': [{'id': output_id for output_id in outputs}] } self.pipeline_dict['steps'].append(subpipeline_dict) def add_output(self, name, data): self.pipeline_dict['outputs'].append({'name': name, 'data': data}) def build(self, primitive_loading='ignore') -> pipeline.Pipeline: """ Output built pipeline instance. Parameters ---------- primitive_loading : str or callable If `primitive_loading` == 'ignore', the primitive resolving function will be skipped. If `primitive_loading` == 'default', a default primitive resolving function will be loaded. If `primitive_loading` is a function, it will become the resolving function. Returns ------- Pipeline A pipeline instance. """ resolver = pipeline.Resolver() resolver.get_pipeline = lambda pipeline_description: self._subpipelines[pipeline_description['id']] if primitive_loading == 'ignore': resolver.get_primitive = lambda primitive_description: None elif primitive_loading == 'full': pass elif callable(primitive_loading): resolver.get_primitive = primitive_loading else: raise ValueError("unknown value of 'primitive_loading'") return pipeline.Pipeline.from_json_structure(self.pipeline_dict, resolver=resolver) class Resolver(pipeline.Resolver): def _get_primitive(self, primitive_description: typing.Dict) -> typing.Optional[typing.Type[base.PrimitiveBase]]: # To hide any logging or stdout output. with utils.silence(): return super()._get_primitive(primitive_description) def get_pipeline(self, pipeline_description: typing.Dict) -> pipeline.Pipeline: if pipeline_description['id'] == '0113b91f-3010-4a47-bd56-a50c4e28a4a4': return pipeline.Pipeline.from_json(TEST_PIPELINE_2, resolver=self) return super().get_pipeline(pipeline_description) Inputs = container.DataFrame Outputs = container.DataFrame class Hyperparams(hyperparams.Hyperparams): pass class Params(params.Params): pass # Silence any validation warnings. with utils.silence(): class LossPrimitive(supervised_learning.SupervisedLearnerPrimitiveBase[Inputs, Outputs, Params, Hyperparams]): metadata = metadata_base.PrimitiveMetadata({ 'id': 'efa24fae-49c4-4482-b49f-ceb351c0d916', 'version': '0.1.0', 'name': "Loss Primitive", 'python_path': 'd3m.primitives.test.LossPrimitive', 'algorithm_types': [ metadata_base.PrimitiveAlgorithmType.CROSS_ENTROPY, ], 'primitive_family': metadata_base.PrimitiveFamily.LOSS_FUNCTION, }) def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> base.CallResult[Outputs]: pass def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None: pass def fit(self, *, timeout: float = None, iterations: int = None) -> base.CallResult[None]: pass def get_params(self) -> Params: pass def set_params(self, *, params: Params) -> None: pass class Model1Primitive(supervised_learning.SupervisedLearnerPrimitiveBase[Inputs, Outputs, Params, Hyperparams]): metadata = metadata_base.PrimitiveMetadata({ 'id': '00c3a435-a87c-405b-bed9-3a8c402d4431', 'version': '0.1.0', 'name': "Model 1 Primitive", 'python_path': 'd3m.primitives.test.Model1Primitive', 'algorithm_types': [ metadata_base.PrimitiveAlgorithmType.RANDOM_FOREST, ], 'primitive_family': metadata_base.PrimitiveFamily.CLASSIFICATION, }) def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> base.CallResult[Outputs]: pass def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None: pass def fit(self, *, timeout: float = None, iterations: int = None) -> base.CallResult[None]: pass def get_params(self) -> Params: pass def set_params(self, *, params: Params) -> None: pass class Model2Hyperparams(hyperparams.Hyperparams): # To test that a primitive instance can be a default value. base_estimator = hyperparams.Hyperparameter[base.PrimitiveBase]( default=LossPrimitive(hyperparams=Hyperparams.defaults()), semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'], ) class Model2Primitive(supervised_learning.SupervisedLearnerPrimitiveBase[Inputs, Outputs, Params, Model2Hyperparams]): metadata = metadata_base.PrimitiveMetadata({ 'id': '4987c4b0-cf4c-4f7f-9bcc-557a6d72589d', 'version': '0.1.0', 'name': "Model 2 Primitive", 'python_path': 'd3m.primitives.test.Model2Primitive', 'algorithm_types': [ metadata_base.PrimitiveAlgorithmType.SUPPORT_VECTOR_MACHINE, ], 'primitive_family': metadata_base.PrimitiveFamily.CLASSIFICATION, }) def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> base.CallResult[Outputs]: pass def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None: pass def fit(self, *, timeout: float = None, iterations: int = None) -> base.CallResult[None]: pass def get_params(self) -> Params: pass def set_params(self, *, params: Params) -> None: pass class TestPipeline(unittest.TestCase): @classmethod def setUpClass(cls): column_index = hyperparams.Hyperparameter[int](-1) class PipelineTestHyperparams(hyperparams.Hyperparams): loss = hyperparams.Hyperparameter[typing.Optional[base.PrimitiveBase]](default=None, semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']) column_to_operate_on = hyperparams.Hyperparameter[int](default=-1, semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter']) ensemble = hyperparams.Set(elements=hyperparams.Hyperparameter[base.PrimitiveBase](default=MonomialPrimitive), default=(), max_size=10, semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']) columns_to_operate_on = hyperparams.Set(column_index, (), 0, None, semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter']) PipelineTestInputs = typing.Union[container.Dataset, container.DataFrame] # Silence any validation warnings. with utils.silence(): class PipelineTestPrimitive(transformer.TransformerPrimitiveBase[PipelineTestInputs, Outputs, PipelineTestHyperparams]): metadata = metadata_base.PrimitiveMetadata({ 'id': 'e42e6f17-77cc-4611-8cca-bba36a46e806', 'version': '0.1.0', 'name': "Pipeline Test Primitive", 'python_path': 'd3m.primitives.test.PipelineTestPrimitive',
<filename>softwares/hisat2-2.1.0/hisat2_simulate_reads.py<gh_stars>1-10 #!/usr/bin/env python # # Copyright 2015, <NAME> <<EMAIL>> # # This file is part of HISAT 2. # # HISAT 2 is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HISAT 2 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HISAT 2. If not, see <http://www.gnu.org/licenses/>. # import sys, math, random, re from collections import defaultdict, Counter from argparse import ArgumentParser, FileType """ """ def reverse_complement(seq): result = "" for nt in seq: base = nt if nt == 'A': base = 'T' elif nt == 'a': base = 't' elif nt == 'C': base = 'G' elif nt == 'c': base = 'g' elif nt == 'G': base = 'C' elif nt == 'g': base = 'c' elif nt == 'T': base = 'A' elif nt == 't': base = 'a' result = base + result return result """ Random source for sequencing errors """ class ErrRandomSource: def __init__(self, prob = 0.0, size = 1 << 20): self.size = size self.rands = [] for i in range(self.size): if random.random() < prob: self.rands.append(1) else: self.rands.append(0) self.cur = 0 def getRand(self): assert self.cur < len(self.rands) rand = self.rands[self.cur] self.cur = (self.cur + 1) % len(self.rands) return rand """ """ def read_genome(genome_file): chr_dic = {} chr_name, sequence = "", "" for line in genome_file: if line[0] == ">": if chr_name and sequence: chr_dic[chr_name] = sequence chr_name = line.strip().split()[0][1:] sequence = "" else: sequence += line[:-1] if chr_name and sequence: chr_dic[chr_name] = sequence return chr_dic """ """ def read_transcript(genome_seq, gtf_file, frag_len): genes = defaultdict(list) transcripts = {} # Parse valid exon lines from the GTF file into a dict by transcript_id for line in gtf_file: line = line.strip() if not line or line.startswith('#'): continue if '#' in line: line = line.split('#')[0].strip() try: chrom, source, feature, left, right, score, \ strand, frame, values = line.split('\t') except ValueError: continue if not chrom in genome_seq: continue # Zero-based offset left, right = int(left) - 1, int(right) - 1 if feature != 'exon' or left >= right: continue values_dict = {} for attr in values.split(';')[:-1]: attr, _, val = attr.strip().partition(' ') values_dict[attr] = val.strip('"') if 'gene_id' not in values_dict or \ 'transcript_id' not in values_dict: continue transcript_id = values_dict['transcript_id'] if transcript_id not in transcripts: transcripts[transcript_id] = [chrom, strand, [[left, right]]] genes[values_dict['gene_id']].append(transcript_id) else: transcripts[transcript_id][2].append([left, right]) # Sort exons and merge where separating introns are <=5 bps for tran, [chr, strand, exons] in transcripts.items(): exons.sort() tmp_exons = [exons[0]] for i in range(1, len(exons)): if exons[i][0] - tmp_exons[-1][1] <= 5: tmp_exons[-1][1] = exons[i][1] else: tmp_exons.append(exons[i]) transcripts[tran] = [chr, strand, tmp_exons] tmp_transcripts = {} for tran, [chr, strand, exons] in transcripts.items(): exon_lens = [e[1] - e[0] + 1 for e in exons] transcript_len = sum(exon_lens) if transcript_len >= frag_len: tmp_transcripts[tran] = [chr, strand, transcript_len, exons] transcripts = tmp_transcripts return genes, transcripts """ """ def read_snp(snp_file): snps = defaultdict(list) for line in snp_file: line = line.strip() if not line or line.startswith('#'): continue try: snpID, type, chr, pos, data = line.split('\t') except ValueError: continue assert type in ["single", "deletion", "insertion"] if type == "deletion": data = int(data) snps[chr].append([snpID, type, int(pos), data]) return snps """ """ def sanity_check_input(genome_seq, genes, transcripts, snps, frag_len): num_canon_ss, num_ss = 0, 0 for transcript, [chr, strand, transcript_len, exons] in transcripts.items(): assert transcript_len >= frag_len if len(exons) <= 1: continue if chr not in genome_seq: continue chr_seq = genome_seq[chr] for i in range(len(exons) - 1): left1, right1 = exons[i] assert left1 < right1 left2, right2 = exons[i+1] assert left2 < right2 assert left1 < left2 and right1 < right2 donor = chr_seq[right1+1:right1+3] acceptor = chr_seq[left2-2:left2] if strand == "-": donor, acceptor = reverse_complement(acceptor), reverse_complement(donor) if donor == "GT" and acceptor == "AG": num_canon_ss += 1 num_ss += 1 if num_ss > 0: print >> sys.stderr, "GT/AG splice sites: {}/{} ({:.2%})".format(num_canon_ss, num_ss, (float(num_canon_ss) / num_ss)) num_alt_single, num_single = 0, 0 for chr, chr_snps in snps.items(): if chr not in genome_seq: continue chr_seq = genome_seq[chr] prev_snp = None for snp in chr_snps: snpID, type, pos, data = snp if prev_snp: assert prev_snp[2] <= pos prev_snp = snp if type != "single": continue assert pos < len(chr_seq) if chr_seq[pos] != data: num_alt_single += 1 num_single += 1 if num_single > 0: print >> sys.stderr, "Alternative bases: {}/{} ({:.2%})".format(num_alt_single, num_single, (float(num_alt_single) / num_single)) """ """ def generate_rna_expr_profile(expr_profile_type, num_transcripts = 10000): # Modelling and simulating generic RNA-Seq experiments with the flux simulator # http://nar.oxfordjournals.org/content/suppl/2012/06/29/gks666.DC1/nar-02667-n-2011-File002.pdf def calc_expr(x, a): x, a, b = float(x), 9500.0, 9500.0 k = -0.6 return (x**k) * math.exp(x/a * (x/b)**2) expr_profile = [0.0] * num_transcripts for i in range(len(expr_profile)): if expr_profile_type == "flux": expr_profile[i] = calc_expr(i + 1, num_transcripts) elif expr_profile_type == "constant": expr_profile[i] = 1.0 else: assert False expr_sum = sum(expr_profile) expr_profile = [expr_profile[i] / expr_sum for i in range(len(expr_profile))] assert abs(sum(expr_profile) - 1.0) < 0.001 return expr_profile """ """ def generate_dna_expr_profile(genome_seq): expr_profile = [] for chr_id, chr_seq in genome_seq.items(): expr_profile.append(len(chr_seq)) expr_sum = float(sum(expr_profile)) expr_profile = [expr_profile[i] / expr_sum for i in range(len(expr_profile))] assert abs(sum(expr_profile) - 1.0) < 0.001 return expr_profile """ """ def getSNPs(chr_snps, left, right): low, high = 0, len(chr_snps) while low < high: mid = (low + high) / 2 snpID, type, pos, data = chr_snps[mid] if pos < left: low = mid + 1 else: high = mid - 1 snps = [] for snp in chr_snps[low:]: snpID, type, pos, data = snp pos2 = pos if type == "deletion": pos2 += data if pos2 >= right: break if pos >= left: if len(snps) > 0: _, prev_type, prev_pos, prev_data = snps[-1] assert prev_pos <= pos prev_pos2 = prev_pos if prev_type == "deletion": prev_pos2 += prev_data if pos <= prev_pos2: continue snps.append(snp) return snps """ """ def getSamAlignment(rna, exons, chr_seq, trans_seq, frag_pos, read_len, chr_snps, err_rand_src, max_mismatch): # Find the genomic position for frag_pos and exon number tmp_frag_pos, tmp_read_len = frag_pos, read_len pos, cigars, cigar_descs = exons[0][0], [], [] e_pos = 0 prev_e = None for e_i in range(len(exons)): e = exons[e_i] if prev_e: i_len = e[0] - prev_e[1] - 1 pos += i_len e_len = e[1] - e[0] + 1 if e_len <= tmp_frag_pos: tmp_frag_pos -= e_len pos += e_len else: pos += tmp_frag_pos e_pos = tmp_frag_pos break prev_e = e # Define Cigar and its descriptions assert e_i < len(exons) e_len = exons[e_i][1] - exons[e_i][0] + 1 assert e_pos < e_len cur_pos = pos match_len = 0 prev_e = None mismatch, remain_trans_len = 0, len(trans_seq) - (frag_pos + read_len) assert remain_trans_len >= 0 for e_i in range(e_i, len(exons)): e = exons[e_i] if prev_e: i_len = e[0] - prev_e[1] - 1 cur_pos += i_len cigars.append(("{}N".format(i_len))) cigar_descs.append([]) tmp_e_left = e_left = e[0] + e_pos e_pos = 0 # Retreive SNPs if rna: snps = getSNPs(chr_snps, e_left, e[1]) else: snps = getSNPs(chr_snps, frag_pos, frag_pos + read_len) # Simulate mismatches due to sequencing errors mms = [] for i in range(e_left, min(e[1], e_left + tmp_read_len - 1)): if err_rand_src.getRand() == 1: assert i < len(chr_seq) err_base = "A" rand = random.randint(0, 2) if chr_seq[i] == "A": err_base = "GCT"[rand] elif chr_seq[i] == "C": err_base = "AGT"[rand] elif chr_seq[i] == "G": err_base = "ACT"[rand] else: err_base = "ACG"[rand] mms.append(["", "single", i, err_base]) tmp_diffs = snps + mms def diff_sort(a , b): return a[2] - b[2] tmp_diffs = sorted(tmp_diffs, cmp=diff_sort) diffs = [] if len(tmp_diffs) > 0: diffs = tmp_diffs[:1] for diff in tmp_diffs[1:]: _, tmp_type, tmp_pos, tmp_data = diff _, prev_type, prev_pos, prev_data = diffs[-1] if prev_type == "deletion": prev_pos += prev_data if tmp_pos <= prev_pos: continue diffs.append(diff) cigar_descs.append([]) prev_diff = None for diff in diffs: diff_id, diff_type, diff_pos,
check_for_just_locations_window_display_data(theKey, value): continue elif lResetRegFilters: if not check_for_just_register_filters_window_display_data(theKey, None): continue elif lResetRegViews: if not check_for_just_initial_view_filters_window_display_data(theKey, None): continue else: myPrint("B", "@@@ ERROR in get_set_config(): unexpected parameter!?") raise(Exception("@@@ ERROR in get_set_config(): unexpected parameter!?")) test = "col_widths." if theKey.startswith(test): if lReset: moneydance.getPreferences().setSetting(theKey, None) else: if theKey[:len(test)] != lastKey: lastKey = theKey[:len(test)] configData.append("COLUMN WIDTHS:") configData.append(pad(theKey+":",30) + moneydance.getPreferences().getSetting(theKey, None).strip()) continue test = "ext_mgmt_win" if theKey.startswith(test): if lReset: moneydance.getPreferences().setSetting(theKey, None) else: if theKey[:len(test)] != lastKey: lastKey = theKey[:len(test)] configData.append("\nEXTENSIONS WINDOW:") configData.append(pad(theKey+":",30) + moneydance.getPreferences().getSetting(theKey, None).strip()) continue test = "moneybot_py_divider" if theKey.startswith(test): if lReset: moneydance.getPreferences().setSetting(theKey, None) else: if theKey[:len(test)] != lastKey: lastKey = theKey[:len(test)] configData.append("\nMONEYBOT:") configData.append(pad(theKey+":",30) + moneydance.getPreferences().getSetting(theKey, None).strip()) continue test = "mbot." if theKey.startswith(test): if lReset: moneydance.getPreferences().setSetting(theKey, None) else: if theKey[:len(test)] != lastKey: lastKey = theKey[:len(test)] configData.append("\nMONEYBOT:") configData.append(pad(theKey+":",30) + moneydance.getPreferences().getSetting(theKey, None).strip()) continue test = "gui." if theKey.startswith(test): if lReset: moneydance.getPreferences().setSetting(theKey, None) else: if theKey[:len(test)] != lastKey: lastKey = theKey[:len(test)] configData.append("\nGUI.:") configData.append(pad(theKey+":",30) + moneydance.getPreferences().getSetting(theKey, None).strip()) continue myPrint("B","@@ RESET WINDOW DATA - ERROR >> What is this key: %s ? @@" %theKey) raise(Exception("ERROR - caught an un-coded key: " + str(theKey))) # END OF config.dict search ######################################################################################################## if lResetAll or lResetRegFilters or lResetRegViews: # Now get the same data for each account accounts = AccountUtil.allMatchesForSearch(moneydance_data, MyAcctFilter(6)) if not lReset: configData.append("\nDATA STORED INTERNALLY BY ACCOUNT (not config.dict):") configData.append("-----------------------------------------------------") dataPrefKey = "col_widths." dataPrefKeys_legacy = [ "gui.col_widths", "rec_reg.credit", "rec_reg.debit" ] keyIterator=[] if lResetRegFilters: keyIterator.append("sel_reg_filter") if lResetRegFilters: keyIterator.append("sel_invreg_filter") if lResetRegViews: keyIterator.append("sel_inv_view") for acct in accounts: last = None if lResetAll: for x in _COLWIDTHS: xx = acct.getPreference(dataPrefKey+x, None) if xx: if lReset: # NOTE: This really sets the preference in LocalStorage() with the acct's UUII+"." prepended as the key!!!! (Sneaky eh!!??) acct.setPreference(dataPrefKey+x, None) # acct.syncItem() # Not entirely sure about this.... If Preference goes to LocalStorage() then Acct shouldn't be affected.. else: if last != acct: last = acct configData.append("\n>>Account: %s" %(acct.getAccountName())) configData.append("Key: %s Value: %s" %(pad(dataPrefKey+x+":",30),str(xx).strip())) if lResetRegFilters or lResetRegViews: for x in keyIterator: xx = acct.getPreference(x, None) if xx: if lReset: # NOTE: This really sets the preference in LocalStorage() with the acct's UUII+"." prepended as the key!!!! (Sneaky eh!!??) acct.setPreference(x, None) # acct.syncItem() # Not entirely sure about this.... If Preference goes to LocalStorage() then Acct shouldn't be affected.. else: if last != acct: last = acct configData.append("\n>>Account: %s" %(acct.getAccountName())) configData.append("Key: %s Value: %s" %(pad(x+":",30),str(xx).strip())) lNeedsSync = False if lResetAll: for theLegacyKey in dataPrefKeys_legacy: # Look for legacy keys actually on the account..! yy = acct.getParameter(theLegacyKey, None) if yy: # Should be a legacy setting if lReset: acct.setParameter(theLegacyKey, None) lNeedsSync = True else: if last != acct: last = acct configData.append("\n>>Account: %s" %(acct.getAccountName())) configData.append("Legacy Key: %s Value: %s" %(pad(theLegacyKey+":",30-7),str(yy).strip())) if lResetRegFilters or lResetRegViews: for theLegacyKey in keyIterator: # Look for legacy keys actually on the account..! yy = acct.getParameter(theLegacyKey, None) if yy: # Should be a legacy setting if lReset: acct.setParameter(theLegacyKey, None) lNeedsSync = True else: if last != acct: last = acct configData.append("\n>>Account: %s" %(acct.getAccountName())) configData.append("Legacy Key: %s Value: %s" %(pad(theLegacyKey+":",30-7),str(yy).strip())) if lReset and lNeedsSync: acct.syncItem() # END OF Accounts search ######################################################################################################## if not lReset: configData.append("\nDATA STORED INTERNALLY WITHIN LOCAL STORAGE (not config.dict):") configData.append("----------------------------------------------------------------") LS = moneydance_ui.getCurrentAccounts().getBook().getLocalStorage() keys=sorted(LS.keys()) if lResetAll: last = None for theKey in keys: value = LS.get(theKey) for theTypeToCheck in dataPrefKeys_legacy: if theKey.endswith("."+theTypeToCheck): if lReset: LS.put(theKey, None) else: splitKey = theKey.split('.') if splitKey[0] != last: last = splitKey[0] lookupAcct = moneydance_data.getAccountByUUID(splitKey[0]) if lookupAcct: configData.append("\n>>Account: %s" %(lookupAcct.getAccountName())) else: configData.append("\n>>Account: <NOT FOUND> ???") configData.append("LS Key: %s Value: %s" %(pad(theKey+":",55),str(value).strip())) # Now look for keys not linked to Accounts... Perhaps deleted ones? for theTypeToCheck in _COLWIDTHS: if theKey.endswith(".col_widths."+theTypeToCheck): splitKey = theKey.split('.') lookupAcct = moneydance_data.getAccountByUUID(splitKey[0]) if lookupAcct: continue # Found one, probably caught above, so skip if lReset: LS.put(theKey, None) else: if splitKey[0] != last: last = splitKey[0] configData.append("\n>>Account: <NOT FOUND> ??? (probably a deleted account)") configData.append("LS Key: %s Value: %s" %(pad(theKey+":",55),str(value).strip())) if lResetRegFilters or lResetRegViews: last = None for theKey in keys: value = LS.get(theKey) if lResetRegFilters: if not check_for_just_register_filters_window_display_data(theKey, None): continue elif lResetRegViews: if not check_for_just_initial_view_filters_window_display_data(theKey, None): continue else: myPrint("B", "@@ ERROR: RESET WINDOW DISPLAY SETTINGS - Unexpected filter!?") raise(Exception("@@ ERROR: RESET WINDOW DISPLAY SETTINGS - Unexpected filter!?")) if lReset: LS.put(theKey, None) else: splitKey = theKey.split('.') if splitKey[0] != last: last = splitKey[0] lookupAcct = moneydance_data.getAccountByUUID(splitKey[0]) if lookupAcct: configData.append("\n>>Account: %s" %(lookupAcct.getAccountName())) else: configData.append("\n>>Account: <NOT FOUND>???") configData.append("LS Key: %s Value: %s" %(pad(theKey+":",55),str(value).strip())) # END OF LocalStorage() search ######################################################################################################## configData.append("\n <END>") for i in range(0, len(configData)): configData[i] = configData[i] + "\n" configData = "".join(configData) if not lReset: jif = QuickJFrame("View the relevant RESET WINDOW DISPLAY SETTINGS that will be reset if you select OK to proceed", configData).show_the_frame() return jif return st,tk = read_preferences_file(lSaveFirst=False) if not st: statusLabel.setText("ERROR: RESET WINDOW DISPLAY SETTINGS >> reading and sorting the data file - no changes made!...".ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(None,"NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE) return myPrint("D", "\nDisplaying the relevant RESET WINDOW DISPLAY SETTINGS (in various places) that I can reset.....:\n") theNewViewFrame = get_set_config(st, tk, False, lAll, lWinLocations, lRegFilters, lRegViews) if not myPopupAskQuestion(theNewViewFrame, "RESET WINDOW DISPLAY SETTINGS", "WARNING: Have you closed all Account Register windows and made sure only the Main Home Screen / Summary page is visible first??", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE): statusLabel.setText("WARNING: Please close all Account Register Windows and make sure only the Main Home Screen Summary/Dashboard is visible before running the Reset Windows Sizes tool..!".ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(theNewViewFrame,"NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE) return if not confirm_backup_confirm_disclaimer(theNewViewFrame, statusLabel, "RESET WINDOW DISPLAY SETTINGS", "%s data?" %(resetWhat)): return if not backup_config_dict(): statusLabel.setText(("RESET WINDOW DISPLAY SETTINGS: ERROR making backup of config.dict - no changes made!").ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(theNewViewFrame,"NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE) return if not backup_local_storage_settings(): statusLabel.setText(("RESET WINDOW DISPLAY SETTINGS: ERROR making backup of LocalStorage() ./safe/settings - no changes made!").ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(theNewViewFrame,"NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE) return # DO THE RESET HERE get_set_config(st, tk, True, lAll, lWinLocations, lRegFilters, lRegViews) moneydance.savePreferences() # save config.dict moneydance_data.getLocalStorage().save() # Flush local storage to safe/settings play_the_money_sound() myPrint("B", "SUCCESS - %s data reset in config.dict config file, internally by Account & Local Storage...."%resetWhat) statusLabel.setText(("OK - %s settings forgotten.... I SUGGEST YOU RESTART MONEYDANCE!" %resetWhat).ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(theNewViewFrame, "SUCCESS - %s - PLEASE RESTART MONEYDANCE"%resetWhat, "RESET WINDOW DISPLAY SETTINGS", JOptionPane.WARNING_MESSAGE) return def hacker_mode_suppress_dropbox_warning(statusLabel): global toolbox_frame_, debug, DARK_GREEN, lCopyAllToClipBoard_TB myPrint("D", "In ", inspect.currentframe().f_code.co_name, "()") ask=MyPopUpDialogBox(toolbox_frame_,theStatus="You can suppress the 'Your file seems to be in a shared folder' Warning..", theMessage="Moneydance support states that you should NEVER store your dataset in Dropbox.\n" "... and that you should store your dataset locally and use Moneydance's built-in syncing instead to share across computers and devices.\n" "THEREFORE YOU PROCEED AT ENTIRELY YOUR OWN RISK AND ACCEPT THAT STORING IN DROPBOX MIGHT DAMAGE YOUR DATA!", theWidth=200, theTitle="SUPPRESS DROPBOX WARNING", lCancelButton=True, OKButtonText="ACCEPT RISK", lAlertLevel=3) if not ask.go(): statusLabel.setText(("'SUPPRESS DROPBOX WARNING' - User chose to exit - no changes made").ljust(800, " ")) statusLabel.setForeground(Color.RED) return if confirm_backup_confirm_disclaimer(toolbox_frame_, statusLabel, "SUPPRESS DROPBOX WARNING", "Suppress 'Your data is stored in a shared folder' (Dropbox) message?"): suppressFile = os.path.join(moneydance_data.getRootFolder().getCanonicalPath(), "suppress_file_in_dropbox_restriction.txt") if not os.path.exists(suppressFile): try: x=open(suppressFile, "w") x.write("DISCLAIMER - YOU SUPPRESS THE 'Your file is stored in a shared folder' (Dropbox) WARNING AT YOUR OWN RISK\n" "STORING YOUR MD DATASET IN DROPBOX CAN DAMAGE YOUR DATASET\n\n" "(Warning courtesy of Toolbox)") x.close() myPrint("B","HACKER MODE: 'SUPPRESS DROPBOX WARNING': User requested to suppress the 'Your file is stored in a shared folder' (dropbox) warning....") myPrint("B", "@@User accepted warnings and disclaimer about dataset damage and instructed Toolbox to create %s - EXECUTED" %(suppressFile)) play_the_money_sound() statusLabel.setText("'SUPPRESS DROPBOX WARNING' - OK, I have suppressed the 'Your file is stored in a shared folder' (dropbox) warning. I suggest a restart of MD".ljust(800, " ")) statusLabel.setForeground(Color.RED) myPopupInformationBox(toolbox_frame_,"OK, I have suppressed the 'Your file is stored in a shared folder' (dropbox) warning. I suggest a restart of MD","'SUPPRESS DROPBOX WARNING'",JOptionPane.ERROR_MESSAGE) return except: myPrint("B","'SUPPRESS DROPBOX WARNING' - Error creating %s" %(suppressFile)) dump_sys_error_to_md_console_and_errorlog() statusLabel.setText("'SUPPRESS DROPBOX WARNING' - ERROR - either the file already exists, or I failed to create the file..(review console log)?".ljust(800, "
= os.path.join(aur_pkg_download_path, i.name + ".tar.gz") # download package sources from AUR urllib.request.urlretrieve("https://aur.archlinux.org" + i.url_path, pkg_tar_file_path) # extract source tarball tar = tarfile.open(pkg_tar_file_path) tar.extractall(path=aur_pkg_download_path) tar.close() os.remove(pkg_tar_file_path) self.path = os.path.join(aur_pkg_download_path, os.listdir(aur_pkg_download_path)[0]) def makepkg(self, uid, gid): """Run makepkg. Args: uid (int): UID of the build user gid (int): GID of the build user Returns: bool. True if build was successfull, False if not """ self._copy_source_to_build_dir() # set uid and gid of the build dir os.chown(self.path, uid, gid) for root, dirs, files in os.walk(self.path): for f in dirs + files: if os.path.isfile(f) or os.path.isdir(f): os.chown(os.path.join(root, f), uid, gid) printInfo("Building package {0} {1}...".format( self.name, self.version)) os.chdir(self.path) rc, out, err = run_command(['makepkg', '--force', '--nodeps', '--noconfirm'], uid) if rc != 0: self.error_info = Exception("Failed to build package '{0}': {1}".format( self.name, '\n'.join(err))) return False # get new version info when build from git if self.build_from_git: git_pkg = PackageSource( self.name, False, self.path) self.version = git_pkg.version for pkg_file in glob.glob(os.path.join(self.path, '*.pkg.tar.xz')): pkg_dest = os.path.join(pacman_cache_dir, os.path.basename(pkg_file)) # move created package to Pacman package cache shutil.move(pkg_file, pkg_dest) # set uid and gid of the build package os.chown(pkg_dest, 0, 0) if self.is_make_dependency: self.install() return True def get_package_file_name(self): """Get the pacman package file name. Returns: str. The name of the package """ return '{0}-{1}-{2}.pkg.tar.xz'.format( self.name, self.version, self.architecture) def get_all_dependencies(self): """Get dependencies and make dependencies together. Returns: list. Names of all dependencies """ return self.dependencies + self.make_dependencies def install(self): """Install the build package.""" if not (self.installation_status == 1 or self.installation_status == 3)\ and (self.build_status == 1 or self.build_status == 2): pkg_names = [self.name] # different names if package is a splitted package if self.split_package_names: pkg_names = self.split_package_names for pkg_name in pkg_names: printInfo("Installing package {0} {1}...".format( pkg_name, self.version)) rc, out, err = run_command( ['pacman', '-U', '--noconfirm', '--force', '--ignore', 'package-query', '--ignore', 'pacman-mirrorlist', '--cachedir', pacman_cache_dir, os.path.join( pacman_cache_dir, '{0}-{1}-{2}.pkg.tar.xz'.format( pkg_name, self.version, self.architecture))]) if rc != 0: self.installation_status = -1 self.error_info = Exception( "Failed to install package '{0}': {1}".format(pkg_name, '\n'.join(err))) return False self.installation_status = 3 def change_user(uid): """Temporarily change the UID and GID for code execution.""" def set_uid_and_guid(): os.setuid(uid) return set_uid_and_guid def run_command(command, uid=None, print_output=True): """Run a command in a subprocess. Args: command (string): Command to run uid (int): UID of the user to run with print_output (bool): True if the output should be printed to stdout and stderr Returns: (int, list, list). Return code of the subprocess, sdtout and stderr """ if uid: process = Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, preexec_fn=change_user(uid)) else: process = Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True) if print_output: err = [] out = [] while True: tmp = process.stdout.readline() if tmp: tmp = tmp.rstrip('\n ') if tmp != '': out.append(tmp) print(tmp) if process.poll() is not None: break time.sleep(.05) for line in process.stdout.readlines(): tmp = line.rstrip('\n ') out.append(tmp) print(tmp) rc = process.poll() if rc != 0: for line in process.stderr.readlines(): tmp = line.rstrip('\n ') printError(tmp) err.append(tmp) return (rc, out, err) else: out, err = process.communicate() rc = process.returncode return (rc, out.splitlines(), err.splitlines()) def get_package_recursive(pkg_name, explicit_build, pkg_dict, locally_available_package_sources, remove_dowloaded_source, is_make_dependency): """Get a package and all their dependencies. Args: pkg_name (str): Name of the package explicit_build (bool): True if package source is given by the user pkg_dict (dict): Store for package information locally_available_package_sources (list): List of all locally available package sources remove_dowloaded_source (bool): If True remove the source downloaded by 'makepkg' before build. If False the sources will be kept, under the condition that the source is of the same version of the package to be build is_make_dependency (bool): True if package shall be installed as a make dependency """ # check if package is already in pkg_dict if pkg_name in pkg_dict: return # check if package is in official repo for pcm_info in packages_in_offical_repositories: if pcm_info['id'] == pkg_name: pcm_pkg = PacmanPackage(pkg_name) pcm_pkg.is_make_dependency = is_make_dependency pkg_dict[pkg_name] = pcm_pkg return # check if package source is locally available if pkg_name in locally_available_package_sources: pkg_path = os.path.join(local_source_dir, pkg_name) lcl_pkg = PackageSource(pkg_name, remove_dowloaded_source, pkg_path) if lcl_pkg.name in pkg_dict: return lcl_pkg.explicit_build = explicit_build lcl_pkg.explicit_build = is_make_dependency pkg_dict[pkg_name] = lcl_pkg # if split package the name can defer pkg_dict[lcl_pkg.name] = lcl_pkg if not lcl_pkg.error_info: for dependency in lcl_pkg.dependencies: get_package_recursive(dependency, False, pkg_dict, locally_available_package_sources, remove_dowloaded_source, True if is_make_dependency else False) for make_dependency in lcl_pkg.make_dependencies: get_package_recursive(make_dependency, False, pkg_dict, locally_available_package_sources, remove_dowloaded_source, True) # check for the package in the AUR else: aur_pkg = PackageSource(pkg_name, remove_dowloaded_source, None) if aur_pkg.name in pkg_dict: return aur_pkg.explicit_build = explicit_build pkg_dict[pkg_name] = aur_pkg # if split package the name can defer pkg_dict[aur_pkg.name] = aur_pkg if not aur_pkg.error_info: for dependency in aur_pkg.dependencies: get_package_recursive(dependency, False, pkg_dict, locally_available_package_sources, remove_dowloaded_source, True if is_make_dependency else False) for make_dependency in aur_pkg.make_dependencies: get_package_recursive(make_dependency, False, pkg_dict, locally_available_package_sources, remove_dowloaded_source, True) def build_package_recursive(pkg_name, pkg_dict, rebuild, install_all_dependencies, uid, gid): """Build a package and all their dependencies. Args: pkg_name (str): Name of the package pkg_dict (dict): Store for package information rebuild (int): Rebuild behaviour: 0: Build only new versions of packages (default) 1: Rebuild all explicit listed packages 2: Rebuild all explicit listed packages and their dependencies uid (int): UID of the build user gid (int): GID of the build user """ pkg = pkg_dict[pkg_name] # break if a error occurred if pkg.error_info: return # break if the package has already been processed if type(pkg) is PackageSource and pkg.build_status != 0: return if type(pkg) is PacmanPackage: # break if the package has already been processed if pkg.installation_status < 0 or pkg.installation_status == 3: return # install pacman package if it is a make dependency if (pkg.is_make_dependency or install_all_dependencies): pkg.install() return dependency_changed = False for dependency in pkg.get_all_dependencies(): pkg_dependency = pkg_dict[dependency] build_package_recursive(dependency, pkg_dict, rebuild, install_all_dependencies, uid, gid) if pkg_dependency.error_info: pkg.build_status = 4 return else: if type(pkg_dependency) is PackageSource and \ pkg_dependency.build_status == 1: dependency_changed = True pkg.get_installation_status() if dependency_changed: if pkg.makepkg(uid, gid): pkg.build_status = 1 else: pkg.build_status = 3 else: # rebuild only if new version is available if rebuild == 0: if pkg.cache_available < 2: if pkg.makepkg(uid, gid): pkg.build_status = 1 else: pkg.build_status = 3 else: pkg.build_status = 2 # rebuild if explicit or a new version is available elif rebuild == 1: if pkg.cache_available < 2 or pkg.explicit_build: if pkg.makepkg(uid, gid): pkg.build_status = 1 else: pkg.build_status = 3 else: pkg.build_status = 2 # rebuild all elif rebuild == 2: if pkg.makepkg(uid, gid): pkg.build_status = 1 else: pkg.build_status = 3 if install_all_dependencies: pkg.install() return def format_log(pkg, msg, prefix=''): """Format a build log for a given packge. Args: pkg (PackageBase): The package msg (str): Message for the package prefix (str): Prefix added for message in multiple lines Returns: str. The formatted build log """ msg_lines = msg.splitlines() if len(msg_lines) > 1: for i in range(1, len(msg_lines)): msg_lines[i] = prefix + ' ' + msg_lines[i] msg = '\n'.join(msg_lines) if pkg.version: return "{0} {1}: {2}".format(pkg.name, pkg.version, msg) return "{0}: {1}".format(pkg.name, msg) def print_build_log_recursive(pkg_names, pkg_dict, prefix='', is_root=False): """Recursivly prints a build log for a given package. Args: pkg_names (PackageBase): The package pkg_dict (dict): Store for package information prefix (str): Prefix for the message is_root (bool): True if first recursion Returns: (bool, list). Tuple consting of the build status and the log messages as a list """ success = True log = [] log_prefix = prefix + '├── ' intermediate_prefix = prefix + '| ' for pos, anchor, pkg_name in enumerate_package_names(pkg_names): pkg = pkg_dict[pkg_name] log_dep = [] if is_root: log_prefix = "" intermediate_prefix = "" elif anchor == 1: log_prefix = prefix + '└── ' intermediate_prefix = prefix + ' ' if type(pkg) == PacmanPackage: if pkg.installation_status < 0: success = False log.append(log_prefix + format_log( pkg, "Failed to install: " + str(pkg.error_info), intermediate_prefix)) elif pkg.installation_status == 0: log.append(log_prefix + format_log(pkg, "Not installed")) elif pkg.installation_status == 1: log.append(log_prefix + format_log(pkg, "Skipped install")) elif pkg.installation_status == 3: log.append(log_prefix + format_log(pkg, "Successfully installed")) else: deps = pkg.get_all_dependencies() if len(deps) > 0: success, log_dep = print_build_log_recursive( deps, pkg_dict, intermediate_prefix) if not success: log.append(log_prefix + format_log( pkg, "Dependency Failed: " + str(pkg.error_info), intermediate_prefix)) elif pkg.error_info: success = False log.append(log_prefix + format_log( pkg, "Failed: " +
is equal to sent packet self.verify_packets_data(ETH_IP_UDP, received) def test_check_increment_dot1q_vlan_single(self, tg): """Check all fields in incremented packet. Dot1Q.vlan increment. """ iface = tg.ports[0] packet_count = 1 stream_id = tg.set_stream(DOT1Q_IP_UDP, count=packet_count, vlan_increment=(2, 5), iface=iface) tg.start_sniff([iface], sniffing_time=2, src_filter=SRC_MAC) tg.send_stream(stream_id) data = tg.stop_sniff([iface]) packets = data.get(iface, []) assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(DOT1Q_IP_UDP, received) def test_check_increment_dot1q_vlan_double(self, tg): """Check all fields in incremented packet. Dot1Q.vlan increment. """ iface = tg.ports[0] packet_count = 1 stream_id = tg.set_stream(QINQ, count=packet_count, vlan_increment=(2, 5), iface=iface) tg.start_sniff([iface], sniffing_time=2, src_filter=SRC_MAC) tg.send_stream(stream_id) data = tg.stop_sniff([iface]) packets = data.get(iface, []) assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(QINQ, received) def test_stop_sniffing(self, tg): """Start continuous stream and stop sniffing. """ iface = tg.ports[0] stream_id_1 = tg.set_stream(PACKET_DEFINITION, continuous=True, iface=iface) tg.start_sniff([iface]) tg.start_streams([stream_id_1]) tg.stop_streams([stream_id_1]) tg.stop_sniff([iface]) start_receive_statistics = tg.get_received_frames_count(iface) end_receive_statistics = tg.get_received_frames_count(iface) assert start_receive_statistics == end_receive_statistics def test_packet_with_ipoption(self, tg): """Test building packet with IPOption. """ iface = tg.ports[0] packet_count = 1 stream_id = tg.set_stream(ETH_IP_IGMP, count=packet_count, iface=iface, adjust_size=False) tg.start_sniff([iface], sniffing_time=2) tg.send_stream(stream_id) data = tg.stop_sniff([iface]) packets = data.get(iface, []) assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(ETH_IP_IGMP, received) def test_dot1q_arp_filter(self, tg): """Check Dot1Q.ARP filter. """ iface = tg.ports[0] packet_count = 1 stream_id_1 = tg.set_stream(DOT1Q_ARP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ARP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="Dot1Q.ARP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.ARP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(DOT1Q_ARP, received) def test_dot1q_arp_custom_filter(self, tg): """Check Dot1Q.ARP filter. """ iface = tg.ports[0] packet_count = 1 filter_dot1q_arp = (12, "81 00 00 00 08 06", "00 00 FF FF 00 00") stream_id_1 = tg.set_stream(DOT1Q_ARP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ARP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=5, filter_layer="Dot1Q.ARP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.ARP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p1 = packets[0] tg.start_sniff([iface], sniffing_time=5, filter_layer=filter_dot1q_arp) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.ARP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p2 = packets[0] assert p1.bin() == p2.bin() def test_not_arp_filter(self, tg): """Check notARP filter. """ iface = tg.ports[0] packet_count = 1 stream_id_1 = tg.set_stream(DOT1Q_IP_ICMP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ARP, count=packet_count, iface=iface) stream_id_3 = tg.set_stream(ETH_IP_UDP, count=packet_count, iface=iface) stream_id_4 = tg.set_stream(DOT1Q_ARP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=4, filter_layer="notARP", src_filter=SRC_MAC) tg.start_streams([stream_id_1, stream_id_2, stream_id_3, stream_id_4]) tg.stop_streams([stream_id_1, stream_id_2, stream_id_3, stream_id_4]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified ARP filter layer are sniffed assert len(packets) == packet_count * 3, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) def test_dot1q_filter(self, tg): """Check Dot1Q filter. """ iface = tg.ports[0] packet_count = 1 stream_id_1 = tg.set_stream(DOT1Q_ARP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ARP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=4, filter_layer="Dot1Q.ARP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) assert tg.get_packet_field(packets[0], "Ethernet", "vlan") def test_dot1q_custom_filter(self, tg): """Check Dot1Q filter. """ iface = tg.ports[0] packet_count = 1 filter_dot1q_arp = (12, "81 00 00 00 08 06", "00 00 FF FF 00 00") stream_id_1 = tg.set_stream(DOT1Q_ARP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ARP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="Dot1Q.ARP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p1 = packets[0] tg.start_sniff([iface], sniffing_time=2, filter_layer=filter_dot1q_arp) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p2 = packets[0] assert p1.bin() == p2.bin() def test_ip_filter(self, tg): """Check IP filter. """ iface = tg.ports[0] packet_count = 1 stream_id_1 = tg.set_stream(DOT1Q_IP_UDP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="IP", dst_filter=DST_MAC) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(ETH_IP_UDP, received) def test_ip_custom_filter(self, tg): """Check IP filter. """ iface = tg.ports[0] packet_count = 1 filter_ip = (12, "08 00", "00 00") stream_id_1 = tg.set_stream(DOT1Q_IP_UDP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="IP", dst_filter=DST_MAC) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p1 = packets[0] tg.start_sniff([iface], sniffing_time=2, filter_layer=filter_ip, dst_filter=DST_MAC) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p2 = packets[0] assert p1.bin() == p2.bin() def test_dot1q_ip_filter(self, tg): """Check Dot1Q.IP filter. """ iface = tg.ports[0] packet_count = 1 stream_id_1 = tg.set_stream(DOT1Q_IP_UDP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="Dot1Q.IP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) received = tg.packet_dictionary(packets[0]) # Verify received packet is equal to sent packet self.verify_packets_data(DOT1Q_IP_UDP, received) def test_dot1q_ip_custom_filter(self, tg): """Check Dot1Q.IP filter. """ iface = tg.ports[0] packet_count = 1 filter_dot1q_ip = (12, "81 00 00 00 08 00", "00 00 FF FF 00 00") stream_id_1 = tg.set_stream(DOT1Q_IP_UDP, count=packet_count, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=packet_count, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="Dot1Q.IP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p1 = packets[0] tg.start_sniff([iface], sniffing_time=2, filter_layer=filter_dot1q_ip) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) packets = data.get(iface, []) # Verify that only packets with specified Dot1Q.IP filter layer are sniffed assert len(packets) == packet_count, \ "Captured packets count {0} does not match expected {1}".format(len(packets), packet_count) p2 = packets[0] assert p1.bin() == p2.bin() @pytest.mark.skip("STP is not integrated yet") def test_stp_filter(self, tg): """Check STP filter. """ iface = tg.ports[0] stream_id_1 = tg.set_stream(STP, count=1, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=1, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="STP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) # Verify that only packets with specified STP layer are sniffed assert len(data[iface]) == 1 assert tg.get_packet_layer(data[iface][0], "STP") is not None @pytest.mark.skip("STP is not integrated yet") def test_stp_custom_filter(self, tg): """Check STP filter. """ iface = tg.ports[0] stream_id_1 = tg.set_stream(STP, count=1, iface=iface) stream_id_2 = tg.set_stream(ETH_IP_UDP, count=1, iface=iface) tg.start_sniff([iface], sniffing_time=2, filter_layer="STP") tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) # Verify that only packets with specified STP layer are sniffed assert len(data[iface]) == 1 p1 = data[iface][0] tg.start_sniff([iface], sniffing_time=2, filter_layer=(14, "42 42 03 00 00", "00 00 00 00 00")) tg.start_streams([stream_id_1, stream_id_2]) tg.stop_streams([stream_id_1, stream_id_2]) data = tg.stop_sniff([iface]) # Verify that only packets with specified STP layer are sniffed assert len(data[iface]) == 1 p2 = data[iface][0] assert p1.bin() == p2.bin() @pytest.mark.skip("STP is
<filename>model-trainer/parser.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from itertools import chain from nltk.parse import DependencyGraph class PartialParse(object): '''A PartialParse is a snapshot of an arc-standard dependency parse It is fully defined by a quadruple (sentence, stack, next, arcs). sentence is a tuple of ordered pairs of (word, tag), where word is a a word string and tag is its part-of-speech tag. Index 0 of sentence refers to the special "root" node (None, self.root_tag). Index 1 of sentence refers to the sentence's first word, index 2 to the second, etc. stack is a list of indices referring to elements of sentence. The 0-th index of stack should be the bottom of the stack, the (-1)-th index is the top of the stack (the side to pop from). next is the next index that can be shifted from the buffer to the stack. When next == len(sentence), the buffer is empty. arcs is a list of triples (idx_head, idx_dep, deprel) signifying the dependency relation `idx_head ->_deprel idx_dep`, where idx_head is the index of the head word, idx_dep is the index of the dependant, and deprel is a string representing the dependency relation label. ''' left_arc_id = 0 '''An identifier signifying a left arc transition''' right_arc_id = 1 '''An identifier signifying a right arc transition''' shift_id = 2 '''An identifier signifying a shift transition''' root_tag = "TOP" '''A POS-tag given exclusively to the root''' def __init__(self, sentence): # the initial PartialParse of the arc-standard parse self.sentence = ((None, self.root_tag),) + tuple(sentence) self.stack = [0] self.next = 1 self.arcs = [] @property def complete(self): '''bool: return true iff the PartialParse is complete Assume that the PartialParse is valid ''' return self.next == len(self.sentence) and len(self.stack) == 1 def parse_step(self, transition_id, deprel=None): '''Update the PartialParse with a transition Args: transition_id : int One of left_arc_id, right_arc_id, or shift_id. You should check against `self.left_arc_id`, `self.right_arc_id`, and `self.shift_id` rather than against the values 0, 1, and 2 directly. deprel : str or None The dependency label to assign to an arc transition (either a left-arc or right-arc). Ignored if transition_id == shift_id Raises: ValueError if transition_id is an invalid id or is illegal given the current state ''' if self.complete: raise ValueError() elif transition_id == self.left_arc_id and deprel and len(self.stack) >= 2: # create and add left arc dependency relation to arcs # then remove dependent from stack self.arcs.append((self.stack[-1], self.stack[-2], deprel)) self.stack.pop(-2) elif transition_id == self.right_arc_id and deprel and len(self.stack) >= 2: # create and add right arc dependency relation to arcs # then remove dependent from stack self.arcs.append((self.stack[-2], self.stack[-1], deprel)) self.stack.pop(-1) elif transition_id == self.shift_id and self.next < len(self.sentence): # shift the next index in buffer to stack and increment next index self.stack.append(self.next) self.next += 1 else: raise ValueError() def get_n_leftmost_deps(self, sentence_idx, n=None): '''Returns a list of n leftmost dependants of word Leftmost means closest to the beginning of the sentence. Note that only the direct dependants of the word on the stack are returned (i.e. no dependants of dependants). Args: sentence_idx : refers to word at self.sentence[sentence_idx] n : the number of dependants to return. "None" refers to all dependants Returns: deps : The n leftmost dependants as sentence indices. If fewer than n, return all dependants. Return in order with the leftmost @ 0, immediately right of leftmost @ 1, etc. ''' deps = [dep[1] for dep in self.arcs if dep[0] == sentence_idx] deps.sort() return deps[:n] def get_n_rightmost_deps(self, sentence_idx, n=None): '''Returns a list of n rightmost dependants of word on the stack @ idx Rightmost means closest to the end of the sentence. Note that only the direct dependants of the word on the stack are returned (i.e. no dependants of dependants). Args: sentence_idx : refers to word at self.sentence[sentence_idx] n : the number of dependants to return. "None" refers to all dependants Returns: deps : The n rightmost dependants as sentence indices. If fewer than n, return all dependants. Return in order with the rightmost @ 0, immediately left of leftmost @ 1, etc. ''' deps = [dep[1] for dep in self.arcs if dep[0] == sentence_idx] deps.sort(reverse=True) return deps[:n] def get_oracle(self, graph): '''Given a projective dependency graph, determine an appropriate trans This method chooses either a left-arc, right-arc, or shift so that, after repeated calls to pp.parse_step(*pp.get_oracle(graph)), the arc-transitions this object models matches the DependencyGraph "graph". For arcs, it also has to pick out the correct dependency relationship. Some relevant details about graph: - graph.nodes[i] corresponds to self.sentence[i] - graph.nodes[i]['head'] is either the i-th word's head word or None if i is the root word (i == 0) - graph.nodes[i]['deps'] returns a dictionary of arcs whose keys are dependency relationships and values are lists of indices of dependents. For example, given the list `dependents = graph.nodes[i]['deps']['det']`, the following arc transitions exist: self.sentences[i] ->_'det' self.sentences[dependents[0]] self.sentences[i] ->_'det' self.sentences[dependents[1]] ... (etc.) - graph is projective. Informally, this means no crossed lines in the dependency graph. More formally, if i -> j and j -> k, then: if i > j (left-ark), i > k if i < j (right-ark), i < k *IMPORTANT* if left-arc and shift operations are both valid and can lead to the same graph, always choose the left-arc operation. *ALSO IMPORTANT* make sure to use the values `self.left_arc_id`, `self.right_arc_id`, `self.shift_id` rather than 0, 1, and 2 directly Hint: take a look at get_left_deps and get_right_deps below Args: graph : nltk.parse.dependencygraph.DependencyGraph A projective dependency graph to head towards Returns: transition_id, deprel : the next transition to take, along with the correct dependency relation label Raises: ValueError if already completed. Otherwise you can always assume that a valid move exists that heads towards the target graph ''' if self.complete: raise ValueError('PartialParse already completed') transition_id, deprel = -1, None # list of all potential left and right dependent relations left_deps, right_deps = [], [] # list of existing arcs arcs = [(arc[0], arc[1]) for arc in self.arcs] # iterate all nodes in graph and find all potential parse base on the # current stack configuration for node_idx in graph.nodes: node = graph.nodes[node_idx] for rel, deps in node['deps'].items(): for dep in deps: # add relation to list if the relation is not already in arcs if (node_idx, dep) not in arcs: if node_idx > dep: left_deps.append((node_idx, dep, rel)) else: right_deps.append((node_idx, dep, rel)) # list of nodes that has right dependent nodes = [pairs[0] for pairs in right_deps] # iterate all possible right dependent relations, perform right arc if # the node and the dependent are in stack, and the dependent is not # that node of another dependent. for node, dep, rel in sorted(right_deps, key=lambda element: (element[0], element[1])): if node in self.stack and dep in self.stack and dep not in nodes: transition_id = self.right_arc_id deprel = rel break # iterate all possible left dependent relations, preform left arc if # the node and the dependent are in stack, the dependent that is # closer to the node has higher priority to ones that aew further away. # left arc has higher priority than right arc, thus even if a right # arc is found, left arc can still replace it for node, dep, rel in sorted(left_deps, key=lambda element: (element[0], -element[1])): if node in self.stack and dep in self.stack : transition_id = self.left_arc_id deprel = rel break # preform shift when no left or right arc if transition_id == -1: transition_id = self.shift_id return transition_id, deprel def parse(self, td_pairs): """Applies the provided transitions/deprels to this PartialParse Simply reapplies parse_step for every element in td_pairs Args: td_pairs: The list of (transition_id, deprel) pairs in the order they should be applied Returns: The list of arcs produced when parsing the sentence. Represented as a list of tuples where each tuple is of the form (head, dependent) """ for
[], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ], normal_columns = [ ('channel_id', 'int'), ('op_id', 'int'), ('peer_id', 'int'), ('tenant_id', 'int'), ('is_local', 'bool'), ('is_data', 'bool'), ('is_transmit', 'bool'), ('alloc_buffer_cnt', 'int'), ('free_buffer_cnt', 'int'), ('send_buffer_cnt', 'int'), ('recv_buffer_cnt', 'int'), ('processed_buffer_cnt', 'int'), ('send_buffer_size', 'int'), ('hash_val', 'int'), ('buffer_pool_id', 'int'), ('pins', 'int'), ('first_in_ts', 'timestamp'), ('first_out_ts', 'timestamp'), ('last_int_ts', 'timestamp'), ('last_out_ts', 'timestamp'), ('status', 'int') ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_dtl_memory', table_id = '12124', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ], normal_columns = [ ('tenant_id', 'int'), ('channel_total_cnt', 'int'), ('channel_block_cnt', 'int'), ('max_parallel_cnt', 'int'), ('max_blocked_buffer_size', 'int'), ('accumulated_blocked_cnt', 'int'), ('current_buffer_used', 'int'), ('seqno', 'int'), ('alloc_cnt', 'int'), ('free_cnt', 'int'), ('free_queue_len', 'int'), ('total_memory_size', 'int'), ('real_alloc_cnt', 'int'), ('real_free_cnt', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_dtl_first_cached_buffer', table_id = '12125', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ], normal_columns = [ ('tenant_id', 'int'), ('channel_id', 'int'), ('calced_val', 'int'), ('buffer_pool_id', 'int'), ('timeout_ts', 'timestamp'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12126', real_tenant_id=False, table_name = '__all_virtual_dblink', keywords = all_def_keywords['__all_dblink'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12127', real_tenant_id=False, table_name = '__all_virtual_dblink_history', keywords = all_def_keywords['__all_dblink_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12128', real_tenant_id=True, table_name = '__all_virtual_tenant_partition_meta_table', keywords = all_def_keywords['__all_tenant_partition_meta_table'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12129', real_tenant_id=False, table_name = '__all_virtual_tenant_role_grantee_map', keywords = all_def_keywords['__all_tenant_role_grantee_map'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12130', real_tenant_id=False, table_name = '__all_virtual_tenant_role_grantee_map_history', keywords = all_def_keywords['__all_tenant_role_grantee_map_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12131', real_tenant_id=False, table_name = '__all_virtual_tenant_keystore', keywords = all_def_keywords['__all_tenant_keystore'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12132', real_tenant_id=False, table_name = '__all_virtual_tenant_keystore_history', keywords = all_def_keywords['__all_tenant_keystore_history'])) def_table_schema( table_name = '__all_virtual_deadlock_stat', table_id = '12141', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('cycle_id', 'uint'), # id of a cycle ('cycle_seq', 'int'), # seq id in a cycle ('session_id', 'int'), ('table_id', 'int'), ('row_key', 'varchar:512'), # ('row_id', 'int'), ('waiter_trans_id', 'varchar:512'), ('holder_trans_id', 'varchar:512'), ('deadlock_rollbacked', 'bool'), # need rollback beacuse of deadlock ('cycle_detect_ts', 'int'), # timestamp when the cycle is first detected ('lock_wait_ts', 'int'), # timestamp when the wait for relationship is started ], partition_columns = ['svr_ip', 'svr_port'], ) # tablespace begin def_table_schema(**gen_iterate_virtual_table_def( table_id = '12142', real_tenant_id=False, table_name = '__all_virtual_tenant_tablespace', keywords = all_def_keywords['__all_tenant_tablespace'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12143', real_tenant_id=False, table_name = '__all_virtual_tenant_tablespace_history', keywords = all_def_keywords['__all_tenant_tablespace_history'])) #tablespace end def_table_schema( table_name = '__ALL_VIRTUAL_INFORMATION_COLUMNS', table_id = '12144', table_type = 'VIRTUAL_TABLE', gm_columns = [], in_tenant_space = True, rowkey_columns = [ ('TABLE_SCHEMA', 'varchar:OB_MAX_DATABASE_NAME_LENGTH'), ('TABLE_NAME', 'varchar:OB_MAX_TABLE_NAME_LENGTH'), ], normal_columns = [ ('TABLE_CATALOG', 'varchar:MAX_TABLE_CATALOG_LENGTH', 'false', ''), ('COLUMN_NAME', 'varchar:OB_MAX_COLUMN_NAME_LENGTH', 'false', ''), ('ORDINAL_POSITION', 'uint', 'false', '0'), ('COLUMN_DEFAULT', 'varchar:OB_MAX_DEFAULT_VALUE_LENGTH', 'true'), ('IS_NULLABLE', 'varchar:COLUMN_NULLABLE_LENGTH', 'false', ''), ('DATA_TYPE', 'varchar:COLUMN_TYPE_LENGTH', 'false', ''), ('CHARACTER_MAXIMUM_LENGTH', 'uint', 'true'), ('CHARACTER_OCTET_LENGTH', 'uint', 'true'), ('NUMERIC_PRECISION', 'uint', 'true'), ('NUMERIC_SCALE','uint', 'true'), ('DATETIME_PRECISION', 'uint', 'true'), ('CHARACTER_SET_NAME', 'varchar:MAX_CHARSET_LENGTH', 'true'), ('COLLATION_NAME', 'varchar:MAX_COLLATION_LENGTH', 'true'), ('COLUMN_TYPE', 'varchar:COLUMN_TYPE_LENGTH'), ('COLUMN_KEY', 'varchar:MAX_COLUMN_KEY_LENGTH', 'false', ''), ('EXTRA', 'varchar:COLUMN_EXTRA_LENGTH', 'false', ''), ('PRIVILEGES', 'varchar:MAX_COLUMN_PRIVILEGE_LENGTH', 'false', ''), ('COLUMN_COMMENT', 'varchar:MAX_COLUMN_COMMENT_LENGTH', 'false', ''), ('GENERATION_EXPRESSION', 'varchar:OB_MAX_DEFAULT_VALUE_LENGTH', 'false', '') ], ) def_table_schema( table_name = '__all_virtual_pg_partition_info', table_id = '12145', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('tenant_id', 'int'), ('table_id', 'int'), ('partition_idx', 'int'), ('tg_id', 'int'), ('pg_idx', 'int'), ('max_decided_trans_version', 'int'), ('max_passed_trans_ts', 'int'), ('freeze_ts', 'int'), ('allow_gc', 'bool'), ('partition_state', 'varchar:TABLE_MAX_VALUE_LENGTH'), ('min_log_service_ts', 'int', 'false', '-1'), ('min_trans_service_ts', 'int', 'false', '-1'), ('min_replay_engine_ts', 'int', 'false', '-1'), ('is_pg', 'bool'), ('weak_read_timestamp', 'int', 'false', '-1'), ('replica_type', 'int', 'false', '0'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12146', real_tenant_id=True, table_name = '__all_virtual_tenant_user_failed_login_stat', keywords = all_def_keywords['__all_tenant_user_failed_login_stat'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12147', real_tenant_id=False, table_name = '__all_virtual_tenant_profile', keywords = all_def_keywords['__all_tenant_profile'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12148', real_tenant_id=False, table_name = '__all_virtual_tenant_profile_history', keywords = all_def_keywords['__all_tenant_profile_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12149', real_tenant_id=False, table_name = '__all_virtual_security_audit', keywords = all_def_keywords['__all_tenant_security_audit'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12150', real_tenant_id=False, table_name = '__all_virtual_security_audit_history', keywords = all_def_keywords['__all_tenant_security_audit_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12151', real_tenant_id=False, table_name = '__all_virtual_trigger', keywords = all_def_keywords['__all_tenant_trigger'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12152', real_tenant_id=False, table_name = '__all_virtual_trigger_history', keywords = all_def_keywords['__all_tenant_trigger_history'])) def_table_schema( table_name = '__all_virtual_cluster_stats', table_id = '12153', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('tenant_id', 'int'), ], only_rs_vtable = True, normal_columns = [ ('refreshed_schema_version', 'int'), ('ddl_lag', 'int'), ('min_sys_table_scn', 'int'), ('min_user_table_scn', 'int'), ], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12154', real_tenant_id=False, table_name = '__all_virtual_sstable_column_checksum', keywords = all_def_keywords['__all_tenant_sstable_column_checksum'])) def_table_schema( table_name = '__all_virtual_ps_stat', table_id = '12155', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], enable_column_def_enum = True, normal_columns = [ ('tenant_id', 'int'), ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('stmt_count', 'int'), ('hit_count', 'int'), ('access_count', 'int'), ('mem_hold', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_ps_item_info', table_id = '12156', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], enable_column_def_enum = True, normal_columns = [ ('tenant_id', 'int'), ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('stmt_id', 'int'), ('db_id', 'int'), ('ps_sql', 'longtext'), ('param_count', 'int'), ('stmt_item_ref_count', 'int'), ('stmt_info_ref_count', 'int'), ('mem_hold', 'int'), ('stmt_type', 'int'), ('checksum', 'int'), ('expired', 'bool') ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_sql_workarea_history_stat', table_id = '12158', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('plan_id', 'int'), ('sql_id', 'varchar:OB_MAX_SQL_ID_LENGTH'), ('operation_type', 'varchar:40'), ('operation_id', 'int'), ('estimated_optimal_size', 'int'), ('estimated_onepass_size', 'int'), ('last_memory_used', 'int'), ('last_execution', 'varchar:10'), ('last_degree', 'int'), ('total_executions', 'int'), ('optimal_executions', 'int'), ('onepass_executions', 'int'), ('multipasses_executions', 'int'), ('active_time', 'int'), ('max_tempseg_size', 'int'), ('last_tempseg_size', 'int'), ('tenant_id', 'int'), ('policy', 'varchar:10'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_sql_workarea_active', table_id = '12159', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('plan_id', 'int'), ('sql_id', 'varchar:OB_MAX_SQL_ID_LENGTH'), ('sql_exec_id', 'int'), ('operation_type', 'varchar:40'), ('operation_id', 'int'), ('sid', 'int'), ('active_time', 'int'), ('work_area_size', 'int'), ('expect_size', 'int'), ('actual_mem_used', 'int'), ('max_mem_used', 'int'), ('number_passes', 'int'), ('tempseg_size', 'int'), ('tenant_id', 'int'), ('policy', 'varchar:6'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_sql_workarea_histogram', table_id = '12160', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('low_optimal_size', 'int'), ('high_optimal_size', 'int'), ('optimal_executions', 'int'), ('onepass_executions', 'int'), ('multipasses_executions', 'int'), ('total_executions', 'int'), ('tenant_id', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_sql_workarea_memory_info', table_id = '12161', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], normal_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('max_workarea_size', 'int'), ('workarea_hold_size', 'int'), ('max_auto_workarea_size', 'int'), ('mem_target', 'int'), ('total_mem_used', 'int'), ('global_mem_bound', 'int'), ('drift_size', 'int'), ('workarea_count', 'int'), ('manual_calc_count', 'int'), ('tenant_id', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12162', real_tenant_id=False, table_name = '__all_virtual_security_audit_record', keywords = all_def_keywords['__all_tenant_security_audit_record'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12163', real_tenant_id=False, table_name = '__all_virtual_sysauth', keywords = all_def_keywords['__all_tenant_sysauth'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12164', real_tenant_id=False, table_name = '__all_virtual_sysauth_history', keywords = all_def_keywords['__all_tenant_sysauth_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12165', real_tenant_id=False, table_name = '__all_virtual_objauth', keywords = all_def_keywords['__all_tenant_objauth'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12166', real_tenant_id=False, table_name = '__all_virtual_objauth_history', keywords = all_def_keywords['__all_tenant_objauth_history'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12167', real_tenant_id=True, table_name = '__all_virtual_backup_info', keywords = all_def_keywords['__all_tenant_backup_info'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12168', real_tenant_id=True, table_name = '__all_virtual_backup_log_archive_status', keywords = all_def_keywords['__all_tenant_backup_log_archive_status'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12170', real_tenant_id=True, table_name = '__all_virtual_backup_task', keywords = all_def_keywords['__all_tenant_backup_task'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12171', real_tenant_id=True, table_name = '__all_virtual_pg_backup_task', keywords = all_def_keywords['__all_tenant_pg_backup_task'])) def_table_schema( table_name = '__all_virtual_pg_backup_log_archive_status', table_id = '12173', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('tenant_id', 'int'), ('table_id', 'int'), ('partition_id', 'int'), ], normal_columns = [ ('incarnation', 'int'), ('log_archive_round', 'int'), ('log_archive_start_ts', 'int'), ('log_archive_status', 'int'), ('log_archive_cur_log_id', 'int'), ('log_archive_cur_ts', 'int'), ('max_log_id', 'int'), ('max_log_ts', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema( table_name = '__all_virtual_server_backup_log_archive_status', table_id = '12174', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('tenant_id', 'int'), ], normal_columns = [ ('incarnation', 'int'), ('log_archive_round', 'int'), ('log_archive_start_ts', 'int'), ('log_archive_cur_ts', 'int'), ('pg_count', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12175', real_tenant_id=False, table_name = '__all_virtual_error', keywords = all_def_keywords['__all_tenant_error'])) def_table_schema( table_name = '__all_virtual_timestamp_service', table_id = '12176', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('tenant_id', 'int'), ], normal_columns = [ ('ts_type', 'int'), ('ts_value', 'int'), ], ) def_table_schema( tablegroup_id = 'OB_INVALID_ID', database_id = 'OB_INFORMATION_SCHEMA_ID', table_name = 'REFERENTIAL_CONSTRAINTS', table_id = '12177', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [], in_tenant_space = True, normal_columns = [ ('CONSTRAINT_CATALOG', 'varchar:MAX_TABLE_CATALOG_LENGTH', 'false', ''), ('CONSTRAINT_SCHEMA', 'varchar:OB_MAX_DATABASE_NAME_LENGTH', 'false', ''), ('CONSTRAINT_NAME', 'varchar:OB_MAX_CONSTRAINT_NAME_LENGTH', 'false', ''), ('UNIQUE_CONSTRAINT_CATALOG', 'varchar:MAX_TABLE_CATALOG_LENGTH', 'false', ''), ('UNIQUE_CONSTRAINT_SCHEMA', 'varchar:OB_MAX_DATABASE_NAME_LENGTH', 'false', ''), ('UNIQUE_CONSTRAINT_NAME', 'varchar:OB_MAX_CONSTRAINT_NAME_LENGTH', 'true', 'NULL'), ('MATCH_OPTION', 'varchar:64', 'false', ''), ('UPDATE_RULE', 'varchar:64', 'false', ''), ('DELETE_RULE', 'varchar:64', 'false', ''), ('TABLE_NAME', 'varchar:OB_MAX_TABLE_NAME_LENGTH', 'false', ''), ('REFERENCED_TABLE_NAME', 'varchar:OB_MAX_TABLE_NAME_LENGTH', 'false', '') ] ) def_table_schema( table_name = '__all_virtual_table_modifications', table_id = '12179', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns = [ ('svr_ip', 'varchar:MAX_IP_ADDR_LENGTH'), ('svr_port', 'int'), ('tenant_id', 'int'), ('table_id', 'int'), ('partition_id', 'int'), ], normal_columns = [ ('insert_row_count', 'int'), ('update_row_count', 'int'), ('delete_row_count', 'int'), ('max_snapshot_version', 'int'), ], partition_columns = ['svr_ip', 'svr_port'], ) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12180', real_tenant_id=True, table_name = '__all_virtual_backup_clean_info', keywords = all_def_keywords['__all_tenant_backup_clean_info'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12181', real_tenant_id=True, table_name = '__all_virtual_restore_pg_info', keywords = all_def_keywords['__all_tenant_restore_pg_info'])) def_table_schema(**gen_iterate_virtual_table_def( table_id = '12182', real_tenant_id=False, table_name = '__all_virtual_object_type', keywords = all_def_keywords['__all_tenant_object_type'])) def_table_schema( table_name = '__all_virtual_trans_table_status', table_id = '12183', table_type = 'VIRTUAL_TABLE', gm_columns = [], rowkey_columns =
# coding: utf-8 """ TextMagic API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class SendMessageInputObject(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 = { 'text': 'str', 'template_id': 'int', 'sending_time': 'int', 'sending_date_time': 'str', 'sending_timezone': 'str', 'contacts': 'str', 'lists': 'str', 'phones': 'str', 'cut_extra': 'bool', 'parts_count': 'int', 'reference_id': 'int', '_from': 'str', 'rrule': 'str', 'create_chat': 'bool', 'tts': 'bool', 'local': 'bool', 'local_country': 'str', 'destination': 'str', 'resources': 'str' } attribute_map = { 'text': 'text', 'template_id': 'templateId', 'sending_time': 'sendingTime', 'sending_date_time': 'sendingDateTime', 'sending_timezone': 'sendingTimezone', 'contacts': 'contacts', 'lists': 'lists', 'phones': 'phones', 'cut_extra': 'cutExtra', 'parts_count': 'partsCount', 'reference_id': 'referenceId', '_from': 'from', 'rrule': 'rrule', 'create_chat': 'createChat', 'tts': 'tts', 'local': 'local', 'local_country': 'localCountry', 'destination': 'destination', 'resources': 'resources' } def __init__(self, text=None, template_id=None, sending_time=None, sending_date_time=None, sending_timezone=None, contacts=None, lists=None, phones=None, cut_extra=False, parts_count=None, reference_id=None, _from=None, rrule=None, create_chat=False, tts=False, local=False, local_country=None, destination=None, resources=None): # noqa: E501 """SendMessageInputObject - a model defined in Swagger""" # noqa: E501 self._text = None self._template_id = None self._sending_time = None self._sending_date_time = None self._sending_timezone = None self._contacts = None self._lists = None self._phones = None self._cut_extra = None self._parts_count = None self._reference_id = None self.__from = None self._rrule = None self._create_chat = None self._tts = None self._local = None self._local_country = None self._destination = None self._resources = None self.discriminator = None if text is not None: self.text = text if template_id is not None: self.template_id = template_id if sending_time is not None: self.sending_time = sending_time if sending_date_time is not None: self.sending_date_time = sending_date_time if sending_timezone is not None: self.sending_timezone = sending_timezone if contacts is not None: self.contacts = contacts if lists is not None: self.lists = lists if phones is not None: self.phones = phones if cut_extra is not None: self.cut_extra = cut_extra if parts_count is not None: self.parts_count = parts_count if reference_id is not None: self.reference_id = reference_id if _from is not None: self._from = _from if rrule is not None: self.rrule = rrule if create_chat is not None: self.create_chat = create_chat if tts is not None: self.tts = tts if local is not None: self.local = local if local_country is not None: self.local_country = local_country if destination is not None: self.destination = destination if resources is not None: self.resources = resources @property def text(self): """Gets the text of this SendMessageInputObject. # noqa: E501 Message text. Required if the **template_id** is not set. # noqa: E501 :return: The text of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._text @text.setter def text(self, text): """Sets the text of this SendMessageInputObject. Message text. Required if the **template_id** is not set. # noqa: E501 :param text: The text of this SendMessageInputObject. # noqa: E501 :type: str """ self._text = text @property def template_id(self): """Gets the template_id of this SendMessageInputObject. # noqa: E501 Template used instead of message text. Required if the **text** is not set. # noqa: E501 :return: The template_id of this SendMessageInputObject. # noqa: E501 :rtype: int """ return self._template_id @template_id.setter def template_id(self, template_id): """Sets the template_id of this SendMessageInputObject. Template used instead of message text. Required if the **text** is not set. # noqa: E501 :param template_id: The template_id of this SendMessageInputObject. # noqa: E501 :type: int """ self._template_id = template_id @property def sending_time(self): """Gets the sending_time of this SendMessageInputObject. # noqa: E501 DEPRECATED, consider using sendingDateTime and sendingTimezone parameters instead: Optional (required with rrule set). Message sending time in unix timestamp format. Default is now. # noqa: E501 :return: The sending_time of this SendMessageInputObject. # noqa: E501 :rtype: int """ return self._sending_time @sending_time.setter def sending_time(self, sending_time): """Sets the sending_time of this SendMessageInputObject. DEPRECATED, consider using sendingDateTime and sendingTimezone parameters instead: Optional (required with rrule set). Message sending time in unix timestamp format. Default is now. # noqa: E501 :param sending_time: The sending_time of this SendMessageInputObject. # noqa: E501 :type: int """ self._sending_time = sending_time @property def sending_date_time(self): """Gets the sending_date_time of this SendMessageInputObject. # noqa: E501 Sending time in Y-m-d H:i:s format (e.g. 2016-05-27 13:02:33). This time is relative to **sendingTimezone**. # noqa: E501 :return: The sending_date_time of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._sending_date_time @sending_date_time.setter def sending_date_time(self, sending_date_time): """Sets the sending_date_time of this SendMessageInputObject. Sending time in Y-m-d H:i:s format (e.g. 2016-05-27 13:02:33). This time is relative to **sendingTimezone**. # noqa: E501 :param sending_date_time: The sending_date_time of this SendMessageInputObject. # noqa: E501 :type: str """ self._sending_date_time = sending_date_time @property def sending_timezone(self): """Gets the sending_timezone of this SendMessageInputObject. # noqa: E501 ID or ISO-name of timezone used for sending when sendingDateTime parameter is set. E.g. if you specify sendingDateTime = \\\"2016-05-27 13:02:33\\\" and sendingTimezone = \\\"America/Buenos_Aires\\\", your message will be sent at May 27, 2016 13:02:33 Buenos Aires time, or 16:02:33 UTC. Default is account timezone. # noqa: E501 :return: The sending_timezone of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._sending_timezone @sending_timezone.setter def sending_timezone(self, sending_timezone): """Sets the sending_timezone of this SendMessageInputObject. ID or ISO-name of timezone used for sending when sendingDateTime parameter is set. E.g. if you specify sendingDateTime = \\\"2016-05-27 13:02:33\\\" and sendingTimezone = \\\"America/Buenos_Aires\\\", your message will be sent at May 27, 2016 13:02:33 Buenos Aires time, or 16:02:33 UTC. Default is account timezone. # noqa: E501 :param sending_timezone: The sending_timezone of this SendMessageInputObject. # noqa: E501 :type: str """ self._sending_timezone = sending_timezone @property def contacts(self): """Gets the contacts of this SendMessageInputObject. # noqa: E501 Comma separated array of contact resources id message will be sent to. # noqa: E501 :return: The contacts of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._contacts @contacts.setter def contacts(self, contacts): """Sets the contacts of this SendMessageInputObject. Comma separated array of contact resources id message will be sent to. # noqa: E501 :param contacts: The contacts of this SendMessageInputObject. # noqa: E501 :type: str """ self._contacts = contacts @property def lists(self): """Gets the lists of this SendMessageInputObject. # noqa: E501 Comma separated array of list resources id message will be sent to. # noqa: E501 :return: The lists of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._lists @lists.setter def lists(self, lists): """Sets the lists of this SendMessageInputObject. Comma separated array of list resources id message will be sent to. # noqa: E501 :param lists: The lists of this SendMessageInputObject. # noqa: E501 :type: str """ self._lists = lists @property def phones(self): """Gets the phones of this SendMessageInputObject. # noqa: E501 Comma separated array of E.164 phone numbers message will be sent to. # noqa: E501 :return: The phones of this SendMessageInputObject. # noqa: E501 :rtype: str """ return self._phones @phones.setter def phones(self, phones): """Sets the phones of this SendMessageInputObject. Comma separated array of E.164 phone numbers message will be sent to. # noqa: E501 :param phones: The phones of this SendMessageInputObject. # noqa: E501 :type: str """ self._phones = phones @property def cut_extra(self): """Gets the cut_extra of this SendMessageInputObject. # noqa: E501 Should sending method cut extra characters which not fit supplied partsCount or return 400 Bad request response instead. # noqa: E501 :return: The cut_extra of this SendMessageInputObject. # noqa: E501 :rtype: bool """ return self._cut_extra @cut_extra.setter def cut_extra(self, cut_extra): """Sets the cut_extra of this SendMessageInputObject. Should sending method cut extra characters which not fit supplied partsCount or return 400 Bad request response instead. # noqa: E501 :param cut_extra: The cut_extra of this SendMessageInputObject. # noqa: E501 :type: bool """ self._cut_extra = cut_extra @property def parts_count(self): """Gets the parts_count of this SendMessageInputObject. # noqa: E501 Maximum message parts count (TextMagic allows sending 1 to 6 message parts). # noqa: E501 :return: The
<reponame>ONSdigital/response-operations-ui import json import logging from datetime import datetime import iso8601 from dateutil import tz from dateutil.parser import parse from flask import Blueprint, abort from flask import current_app as app from flask import ( flash, jsonify, make_response, redirect, render_template, request, session, url_for, ) from flask_login import login_required from structlog import wrap_logger from wtforms import ValidationError from response_operations_ui.common.date_restriction_generator import ( get_date_restriction_text, ) from response_operations_ui.common.dates import localise_datetime from response_operations_ui.common.filters import get_collection_exercise_by_period from response_operations_ui.common.mappers import ( convert_events_to_new_format, format_short_name, map_collection_exercise_state, ) from response_operations_ui.common.validators import valid_date_for_event from response_operations_ui.controllers import ( collection_exercise_controllers, collection_instrument_controllers, sample_controllers, survey_controllers, ) from response_operations_ui.controllers.collection_exercise_controllers import ( update_collection_exercise_eq_version, ) from response_operations_ui.exceptions.exceptions import ApiError from response_operations_ui.forms import ( CreateCollectionExerciseDetailsForm, EditCollectionExerciseDetailsForm, EventDateForm, RemoveLoadedSample, ) logger = wrap_logger(logging.getLogger(__name__)) collection_exercise_bp = Blueprint( "collection_exercise_bp", __name__, static_folder="static", template_folder="templates" ) def build_collection_exercise_details(short_name, period): survey = survey_controllers.get_survey_by_shortname(short_name) survey_id = survey["id"] exercises = collection_exercise_controllers.get_collection_exercises_by_survey(survey_id) exercise = get_collection_exercise_by_period(exercises, period) if not exercise: logger.error("Failed to find collection exercise by period", short_name=short_name, period=period) abort(404) collection_exercise_id = exercise["id"] survey["shortName"] = format_short_name(survey["shortName"]) full_exercise = collection_exercise_controllers.get_collection_exercise_by_id(collection_exercise_id) exercise_events = collection_exercise_controllers.get_collection_exercise_events_by_id(collection_exercise_id) collection_instruments = collection_instrument_controllers.get_collection_instruments_by_classifier( collection_exercise_id=collection_exercise_id, survey_id=survey_id ) eq_ci_selectors = collection_instrument_controllers.get_collection_instruments_by_classifier( ci_type="EQ", survey_id=survey_id ) summary_id = collection_exercise_controllers.get_linked_sample_summary_id(collection_exercise_id) sample_summary = sample_controllers.get_sample_summary(summary_id) if summary_id else None ci_classifiers = survey_controllers.get_survey_ci_classifier(survey_id) return { "survey": survey, "collection_exercise": full_exercise, "events": convert_events_to_new_format(exercise_events), "collection_instruments": collection_instruments, "eq_ci_selectors": eq_ci_selectors, "sample_summary": _format_sample_summary(sample_summary), "ci_classifiers": ci_classifiers, } @collection_exercise_bp.route("/<short_name>/<period>", methods=["GET"]) @login_required def view_collection_exercise(short_name, period): ce_details = build_collection_exercise_details(short_name, period) breadcrumbs = [ {"text": "Surveys", "url": "/surveys"}, { "text": f"{ce_details['survey']['surveyRef']} {ce_details['survey']['shortName']}", "url": f"/surveys/{ce_details['survey']['shortName'].replace(' ', '')}", }, {"text": f"{ce_details['collection_exercise']['exerciseRef']}"}, ] ce_state = ce_details["collection_exercise"]["state"] show_set_live_button = ce_state in ("READY_FOR_REVIEW", "FAILEDVALIDATION") locked = ce_state in ("LIVE", "READY_FOR_LIVE", "EXECUTION_STARTED", "VALIDATED", "EXECUTED", "ENDED") processing = ce_state in ("EXECUTION_STARTED", "EXECUTED", "VALIDATED") validation_failed = ce_state == "FAILEDVALIDATION" validation_errors = ce_details["collection_exercise"]["validationErrors"] missing_ci = validation_errors and any( "MISSING_COLLECTION_INSTRUMENT" in unit["errors"] for unit in validation_errors ) ce_details["collection_exercise"]["state"] = map_collection_exercise_state(ce_state) # NOQA _format_ci_file_name(ce_details["collection_instruments"], ce_details["survey"]) show_msg = request.args.get("show_msg") success_panel = request.args.get("success_panel") info_panel = request.args.get("info_panel") sorted_nudge_list = get_existing_sorted_nudge_events(ce_details["events"]) error_json = _get_error_from_session() return render_template( "collection_exercise/collection-exercise.html", breadcrumbs=breadcrumbs, ce=ce_details["collection_exercise"], collection_instruments=ce_details["collection_instruments"], eq_ci_selectors=ce_details["eq_ci_selectors"], error=error_json, events=ce_details["events"], locked=locked, missing_ci=missing_ci, processing=processing, sample=ce_details["sample_summary"], show_set_live_button=show_set_live_button, survey=ce_details["survey"], success_panel=success_panel, validation_failed=validation_failed, show_msg=show_msg, ci_classifiers=ce_details["ci_classifiers"]["classifierTypes"], info_panel=info_panel, existing_nudge=sorted_nudge_list if len(sorted_nudge_list) > 0 else [], is_eq_v3_enabled=app.config["EQ_VERSION_ENABLED"], ) def _get_error_from_session(): """ This is an ugly fix for errors being written to the permanently to the session. This guarantees that an error will be displayed once and then removed. If errors are ever tidied up (using flash for instance) then this code can go. """ if session.get("error"): error_json = json.loads(session.get("error")) session.pop("error") return error_json return None def get_existing_sorted_nudge_events(events): sorted_nudge_list = [] nudge_tags = ["nudge_email_0", "nudge_email_1", "nudge_email_2", "nudge_email_3", "nudge_email_4"] nudge_events = {} for nudge in nudge_tags: if nudge in events: nudge_events[nudge] = events[nudge].copy() for key, val in nudge_events.items(): for k, v in val.items(): if k == "date": nudge_events[key][k] = str(parse(v, fuzzy=True).date()) nudge_events = sorted( nudge_events.items(), key=lambda x: ( x[1]["date"], x[1]["time"], ), ) for k, v in nudge_events: sorted_nudge_list.append(k) return sorted_nudge_list @collection_exercise_bp.route("/<short_name>/<period>", methods=["POST"]) @login_required def post_collection_exercise(short_name, period): if "load-sample" in request.form: return _upload_sample(short_name, period) elif "load-ci" in request.form: return _upload_collection_instrument(short_name, period) elif "ready-for-live" in request.form: return _set_ready_for_live(short_name, period) elif "select-ci" in request.form: return _select_collection_instrument(short_name, period) elif "unselect-ci" in request.form: return _unselect_collection_instrument(short_name, period) if "eq-version" in request.form: return _update_eq_version(short_name, period) return view_collection_exercise(short_name, period) @collection_exercise_bp.route("response_chasing/<ce_id>/<survey_id>", methods=["GET"]) @login_required def response_chasing(ce_id, survey_id): logger.info("Response chasing", ce_id=ce_id, survey_id=survey_id) response = collection_exercise_controllers.download_report(ce_id, survey_id) return response.content, response.status_code, response.headers.items() def _set_ready_for_live(short_name, period): survey_id = survey_controllers.get_survey_id_by_short_name(short_name) exercises = collection_exercise_controllers.get_collection_exercises_by_survey(survey_id) exercise = get_collection_exercise_by_period(exercises, period) if not exercise: abort(404) try: collection_exercise_controllers.execute_collection_exercise(exercise["id"]) success_panel = "Collection exercise executed" except ApiError: session["error"] = json.dumps( { "section": "head", "header": "Error: Failed to execute Collection Exercise", "message": "Error processing collection exercise", } ) success_panel = None return redirect( url_for( "collection_exercise_bp.view_collection_exercise", short_name=short_name, period=period, success_panel=success_panel, ) ) def _upload_sample(short_name, period): error = _validate_sample() if not error: survey_id = survey_controllers.get_survey_id_by_short_name(short_name) exercises = collection_exercise_controllers.get_collection_exercises_by_survey(survey_id) # Find the collection exercise for the given period exercise = get_collection_exercise_by_period(exercises, period) if not exercise: return make_response(jsonify({"message": "Collection exercise not found"}), 404) sample_summary = sample_controllers.upload_sample(short_name, period, request.files["sampleFile"]) logger.info( "Linking sample summary with collection exercise", collection_exercise_id=exercise["id"], sample_id=sample_summary["id"], ) collection_exercise_controllers.link_sample_summary_to_collection_exercise( collection_exercise_id=exercise["id"], sample_summary_id=sample_summary["id"] ) return redirect( url_for( "collection_exercise_bp.view_collection_exercise", short_name=short_name, period=period, error=error, show_msg="true", ) ) def _select_collection_instrument(short_name, period): success_panel = None cis_selected = request.form.getlist("checkbox-answer") cis_added = [] if cis_selected: for ci in cis_selected: ci_added = collection_instrument_controllers.link_collection_instrument(request.form["ce_id"], ci) cis_added.append(ci_added) if all(added for added in cis_added): success_panel = "Collection instruments added" else: session["error"] = json.dumps( { "section": "ciSelect", "header": "Error: Failed to add collection instrument(s)", "message": "Please try again", } ) else: session["error"] = json.dumps( { "section": "ciSelect", "header": "Error: No collection instruments selected", "message": "Please select a collection instrument", } ) return redirect( url_for( "collection_exercise_bp.view_collection_exercise", short_name=short_name, period=period, success_panel=success_panel, ) ) def _update_eq_version(short_name, period): eq_version = request.form.get("eq-version") ce_details = build_collection_exercise_details(short_name, period) ce = ce_details["collection_exercise"] if ce["eqVersion"] != eq_version: update_collection_exercise_eq_version(ce["id"], eq_version) flash("eQ version updated successfully.") return redirect( url_for( "collection_exercise_bp.view_collection_exercise", period=period, short_name=short_name, success_panel=f"eQ version updated to {eq_version}.", ) ) return redirect( url_for( "collection_exercise_bp.view_collection_exercise", period=period, short_name=short_name, info_panel="eQ version is not updated as the selected version and existing version are same.", ) ) def _upload_collection_instrument(short_name, period): success_panel = None error = _validate_collection_instrument() if not error: file = request.files["ciFile"] is_ru_specific_instrument = False if file.filename.split(".")[0].isdigit(): is_ru_specific_instrument = True logger.info("Collection instrument about to be uploaded", filename=file.filename) survey_id = survey_controllers.get_survey_id_by_short_name(short_name) exercises = collection_exercise_controllers.get_collection_exercises_by_survey(survey_id) # Find the collection exercise for the given period exercise = get_collection_exercise_by_period(exercises, period) if not exercise: return make_response(jsonify({"message": "Collection exercise not found"}), 404) error_text = None if is_ru_specific_instrument: ru_ref = file.filename.split(".")[0] upload_success, error_text = collection_instrument_controllers.upload_ru_specific_collection_instrument( exercise["id"], file, ru_ref ) else: form_type = _get_form_type(file.filename) upload_success = collection_instrument_controllers.upload_collection_instrument( exercise["id"], file, form_type ) if upload_success: success_panel = "Collection instrument loaded" else: message = error_text if error_text else "Please try again" session["error"] = json.dumps( {"section": "ciFile", "header": "Error: Failed to upload collection instrument", "message": message} ) else: session["error"] = json.dumps(error) return redirect( url_for( "collection_exercise_bp.view_collection_exercise", short_name=short_name, period=period, success_panel=success_panel, ) ) def _unselect_collection_instrument(short_name, period): success_panel = _unlink_collection_instrument() return redirect( url_for( "collection_exercise_bp.view_collection_exercise", short_name=short_name, period=period, success_panel=success_panel, ) ) def _validate_collection_instrument(): error = None if "ciFile" in request.files: file = request.files["ciFile"] error = validate_file_extension_is_correct(file) if error is None: ci_name = file.filename.split(".")[0] if ci_name.isdigit(): error = validate_ru_specific_collection_instrument(file, ci_name) else: # file name format is surveyId_period_formType form_type = _get_form_type(file.filename) if file.filename.count("_") == 2 else "" if not form_type.isdigit() or len(form_type) != 4: logger.info("Invalid file format uploaded", filename=file.filename) error = { "section": "ciFile", "header": "Error: Invalid file name format for collection instrument", "message": "Please provide file with correct form type in file name", } else: logger.info("No file uploaded") error = { "section": "ciFile", "header": "Error: No collection instrument supplied", "message": "Please provide a collection instrument", } return error def validate_ru_specific_collection_instrument(file, ci_name): logger.info("Ru specific collection instrument detected", filename=file.filename) if len(ci_name) == 11: return None logger.info("Invalid ru specific file format uploaded", filename=file.filename) error = { "section": "ciFile", "header": "Error: Invalid file name format for ru specific collection instrument", "message": "Please provide a file with a valid 11 digit ru ref in the file name", } return error def validate_file_extension_is_correct(file): if str.endswith(file.filename, ".xlsx"): return None if str.endswith(file.filename, ".xls"): return None logger.info("Invalid file format uploaded", filename=file.filename) error = { "section": "ciFile", "header": "Error: Wrong file type for collection instrument", "message": "Please use XLSX file only", } return error def _validate_sample(): error = None if "sampleFile" in request.files: file = request.files["sampleFile"] if not str.endswith(file.filename, ".csv"): logger.info("Invalid file format uploaded", filename=file.filename) error = "Invalid file format" else: logger.info("No file uploaded") error = "File not uploaded" return error def _format_sample_summary(sample): if sample and sample.get("ingestDateTime"): submission_datetime = localise_datetime(iso8601.parse_date(sample["ingestDateTime"])) submission_time = submission_datetime.strftime("%I:%M%p on %B %d, %Y") sample["ingestDateTime"] = submission_time return sample def _format_ci_file_name(collection_instruments, survey_details): for ci in collection_instruments: if "xlsx" not in str(ci.get("file_name", "")): ci["file_name"] = f"{survey_details['surveyRef']} {ci['file_name']} eQ" def _get_form_type(file_name): file_name = file_name.split(".")[0] return file_name.split("_")[2] # file name format is surveyId_period_formType @collection_exercise_bp.route("/<short_name>/<period>/edit-collection-exercise-details", methods=["GET"]) @login_required def view_collection_exercise_details(short_name, period): logger.info("Retrieving collection exercise data for form", short_name=short_name, period=period) ce_details = build_collection_exercise_details(short_name, period) form = EditCollectionExerciseDetailsForm(form=request.form) survey_details = survey_controllers.get_survey(short_name) ce_state = ce_details["collection_exercise"]["state"] locked = ce_state in ("LIVE", "READY_FOR_LIVE", "EXECUTION_STARTED", "VALIDATED", "EXECUTED", "ENDED") return render_template( "edit-collection-exercise-details.html", survey_ref=ce_details["survey"]["surveyRef"], form=form, short_name=short_name, period=period, locked=locked, ce_state=ce_details["collection_exercise"]["state"], user_description=ce_details["collection_exercise"]["userDescription"], collection_exercise_id=ce_details["collection_exercise"]["id"], survey_id=survey_details["id"], ) @collection_exercise_bp.route("/<short_name>/<period>/edit-collection-exercise-details", methods=["POST"]) @login_required def edit_collection_exercise_details(short_name, period): form = EditCollectionExerciseDetailsForm(form=request.form) if not form.validate(): logger.info( "Failed validation, retrieving collection exercise data for form", short_name=short_name, period=period ) ce_details = build_collection_exercise_details(short_name, period) ce_state = ce_details["collection_exercise"]["state"] survey_id = survey_controllers.get_survey_id_by_short_name(short_name) locked = ce_state in ("LIVE", "READY_FOR_LIVE", "EXECUTION_STARTED", "VALIDATED", "EXECUTED", "ENDED") return render_template( "edit-collection-exercise-details.html", survey_ref=ce_details["survey"]["surveyRef"], form=form, short_name=short_name, period=period, locked=locked, ce_state=ce_details["collection_exercise"]["state"], errors=form.errors, user_description=ce_details["collection_exercise"]["userDescription"], collection_exercise_id=ce_details["collection_exercise"]["id"], survey_id=survey_id, ) else: logger.info("Updating collection exercise details", short_name=short_name, period=period) form = request.form collection_exercise_controllers.update_collection_exercise_user_description(
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pathlib import proto import re import shutil import tempfile from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple, Union from google.api_core import operation from google.api_core import exceptions as api_exceptions from google.auth import credentials as auth_credentials from google.cloud import aiplatform from google.cloud.aiplatform import base from google.cloud.aiplatform import explain from google.cloud.aiplatform import initializer from google.cloud.aiplatform import jobs from google.cloud.aiplatform import models from google.cloud.aiplatform import utils from google.cloud.aiplatform.utils import gcs_utils from google.cloud.aiplatform.compat.services import endpoint_service_client from google.cloud.aiplatform.compat.types import ( encryption_spec as gca_encryption_spec, endpoint as gca_endpoint_compat, endpoint_v1 as gca_endpoint_v1, explanation as gca_explanation_compat, io as gca_io_compat, machine_resources as gca_machine_resources_compat, model as gca_model_compat, model_service as gca_model_service_compat, env_var as gca_env_var_compat, ) from google.protobuf import json_format _LOGGER = base.Logger(__name__) _SUPPORTED_MODEL_FILE_NAMES = [ "model.pkl", "model.joblib", "model.bst", "saved_model.pb", "saved_model.pbtxt", ] class Prediction(NamedTuple): """Prediction class envelopes returned Model predictions and the Model id. Attributes: predictions: The predictions that are the output of the predictions call. The schema of any single prediction may be specified via Endpoint's DeployedModels' [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model] [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata] deployed_model_id: ID of the Endpoint's DeployedModel that served this prediction. explanations: The explanations of the Model's predictions. It has the same number of elements as instances to be explained. Default is None. """ predictions: Dict[str, List] deployed_model_id: str explanations: Optional[Sequence[gca_explanation_compat.Explanation]] = None class Endpoint(base.VertexAiResourceNounWithFutureManager): client_class = utils.EndpointClientWithOverride _is_client_prediction_client = False _resource_noun = "endpoints" _getter_method = "get_endpoint" _list_method = "list_endpoints" _delete_method = "delete_endpoint" def __init__( self, endpoint_name: str, project: Optional[str] = None, location: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, ): """Retrieves an endpoint resource. Args: endpoint_name (str): Required. A fully-qualified endpoint resource name or endpoint ID. Example: "projects/123/locations/us-central1/endpoints/456" or "456" when project and location are initialized or passed. project (str): Optional. Project to retrieve endpoint from. If not set, project set in aiplatform.init will be used. location (str): Optional. Location to retrieve endpoint from. If not set, location set in aiplatform.init will be used. credentials (auth_credentials.Credentials): Optional. Custom credentials to use to upload this model. Overrides credentials set in aiplatform.init. """ super().__init__( project=project, location=location, credentials=credentials, resource_name=endpoint_name, ) endpoint_name = utils.full_resource_name( resource_name=endpoint_name, resource_noun="endpoints", project=project, location=location, ) # Lazy load the Endpoint gca_resource until needed self._gca_resource = gca_endpoint_compat.Endpoint(name=endpoint_name) self._prediction_client = self._instantiate_prediction_client( location=self.location, credentials=credentials, ) def _skipped_getter_call(self) -> bool: """Check if GAPIC resource was populated by call to get/list API methods Returns False if `_gca_resource` is None or fully populated. Returns True if `_gca_resource` is partially populated """ return self._gca_resource and not self._gca_resource.create_time def _sync_gca_resource_if_skipped(self) -> None: """Sync GAPIC service representation of Endpoint class resource only if get_endpoint() was never called.""" if self._skipped_getter_call(): self._gca_resource = self._get_gca_resource( resource_name=self._gca_resource.name ) def _assert_gca_resource_is_available(self) -> None: """Ensures Endpoint getter was called at least once before asserting on gca_resource's availability.""" super()._assert_gca_resource_is_available() self._sync_gca_resource_if_skipped() @property def traffic_split(self) -> Dict[str, int]: """A map from a DeployedModel's ID to the percentage of this Endpoint's traffic that should be forwarded to that DeployedModel. If a DeployedModel's ID is not listed in this map, then it receives no traffic. The traffic percentage values must add up to 100, or map must be empty if the Endpoint is to not accept any traffic at a moment. """ self._sync_gca_resource() return dict(self._gca_resource.traffic_split) @property def network(self) -> Optional[str]: """The full name of the Google Compute Engine [network](https://cloud.google.com/vpc/docs/vpc#networks) to which this Endpoint should be peered. Takes the format `projects/{project}/global/networks/{network}`. Where {project} is a project number, as in `12345`, and {network} is a network name. Private services access must already be configured for the network. If left unspecified, the Endpoint is not peered with any network. """ self._assert_gca_resource_is_available() return getattr(self._gca_resource, "network", None) @classmethod def create( cls, display_name: str, description: Optional[str] = None, labels: Optional[Dict[str, str]] = None, metadata: Optional[Sequence[Tuple[str, str]]] = (), project: Optional[str] = None, location: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, sync=True, ) -> "Endpoint": """Creates a new endpoint. Args: display_name (str): Required. The user-defined name of the Endpoint. The name can be up to 128 characters long and can be consist of any UTF-8 characters. project (str): Required. Project to retrieve endpoint from. If not set, project set in aiplatform.init will be used. location (str): Required. Location to retrieve endpoint from. If not set, location set in aiplatform.init will be used. description (str): Optional. The description of the Endpoint. labels (Dict[str, str]): Optional. The labels with user-defined metadata to organize your Endpoints. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. metadata (Sequence[Tuple[str, str]]): Optional. Strings which should be sent along with the request as metadata. credentials (auth_credentials.Credentials): Optional. Custom credentials to use to upload this model. Overrides credentials set in aiplatform.init. encryption_spec_key_name (Optional[str]): Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this Endpoint and all sub-resources of this Endpoint will be secured by this key. Overrides encryption_spec_key_name set in aiplatform.init. sync (bool): Whether to execute this method synchronously. If False, this method will be executed in concurrent Future and any downstream object will be immediately returned and synced when the Future has completed. Returns: endpoint (endpoint.Endpoint): Created endpoint. """ api_client = cls._instantiate_client(location=location, credentials=credentials) utils.validate_display_name(display_name) if labels: utils.validate_labels(labels) project = project or initializer.global_config.project location = location or initializer.global_config.location return cls._create( api_client=api_client, display_name=display_name, project=project, location=location, description=description, labels=labels, metadata=metadata, credentials=credentials, encryption_spec=initializer.global_config.get_encryption_spec( encryption_spec_key_name=encryption_spec_key_name ), sync=sync, ) @classmethod @base.optional_sync() def _create( cls, api_client: endpoint_service_client.EndpointServiceClient, display_name: str, project: str, location: str, description: Optional[str] = None, labels: Optional[Dict[str, str]] = None, metadata: Optional[Sequence[Tuple[str, str]]] = (), credentials: Optional[auth_credentials.Credentials] = None, encryption_spec: Optional[gca_encryption_spec.EncryptionSpec] = None, sync=True, ) -> "Endpoint": """Creates a new endpoint by calling the API client. Args: api_client (EndpointServiceClient): Required. An instance of EndpointServiceClient with the correct api_endpoint already set based on user's preferences. display_name (str): Required. The user-defined name of the Endpoint. The name can be up to 128 characters long and can be consist of any UTF-8 characters. project (str): Required. Project to retrieve endpoint from. If not set, project set in aiplatform.init will be used. location (str): Required. Location to retrieve endpoint from. If not set, location set in aiplatform.init will be used. description (str): Optional. The description of the Endpoint. labels (Dict[str, str]): Optional. The labels with user-defined metadata to organize your Endpoints. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. metadata (Sequence[Tuple[str, str]]): Optional. Strings which should be sent along with the request as metadata. credentials (auth_credentials.Credentials): Optional. Custom credentials to use to upload this model. Overrides credentials set in aiplatform.init. encryption_spec (Optional[gca_encryption_spec.EncryptionSpec]): Optional. The Cloud KMS customer managed encryption key used to protect the dataset. The key needs to be in the same region as where the compute resource is created. If set, this Dataset and all sub-resources of this Dataset will be secured by this key. sync (bool): Whether to create this endpoint synchronously. Returns: endpoint (endpoint.Endpoint): Created endpoint. """ parent = initializer.global_config.common_location_path( project=project, location=location ) gapic_endpoint = gca_endpoint_compat.Endpoint( display_name=display_name, description=description, labels=labels, encryption_spec=encryption_spec, ) operation_future = api_client.create_endpoint( parent=parent, endpoint=gapic_endpoint, metadata=metadata ) _LOGGER.log_create_with_lro(cls, operation_future) created_endpoint = operation_future.result() _LOGGER.log_create_complete(cls, created_endpoint, "endpoint") return cls._construct_sdk_resource_from_gapic( gapic_resource=created_endpoint, project=project, location=location, credentials=credentials, ) @classmethod def _construct_sdk_resource_from_gapic( cls, gapic_resource: proto.Message, project: Optional[str] =
import tensorflow as tf from MCQ.Consts import Consts class MultiHeadAttention(tf.keras.layers.Layer): def __init__(self, numHeads: int): """Multi head attention. Args: numHeads (int): Number of heads. logitsOnly (bool, optional): Only return logits for query @ key. Defaults to False. """ super().__init__() self._numHeads = numHeads def build(self, input_shape: tf.TensorShape): self._featureDim = input_shape[-1] tf.assert_equal(self._featureDim % self._numHeads, 0) self._depth = self._featureDim // self._numHeads self._wq = tf.keras.layers.Dense(self._featureDim) self._wk = tf.keras.layers.Dense(self._featureDim) self._wv = tf.keras.layers.Dense(self._featureDim) self._dense = tf.keras.layers.Dense(self._featureDim) def _splitHeads(self, x, batch_size): """ 分拆最后一个维度到 (_numHeads, depth). 转置结果使得形状为 (batch_size, _numHeads, seq_len, depth) """ x = tf.reshape(x, (batch_size, -1, self._numHeads, self._depth)) return tf.transpose(x, perm=[0, 2, 1, 3]) @staticmethod def _scaledDotProductAttention(q: tf.Tensor, k: tf.Tensor, v: tf.Tensor, mask: tf.Tensor = None): """ 计算注意力权重。 q, k, v 必须具有匹配的前置维度。 k, v 必须有匹配的倒数第二个维度,例如:seq_len_k = seq_len_v。 虽然 mask 根据其类型(填充或前瞻)有不同的形状,但是 mask 必须能进行广播转换以便求和。 参数: q: 请求的形状 == (..., seq_len_q, depth) k: 主键的形状 == (..., seq_len_k, depth) v: 数值的形状 == (..., seq_len_v, depth_v) mask: Float 张量,其形状能转换成 (..., seq_len_q, seq_len_k)。默认为None。 返回值: 输出,注意力权重 """ # (..., seq_len_q, seq_len_k) matmul_qk = tf.matmul(q, k, transpose_b=True) # 缩放 matmul_qk dk = tf.cast(tf.shape(k)[-1], tf.float32) scaled_attention_logits = matmul_qk / tf.math.sqrt(dk) # 将 mask 加入到缩放的张量上。 if mask is not None: scaled_attention_logits += (mask * -1e9) # softmax 在最后一个轴(seq_len_k)上归一化,因此分数相加等于1。 # (..., seq_len_q, seq_len_k) attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, depth_v) output = tf.matmul(attention_weights, v) return output, attention_weights def call(self, query: tf.Tensor, key: tf.Tensor, value: tf.Tensor, mask: tf.Tensor = None, training: bool = False): batch_size = tf.shape(query)[0] # (batch_size, seq_len, d_model) q = self._wq(query) # (batch_size, seq_len, d_model) k = self._wk(key) if self._wv is not None: # (batch_size, seq_len, d_model) v = self._wv(value) # (batch_size, _numHeads, seq_len_q, depth) q = self._splitHeads(q, batch_size) # (batch_size, _numHeads, seq_len_k, depth) k = self._splitHeads(k, batch_size) # (batch_size, _numHeads, seq_len_v, depth) v = self._splitHeads(v, batch_size) # (batch_size, _numHeads, seq_len_q, depth), (batch_size, _numHeads, seq_len_q, seq_len_k) scaled_attention, attention_weights = self._scaledDotProductAttention(q, k, v, mask) # (batch_size, seq_len_q, _numHeads, depth) scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch_size, seq_len_q, d_model) concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self._featureDim)) # (batch_size, seq_len_q, d_model) output = self._dense(concat_attention) return output, attention_weights def PointwiseFeedforwardNetwork(featureDim, hiddenDim): return tf.keras.Sequential([ # (batch_size, seq_len, hiddenDim) tf.keras.layers.Dense(hiddenDim, activation='relu'), # (batch_size, seq_len, featureDim) tf.keras.layers.Dense(featureDim) ]) class EncoderLayer(tf.keras.layers.Layer): def __init__(self, numHeads: int, hiddenDim: int, rate: float = 0.1): """Encoder layer for Transformer. Args: numHeads (int): Number of heads for MultiHeadAttention. hiddenDim (int): Hidden layer dim for PointwiseFeedfowardNetwork. rate (float, optional): Dropout rate. Defaults to 0.1. """ super().__init__() self._numHeads = numHeads self._hiddenDim = hiddenDim self._layerNorms = [ tf.keras.layers.LayerNormalization(epsilon=1e-6), tf.keras.layers.LayerNormalization(epsilon=1e-6) ] self._dropouts = [ tf.keras.layers.Dropout(rate), tf.keras.layers.Dropout(rate) ] def build(self, input_shape: tf.TensorShape): featureDim = input_shape[-1] self._multiHeadAttention = MultiHeadAttention(self._numHeads) self._feedfowardNetwork = PointwiseFeedforwardNetwork(featureDim, self._hiddenDim) def call(self, x: tf.Tensor, mask: tf.Tensor, training: bool = False): # (batch_size, input_seq_len, featureDim) attnOutput, _ = self._multiHeadAttention(x, x, x, mask) attnOutput = self._dropouts[0](attnOutput, training=training) # (batch_size, input_seq_len, featureDim) attnOutput = self._layerNorms[0](x + attnOutput) # (batch_size, input_seq_len, featureDim) ffnOutput = self._feedfowardNetwork(attnOutput) ffnOutput = self._dropouts[1](ffnOutput, training=training) # (batch_size, input_seq_len, featureDim) return self._layerNorms[1](attnOutput + ffnOutput) class DecoderLayer(tf.keras.layers.Layer): def __init__(self, numHeads: int, hiddenDim: int, rate: float = 0.1): """Decoder layer for Transformer. Args: numHeads (int): Number of heads for MultiHeadAttention. hiddenDim (int): Hidden layer dim for PointwiseFeedfowardNetwork. rate (float, optional): Dropout rate. Defaults to 0.1. logitsOnly (bool, optional): Should only return logits (query @ key) for attentions. Defaults to False. """ super().__init__() self._numHeads = numHeads self._hiddenDim = hiddenDim self._layerNorms = [ tf.keras.layers.LayerNormalization(epsilon=1e-6) ] self._dropouts = [ tf.keras.layers.Dropout(rate) ] self._dropouts.append(tf.keras.layers.Dropout(rate)) self._layerNorms.append(tf.keras.layers.LayerNormalization(epsilon=1e-6)) self._dropouts.append(tf.keras.layers.Dropout(rate)) self._layerNorms.append(tf.keras.layers.LayerNormalization(epsilon=1e-6)) def build(self, input_shape: tf.TensorShape): featureDim = input_shape[-1] self._multiHeadAttentions = [ MultiHeadAttention(self._numHeads), MultiHeadAttention(self._numHeads) ] self._feedfowardNetwork = PointwiseFeedforwardNetwork(featureDim, self._hiddenDim) def call(self, x: tf.Tensor, encoderOutput: tf.Tensor, lookAheadMask: tf.Tensor, paddingMask: tf.Tensor, training: bool = False): # encoderOutput.shape == (batch_size, input_seq_len, d_model) # (batch_size, target_seq_len, d_model) attn1, _ = self._multiHeadAttentions[0](x, x, x, lookAheadMask, training) attn1 = self._dropouts[0](attn1, training) out1 = attn1 out1 = self._layerNorms[0](attn1 + x) # (batch_size, target_seq_len, d_model) attn2, _ = self._multiHeadAttentions[1](out1, encoderOutput, encoderOutput, paddingMask, training) # if self._logitsOnly: # return None, attn_weights_block2 attn2 = self._dropouts[1](attn2, training) # (batch_size, target_seq_len, d_model) out2 = self._layerNorms[1](attn2 + out1) # (batch_size, target_seq_len, d_model) ffn_output = self._feedfowardNetwork(out2) ffn_output = self._dropouts[2](ffn_output, training) # (batch_size, target_seq_len, d_model) out3 = self._layerNorms[2](ffn_output + out2) return out3 class Encoder(tf.keras.layers.Layer): def __init__(self, numLayers: int, numHeads: int, hiddenDim: int, rate: float = 0.1): super(Encoder, self).__init__() self._numLayers = numLayers self._encoderLayers = [ EncoderLayer(numHeads, hiddenDim, rate) for _ in range(numLayers) ] # self._dropout = tf.keras.layers.Dropout(rate) def call(self, x, mask = None, training = False): # x = self._dropout(x, training) for i in range(self._numLayers): x = self._encoderLayers[i](x, mask, training) # (batch_size, input_seq_len, featureDim) return x class Decoder(tf.keras.layers.Layer): def __init__(self, numLayers, numCodebooks, numCodewords, numHeads, hiddenDim, rate=0.1): super().__init__() self._numLayers = numLayers self._numCodebooks = numCodebooks self._numCodewords = numCodewords self._decoderLayers = [ DecoderLayer(numHeads, hiddenDim, rate) for i in range(numCodebooks) ] # self.dropout = tf.keras.layers.Dropout(rate) def build(self, input_shape): pass # self._xTwistedInitialSequence = self.add_weight(name="InitialSequence", shape=[1, 1, 2 * input_shape[-1]], initializer="random_normal") @staticmethod def _lookAhead(size): mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0) # (seq_len, seq_len) return mask def call(self, x, encoderOutput, training): # [batch, 1, d] xInput = tf.expand_dims(x, 1) xFeed = xInput # [batch, 1, 3d] <- [batch, 1, d] - [1, 1, 2d] # xInput = tf.concat([xSequenced, tf.broadcast_to(self._xTwistedInitialSequence, [xSequenced.shape[0], 1, xSequenced.shape[-1]])], 1) # codebookLogits = tf.TensorArray(tf.float32, size=self._numCodebooks) for m in range(self._numCodebooks): lookAheadMask = self._lookAhead(tf.shape(xFeed)[1]) for i in range(self._numLayers): # [batch, m, d] xFeed = self._decoderLayers[i](xFeed, encoderOutput, lookAheadMask, None, training) # xSequenced = tf.concat([xSequenced, xTwisted], 1) # codebookLogits.write(i, codewordLogits) if m < self._numCodebooks - 1: # [batch, m+1, d] xFeed = tf.concat([xInput, xFeed], axis=1) return xFeed # if training: # quantized = tf.zeros([x.shape[0], num_samples, x.shape[-1]]) # else: # quantized = None # x_sequenced = tf.expand_dims(x, 1) # cumulative = tf.zeros(x.shape) # context_node = tf.concat([x_sequenced, self.init_value, cumulative[:, None, ...]], -1) # pi = list() # partialMask = tf.zeros([1, self.numCodewords]) # left = 0 # right = (self.numCodebooks-1)*self.numCodewords # codewordMask = tf.pad(partialMask, [[0, 0], [left, right]], constant_values=1.) # assert codewordMask.shape[-1] == self.numCodebooks * self.numCodewords # for i in range(self.numCodebooks): # x_twisted, codeword_logits = self.dec_layers[i]( # context_node, enc_output, training, None, # codewordMask, logits_only=i==self.numCodebooks-1) # codeword_logits = tf.reshape(codeword_logits, [x.shape[0], -1]) # """ ************************** """ # if training: # thisCodebook_p = codeword_logits[..., self.numCodewords*i:self.numCodewords*(i+1)] # # log_probability = tf.math.log(codeword_probability + 1e-10) # # thisCodebook_p = codeword_probability[..., self.numCodewords*i:self.numCodewords*(i+1)] # # [batch, num_samples] # codeword, picked_p = self.pick_codeword_by_categorical(codebook[:, self.numCodewords*i:self.numCodewords*(i+1)], thisCodebook_p, num_samples) # quantized += codeword # cumulative += tf.reduce_mean(codeword, 1) # else: # thisCodebook_p = self.softmax(codeword_logits[..., self.numCodewords*i:self.numCodewords*(i+1)]) # # log_probability = tf.math.log(codeword_probability + 1e-10) # # thisCodebook_p = codeword_probability[..., self.numCodewords*i:self.numCodewords*(i+1)] # codeword, picked_p = self.pick_codeword_from_wo_gumbel(codebook[:, self.numCodewords*i:self.numCodewords*(i+1)], thisCodebook_p) # cumulative += codeword # log_probability = tf.math.log(picked_p) # pi.append(log_probability) # """ ************************ """ # if i == self.numCodebooks - 1: # break # context_node = tf.concat([x_sequenced, x_twisted, cumulative[:, None, ...]], -1) # left += self.numCodewords # right -= self.numCodewords # codewordMask = tf.pad(partialMask, [[0, 0], [left, right]], constant_values=1.) # assert codewordMask.shape[-1] == self.numCodebooks * self.numCodewords # if not training: # quantized = cumulative # # x.shape == (batch_size, target_seq_len, d_model) # return pi, quantized def clipped_probability(self, logits, mask=None): p = tf.nn.tanh(logits) p *= 10.0 if mask is not None: p += (mask * -1e9) return tf.nn.softmax(p) def softmax(self, logits, mask=None): if mask is not None: logits += (mask * -1e9) return tf.nn.softmax(logits) def pick_codeword_from(self, subCodebook, logits, temperature): def sample_gumbel(shape, eps=1e-20): U = tf.random.uniform(shape, minval=0., maxval=1.) return -1. * tf.math.log(-1. * tf.math.log(U + eps) + eps) def gumbel_softmax(logits, temperature): gumbel_softmax_sample = logits + sample_gumbel(tf.shape(logits)) y = tf.nn.softmax(gumbel_softmax_sample / temperature) y_hard = tf.cast(tf.equal(y, tf.reduce_max(y, -1, keepdims=True)), y.dtype) y_onehot = tf.stop_gradient(y_hard - y) + y return y, y_onehot gumbel_p, gumbel_sampled = gumbel_softmax(logits, temperature) return tf.einsum("ijk,ij->ik", subCodebook, gumbel_sampled), gumbel_p def pick_codeword_from_wo_gumbel(self, subCodebook, probability): y_hard = tf.argmax(probability, -1)[:, None] return tf.gather_nd(subCodebook, y_hard, batch_dims=1), tf.gather_nd(probability, y_hard, batch_dims=1) y_hard = tf.cast(tf.equal(probability, tf.reduce_max(probability, -1, keepdims=True)), probability.dtype) return y_hard @ subCodebook, y_hard def pick_codeword_by_categorical(self, subCodebook, logits, num_samples): # p = tf.nn.tanh(logits) # p *= 10.0 p = logits # [batch, num_samples, 1] y_hard = tf.random.categorical(p, num_samples)[..., None] # [batch] ix = tf.range(tf.shape(y_hard)[0], dtype=y_hard.dtype) # [batch, num_samples, 1] ix = tf.repeat(ix[:, None,
if (self.iFlag_replace_parameter == 1): self.swaty_prepare_watershed_parameter_file() self.swaty_prepare_subbasin_parameter_file() self.swaty_prepare_hru_parameter_file() self.swaty_prepare_soil_parameter_file() #actual update parameter self.swaty_write_watershed_input_file() self.swaty_write_subbasin_input_file() self.swaty_write_hru_input_file() else: pass pass else: #during calibration #an inital simulation is needed? self.convert_pest_parameter_to_model_input() #this step only construct object self.swaty_write_watershed_input_file() self.swaty_write_subbasin_input_file() self.swaty_write_hru_input_file() pass self.swaty_copy_executable_file() sFilename_bash = self.swaty_prepare_simulation_bash_file() sFilename_job = self.swaty_prepare_simulation_job_file() return def convert_pest_parameter_to_model_input(self): self.convert_pest_parameter_to_actual_parameter() #build object return def convert_pest_parameter_to_actual_parameter(self): sWorkspace_simulation_case = self.sWorkspace_output_case #read the default parameter value sFilename_pest_watershed = os.path.join( sWorkspace_simulation_case, 'watershed.para' ) aData_dummy0 = text_reader_string(sFilename_pest_watershed, cDelimiter_in=',') #read pest default parameter value sFilename_pest_watershed = os.path.join( sWorkspace_simulation_case, 'watershed_default_parameter.txt' ) aData_dummy1 = text_reader_string(sFilename_pest_watershed, cDelimiter_in=',') #read the bound sFilename_parameter_bounds_watershed = os.path.join(self.sWorkspace_input, 'parameter_bounds_watershed.txt' ) aData_dummy2 = text_reader_string(sFilename_parameter_bounds_watershed, cDelimiter_in=',') #replace watershed by writing into a new file sFilename_watershed_out = os.path.join( sWorkspace_simulation_case, 'watershed_updated.para' ) ofs=open(sFilename_watershed_out, 'w') #assume the paramete may be out of bound because of the ratio operations #maintain the order of the parameter sLine_header = aData_dummy0[0,:] nParameter_watershed = sLine_header.shape[0] - 1 sLine_header = ','.join(sLine_header) sLine = sLine_header + '\n' ofs.write(sLine) aData_dummy00 = aData_dummy0[1,1:(nParameter_watershed+1)] self.nParameter_watershed = nParameter_watershed sLine = 'watershed' for i in range(nParameter_watershed): # we assume the order are the same as well, because the default parameter should be extracted using the same configuration # we must verify that the bounds have a same order dValue = float(aData_dummy00[i]) dValue_lower = float(aData_dummy2[i,1]) dValue_upper = float(aData_dummy2[i,2]) if dValue < dValue_lower: dValue = dValue_lower if dValue > dValue_upper: dValue = dValue_upper sLine = sLine + ',' + "{:0f}".format( dValue ) pass sLine = sLine + '\n' ofs.write(sLine) ofs.close() #subbasin #read the default parameter value sFilename_pest_subbasin = os.path.join( sWorkspace_simulation_case, 'subbasin.para' ) aData_dummy0 = text_reader_string(sFilename_pest_subbasin, cDelimiter_in=',') #read pest default parameter value sFilename_pest_subbasin = os.path.join( sWorkspace_simulation_case, 'subbasin_default_parameter.txt' ) aData_dummy1 = text_reader_string(sFilename_pest_subbasin, cDelimiter_in=',') #read the bound sFilename_parameter_bounds_subbasin = os.path.join(self.sWorkspace_input, 'parameter_bounds_subbasin.txt' ) aData_dummy2 = text_reader_string(sFilename_parameter_bounds_subbasin, cDelimiter_in=',') #replace subbasin by writing into a new file sFilename_subbasin_out = os.path.join( sWorkspace_simulation_case, 'subbasin_updated.para' ) ofs=open(sFilename_subbasin_out, 'w') #assume the paramete may be out of bound because of the ratio operations #maintain the order of the parameter sLine_header = aData_dummy0[0,:] nParameter_subbasin = sLine_header.shape[0] - 1 sLine_header = ','.join(sLine_header) sLine = sLine_header + '\n' ofs.write(sLine) aData_dummy00 = aData_dummy0[1,1:(nParameter_subbasin+1)] self.nParameter_subbasin = nParameter_subbasin for iSubbasin in range(1, self.nsubbasin): sSubbasin = "{:05d}".format( iSubbasin ) sLine = sSubbasin for j in range(nParameter_subbasin): # we assume the order are the same as well, because the default parameter should be extracted using the same configuration # we must verify that the bounds have a same order dValue = float(aData_dummy00[j]) dValue_lower = float(aData_dummy2[j,1]) dValue_upper = float(aData_dummy2[j,2]) if dValue < dValue_lower: dValue = dValue_lower if dValue > dValue_upper: dValue = dValue_upper sLine = sLine + ',' + "{:0f}".format( dValue ) pass sLine = sLine + '\n' ofs.write(sLine) ofs.close() #write to the actual swat input files return def run(self): if (self.iFlag_run ==1): sFilename_bash = os.path.join(self.sWorkspace_output_case, 'run_swat.sh' ) if (os.path.exists(sFilename_bash)): os.chdir(self.sWorkspace_output_case) sCommand = './run_swat.sh ' print(sCommand) p = subprocess.Popen(sCommand, shell= True) p.wait() pass else: pass return def analyze(self): self.swaty_extract_stream_discharge() return def evaluate(self): return def swaty_generate_model_structure_files(self): self.swaty_prepare_watershed_configuration() self.swaty_retrieve_soil_info() return def generate_parameter_bounds(self): sFilename_parameter_bounds = self.sFilename_parameter_bounds aData_dummy = text_reader_string(sFilename_parameter_bounds, cDelimiter_in=',', iSkipline_in=1) aName = aData_dummy[:, 1] aLower = aData_dummy[:, 2] aUpper = aData_dummy[:, 3] nParameter = aName.size aParameter_watershed = ['sftmp','smtmp','esco','smfmx','timp','epco'] aParameter_subbasin = ['ch_k2','ch_n2','plaps','tlaps'] aParameter_hru = ['cn2', 'rchrg_dp', 'gwqmn', 'gw_revap','revapmn','gw_delay','alpha_bf','ov_n'] aParameter_soil = ['sol_awc','sol_k','sol_alb','sol_bd'] #split into different group? aData_out_watershed = list() aData_out_subbasin = list() aData_out_hru = list() aData_out_soil = list() for i in range(nParameter): sPara = aName[i].lower() dValue_lower = aLower[i] dValue_upper = aUpper[i] #sLower = "{:0f}".format( dValue_lower ) #sUpper = "{:0f}".format( dValue_upper ) if sPara in aParameter_watershed: sLine = sPara + ',' + dValue_lower + ',' + dValue_upper aData_out_watershed.append(sLine) pass else: if sPara in aParameter_subbasin: sLine = sPara + ',' + dValue_lower + ',' + dValue_upper aData_out_subbasin.append(sLine) pass else: if sPara in aParameter_hru: sLine = sPara + ',' + dValue_lower + ',' + dValue_upper aData_out_hru.append(sLine) pass else: sLine = sPara + ',' + dValue_lower + ',' + dValue_upper aData_out_soil.append(sLine) pass pass pass pass #export sFilename_parameter_bounds_watershed = os.path.join(self.sWorkspace_input, 'parameter_bounds_watershed.txt' ) ofs=open(sFilename_parameter_bounds_watershed, 'w') for i in aData_out_watershed: ofs.write(i + '\n') ofs.close() sFilename_parameter_bounds_subbasin = os.path.join(self.sWorkspace_input, 'parameter_bounds_subbasin.txt' ) ofs=open(sFilename_parameter_bounds_subbasin, 'w') for i in aData_out_subbasin: ofs.write(i + '\n') ofs.close() sFilename_parameter_bounds_hru = os.path.join(self.sWorkspace_input, 'parameter_bounds_hru.txt' ) ofs=open(sFilename_parameter_bounds_hru, 'w') for i in aData_out_hru: ofs.write(i + '\n') ofs.close() sFilename_parameter_bounds_soil = os.path.join(self.sWorkspace_input, 'parameter_bounds_soil.txt' ) ofs=open(sFilename_parameter_bounds_soil, 'w') for i in aData_out_soil: ofs.write(i + '\n') ofs.close() return def extract_default_parameter_value(self, aParameter_in): #watershed aParameter = list() for p in aParameter_in: if p.iParameter_type == 1: aParameter.append(p) self.extract_default_parameter_value_watershed(aParameter) #subbasin aParameter.clear() for p in aParameter_in: if p.iParameter_type == 2: aParameter.append(p) self.extract_default_parameter_value_subbasin(aParameter) #hru aParameter.clear() for p in aParameter_in: if p.iParameter_type == 3: aParameter.append(p) self.extract_default_parameter_value_hru(aParameter) #soil aParameter.clear() for p in aParameter_in: if p.iParameter_type == 4: aParameter.append(p) self.extract_default_parameter_value_soil(aParameter) return def extract_default_parameter_value_watershed(self, aParameter_watershed): sWorkspace_source_case = self.sWorkspace_simulation_copy sWorkspace_target_case = self.sWorkspace_output_case nParameter_watershed = len(aParameter_watershed) if nParameter_watershed < 1: return #open the new file to write out sFilename = 'watershed_default_parameter.txt' sFilename_watershed_out = os.path.join(str(Path(sWorkspace_target_case)) , sFilename ) if os.path.exists(sFilename_watershed_out): os.remove(sFilename_watershed_out) ofs=open(sFilename_watershed_out, 'w') #we need to save the array and output them in the last step aData_out = np.full(nParameter_watershed, -9999, dtype=float) aExtension = ['.bsn','.wwq'] aBSN=['sftmp','smtmp','esco','smfmx','timp','epco'] aWWQ=['ai0'] aExtension = np.asarray(aExtension) nFile_type= len(aExtension) #the parameter is located in the different files aParameter_table = np.empty( (nFile_type) , dtype = object ) #need a better way to control this for iVariable in range(nParameter_watershed): sParameter_watershed = aParameter_watershed[iVariable].sName if sParameter_watershed in aBSN: if( aParameter_table[0] is None ): aParameter_table[0] = np.array(sParameter_watershed) else: aParameter_table[0] = np.append(aParameter_table[0],sParameter_watershed) pass else: if sParameter_watershed in aWWQ: if( aParameter_table[1] is None ): aParameter_table[1] = sParameter_watershed else: aParameter_table[1]=np.append(aParameter_table[1],sParameter_watershed) pass pass aParameter_user = np.full( (nFile_type) , None , dtype = np.dtype(object) ) aParameter_count = np.full( (nFile_type) , 0 , dtype = int ) aParameter_flag = np.full( (nFile_type) , 0 , dtype = int ) aParameter_index = np.full( (nFile_type) , -1 , dtype = np.dtype(object) ) for p in range(0, nParameter_watershed): para = aParameter_watershed[p].sName for i in range(0, nFile_type): aParameter_tmp = aParameter_table[i] if aParameter_tmp is not None: if para in aParameter_tmp: aParameter_count[i]= aParameter_count[i]+1 aParameter_flag[i]=1 if(aParameter_count[i] ==1): aParameter_index[i] = [p] aParameter_user[i]= [para] else: aParameter_index[i] = np.append(aParameter_index[i],[p]) aParameter_user[i] = np.append(aParameter_user[i],[para]) continue #write the head sLine = 'watershed' for iFile_type in range(0, nFile_type): sExtension = aExtension[iFile_type] iFlag = aParameter_flag[iFile_type] if( iFlag == 1): aParameter_indices = np.array(aParameter_index[iFile_type]) for i in range(len(aParameter_indices)): dummy_index = aParameter_indices[i] pParameter = aParameter_watershed[dummy_index] sVariable = pParameter.sName sLine = sLine + ',' + sVariable sLine = sLine + '\n' ofs.write(sLine) aDate_out = np.full(nParameter_watershed, -9999, dtype=float) #write value for iFile_type in range(0, nFile_type): sExtension = aExtension[iFile_type] iFlag = aParameter_flag[iFile_type] if( iFlag == 1): #there should be only one for each extension sFilename = 'basins' + sExtension sFilename_watershed = os.path.join(str(Path(sWorkspace_source_case)) , sFilename ) nline = line_count(sFilename_watershed) ifs=open(sFilename_watershed, 'rb') for iLine in range(nline): sLine0=(ifs.readline()) if len(sLine0) < 1: continue sLine0=sLine0.rstrip() #print(sLine0) sLine= sLine0.decode("utf-8", 'ignore') for i in range(0, aParameter_count[iFile_type]): aParameter_indices = np.array(aParameter_index[iFile_type]) aParameter_filetype = np.array(aParameter_user[iFile_type]) if 'sftmp' in sLine.lower() and 'sftmp' in aParameter_filetype : #this one may not in the same order as shown in the actual fil sValue = (sLine.split('|'))[0].strip() dValue = float(sValue) dummy_index = np.where( aParameter_filetype=='sftmp' ) dummy_index2 = aParameter_indices[dummy_index] aData_out[dummy_index2] = dValue break #important else: if 'smtmp' in sLine.lower() and 'smtmp' in aParameter_filetype: sValue = (sLine.split('|'))[0].strip() dValue = float(sValue) dummy_index = np.where( aParameter_filetype=='smtmp' ) dummy_index2 = aParameter_indices[dummy_index] aData_out[dummy_index2] = dValue break #important else: if 'esco' in sLine.lower() and 'esco' in aParameter_filetype: sValue = (sLine.split('|'))[0].strip() dValue = float(sValue) dummy_index = np.where( aParameter_filetype=='esco' ) dummy_index2 = aParameter_indices[dummy_index] aData_out[dummy_index2] = dValue break #important else: if 'smfmx' in sLine.lower() and 'smfmx' in aParameter_filetype: sValue = (sLine.split('|'))[0].strip() dValue = float(sValue) dummy_index = np.where( aParameter_filetype=='smfmx' ) dummy_index2 = aParameter_indices[dummy_index] aData_out[dummy_index2] = dValue break #important else: if 'timp' in sLine.lower() and 'timp' in aParameter_filetype: sValue = (sLine.split('|'))[0].strip() dValue = float(sValue) dummy_index = np.where(
power_key: pass else: self.logger.error("regrid: no power data key found") return None if step == None: # use the original stepsize self.xstep, self.ystep = self.get_grid_stepsize() else: self.xstep, self.ystep = step self.data['grid_x'] = NP.arange( -width/2, width/2+self.xstep/2, self.xstep/2) self.data['grid_y'] = NP.arange( -height/2,height/2+self.ystep/2, self.ystep/2) self.logger.debug("regrid: grid shape is %dx%d", len(self.data['grid_x']), len(self.data['grid_y'])) self.data['grid_z'] = {} for chnl in self.channel: self.logger.debug("regrid: processing %s", chnl) points = list(zip(self.data['xdec_offset'],self.data['dec_offset'])) self.logger.debug("regrid: %d positions", len(points)) values = self.data[power_key][chnl] self.logger.debug("regrid: %d values", len(values)) xi, yi = NP.meshgrid(self.data['grid_x'], self.data['grid_y']) try: self.data['grid_z'][chnl] = scipy.interpolate.griddata(points, values, (xi, yi), method='nearest') except ValueError as details: self.logger.error("regrid: gridding failed: %s", str(details)) self.logger.debug("regrid: channel %s length of points is %d", chnl, len(points)) self.logger.debug("regrid: channel %s length of values is %d", chnl, len(values)) continue def radec_from_azel(self): """ compute RA and dec from az and el """ RA = []; decs = []; RAdecs = [] for idx in list(range(self.numdata)): # setup dt = self.data['datetime'][idx] # format time as (YEAR, DOY.fff) time_tuple = (dt.year, DT.day_of_year(dt.year,dt.month,dt.day) + ( dt.hour + dt.minute/60. + dt.second/3600. + dt.microsecond/3600./1e6)/24.) azimuth = self.data['az'][idx] elevation = self.data['el'][idx] # compute ra,dec = A.AzEl_to_RaDec(azimuth, elevation, self.latitude, -self.longitude, time_tuple) RA.append(ra) decs.append(dec) RAdecs.append((RA,decs)) self.data['ra'] = RA self.data['dec'] = decs self.data['radec'] = RAdecs def radec2000_from_radec(self): """ compute RA2000 and dec2000 from observed RA and dec """ RA2000 = []; decs2000 = []; RAdec2000 = [] for idx in list(range(self.numdata)): # setup tm = self.data['unixtime'][idx] mjd = DT.UnixTime_to_MJD(tm) MJD = int(mjd) UT = 24*(mjd-MJD) ra = self.data['ra'] dec = self.data['dec'] # compute ra2000,dec2000 = A.apparent_to_J2000(MJD,UT, ra, dec, self.longitude, self.latitude) RA2000.append(ra2000) decs2000.append(dec2000) RAdec2000.append((ra2000,dec2000)) self.data['ra2000'] = RA2000 self.data['dec2000'] = dec2000 self.data['radec2000'] = RAdec2000 def radec_from_radec2000(self): """ compute apparent RA and dec. from J2000 RA and dec """ RA = []; decs = []; RAdecs = [] for idx in list(range(self.numdata)): # setup tm = self.data['unixtime'][idx] mjd = DT.UnixTime_to_MJD(tm) MJD = int(mjd) UT = 24*(mjd-MJD) ra2000 = self.data['ra2000'][idx] dec2000 = self.data['dec2000'][idx] # compute ra, dec = A.J2000_to_apparent(MJD, UT, ra2000*math.pi/12, dec2000*math.pi/180) RA.append(ra) decs.append(dec) RAdecs.append((ra,dec)) self.data['ra'] = RA self.data['dec'] = decs self.data['radec'] = RAdecs def azel_from_radec(self): """ compute azimuth and elevation from apparent right ascension and declination """ azs = []; els = []; azels = [] for idx in list(range(self.numdata)): # setup ra = self.data['ra'][idx] dec = self.data['dec'][idx] timetuple = self.data['datetime'][idx].timetuple() year = timetuple.tm_year doy = timetuple.tm_yday + (timetuple.tm_hour +(timetuple.tm_min+timetuple.tm_sec/60)/60)/24 # compute az, el = A.RaDec_to_AzEl(ra, dec, self.latitude, self.longitude, (year,doy)) azs.append(az) els.append(el) azels.append((az,el)) self.data['az'] = azs self.data['el'] = els self.data['azel'] = azels def get_offsets(self, source="Sun", xdec_ofst=0., dec_ofst=0.): """ Generates a map in coordinates relative to a source If the source is the default, the position of the Sun will be computed for the time of each sample. IT SEEMS LIKE A GOOD IDEA TO DO THIS FOR PLANETS ALSO. This adds elements with keys ``xdec_offset`` and ``dec_offset`` to the attribute ``data``. @param source : source at map center @type source : ephem source instance @param xdec_ofst : relative X-dec position of sample @type xdec_ofst : float @param dec_ofst : relative dec position of sample @type dec_ofst : float @return: (dxdecs,ddecs) in degrees """ if source.lower() == "sun": src = AE.ephem.Sun() else: src = AE.calibrator(source) self.data['dec_offset'] = [] self.data['xdec_offset'] = [] for count in range(len(self.data['unixtime'])): dt = datetime.datetime.utcfromtimestamp( self.data['unixtime'][count]) if type(src) == AE.Quasar: pass else: src.compute(dt) ra_center = src.ra*12/math.pi # hours dec_center = src.dec*180/math.pi # degrees decrad = src.dec # right ascension increases to the left, cross-dec to the right self.data['xdec_offset'].append(xdec_ofst - (self.data['ra'][count] - ra_center)*15*math.cos(decrad) ) self.data['dec_offset'].append( dec_ofst + self.data['dec'][count] - dec_center) # change list to NP.array self.data['xdec_offset'] = NP.array(self.data['xdec_offset']) self.data['dec_offset'] = NP.array(self.data['dec_offset']) class Map(Observation, GriddingMixin): """ Map class without special features for GAVRT and Malargue Most of the methods are mixed in to avoid conflicting with subclasses """ def __init__(self, parent=None, name=None, dss=None, date=None, project=None): """ Create a Map object Args: parent (Session): an observing session to which this belongs name (str): an identifier, like a scan number dss (int): station where the data were taken date (str): date of observation as "YEAR/DOY" project (str): project for which this observation was made """ Observation.__init__(self, parent=parent, name=name, dss=dss, date=date, project=project) class Recording(h5py.File): """ Class for raw data This is typically the contents of a data file transcribed into a standard format. It may be the data of one Observation object, or data for multiple Observation objects, or contain part of the data for an Observation object. If the data being curated are not in a standard project, and they are not in a standard place, """ def __init__(self, session=None, path=None, date=None, dss=None, name=None): """ Initialize a metadata container and data directory Args ==== session (Session): required, unless: path (str) : location of raw data files date """ self.logger = logging.getLogger(logger.name+".Recording") if session: self.session = session if not name: name = session.project + "-" + str(session.year) + "-" + \ ('%03d' % session.doy) + "-dss" + str(session.dss)+".info" self.year = session.year self.doy = session.doy self.dss = session.dss self.project = session.project self.session_dir = session.session_dir elif path and name: self.session = Session() # for its methods and attributes self.session_dir = path self.name = name else: raise RuntimeError("either a session or a path and filename required") h5py.File.__init__(self, name, 'w') self.attrs['project'] = self.project self.attrs['dss'] = self.dss self.attrs['year'] = self.year self.attrs['doy'] = self.doy class Session(object): """ Base class for an observing session on a given year and DOY Public Attributes:: doy (int) - day of year for session logger (logging.Logger) - logging.Logger object parent (object) - a data reduction session (mult. observ. sessions) year (int) - doy (int) - project (str) - session_dir (str) - path to results from this session A session usually refers to a telescope, date and project. This will normally define a path to the session directory. """ def __init__(self, parent=None, date=None, project=None, dss=None, path=None): """ initialize data reduction for one observing session Args ==== parent: (object) optional class for a data reduction tool date: (str) required, format YEAR/DOY project: (str) required dss (int) required path (str) optional If `path` is given for a non-standard observing files location, and it does not exist, it will be created. Then the Recording and Observation instances must be directed to where the files are. """ self.logger = logging.getLogger(logger.name+".Session") if parent: self.session = parent if date and project and dss: y,d = date.split('/') self.year = int(y); self.doy = int(d) self.project = project self.dss = dss self.name = "'%s %4d/%03d'" % (self.project, self.year, self.doy) else: self.logger.error("__init__: missing DSS or year or DOY or project") raise Exception("Where and when and for what project were the data taken?") self.find_session_dir(path=path) def find_session_dir(self, path=None): """ find or make the sessions directory Args: path (str) - explicit path to files """ self.logger.debug("find_session_dir: entered for path=%s", path) if path: self.session_dir = path else: obs_dir = local_dirs.projects_dir + self.project \ +"/Observations/dss"+str(self.dss)+"/" self.session_dir = obs_dir+ "%4d" % self.year +"/"+ "%03d" % self.doy +"/" if not os.path.exists(self.session_dir): os.makedirs(self.session_dir, mode=0o775) def select_data_files(self, datapath=None, name_pattern="", auto=True, load_hdf=False): """ Provide the user with menu to select data files. Finding the right data store is complicated as there are many kinds of data files * If datapath is ...RA_data/HDF5/... then the files could be .h5 (Ashish) or .hdf5 (Dean). * If datapath is ...RA_data/FITS/... then the extent is .fits. * If datapath is ...project_data/... then the extent is .pkl * If datapath is ...projects/... (default) then the extent is probably .csv or .dat or .prd. @param datapath : path to top of the tree where the DSS subdirectories are @type datapath : str @param name_pattern : pattern for selecting file names, e.g. source @type name_pattern : str @param load_hdf : use RA_data/HDF5 directory if True @type load_hdf : bool @para auto : take all files found @type
is None: ff_hidden_dim = p.ff_hidden_dim sub_list = [ ('i.vec->after_feedforward', self._Seq( 'feedforward', self._LN('ln', p.model_dim, use_fused_layernorm=p.use_fused_layernorm), self._Linear('linear01', p.model_dim, ff_hidden_dim), self._Bias('bias01', ff_hidden_dim), self._Activation('act', p.ff_activation_fn), self._Dropout('relu_dropout', p.relu_dropout_prob), self._Linear('linear02', ff_hidden_dim, p.model_dim), self._Bias('bias02', p.model_dim), self._Dropout('dropout', p.residual_dropout_prob))), ('i.vec,after_feedforward->added', self._Add('add', p.ff_residual_weight)), ('added,i.paddings->o.vec', self._Pad('pad')), ('i.paddings->o.paddings', self._Id('id')), ] if p.packed_input: sub_list.append(('i.segment_mask->o.segment_mask', self._Id('segment_mask'))) return self._Graph( name, ['i'], # input NestedMap with {vec, paddings, segment_mask} ['o'], # output NestedMap with {vec, paddings, segment_mask} *sub_list) def _MaybeSplit(self, name, blocks): p = self.params if p.num_splits == 1 and p.num_micro_batches == 1: return None num_layers = len(blocks) assert num_layers >= p.num_splits layers_per_split = (num_layers - 1) // p.num_splits + 1 cells = [] while blocks: head, blocks = blocks[:layers_per_split], blocks[layers_per_split:] cells.append(self._Seq('cell_{}'.format(len(cells)), *head)) assert len(cells) == p.num_splits return gpipe.PipeliningLayer.Params().Set( name=name, cell_tpl=cells, nested_map_fprop=True, num_micro_batches=p.num_micro_batches) def _DepthwiseConv2D(self, name, filter_size, is_causal=False): """A depthwise convolution block for lightweight conv.""" p = self.params conv_builder_params = conv_layers.Builder.Params() if p.norm_layer_tpl: conv_builder_params.norm_layer_tpl = p.norm_layer_tpl conv_builder = conv_builder_params.Instantiate() return conv_builder.DepthwiseConv2D( name=name, in_dim=p.model_dim, depth_multiplier=1, filter_shape=[filter_size, 1], stride=(1, 1), dilation=(1, 1), activation=p.conv_activation, is_causal=is_causal) def _NormalizedDepthwiseConv2D(self, name, kernel_size, is_causal=False): """A depthwise convolution block for lightweight conv.""" p = self.params conv_builder_params = conv_layers.Builder.Params() conv_builder = conv_builder_params.Instantiate() return conv_builder.NormalizedDepthwiseConv2D( name=name, kernel_size=kernel_size, num_heads=p.num_heads, in_dim=p.model_dim, dropconnect_prob=p.atten_dropout_prob, deterministic_dropout=p.deterministic_dropout, is_causal=is_causal) def LConv(self, name, kernel_size, is_causal=False, convolution_fn=None): """[DEPRECATED] A lightweight convolution block as described in. Use conv_layer_builder.LConv() instead. https://arxiv.org/abs/1901.10430 Corresponding PyTorch Implementation (L587): https://github.com/pytorch/fairseq/blob/v0.6.2/fairseq/models/lightconv.py This block can be used as an alternative to self-attention block. Args: name: name of the params kernel_size: kernel size used in the conv layer. is_causal: is causal padding or not. convolution_fn: Convolution to apply, default _NormalizedDepthwiseConv2D. Returns: A LightWeightConvLayerBlock layer params. """ p = self.params if convolution_fn is None: convolution_fn = getattr(self, '_NormalizedDepthwiseConv2D') sub_list = [ ('i.vec->pre_conv', self._Seq( 'pre_conv', self._LN('ln', p.model_dim, use_fused_layernorm=p.use_fused_layernorm), self._Linear('linear', p.model_dim, p.model_dim * 2), self._Bias('bias', p.model_dim * 2), self._Glu('glu'), self._ExpandDims('expand'))), ('pre_conv,i.paddings->post_conv,o.paddings', convolution_fn('conv', kernel_size, is_causal)), ('post_conv->after_dropout', self._Seq( 'post_conv', self._Squeeze('squeeze'), self._Linear('linear', p.model_dim, p.model_dim), self._Bias('bias', p.model_dim), self._Dropout('dropout', p.residual_dropout_prob))), ('i.vec,after_dropout->o.vec', self._Add('add')), ] if p.packed_input: sub_list.append(('i.segment_mask->o.segment_mask', self._Id('segment_mask'))) return self._Graph( name, ['i'], # input NestedMap with {vec, paddings, segment_mask} ['o'], # output NestedMap with {vec, paddings, segment_mask} *sub_list ) def LconvBlock(self, name, kernel_size, is_causal, convolution_fn): """A lightweight conv block followed by a feedforward one.""" return self._Seq( name, self.LConv( name='lconv', kernel_size=kernel_size, is_causal=is_causal, convolution_fn=convolution_fn), self.Feedforward('ff', is_causal)) def Seq(self, name, *subs): """Returns a stack of sequential layers.""" return self._Seq(name, *subs) def LConvStack(self, name, kernel_sizes, is_causal=False): """Returns a stack of LConv layers with kernel size in kernel_sizes.""" blocks = [] for i, kernel_size in enumerate(kernel_sizes): blocks.append( self.LconvBlock( name='block_{}'.format(i), kernel_size=kernel_size, is_causal=is_causal, convolution_fn=None)) return self._MaybeSplit(name, blocks) or self._Seq(name, *blocks) def _Stride(self, name, stride, first_n=None): """Strides the input sequence. Args: name: name of this layer. stride: To use every k-th token, set the stride to k. When stride == 0, only returns the first token of the input. When stride == 1, returns every token in the input. first_n: only considers the first N tokens for the output. We use [:first_n:stride] to select the output tokens. If first_n is None, this flag is a no-op. If stride is positive, the output sequence length is "(first_n-1) // stride + 1". If stride is 0, first_n has to be None or 1. first_n can't be 0. If first_n <= stride, only the first token is used. Returns: A layer params that does stride. """ assert first_n is None or first_n > 0 if stride == 0: assert first_n is None or first_n == 1 return self._Fn( name=name, fn=lambda x: tf.expand_dims(x[:, 0], 1), fn_out=lambda x: tshape.Shape(x[0:1] + [1] + x[2:]), fn_flops=lambda x: 1) if first_n: # out_seq_len is 1 if first_n is 1 ~ stride and is 2 if it's stride+1 ~ # 2*stride... out_seq_len = (first_n - 1) // stride + 1 return self._Fn( name=name, fn=lambda x: x[:, :first_n:stride], fn_out=lambda x: tshape.Shape(x[0:1] + [out_seq_len] + x[2:]), fn_flops=lambda x: 1) if stride == 1: return self._Id(name) return self._Fn( name=name, fn=lambda x: x[:, ::stride], fn_out=lambda x: tshape.Shape(x[0:1] + x[1] // stride + x[2:]), fn_flops=lambda x: 1) def _StridedAttention(self, name, stride=1, first_n=None, num_heads=None): """Computes self attention with optional stride. Args: name: name of this layer. stride: If omitted, the default is 1: use every token in the query. To use every k-th token, set the stride to k. When set to 0, only use the first token of the query. first_n: only considers the first N tokens for the output. We use [:first_n:stride] to select the output tokens. If first_n is None, this flag is a no-op. If stride is positive, the output sequence length is "(first_n-1) // stride + 1". If stride is 0, first_n has to be None or 1. first_n can't be 0. If first_n <= stride, only the first token is used. num_heads: the number of heads. Returns: A self attention layer params. """ p = self.params input_to_add = ('i.vec' if p.selfatten_add_unnormalized_input else 'after_ln') attention_inputs = 'strided_query,after_ln,after_ln,i.paddings' if p.packed_input: attention_inputs += ',i.segment_mask' if num_heads is None: num_heads = p.num_heads sub_list = [ ('i.vec->after_ln', self._LN('LN', p.model_dim, use_fused_layernorm=p.use_fused_layernorm)), ('after_ln->strided_query', self._Stride('query_after_stride', stride, first_n)), ('{}->after_att,prob'.format(attention_inputs), self._MultiHeadedAtten('atten', num_heads)), ('after_att->after_dropout', self._Dropout('dropout', p.residual_dropout_prob)), ('{}->strided_input'.format(input_to_add), self._Stride('before_add', stride, first_n)), ('strided_input,after_dropout->o.vec', self._Add('add')), ('i.paddings->o.paddings', self._Stride('padding_after_Stride', stride, first_n)), ] if p.packed_input: sub_list.append(('i.segment_mask->o.segment_mask', self._Id('segment_mask'))) return self._Graph( name, ['i'], # input NestedMap with {vec, paddings, segment_mask} ['o'], # output NestedMap with {vec, paddings, segment_mask} *sub_list) def TransformerEncoderLayer(self, name, stride=1, first_n=None, ff_hidden_dim=None, num_heads=None): """(inputs, paddings) -> (encoded, paddings). Args: name: the string name of the encoder layer params. stride: To use every k-th token, set the stride to k. When stride == 0, only returns the first token of the input. When stride == 1, returns every token in the input. first_n: only considers the first N tokens for the output. We use [:first_n:stride] to select the output tokens. If first_n is None, this flag is a no-op. If stride is positive, the output sequence length is "(first_n-1) // stride + 1". If stride is 0, first_n has to be None or 1. first_n can't be 0. If first_n <= stride, only the first token is used. ff_hidden_dim: The feed forward layer's hidden dimension. If specified, this will override p.ff_hidden_dim. num_heads: The number of heads for the multi-head attention module. If specified, this will override p.num_heads. Returns: A transformer encoder layer params that supports optional stride. """ p = self.params if ff_hidden_dim is None: ff_hidden_dim = p.ff_hidden_dim if num_heads is None: num_heads = p.num_heads return self._Seq(name, self._Seq( 'block', self._StridedAttention('self_atten', stride=stride, first_n=first_n, num_heads=num_heads), self.Feedforward('ff', ff_hidden_dim=ff_hidden_dim))) def Stack(self, name, blocks): """Returns a stack of sequential layers.""" return self._MaybeSplit(name, blocks) or self._Seq(name, *blocks) def TransformerEncoderStack(self, name, num_layers=1): """Returns a stack of num_layers self-attention layers.""" blocks = [ self.TransformerEncoderLayer(name='iter_{:0>3d}'.format(d)) for d in range(num_layers) ] return self.Stack(name, blocks) # pyformat: enable class LmBuilder(Builder): """Langange model builder with causal padding.""" @classmethod def Params(cls): p = super().Params() p.Define('xla_num_partitions', None, 'Number of SPMD partitions.') p.Define('dtype', tf.float32, 'Datatype to use.') return p def _ShardedVar(self, name, weights, split_dim): return moe_layers.ShardedVarLayer.Params().Set( name=name, weights=weights, split_dimension=split_dim, fprop_dtype=self.params.fprop_dtype, num_devices=self.params.xla_num_partitions) def _LinearWeight(self, name, input_dim, output_dim, split_dim): return self._ShardedVar( name=name, weights=[('w', py_utils.WeightParams( shape=[input_dim, output_dim], init=py_utils.WeightInit.Uniform((3. / input_dim)**0.5), dtype=self.params.dtype))], split_dim=split_dim) def _Linear(self, name, input_dim, output_dim, split_dim=0): return self._Graph( name, ['inputs'], ['outputs'], ('->w', self._LinearWeight('w', input_dim, output_dim, split_dim)), ('inputs,w->outputs', self._Fn( 'linear', fn=lambda inputs, w: tf.einsum('BLI,IO->BLO', inputs, w))), ) def _BiasWeight(self, name, dim): return self._ShardedVar( name=name, weights=[('b', py_utils.WeightParams( shape=[dim], init=py_utils.WeightInit.Constant(0.0), dtype=self.params.dtype))], split_dim=0) def _Bias(self, name, dim): return self._Graph( name, ['inputs'], ['outputs'], ('->b', self._BiasWeight('b', dim)), ('inputs,b->outputs', self._Fn('bias', fn=lambda inputs, b: inputs + b)), ) def Feedforward(self, name): p = self.params ff_list = [ self._LN('ln', p.model_dim, use_fused_layernorm=p.use_fused_layernorm), self._Linear('linear01', p.model_dim, p.ff_hidden_dim, split_dim=1) ] if p.use_bias: ff_list.append(self._Bias('bias01', p.ff_hidden_dim)) ff_list += [ self._Activation('act', p.ff_activation_fn), self._Dropout('relu_dropout', p.relu_dropout_prob), self._Linear('linear02', p.ff_hidden_dim, p.model_dim, split_dim=0) ] if p.use_bias: ff_list.append(self._Bias('bias02', p.model_dim)) ff_list.append(self._Dropout('dropout', p.residual_dropout_prob)) sub_list = [ ('i.vec->after_feedforward', self._Seq('feedforward', *ff_list)), ('i.vec,after_feedforward->added', self._Add('add', p.ff_residual_weight)), ('added,i.paddings->o.vec', self._Pad('pad')), ('i.paddings->o.paddings', self._Id('id')), ] return self._Graph( name, ['i'], # input NestedMap with {vec, paddings} ['o'], # output NestedMap with {vec, paddings} *sub_list) def _Attention(self, name, is_causal=True): """Computes self attention with optional stride. Args: name: name of this layer. is_causal: If true, add cause per_step padding to
""" This file contains algorithms for finding graph-pit assignments with cannot-link constraints described by a cannot-link graph. References: [1] Speeding Up Permutation Invariant Training for Source Separation """ from collections import deque from dataclasses import dataclass import numpy as np from .graph import Graph import logging from .utils import Dispatcher logger = logging.getLogger('graph-assignment-solver') def _find_mapping_apply_connected_components( assignment_solver, score_matrix, cannot_link_graph, **kwargs ): num_targets, num_estimates = score_matrix.shape assert num_targets == cannot_link_graph.num_vertices, ( num_targets, cannot_link_graph.num_vertices ) mapping = np.zeros(num_targets, dtype=int) for connected_component in cannot_link_graph.connected_components: cc_sm = score_matrix[(connected_component.labels, slice(None))] partial_solution = assignment_solver( cc_sm, connected_component, **kwargs ) if partial_solution is None: return None mapping[connected_component.labels] = partial_solution return mapping @dataclass class GraphAssignmentSolver: """ Base class for graph-based assignment solvers. Attributes: minimize: If `True`, find the minimum. Otherwise, find the maximum optimize_connected_components: If `True`, the assignment algorithm is applied to each connected component of the graph individually. """ minimize: bool = False optimize_connected_components: bool = True def __call__(self, score_matrix, cannot_link_graph): score_matrix = np.asanyarray(score_matrix) self._check_inputs(score_matrix, cannot_link_graph) if self.optimize_connected_components: coloring = _find_mapping_apply_connected_components( self.find_assignment, score_matrix, cannot_link_graph ) else: coloring = self.find_assignment(score_matrix, cannot_link_graph) if coloring is None: num_targets, num_estimates = score_matrix.shape logger.debug( f'Couldn\'t find a solution with the assignment solver ' f'{self.__class__.__name__}. This could mean that the ' f'cannot_link_graph is not colorable with {num_estimates} ' f'colors.' ) return coloring def _check_inputs(self, score_matrix, cannot_link_graph): num_targets, num_estimates = score_matrix.shape if not np.issubdtype(score_matrix.dtype, np.floating): raise TypeError( f'The score matrix must be floating point, not ' f'{score_matrix.dtype}!' ) if num_targets != cannot_link_graph.num_vertices: raise ValueError( f'The shape of score_matrix and number of vertices in the' f' cannot_link_graph must match, but ' f'score_matrix.shape={score_matrix.shape}, ' f'cannot_link_graph.num_vertices=' f'{cannot_link_graph.num_vertices}' ) def find_assignment( self, score_matrix: np.ndarray, cannot_link_graph: Graph ): """ Runs the assignment algorithm. Args: score_matrix (num_targets num_estimates): The score matrix to use cannot_link_graph: The graph that describes the overlaps / entries in `score_matrix` that cannot be used together. Has to have `num_targets` vertices. """ raise NotImplementedError() class OptimalBruteForceGraphAssignmentSolver(GraphAssignmentSolver): """ A brute-force assignment algorithm. Tests every possible permitted assignment and returns the one with the smallest (or largest, if `minimize`=False) score. """ def find_assignment(self, score_matrix, cannot_link_graph): num_targets, num_estimates = score_matrix.shape colorings = list( cannot_link_graph.enumerate_graph_colorings(num_estimates) ) if not colorings: return None # This is the old loop-based implementation. I'd like to keep it here # in case the indexing-based variant becomes too memory demanding # # best = RunningValue('min' if minimize else 'max') # # for permutation in colorings: # assert len(permutation) == num_targets, permutation # best( # score_matrix[(range(num_targets), permutation)].sum(), # permutation # ) # return best.data # The following lines create the same index as # np.arange(num_targets)[None].repeat(len(colorings), axis=0) # but without copying the elements of the arange x = np.arange(num_targets) first_index = np.lib.stride_tricks.as_strided( x, (len(colorings), x.size), (0, x.itemsize) ) # Do some intelligent indexing for speed up over for loop. The advanced # indexing creates copies of the matrix, so it could potentially become # large. scores = np.sum(score_matrix[(first_index, colorings)], axis=-1) if self.minimize: idx = np.argmin(scores) else: idx = np.argmax(scores) return colorings[idx] @dataclass class GreedyCOPGraphAssignmentSolver(GraphAssignmentSolver): """ Greedy algorithm. If used in the constrained k-means algorithm, it results in the COP-k-means [1]. Has a runtime of O(N**2 log(N)) - sort values of NxN matrix: O(N**2 log(N)) - Go through the sorted values and select the best ones respecting the constraints: O(N**2) Note: This algorithm does not always find a solution. It returns `None` if no solution is found. Returns: Permutation with shape (N). Each entry in the returned array is an index along the K axis. References: [1] Wagstaff, Kiri, <NAME>, <NAME>, and <NAME>. “Constrained K-Means Clustering with Background Knowledge,” """ def find_assignment(self, score_matrix, cannot_link_graph): if not self.minimize: score_matrix = -score_matrix num_targets, num_estimates = score_matrix.shape coloring = -np.ones(num_targets, dtype=int) # Copy the score matrix because we are going to modify it score_matrix: np.ndarray = score_matrix.copy() # score_matrix_flat is a view in score_matrix # -> changing score_matrix also changes score_matrix_flat score_matrix_flat = score_matrix.reshape(num_targets * num_estimates) mask = np.zeros(score_matrix.shape, dtype=bool) mask_flat = mask.reshape(num_targets * num_estimates) # argmax does not support axis=(-2, -1) # -> use score_matrix_flat for idx in np.argsort(score_matrix_flat): if mask_flat[idx]: # This means the whole matrix is filled with -inf. # There is no solution using this scheme. continue i, j = np.unravel_index(idx, score_matrix.shape) # Remove the usual candidates (same row) mask[i, :] = True # Remove candidates from the cannot-link graph # score_matrix[:, j] += adjacency_matrix[i] for k in cannot_link_graph.neighbors_of(i): mask[(k, j)] = True coloring[i] = j if np.any(coloring == -1): return None return coloring @dataclass class DFSGraphAssignmentSolver(GraphAssignmentSolver): """ A depth-first search algorithm for greedy permutation solving. This greedy permutation solving algorithm always finds a solution if there is one (compared to the greedy COP variant), but in the worst case tries every possible combination. This algorithm is not guaranteed to find the optimal solution. Algorithm: 1. Pick the best available score 2. Eliminate all scores that are invalid given the selection from (1) and the cannot-link graph 3. Go back to 1. If 1 does not succeed, backtrack. Note: In the worst case, this function performs the same operation as the optimal solver (i.e., tries every possible combination), but it often finds a good (but not necessarily optimal) solution faster than the optimal algorithm. Depending on the use-case and motivation, this "greedy" (it's not 100% greedy but I don't know how else to call it) solution might even be a better solution than the "optimal" one. Returns: Permutation with shape (N). Each entry in the returned array is an index along the K axis. """ def find_assignment(self, score_matrix, cannot_link_graph): stack = deque() N, K = score_matrix.shape if not self.minimize: score_matrix = -score_matrix score_matrix_flat = score_matrix.reshape(N * K) sorted_indices = np.argsort(score_matrix_flat) # a state is (coloring, sorted_index, mask, depth) # Saving a boolean mask saves some memory compared to saving the full # modified score matrix. stack.append( (-np.ones(N, dtype=int), 0, np.zeros_like(score_matrix, dtype=bool), 0) ) while stack: coloring, sorted_index, mask, depth = stack.pop() mask_flat = mask.reshape(N * K) for idx in range(sorted_index, score_matrix_flat.shape[0]): sidx = sorted_indices[idx] if mask_flat[sidx]: continue # Push current state i, j = np.unravel_index(sidx, score_matrix.shape) stack.append((coloring.copy(), idx + 1, mask.copy(), depth)) # update state coloring[i] = j mask[i, :] = True for k in cannot_link_graph.adjacency_list[i]: mask[k, j] = True depth = depth + 1 if depth == N: return coloring class OptimalBranchAndBoundGraphAssignmentSolver(GraphAssignmentSolver): """ A bran-and-bound algorithm to find the optimal solution to the graph permutation problem. Runtime: Has the same worst-case complexity as the brute-force variant, but is in many cases a lot faster. The better the scores are, the faster the algorithm becomes. """ def find_assignment(self, score_matrix, cannot_link_graph): num_targets, num_estimates = score_matrix.shape if not self.minimize: score_matrix = -score_matrix # Make sure there are no negative values in the matrix # We can subtract the minimum from each column (or is this a row?). # This could make things easier to compute score_matrix = score_matrix - np.min( score_matrix, axis=-1, keepdims=True ) assert np.all(score_matrix >= 0), score_matrix best_cost = None def find_best_permutation(cost_matrix, cost, depth): nonlocal best_cost current_vertex_costs = cost_matrix[0] best_perm = None for idx in np.argsort(current_vertex_costs): current_cost = current_vertex_costs[idx] + cost if best_cost is not None and current_cost >= best_cost: return best_perm if depth == num_targets - 1: # We are at a leaf (or, one before leaf node) best_cost = current_cost return (idx,) # We are not at a leaf _cost_matrix = cost_matrix[1:].copy() for k in cannot_link_graph.neighbors_of(depth): k = k - depth - 1 if k >= 0: _cost_matrix[(k, idx)] = float('inf') perm = find_best_permutation( _cost_matrix, current_cost, depth + 1 ) if perm is not None: best_perm = (idx,) + perm return best_perm return find_best_permutation(score_matrix, 0, 0) @dataclass class OptimalDynamicProgrammingAssignmentSolver(GraphAssignmentSolver): """ An assignment algorithm that runs in num_colors**num_colors * num_vertices time, so it is linear in the number of vertices (but exponential in the number of colors). Warnings: Assumes that the nodes are sorted so that traversing them in order never leaves more than num_colors nodes in a partial state (i.e., some of its neighbors are colored and some are not). If this
string.ljust ("Check " + testId, rpadding), line = readLine () words = line.split() expected = rrInstance.model.getFloatingSpeciesInitAmountIds() print passMsg (words != expected) def checkEigenValueIds (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () words = line.split() expected = rrInstance.getEigenvalueIds() m = rrInstance.model.getNumFloatingSpecies() for i in range(0,m): if words[i] != expected[i]: errorFlag = True break print passMsg (errorFlag) def checkGetRatesOfChangeIds (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () words = line.split() expected = rrInstance.model.getFloatingSpeciesAmountRateIds() print passMsg (expected != words) def checkSetSteadyStateSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () m = rrInstance.model.getNumFloatingSpecies() words = line.split() result = rrInstance.steadyStateSelections = words if result == False: errorFlag = True print passMsg (errorFlag) def checkGetSteadyStateSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () words = line.split() result = str(rrInstance.steadyStateSelections) print passMsg (result == words) def checkSetTimeCourseSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () words = line.split() result = rrInstance.selections = words if result == False: errorFlag = True print passMsg (errorFlag) def checkGetTimeCourseSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False line = readLine () words = line.split() result = str(rrInstance.selections) print passMsg (result == words) def checkComputeSteadyStateValues(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False list = rrInstance.steadyStateSelections ss = rrInstance.computeSteadyStateValues() words = readLine().split() for i in range (len (list)): if expectApproximately(float (words[i]), ss[i], 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkFloatingSpeciesConcentrations(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False ss = rrInstance.model.getFloatingSpeciesConcentrations() words = readLine().split() for i in range (len (ss)): if expectApproximately(float (words[i]), ss[i], 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkBoundarySpeciesConcentrations(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False ss = rrInstance.model.getBoundarySpeciesConcentrations() words = readLine().split() for i in range (len (ss)): if expectApproximately(float (words[i]), ss[i], 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkGlobalParameterValues(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False ss = rrInstance.model.getGlobalParameterValues() words = readLine().split() for i in range (len (ss)): if expectApproximately(float (words[i]), ss[i], 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkInitalFloatingSpeciesConcentations(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False ss = rrInstance.model.getFloatingSpeciesInitConcentrations() words = readLine().split() same = len(words) == len(ss) and \ len(words) == sum([1 for i,j in zip(words,ss) if expectApproximately(float (i), j, 1E-6)]) print passMsg (not same) def checkReactionRates(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False ss = rrInstance.model.getReactionRates() words = readLine().split() for i in range (len (ss)): if expectApproximately(float (words[i]), ss[i], 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkGetReactionRatesByIndex(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False words = readLine().split() n = rrInstance.model.getNumReactions() for i in range (n): value = rrInstance.model.getReactionRate (i) if expectApproximately(float (words[i]), value, 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def checkNumberOfDependentSpecies(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = int (readLine()) n = rrInstance.model.getNumDepFloatingSpecies() if n != value: errorFlag = True print passMsg (errorFlag) def checkNumberOfIndependentSpecies(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = int (readLine()) n = rrInstance.model.getNumIndFloatingSpecies() if n != value: errorFlag = True print passMsg (errorFlag) def checkInitialConditions(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False words = readLine().split() values = rrInstance.model.getFloatingSpeciesInitConcentrations() for i in range(len(words)): if expectApproximately (float (words[i]), values[i], 1E-6) == False: errorFlag = True print passMsg (errorFlag) def checkNumberOfRules(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = int (readLine()) if rrInstance.getNumRules() != value: errorFlag = True print passMsg (errorFlag) def checkGetRatesOfChange(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False words = readLine().split() values = rrInstance.model.getRatesOfChange() for i in range (len(words)): if expectApproximately (float (words[i]), values[i], 1E-6) == False: errorFlag = True print passMsg (errorFlag) def checkGetReactionRatesEx (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False inputConcs = asarray (readLine().split(), dtype=float64) values = rrInstance.getReactionRatesEx (inputConcs) outputRates = asarray (readLine().split(), dtype=float64) if not allclose (values, outputRates): errorFlag = True print passMsg (errorFlag) def checkGetRatesOfChangeEx (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False inputConcs = asarray (readLine().split(), dtype=float64) values = rrInstance.model.getRatesOfChangeEx (inputConcs) outputRates = asarray (readLine().split(), dtype=float64) if not allclose (values, outputRates): errorFlag = True print passMsg (errorFlag) def checkRateRateOfChangeByIndex(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False inputConcs = asarray (readLine().split(), dtype=float64) outputRates = asarray (readLine().split(), dtype=float64) rrInstance.setFloatingSpeciesConcentrations (inputConcs) for i in range (len (inputConcs)): value = rrInstance.getRateOfChange (i) if expectApproximately (value, outputRates[i], 1E-6) == False: errorFlag = True break print passMsg (errorFlag) # --------------------------------------------------------------------------- def setGetValues(rrInstance, IdList, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False for i in range (len(IdList)): value = random.random()*10 rrInstance.model[dList[i]] = value if expectApproximately (rrInstance.model[IdList[i]], value, 1E-6) == False: errorFlag = True break print passMsg (errorFlag) def setGetTimeStart(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = random.random ()*10 rrInstance.setTimeStart (value) if expectApproximately (rrInstance.getTimeStart (), value, 1E-6) == False: errorFlag = True print passMsg (errorFlag) def setGetTimeEnd(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = random.random ()*10 rrInstance.setTimeEnd (value) if expectApproximately (rrInstance.getTimeEnd (), value, 1E-6) == False: errorFlag = True print passMsg (errorFlag) def setGetNumberOfPoints(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False value = random.randint (1, 100) rrInstance.setNumPoints (value) if rrInstance.getNumPoints () != value: errorFlag = True print passMsg (errorFlag) def setGetTimeCourseSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False myList = rrInstance.getFloatingSpeciesIds() newList = list (myList) random.shuffle (newList) rrInstance.setTimeCourseSelectionList (newList) if rrInstance.getTimeCourseSelectionList() != newList: errorFlag = True print passMsg (errorFlag) def setGetSteadyStateSelectionList(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False myList = rrInstance.getFloatingSpeciesIds() newList = list (myList) while newList == myList: random.shuffle (newList) rrInstance.setSteadyStateSelectionList (newList) getList = rrInstance.getSteadyStateSelectionList() if getList != newList: errorFlag = True print passMsg (errorFlag) def setGetFloatingSpeciesByIndex(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False n = rrInstance.getNumFloatingSpecies() for i in range (n): value = random.random()*10 rrInstance.setFloatingSpeciesByIndex (i, value) if expectApproximately(rrInstance.getFloatingSpeciesByIndex (i), value, 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def setGetBoundarySpeciesByIndex(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False n = rrInstance.getNumBoundarySpecies() for i in range (n): value = random.random()*10 rrInstance.setBoundarySpeciesByIndex (i, value) if expectApproximately(rrInstance.getBoundarySpeciesByIndex (i), value, 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def setGetCompartmentByIndex(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False n = rrInstance.getNumCompartments() for i in range (n): value = random.random()*10 rrInstance.setCompartmentByIndex (i, value) if expectApproximately(rrInstance.getCompartmentByIndex (i), value, 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def setGetGlobalParameterByIndex (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False n = rrInstance.getNumberOfGlobalParameters() for i in range (n): value = random.random()*10 rrInstance.setGlobalParameterByIndex (i, value) if expectApproximately(rrInstance.getGlobalParameterByIndex (i), value, 1E-6) == False: errorFlag = True break; print passMsg (errorFlag) def setGetFloatingSpeciesConcentrations (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False getArray = rrInstance.getFloatingSpeciesConcentrations() setArray = zeros(len(getArray)) for i in range(len(getArray)): value = random.random()*10 setArray[i] = value rrInstance.setFloatingSpeciesConcentrations (setArray) if (setArray != rrInstance.getFloatingSpeciesConcentrations()).all(): errorFlag = True print passMsg (errorFlag) def setGetBoundarySpeciesConcentrations (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False getArray = rrInstance.getBoundarySpeciesConcentrations() setArray = zeros(len(getArray)) for i in range(len(getArray)): value = random.random()*10 setArray[i] = value rrInstance.setBoundarySpeciesConcentrations (rrInstance.PythonArrayTorrVector (setArray)) if (setArray != rrInstance.getBoundarySpeciesConcentrations()).all(): errorFlag = True print passMsg (errorFlag) def setGetInitialFloatingSpeciesConcentrations (rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False getArray = rrInstance.getFloatingSpeciesInitialConcentrations () setArray = zeros(len(getArray)) for i in range(len(getArray)): value = random.random()*10 setArray[i] = value rrInstance.setFloatingSpeciesInitialConcentrations (setArray) if (setArray != rrInstance.getFloatingSpeciesInitialConcentrations()).all(): errorFlag = True print passMsg (errorFlag) def setGetReset(rrInstance, testId): print string.ljust ("Check " + testId, rpadding), errorFlag = False values = zeros (rrInstance.getNumberOfFloatingSpecies()) for
a Tryptophan residue""" ##R-Group CA_CB_length = geo.CA_CB_length C_CA_CB_angle = geo.C_CA_CB_angle N_C_CA_CB_diangle = geo.N_C_CA_CB_diangle CB_CG_length = geo.CB_CG_length CA_CB_CG_angle = geo.CA_CB_CG_angle N_CA_CB_CG_diangle = geo.N_CA_CB_CG_diangle CG_CD1_length = geo.CG_CD1_length CB_CG_CD1_angle = geo.CB_CG_CD1_angle CA_CB_CG_CD1_diangle = geo.CA_CB_CG_CD1_diangle CG_CD2_length = geo.CG_CD2_length CB_CG_CD2_angle = geo.CB_CG_CD2_angle CA_CB_CG_CD2_diangle = geo.CA_CB_CG_CD2_diangle CD1_NE1_length = geo.CD1_NE1_length CG_CD1_NE1_angle = geo.CG_CD1_NE1_angle CB_CG_CD1_NE1_diangle = geo.CB_CG_CD1_NE1_diangle CD2_CE2_length = geo.CD2_CE2_length CG_CD2_CE2_angle = geo.CG_CD2_CE2_angle CB_CG_CD2_CE2_diangle = geo.CB_CG_CD2_CE2_diangle CD2_CE3_length = geo.CD2_CE3_length CG_CD2_CE3_angle = geo.CG_CD2_CE3_angle CB_CG_CD2_CE3_diangle = geo.CB_CG_CD2_CE3_diangle CE2_CZ2_length = geo.CE2_CZ2_length CD2_CE2_CZ2_angle = geo.CD2_CE2_CZ2_angle CG_CD2_CE2_CZ2_diangle = geo.CG_CD2_CE2_CZ2_diangle CE3_CZ3_length = geo.CE3_CZ3_length CD2_CE3_CZ3_angle = geo.CD2_CE3_CZ3_angle CG_CD2_CE3_CZ3_diangle = geo.CG_CD2_CE3_CZ3_diangle CZ2_CH2_length = geo.CZ2_CH2_length CE2_CZ2_CH2_angle = geo.CE2_CZ2_CH2_angle CD2_CE2_CZ2_CH2_diangle = geo.CD2_CE2_CZ2_CH2_diangle carbon_b = calculateCoordinates( N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle ) CB = Atom("CB", carbon_b, 0.0, 1.0, " ", " CB", 0, "C") carbon_g = calculateCoordinates( N, CA, CB, CB_CG_length, CA_CB_CG_angle, N_CA_CB_CG_diangle ) CG = Atom("CG", carbon_g, 0.0, 1.0, " ", " CG", 0, "C") carbon_d1 = calculateCoordinates( CA, CB, CG, CG_CD1_length, CB_CG_CD1_angle, CA_CB_CG_CD1_diangle ) CD1 = Atom("CD1", carbon_d1, 0.0, 1.0, " ", " CD1", 0, "C") carbon_d2 = calculateCoordinates( CA, CB, CG, CG_CD2_length, CB_CG_CD2_angle, CA_CB_CG_CD2_diangle ) CD2 = Atom("CD2", carbon_d2, 0.0, 1.0, " ", " CD2", 0, "C") nitrogen_e1 = calculateCoordinates( CB, CG, CD1, CD1_NE1_length, CG_CD1_NE1_angle, CB_CG_CD1_NE1_diangle ) NE1 = Atom("NE1", nitrogen_e1, 0.0, 1.0, " ", " NE1", 0, "N") carbon_e2 = calculateCoordinates( CB, CG, CD2, CD2_CE2_length, CG_CD2_CE2_angle, CB_CG_CD2_CE2_diangle ) CE2 = Atom("CE2", carbon_e2, 0.0, 1.0, " ", " CE2", 0, "C") carbon_e3 = calculateCoordinates( CB, CG, CD2, CD2_CE3_length, CG_CD2_CE3_angle, CB_CG_CD2_CE3_diangle ) CE3 = Atom("CE3", carbon_e3, 0.0, 1.0, " ", " CE3", 0, "C") carbon_z2 = calculateCoordinates( CG, CD2, CE2, CE2_CZ2_length, CD2_CE2_CZ2_angle, CG_CD2_CE2_CZ2_diangle ) CZ2 = Atom("CZ2", carbon_z2, 0.0, 1.0, " ", " CZ2", 0, "C") carbon_z3 = calculateCoordinates( CG, CD2, CE3, CE3_CZ3_length, CD2_CE3_CZ3_angle, CG_CD2_CE3_CZ3_diangle ) CZ3 = Atom("CZ3", carbon_z3, 0.0, 1.0, " ", " CZ3", 0, "C") carbon_h2 = calculateCoordinates( CD2, CE2, CZ2, CZ2_CH2_length, CE2_CZ2_CH2_angle, CD2_CE2_CZ2_CH2_diangle ) CH2 = Atom("CH2", carbon_h2, 0.0, 1.0, " ", " CH2", 0, "C") ##Create Residue DS res = Residue((" ", segID, " "), "TRP", " ") res.add(N) res.add(CA) res.add(C) res.add(O) res.add(CB) res.add(CG) res.add(CD1) res.add(CD2) res.add(NE1) res.add(CE2) res.add(CE3) res.add(CZ2) res.add(CZ3) res.add(CH2) return res def make_res_of_type(segID: int, N, CA, C, O, geo: Geo) -> Residue: if isinstance(geo, AceGeo): res = makeAce(segID, N, CA, C, O, geo) elif isinstance(geo, NmeGeo): res = makeNme(segID, N, CA, C, O, geo) elif isinstance(geo, GlyGeo): res = makeGly(segID, N, CA, C, O, geo) elif isinstance(geo, AlaGeo): res = makeAla(segID, N, CA, C, O, geo) elif isinstance(geo, SerGeo): res = makeSer(segID, N, CA, C, O, geo) elif isinstance(geo, CysGeo): res = makeCys(segID, N, CA, C, O, geo) elif isinstance(geo, ValGeo): res = makeVal(segID, N, CA, C, O, geo) elif isinstance(geo, IleGeo): res = makeIle(segID, N, CA, C, O, geo) elif isinstance(geo, LeuGeo): res = makeLeu(segID, N, CA, C, O, geo) elif isinstance(geo, ThrGeo): res = makeThr(segID, N, CA, C, O, geo) elif isinstance(geo, ArgGeo): res = makeArg(segID, N, CA, C, O, geo) elif isinstance(geo, LysGeo): res = makeLys(segID, N, CA, C, O, geo) elif isinstance(geo, AspGeo): res = makeAsp(segID, N, CA, C, O, geo) elif isinstance(geo, GluGeo): res = makeGlu(segID, N, CA, C, O, geo) elif isinstance(geo, AsnGeo): res = makeAsn(segID, N, CA, C, O, geo) elif isinstance(geo, GlnGeo): res = makeGln(segID, N, CA, C, O, geo) elif isinstance(geo, MetGeo): res = makeMet(segID, N, CA, C, O, geo) elif isinstance(geo, HisGeo): res = makeHis(segID, N, CA, C, O, geo) elif isinstance(geo, ProGeo): res = makePro(segID, N, CA, C, O, geo) elif isinstance(geo, PheGeo): res = makePhe(segID, N, CA, C, O, geo) elif isinstance(geo, TyrGeo): res = makeTyr(segID, N, CA, C, O, geo) elif isinstance(geo, TrpGeo): res = makeTrp(segID, N, CA, C, O, geo) else: res = makeGly(segID, N, CA, C, O, geo) return res def initialize_res(residue: Union[Geo, str]) -> Structure: """Creates a new structure containing a single amino acid. The type and geometry of the amino acid are determined by the argument, which has to be either a geometry object or a single-letter amino acid code. The amino acid will be placed into chain A of model 0.""" if isinstance(residue, Geo): geo = residue elif isinstance(residue, str): geo = geometry(residue) else: raise ValueError("Invalid residue argument:", residue) segID = 1 AA = geo.residue_name CA_N_length = geo.CA_N_length CA_C_length = geo.CA_C_length N_CA_C_angle = geo.N_CA_C_angle CA_coord = np.array([0.0, 0.0, 0.0]) C_coord = np.array([CA_C_length, 0, 0]) N_coord = np.array( [ CA_N_length * math.cos(N_CA_C_angle * (math.pi / 180.0)), CA_N_length * math.sin(N_CA_C_angle * (math.pi / 180.0)), 0, ] ) N = Atom("N", N_coord, 0.0, 1.0, " ", " N", 0, "N") # Check if the peptide is capped or not if geo.residue_name == "ACE": CA = Atom("CH3", CA_coord, 0.0, 1.0, " ", " CH3", 0, "C") else: CA = Atom("CA", CA_coord, 0.0, 1.0, " ", " CA", 0, "C") C = Atom("C", C_coord, 0.0, 1.0, " ", " C", 0, "C") ##Create Carbonyl atom (to be moved later) C_O_length = geo.C_O_length CA_C_O_angle = geo.CA_C_O_angle N_CA_C_O_diangle = geo.N_CA_C_O_diangle carbonyl = calculateCoordinates( N, CA, C, C_O_length, CA_C_O_angle, N_CA_C_O_diangle ) O = Atom("O", carbonyl, 0.0, 1.0, " ", " O", 0, "O") res = make_res_of_type(segID, N, CA, C, O, geo) cha = Chain("A") cha.add(res) mod = Model(0) mod.add(cha) struc = Structure("X") struc.add(mod) return struc def getReferenceResidue(structure: Structure, index) -> Residue: """Returns the first (index = 0) or last (index = -1) residue of chain A model 0 of the given structure. This function is a helper function that should not normally be called directly.""" # If the following line doesn't work we're in trouble. # Likely initialize_res() wasn't called. resRef = structure[0]["A"].child_list[index] name = resRef.get_resname() # If the residue is not an amino acid we're in trouble. # Likely somebody is trying to append residues to an existing # structure that has non-amino-acid molecules in the chain. if name in ["ACE", "NME"]: pass else: assert is_aa(resRef) return resRef def add_residue_from_geo(structure: Structure, geo: Geo) -> Structure: """Adds a residue to chain A model 0 of the given structure, and returns the new structure. The residue to be added is determined by the geometry object given as second argument. This function is a helper function and should not normally be called directly. Call add_residue() instead.""" resRef = getReferenceResidue(structure, -1) AA = geo.residue_name segID = resRef.get_id()[1] segID += 1 ##geometry to bring together residue peptide_bond = geo.peptide_bond CA_C_N_angle = geo.CA_C_N_angle C_N_CA_angle = geo.C_N_CA_angle ##Backbone Coordinates N_CA_C_angle = geo.N_CA_C_angle CA_N_length = geo.CA_N_length CA_C_length = geo.CA_C_length phi = geo.phi psi_im1 = geo.psi_im1 omega = geo.omega if resRef.get_resname() == "ACE": CA_name = "CH3" else: CA_name = "CA" N_coord = calculateCoordinates( resRef["N"], resRef[CA_name], resRef["C"], peptide_bond, CA_C_N_angle, psi_im1 ) N = Atom("N", N_coord, 0.0, 1.0, " ", " N", 0, "N") CA_coord = calculateCoordinates( resRef[CA_name], resRef["C"], N, CA_N_length, C_N_CA_angle, omega ) CA = Atom("CA", CA_coord, 0.0, 1.0, " ", " CA", 0, "C") C_coord = calculateCoordinates(resRef["C"], N, CA, CA_C_length, N_CA_C_angle, phi) C = Atom("C", C_coord, 0.0, 1.0, " ", " C", 0, "C") ##Create Carbonyl atom (to be moved later) C_O_length = geo.C_O_length CA_C_O_angle = geo.CA_C_O_angle N_CA_C_O_diangle = geo.N_CA_C_O_diangle carbonyl = calculateCoordinates( N, CA, C, C_O_length, CA_C_O_angle, N_CA_C_O_diangle ) O = Atom("O", carbonyl, 0.0, 1.0, " ", " O", 0, "O") if geo.residue_name == "NME": CA = Atom("CH3", CA_coord, 0.0, 1.0, " ", " CH3", 0, "C") new_CA_name = "CH3" else: new_CA_name = "CA" res = make_res_of_type(segID, N, CA, C, O, geo) resRef["O"].set_coord( calculateCoordinates( res["N"], resRef[CA_name], resRef["C"], C_O_length, CA_C_O_angle, 180.0 ) ) ghost = Atom( "N", calculateCoordinates( res["N"], res[new_CA_name], res["C"], peptide_bond, CA_C_N_angle, psi_im1 ), 0.0, 0.0, " ", "N", 0, "N", ) res["O"].set_coord( calculateCoordinates( res["N"], res[new_CA_name], res["C"], C_O_length, CA_C_O_angle, 180.0 ) ) structure[0]["A"].add(res) if geo.residue_name == "NME": if structure[0]["A"][1].get_resname() == "ACE": del structure[0]["A"][1]["N"] del structure[0]["A"][segID]["C"] del structure[0]["A"][segID]["O"] return structure def make_extended_structure(AA_chain: str, capping: bool = False) -> Structure: """Place a sequence of amino acids into a peptide in the extended conformation. The argument AA_chain holds the
""" See https://github.com/deepset-ai/haystack/issues/955 for further context """ import os import logging from copy import deepcopy from typing import Dict, Generator, List, Optional, Union import numpy as np from elasticsearch.helpers import bulk, scan from tqdm.auto import tqdm from haystack.utils import get_batches_from_generator from haystack import Document from haystack.document_store.base import BaseDocumentStore from haystack.document_store.elasticsearch import OpenDistroElasticsearchDocumentStore from haystack.retriever.base import BaseRetriever from haystack.reader.base import BaseReader from api.custom_components.bertopic import BERTopic2 from api.custom_components.top2vec import Top2Vec2 dirname = os.path.dirname(__file__) logger = logging.getLogger(__name__) class TopicRetriever(BaseRetriever): def __init__( self, document_store: BaseDocumentStore, embedding_model: str, model_format: str = "bertopic", umap_args: dict = None, hdbscan_args: dict = None, vectorizer_args: dict = None, top_k: int = 10, progress_bar: bool = True ): """ :param document_store: An instance of DocumentStore from which to retrieve documents. :param embedding_model: Local path or name of model in Hugging Face's model hub such as ``'deepset/sentence_bert'`` :param model_format: Name of framework that was used for saving the model. Options: - ``'top2vec'`` - ``'bertopic'`` :param umap_args: Pass custom arguments to UMAP. :param hdbscan_args: Pass custom arguments to HDBSCAN. :param hdbscan_args: Pass custom arguments to CountVectorizer. Only needed if model_format="bertopic". :param top_k: How many documents to return per query. :param progress_bar: If true displays progress bar during embedding. """ # # save init parameters to enable export of component config as YAML # self.set_config( # document_store=document_store, embedding_model=embedding_model, umap_args=umap_args, # hdbscan_args=hdbscan_args, top_k=top_k # ) self.document_store = document_store self.embedding_model = embedding_model self.model_format = model_format self.umap_args = umap_args self.hdbscan_args = hdbscan_args self.vectorizer_args = vectorizer_args self.top_k = top_k self.progress_bar = progress_bar logger.info(f"Init retriever using embeddings of model {embedding_model}") if self.model_format == "top2vec": raise NotImplementedError("model_format='top2vec' isn't fully implemented yet.") # self.embedding_encoder = _Top2VecEncoder(self) elif self.model_format == "bertopic": self.embedding_encoder = _BERTopicEncoder(self) else: raise ValueError("Argument model_format can only take the values 'top2vec' or 'bertopic'.") def retrieve(self, query: str, filters: dict = None, top_k: Optional[int] = None, index: str = None) -> List[Document]: """ Scan through documents in DocumentStore and return a small number documents that are most relevant to the query. :param query: The query :param filters: A dictionary where the keys specify a metadata field and the value is a list of accepted values for that field :param top_k: How many documents to return per query. :param index: The name of the index in the DocumentStore from which to retrieve documents """ if top_k is None: top_k = self.top_k if index is None: index = self.document_store.index query_emb = self.embed_queries(texts=[query]) documents = self.document_store.query_by_embedding(query_emb=query_emb[0], filters=filters, top_k=top_k, index=index) return documents def embed_queries(self, texts: List[str]) -> List[np.ndarray]: """ Create embeddings for a list of queries. :param texts: Queries to embed :return: Embeddings, one per input queries """ # for backward compatibility: cast pure str input if isinstance(texts, str): texts = [texts] assert isinstance(texts, list), "Expecting a list of texts, i.e. create_embeddings(texts=['text1',...])" return self.embedding_encoder.embed_queries(texts) def embed_queries_umap(self, texts: List[str]) -> List[np.ndarray]: """ Create UMAP embeddings for a list of queries. :param texts: Queries to embed :return: Embeddings, one per input queries """ # for backward compatibility: cast pure str input if isinstance(texts, str): texts = [texts] assert isinstance(texts, list), "Expecting a list of texts, i.e. create_embeddings(texts=['text1',...])" return self.embedding_encoder.embed_queries_umap(texts) def embed_passages(self, docs: List[Document], embeddings: np.array = None) -> List[np.ndarray]: """ Create embeddings for a list of passages. Produces the original embeddings, the UMAP embeddings, the topic number and the topic label of each document. :param docs: List of documents to embed :return: Embeddings, one per input passage """ return self.embedding_encoder.embed_passages(docs, embeddings) def run_indexing(self, documents: List[dict], **kwargs): documents = deepcopy(documents) document_objects = [Document.from_dict(doc) for doc in documents] embeddings, umap_embeddings, topic_numbers, topic_labels = self.embed_passages(document_objects) for doc, emb, umap_emb, topn, topl in zip(documents, embeddings, umap_embeddings, topic_numbers, topic_labels): doc["embedding"] = emb doc["umap_embeddings"] = umap_emb doc["topic_number"] = topn doc["topic_label"] = topl output = {**kwargs, "documents": documents} return output, "output_1" def train(self, docs: List[Document], embeddings: np.array = None): """ Trains the underlying embedding encoder model. If model_format="top2vec", a Top2Vec model will be trained, otherwise, if model_format="bertopic", a BERTopic model will be trained. :param docs: List of documents to train the model on. """ self.embedding_encoder.train(docs, embeddings) def get_topic_names(self) -> List[str]: return self.embedding_encoder.topic_names class _BERTopicEncoder(): def __init__( self, retriever: TopicRetriever ): self.saved_model_path = os.path.join(dirname, '../../artifacts/saved_models/bertopic.pkl') self.embedding_model = retriever.embedding_model self.umap_args = retriever.umap_args self.hdbscan_args = retriever.hdbscan_args self.vectorizer_args = retriever.vectorizer_args self.show_progress_bar = retriever.progress_bar if retriever.document_store.similarity != "cosine": logger.warning( f"You are using a Sentence Transformer with the {retriever.document_store.similarity} function. " f"We recommend using cosine instead. " f"This can be set when initializing the DocumentStore") # Initializing the model try: logger.info("Loading the BERTopic model from disk.") self.model = BERTopic2.load(self.saved_model_path, self.embedding_model) self.topic_names = list(self.model.topic_names.values()) except Exception as e: logger.info(f"The BERTopic model hasn't been successfuly loaded: {e}") self.model = None self.topic_names = None def embed_queries(self, texts: List[str]) -> List[np.ndarray]: self._check_is_trained() # texts can be a list of strings or a list of [title, text] # emb = self.model.embedding_model.embedding_model.encode(texts, batch_size=200, show_progress_bar=self.show_progress_bar) emb = self.model.embedding_model.embed(texts, verbose=self.show_progress_bar) emb = [r for r in emb] # get back list of numpy embedding vectors return emb def embed_queries_umap(self, texts: List[str]) -> List[np.ndarray]: embeddings = self.embed_queries(texts) umap_embeddings = self.model.umap_model.transform(np.array(embeddings)) umap_embeddings = [i for i in umap_embeddings] return umap_embeddings def embed_passages(self, docs: List[Document], embeddings: np.array = None) -> List[np.ndarray]: self._check_is_trained() passages = [[d.meta["name"] if d.meta and "name" in d.meta else "", d.text] for d in docs] # type: ignore embeddings, umap_embeddings, topic_numbers, _ = self.model.transform(passages, embeddings) topic_labels = [self.model.topic_names[i] for i in topic_numbers] return [embeddings, umap_embeddings, topic_numbers, topic_labels] def train(self, docs: List[Document], embeddings: np.array = None): # Initializing the BERTopic model from umap import UMAP from hdbscan import HDBSCAN from sklearn.feature_extraction.text import CountVectorizer if self.umap_args: umap_model = UMAP(**self.umap_args) else: umap_model = UMAP( n_neighbors=15, n_components=2, metric='cosine', random_state=1 ) if self.hdbscan_args: hdbscan_model = HDBSCAN(**self.hdbscan_args) else: hdbscan_model = HDBSCAN( min_cluster_size=15, metric='euclidean', prediction_data=True ) if self.vectorizer_args: vectorizer_model = CountVectorizer(**self.vectorizer_args) n_gram_range = self.vectorizer_args.get(['ngram_range'], (1,1)) else: vectorizer_model = CountVectorizer( ngram_range=(1, 2), stop_words="english" ) n_gram_range = (1, 2) self.model = BERTopic2( n_gram_range=n_gram_range, nr_topics=20, low_memory=True, embedding_model=self.embedding_model, umap_model=umap_model, hdbscan_model=hdbscan_model, vectorizer_model=vectorizer_model ) logger.info(f"Beginning training of BERTopic with {len(docs)} documents.") self.model = self.model.fit(docs, embeddings) self.topic_names = list(self.model.topic_names.values()) logger.info(f"Saving fitted BERTopic model to disk.") self.model.save(self.saved_model_path, save_embedding_model=False) def _check_is_trained(self): if self.model is None: raise ValueError("The BERTopic model isn't either loaded or trained yet.") class _Top2VecEncoder(): def __init__( self, retriever: TopicRetriever ): self.saved_model_path = os.path.join(dirname, '../../artifacts/saved_models/top2vec.pkl') self.embedding_model = retriever.embedding_model self.umap_args = retriever.umap_args self.hdbscan_args = retriever.hdbscan_args self.show_progress_bar = retriever.progress_bar self.document_store = retriever.document_store if self.document_store.similarity != "cosine": logger.warning( f"You are using a Sentence Transformer with the {self.document_store.similarity} function. " f"We recommend using cosine instead. " f"This can be set when initializing the DocumentStore") def embed(self, texts: Union[List[List[str]], List[str], str]) -> List[np.ndarray]: # texts can be a list of strings or a list of [title, text] # get back list of numpy embedding vectors self.model._check_model_status() # Setting the embed attribute based on the embedding_model emb = self.model.embed(texts, batch_size=200, show_progress_bar=self.show_progress_bar) emb = [r for r in emb] return emb def embed_queries(self, texts: List[str]) -> List[np.ndarray]: # Initializing the top2vec model self.init_model() return self.embed(texts) def embed_passages(self, docs: List[Document]) -> List[np.ndarray]: # Initializing the top2vec model self.init_model(docs) passages = [[d.meta["name"] if d.meta and "name" in d.meta else "", d.text] for d in docs] # type: ignore embeddings = self.embed(passages) umap_embeddings = self.model.get_umap().transform(embeddings) topic_numbers = self.model.doc_top_reduced topic_labels = self.create_topic_labels() return [embeddings, umap_embeddings, topic_numbers, topic_labels] def create_topic_labels(self): # TODO: Give more importance to words with higher score and that are unique to a cluster. # Get topic words topic_words, _, _ = self.model.get_topics(20, reduced=True) # Produce topic labels by concatenating top 5 words topic_labels = ["_".join(words[:5]) for words in topic_words] return topic_labels def init_model(self, docs=None): try: logger.info("Loading the Top2Vec model from disk.") self.model = Top2Vec2.load(self.saved_model_path) # Ensure the embedding model matches assert self.model.embedding_model == self.embedding_model, \ "The Top2Vec embedding model doesn't match the embedding model in the Retriever." # TODO: Ensure the umap_args and hdbscan_args match as well except Exception as e: logger.info(f"The Top2Vec model hasn't been trained or isn't valid: {e}") if self.document_store.get_document_count() > 1000: self.train() else: if docs is None: raise
<reponame>DataFinnovation/Arelle # -*- coding: utf-8 -*- ''' loadFromExcel.py is an example of a plug-in that will load an extension taxonomy from Excel input and optionally save an (extension) DTS. (c) Copyright 2013 Mark V Systems Limited, All rights reserved. ''' import os, io, sys, time, re, traceback, json, posixpath from fnmatch import fnmatch from collections import defaultdict, OrderedDict from arelle import PythonUtil, XbrlConst, ModelDocument, UrlUtil from arelle.PythonUtil import OrderedDefaultDict, OrderedSet from arelle.ModelDocument import Type, create as createModelDocument from arelle.ModelValue import qname, QName from arelle.XbrlConst import (qnLinkLabel, standardLabelRoles, qnLinkReference, standardReferenceRoles, qnLinkPart, gen, link, defaultLinkRole, conceptLabel, elementLabel, conceptReference, summationItem ) qnXbrldtClosed = qname("{http://xbrl.org/2005/xbrldt}xbrldt:closed") importColHeaderMap = defaultdict(list) resourceParsePattern = re.compile(r"(label[s]?|reference[s]?|relationship to),?\s*([\w][\w\s#+-:/]+[\w#+-/])(\s*[(]([^)]+)[)])?$") roleNumberPattern = re.compile(r"(.*)[#]([0-9][0-9A-Za-z]*)") xlUnicodePattern = re.compile("_x([0-9A-F]{4})_") excludeDesignatedEnumerations = False annotateEnumerationsDocumentation = False annotateElementDocumentation = False saveXmlLang = None NULLENTRY = ({},) facetSortOrder = { "fractionDigits" : "_00", "length": "_01", "minInclusive": "_02", "maxInclusive": "_03", "minExclusive": "_04", "maxExclusive": "_05", "minLength": "_06", "maxLength": "_07", "pattern": "_08", "totalDigits": "_09", "whiteSpace": "_10", "enumeration": "_11"} def loadFromExcel(cntlr, modelXbrl, excelFile, mappedUri): from openpyxl import load_workbook from arelle import ModelDocument, ModelXbrl, XmlUtil from arelle.ModelDocument import ModelDocumentReference from arelle.ModelValue import qname def xlUnicodeChar(match): return chr(int(match.group(1), 16)) def xlValue(cell): # excel values may have encoded unicode, such as _0000D_ v = cell.value if isinstance(v, str): return xlUnicodePattern.sub(xlUnicodeChar, v).replace('\r\n','\n').replace('\r','\n') return v defaultLabelLang = saveXmlLang or "en" importColumnHeaders = { "名前空間プレフィックス": "prefix", "prefix": "prefix", "要素名": "name", "name": "name", "type": "type", "typePrefix": "typePrefix", # usually part of type but optionally separate column "substitutionGroup": "substitutionGroup", "periodType": "periodType", "balance": "balance", "abstract": "abstract", # contains true if abstract "nillable": "nillable", "depth": "depth", "minLength": "minLength", "maxLength": "maxLength", "minInclusive": "minInclusive", "maxInclusive": "maxInclusive", "length": "length", "fixed": "fixed", "pattern": "pattern", "enumeration": "enumeration", "excludedEnumeration": "excludedEnumeration", "preferred label": "preferredLabel", "preferredLabel": "preferredLabel", "presentation parent": "presentationParent", # qname -- instead of label hierarchy and depth "calculation parent": "calculationParent", # qname "calculation weight": "calculationWeight", # label col heading: ("label", role, lang [indented]), "標準ラベル(日本語)": ("label", XbrlConst.standardLabel, "ja", "indented"), "冗長ラベル(日本語)": ("label", XbrlConst.verboseLabel, "ja"), "標準ラベル(英語)": ("label", XbrlConst.standardLabel, "en"), "冗長ラベル(英語)": ("label", XbrlConst.verboseLabel, "en"), "用途区分、財務諸表区分及び業種区分のラベル(日本語)": ("labels", XbrlConst.standardLabel, "ja"), "用途区分、財務諸表区分及び業種区分のラベル(英語)": ("labels", XbrlConst.standardLabel, "en"), # label [, role [(lang)]] : ("label", http resource role, lang [indented|overridePreferred]) "label": ("label", XbrlConst.standardLabel, defaultLabelLang, "indented"), "label, standard": ("label", XbrlConst.standardLabel, defaultLabelLang, "overridePreferred"), "label, terse": ("label", XbrlConst.terseLabel, defaultLabelLang), "label, verbose": ("label", XbrlConst.verboseLabel, defaultLabelLang), "label, documentation": ("label", XbrlConst.documentationLabel, defaultLabelLang), "group": "linkrole", "linkrole": "linkrole", "ELR": "linkrole", "dimension default": "dimensionDefault" # reference ("reference", reference http resource role, reference part QName) # reference, required": ("reference", "http://treasury.gov/dataact/role/taxonomyImplementationNote", qname("{http://treasury.gov/dataact/parts-2015-12-31}dataact-part:Required")) # attribute, qname (attribute on element in xsd) } fatalLoadingErrors = [] startedAt = time.time() if os.path.isabs(excelFile): # allow relative filenames to loading directory priorCWD = os.getcwd() os.chdir(os.path.dirname(excelFile)) else: priorCWD = None importExcelBook = load_workbook(excelFile, data_only=True) sheetNames = importExcelBook.get_sheet_names() dtsSheet = None if "XBRL DTS" in sheetNames: dtsSheet = "XBRL DTS" elif "DTS" in sheetNames: dtsSheet = "DTS" elif "Sheet2" in sheetNames: dtsSheet = "Sheet2" if dtsSheet: dtsWs = importExcelBook[dtsSheet] else: dtsWs = None imports = {"xbrli": ( ("namespace", XbrlConst.xbrli), ("schemaLocation", "http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd") )} # xml of imports importXmlns = {} hasPreLB = hasCalLB = hasDefLB = hasRefLB = hasGenLB = False # xxxLB structure [ (elr1, def1, "_ELR_", [roots]), (elr2, def2, "_ELR_", [rootw]) ...] # roots = (rootHref, None, "_root_", [children]) # children = (childPrefix, childName, arcrole, [grandChildren]) preLB = [] defLB = [] calLB = [] refLB = [] genLB = [] def lbDepthList(lbStruct, depth, parentList=None): if len(lbStruct) > 0: if depth == topDepth or not hasDepthColumn: return lbStruct[-1].childStruct return lbDepthList(lbStruct[-1].childStruct, depth-1, list) else: if hasDepthColumn: cntlr.addToLog("Depth error, Excel sheet: {excelSheet} row: {excelRow}" .format(excelSheet=importSheetName, excelRow=iRow), messageCode="importExcel:depth") return None splitString = None # to split repeating groups (order, depth) importFileName = None # for alternate import file importSheetNames = [] skipRows = [] # [(from,to),(from,to)] row number starting at 1 genDocs = {} # generated documents (schema + referenced linkbases) genElementsDoc = None def newDoc(name): genDocs[name] = PythonUtil.attrdict( name = name, initialComment = None, schemaDocumentation = None, extensionSchemaPrefix = "", extensionSchemaFilename = "", extensionSchemaRelDirname = None, # only non-null for relative directory path extensionSchemaNamespaceURI = "", extensionSchemaVersion = None, # <schema @version> extensionRoles = {}, # key is roleURI, value is role definition extensionRoleLabels= defaultdict(set), # key is roleURI, value is set( (lang, label) ) extensionElements = {}, extensionTypes = {}, # attrs are name, base. has facets in separate dict same as elements extensionLabels = {}, # key = (prefix, name, lang, role), value = label text extensionReferences = OrderedDefaultDict(OrderedSet), # key = (prefix, name, role) values = (partQn, text) hasEnumerationDocumentation = False, imports = {"xbrli": ( ("namespace", XbrlConst.xbrli), ("schemaLocation", "http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd") )}, # xml of imports includes = [], # just schemaLocation importXmlns = {}, importFilenames = {}, # file names relative to base childGenDocs = [], linkbaseRefs = [], labelLinkbases = [], referenceLinkbases = [], hasPreLB = False, hasCalLB = False, hasDefLB = False, hasRefLB = False, hasGenLB = False, generated = False ) return genDocs[name] thisDoc = newDoc(None) excelDir = os.path.dirname(excelFile) + os.path.sep def docRelpath(filename, baseDir=None): if baseDir is None: baseDir = thisDoc.extensionSchemaRelDirname if (baseDir is not None and not (UrlUtil.isAbsolute(filename) or os.path.isabs(filename))): return posixpath.relpath(filename, baseDir) return filename isUSGAAP = False isGenerateAndImport = True extensionPrefixForCoreLabels = None dtsActionColIndex = 0 dtsFiletypeColIndex = 1 dtsPrefixColIndex = 2 dtsFilenameColIndex = 3 dtsNamespaceURIColIndex = 4 for iRow, row in enumerate(dtsWs.rows if dtsWs else ()): try: if (len(row) < 1): # skip if col 1 is non-existent continue _col0 = row[0].value if isinstance(_col0, str) and _col0.startswith("#"): # empty or "#" continue if iRow == 0: # title row may have columns differently laid out for i, col in enumerate(row): v = xlValue(col) if isinstance(v, str): if v == "specification": dtsActionColIndex = i if v.startswith("file type"): dtsFiletypeColIndex = i if v.startswith("prefix"): dtsPrefixColIndex = i if v.startswith("file, href or role definition"): dtsFilenameColIndex = i if v.startswith("namespace URI"): dtsNamespaceURIColIndex = i continue action = filetype = prefix = filename = namespaceURI = None if len(row) > dtsActionColIndex: action = xlValue(row[dtsActionColIndex]) if len(row) > dtsFiletypeColIndex: filetype = xlValue(row[dtsFiletypeColIndex]) if len(row) > dtsPrefixColIndex: prefix = xlValue(row[dtsPrefixColIndex]) if len(row) > dtsFilenameColIndex: filename = xlValue(row[dtsFilenameColIndex]) if len(row) > dtsNamespaceURIColIndex: namespaceURI = xlValue(row[dtsNamespaceURIColIndex]) lbType = lang = None if action == "import": if filetype in ("role", "arcrole"): continue elif filetype == "schema": thisDoc.imports[prefix] = ( ("namespace", namespaceURI), ("schemaLocation", docRelpath(filename)) ) thisDoc.importXmlns[prefix] = namespaceURI thisDoc.importFilenames[prefix] = filename if re.match(r"http://[^/]+/us-gaap/", namespaceURI): isUSGAAP = True elif filetype == "linkbase": typeLang = prefix.split() if len(typeLang) > 0: lbType = typeLang[0] else: lbType = "unknown" thisDoc.linkbaseRefs.append( (lbType, filename, False) ) elif action == "include" and filename: thisDoc.includes.append(docRelpath(filename)) elif action == "xmlns" and prefix and namespaceURI: thisDoc.importXmlns[prefix] = namespaceURI elif action in ("extension", "generate"): if filetype == "schema": if prefix: # starts new document. if not thisDoc.name: del genDocs[thisDoc.name] # remove anonymous doc thisDoc = newDoc(prefix) # new doc with prefix as its name thisDoc.extensionSchemaPrefix = prefix thisDoc.extensionSchemaFilename = filename thisDoc.extensionSchemaNamespaceURI = namespaceURI if not UrlUtil.isAbsolute(filename) and not os.path.isabs(filename): thisDoc.extensionSchemaRelDirname = posixpath.dirname(filename) else: thisDoc.extensionSchemaRelDirname = None elif filetype == "linkbase": typeLang = prefix.split() if len(typeLang) > 0: lbType = typeLang[0] else: lbType = "unknown" if len(typeLang) > 1: lang = referenceRole = typeLang[1] else: lang = None referenceRole = XbrlConst.standardReference if lbType in ("label", "generic-label"): # lang, if provided, is a regex pattern thisDoc.labelLinkbases.append((lbType, lang, filename)) if action == "extension" and not extensionPrefixForCoreLabels: extensionPrefixForCoreLabels = thisDoc.extensionSchemaPrefix elif lbType in ("reference", "generic-reference"): hasRefLB = True thisDoc.referenceLinkbases.append((lbType, referenceRole, filename)) elif lbType == "presentation": thisDoc.hasPreLB = hasPreLB = True elif lbType == "definition": thisDoc.hasDefLB = hasDefLB = True elif lbType == "calculation": thisDoc.hasCalLB = hasCalLB = True elif lbType == "generic": thisDoc.hasGenLB = hasGenLB = True thisDoc.linkbaseRefs.append( (lbType, filename, True) ) elif filetype == "initialComment" and prefix: thisDoc.initialComment = prefix elif filetype == "schemaDocumentation" and prefix: thisDoc.schemaDocumentation = prefix elif filetype == "enumerationDocumentation": thisDoc.hasEnumerationDocumentation = True elif filetype == "role" and namespaceURI: # filename is definition, prefix is optional used-on QNames thisDoc.extensionRoles[namespaceURI] = (filename, prefix) elif filetype == "role label"
= Constraint(expr=m.x309*m.x309 - m.x3339*m.b3004 <= 0) m.c3411 = Constraint(expr=m.x310*m.x310 - m.x3340*m.b3004 <= 0) m.c3412 = Constraint(expr=m.x311*m.x311 - m.x3341*m.b3004 <= 0) m.c3413 = Constraint(expr=m.x312*m.x312 - m.x3342*m.b3004 <= 0) m.c3414 = Constraint(expr=m.x313*m.x313 - m.x3343*m.b3004 <= 0) m.c3415 = Constraint(expr=m.x314*m.x314 - m.x3344*m.b3004 <= 0) m.c3416 = Constraint(expr=m.x315*m.x315 - m.x3345*m.b3004 <= 0) m.c3417 = Constraint(expr=m.x316*m.x316 - m.x3346*m.b3004 <= 0) m.c3418 = Constraint(expr=m.x317*m.x317 - m.x3347*m.b3004 <= 0) m.c3419 = Constraint(expr=m.x318*m.x318 - m.x3348*m.b3004 <= 0) m.c3420 = Constraint(expr=m.x319*m.x319 - m.x3349*m.b3004 <= 0) m.c3421 = Constraint(expr=m.x320*m.x320 - m.x3350*m.b3004 <= 0) m.c3422 = Constraint(expr=m.x321*m.x321 - m.x3351*m.b3004 <= 0) m.c3423 = Constraint(expr=m.x322*m.x322 - m.x3352*m.b3004 <= 0) m.c3424 = Constraint(expr=m.x323*m.x323 - m.x3353*m.b3004 <= 0) m.c3425 = Constraint(expr=m.x324*m.x324 - m.x3354*m.b3004 <= 0) m.c3426 = Constraint(expr=m.x325*m.x325 - m.x3355*m.b3004 <= 0) m.c3427 = Constraint(expr=m.x326*m.x326 - m.x3356*m.b3004 <= 0) m.c3428 = Constraint(expr=m.x327*m.x327 - m.x3357*m.b3004 <= 0) m.c3429 = Constraint(expr=m.x328*m.x328 - m.x3358*m.b3004 <= 0) m.c3430 = Constraint(expr=m.x329*m.x329 - m.x3359*m.b3004 <= 0) m.c3431 = Constraint(expr=m.x330*m.x330 - m.x3360*m.b3004 <= 0) m.c3432 = Constraint(expr=m.x331*m.x331 - m.x3361*m.b3004 <= 0) m.c3433 = Constraint(expr=m.x332*m.x332 - m.x3362*m.b3004 <= 0) m.c3434 = Constraint(expr=m.x333*m.x333 - m.x3363*m.b3004 <= 0) m.c3435 = Constraint(expr=m.x334*m.x334 - m.x3364*m.b3004 <= 0) m.c3436 = Constraint(expr=m.x335*m.x335 - m.x3365*m.b3004 <= 0) m.c3437 = Constraint(expr=m.x336*m.x336 - m.x3366*m.b3004 <= 0) m.c3438 = Constraint(expr=m.x337*m.x337 - m.x3367*m.b3004 <= 0) m.c3439 = Constraint(expr=m.x338*m.x338 - m.x3368*m.b3004 <= 0) m.c3440 = Constraint(expr=m.x339*m.x339 - m.x3369*m.b3004 <= 0) m.c3441 = Constraint(expr=m.x340*m.x340 - m.x3370*m.b3004 <= 0) m.c3442 = Constraint(expr=m.x341*m.x341 - m.x3371*m.b3004 <= 0) m.c3443 = Constraint(expr=m.x342*m.x342 - m.x3372*m.b3004 <= 0) m.c3444 = Constraint(expr=m.x343*m.x343 - m.x3373*m.b3004 <= 0) m.c3445 = Constraint(expr=m.x344*m.x344 - m.x3374*m.b3004 <= 0) m.c3446 = Constraint(expr=m.x345*m.x345 - m.x3375*m.b3004 <= 0) m.c3447 = Constraint(expr=m.x346*m.x346 - m.x3376*m.b3004 <= 0) m.c3448 = Constraint(expr=m.x347*m.x347 - m.x3377*m.b3004 <= 0) m.c3449 = Constraint(expr=m.x348*m.x348 - m.x3378*m.b3004 <= 0) m.c3450 = Constraint(expr=m.x349*m.x349 - m.x3379*m.b3004 <= 0) m.c3451 = Constraint(expr=m.x350*m.x350 - m.x3380*m.b3004 <= 0) m.c3452 = Constraint(expr=m.x351*m.x351 - m.x3381*m.b3004 <= 0) m.c3453 = Constraint(expr=m.x352*m.x352 - m.x3382*m.b3004 <= 0) m.c3454 = Constraint(expr=m.x353*m.x353 - m.x3383*m.b3004 <= 0) m.c3455 = Constraint(expr=m.x354*m.x354 - m.x3384*m.b3004 <= 0) m.c3456 = Constraint(expr=m.x355*m.x355 - m.x3385*m.b3004 <= 0) m.c3457 = Constraint(expr=m.x356*m.x356 - m.x3386*m.b3004 <= 0) m.c3458 = Constraint(expr=m.x357*m.x357 - m.x3387*m.b3004 <= 0) m.c3459 = Constraint(expr=m.x358*m.x358 - m.x3388*m.b3004 <= 0) m.c3460 = Constraint(expr=m.x359*m.x359 - m.x3389*m.b3004 <= 0) m.c3461 = Constraint(expr=m.x360*m.x360 - m.x3390*m.b3004 <= 0) m.c3462 = Constraint(expr=m.x361*m.x361 - m.x3391*m.b3004 <= 0) m.c3463 = Constraint(expr=m.x362*m.x362 - m.x3392*m.b3004 <= 0) m.c3464 = Constraint(expr=m.x363*m.x363 - m.x3393*m.b3004 <= 0) m.c3465 = Constraint(expr=m.x364*m.x364 - m.x3394*m.b3004 <= 0) m.c3466 = Constraint(expr=m.x365*m.x365 - m.x3395*m.b3004 <= 0) m.c3467 = Constraint(expr=m.x366*m.x366 - m.x3396*m.b3004 <= 0) m.c3468 = Constraint(expr=m.x367*m.x367 - m.x3397*m.b3004 <= 0) m.c3469 = Constraint(expr=m.x368*m.x368 - m.x3398*m.b3004 <= 0) m.c3470 = Constraint(expr=m.x369*m.x369 - m.x3399*m.b3004 <= 0) m.c3471 = Constraint(expr=m.x370*m.x370 - m.x3400*m.b3004 <= 0) m.c3472 = Constraint(expr=m.x371*m.x371 - m.x3401*m.b3004 <= 0) m.c3473 = Constraint(expr=m.x372*m.x372 - m.x3402*m.b3004 <= 0) m.c3474 = Constraint(expr=m.x373*m.x373 - m.x3403*m.b3004 <= 0) m.c3475 = Constraint(expr=m.x374*m.x374 - m.x3404*m.b3004 <= 0) m.c3476 = Constraint(expr=m.x375*m.x375 - m.x3405*m.b3004 <= 0) m.c3477 = Constraint(expr=m.x376*m.x376 - m.x3406*m.b3004 <= 0) m.c3478 = Constraint(expr=m.x377*m.x377 - m.x3407*m.b3004 <= 0) m.c3479 = Constraint(expr=m.x378*m.x378 - m.x3408*m.b3004 <= 0) m.c3480 = Constraint(expr=m.x379*m.x379 - m.x3409*m.b3004 <= 0) m.c3481 = Constraint(expr=m.x380*m.x380 - m.x3410*m.b3004 <= 0) m.c3482 = Constraint(expr=m.x381*m.x381 - m.x3411*m.b3004 <= 0) m.c3483 = Constraint(expr=m.x382*m.x382 - m.x3412*m.b3004 <= 0) m.c3484 = Constraint(expr=m.x383*m.x383 - m.x3413*m.b3004 <= 0) m.c3485 = Constraint(expr=m.x384*m.x384 - m.x3414*m.b3004 <= 0) m.c3486 = Constraint(expr=m.x385*m.x385 - m.x3415*m.b3004 <= 0) m.c3487 = Constraint(expr=m.x386*m.x386 - m.x3416*m.b3004 <= 0) m.c3488 = Constraint(expr=m.x387*m.x387 - m.x3417*m.b3004 <= 0) m.c3489 = Constraint(expr=m.x388*m.x388 - m.x3418*m.b3004 <= 0) m.c3490 = Constraint(expr=m.x389*m.x389 - m.x3419*m.b3004 <= 0) m.c3491 = Constraint(expr=m.x390*m.x390 - m.x3420*m.b3004 <= 0) m.c3492 = Constraint(expr=m.x391*m.x391 - m.x3421*m.b3004 <= 0) m.c3493 = Constraint(expr=m.x392*m.x392 - m.x3422*m.b3004 <= 0) m.c3494 = Constraint(expr=m.x393*m.x393 - m.x3423*m.b3004 <= 0) m.c3495 = Constraint(expr=m.x394*m.x394 - m.x3424*m.b3004 <= 0) m.c3496 = Constraint(expr=m.x395*m.x395 - m.x3425*m.b3004 <= 0) m.c3497 = Constraint(expr=m.x396*m.x396 - m.x3426*m.b3004 <= 0) m.c3498 = Constraint(expr=m.x397*m.x397 - m.x3427*m.b3004 <= 0) m.c3499 = Constraint(expr=m.x398*m.x398 - m.x3428*m.b3004 <= 0) m.c3500 = Constraint(expr=m.x399*m.x399 - m.x3429*m.b3004 <= 0) m.c3501 = Constraint(expr=m.x400*m.x400 - m.x3430*m.b3004 <= 0) m.c3502 = Constraint(expr=m.x401*m.x401 - m.x3431*m.b3005 <= 0) m.c3503 = Constraint(expr=m.x402*m.x402 - m.x3432*m.b3005 <= 0) m.c3504 = Constraint(expr=m.x403*m.x403 - m.x3433*m.b3005 <= 0) m.c3505 = Constraint(expr=m.x404*m.x404 - m.x3434*m.b3005 <= 0) m.c3506 = Constraint(expr=m.x405*m.x405 - m.x3435*m.b3005 <= 0) m.c3507 = Constraint(expr=m.x406*m.x406 - m.x3436*m.b3005 <= 0) m.c3508 = Constraint(expr=m.x407*m.x407 - m.x3437*m.b3005 <= 0) m.c3509 = Constraint(expr=m.x408*m.x408 - m.x3438*m.b3005 <= 0) m.c3510 = Constraint(expr=m.x409*m.x409 - m.x3439*m.b3005 <= 0) m.c3511 = Constraint(expr=m.x410*m.x410 - m.x3440*m.b3005 <= 0) m.c3512 = Constraint(expr=m.x411*m.x411 - m.x3441*m.b3005 <= 0) m.c3513 = Constraint(expr=m.x412*m.x412 - m.x3442*m.b3005 <= 0) m.c3514 = Constraint(expr=m.x413*m.x413 - m.x3443*m.b3005 <= 0) m.c3515 = Constraint(expr=m.x414*m.x414 - m.x3444*m.b3005 <= 0) m.c3516 = Constraint(expr=m.x415*m.x415 - m.x3445*m.b3005 <= 0) m.c3517 = Constraint(expr=m.x416*m.x416 - m.x3446*m.b3005 <= 0) m.c3518 = Constraint(expr=m.x417*m.x417 - m.x3447*m.b3005 <= 0) m.c3519 = Constraint(expr=m.x418*m.x418 - m.x3448*m.b3005 <= 0) m.c3520 = Constraint(expr=m.x419*m.x419 - m.x3449*m.b3005 <= 0) m.c3521 = Constraint(expr=m.x420*m.x420 - m.x3450*m.b3005 <= 0) m.c3522 = Constraint(expr=m.x421*m.x421 - m.x3451*m.b3005 <= 0) m.c3523 = Constraint(expr=m.x422*m.x422 - m.x3452*m.b3005 <= 0) m.c3524 = Constraint(expr=m.x423*m.x423 - m.x3453*m.b3005 <= 0) m.c3525 = Constraint(expr=m.x424*m.x424 - m.x3454*m.b3005 <= 0) m.c3526 = Constraint(expr=m.x425*m.x425 - m.x3455*m.b3005 <= 0) m.c3527 = Constraint(expr=m.x426*m.x426 - m.x3456*m.b3005 <= 0) m.c3528 = Constraint(expr=m.x427*m.x427 - m.x3457*m.b3005 <= 0) m.c3529 = Constraint(expr=m.x428*m.x428 - m.x3458*m.b3005 <= 0) m.c3530 = Constraint(expr=m.x429*m.x429 - m.x3459*m.b3005 <= 0) m.c3531 = Constraint(expr=m.x430*m.x430 - m.x3460*m.b3005 <= 0) m.c3532 = Constraint(expr=m.x431*m.x431 - m.x3461*m.b3005 <= 0) m.c3533 = Constraint(expr=m.x432*m.x432 - m.x3462*m.b3005 <= 0) m.c3534 = Constraint(expr=m.x433*m.x433 - m.x3463*m.b3005 <= 0) m.c3535 = Constraint(expr=m.x434*m.x434 - m.x3464*m.b3005 <= 0) m.c3536 = Constraint(expr=m.x435*m.x435 - m.x3465*m.b3005 <= 0) m.c3537 = Constraint(expr=m.x436*m.x436 - m.x3466*m.b3005 <= 0) m.c3538 = Constraint(expr=m.x437*m.x437 - m.x3467*m.b3005 <= 0) m.c3539 = Constraint(expr=m.x438*m.x438 - m.x3468*m.b3005 <= 0) m.c3540 = Constraint(expr=m.x439*m.x439 - m.x3469*m.b3005 <= 0) m.c3541 = Constraint(expr=m.x440*m.x440 - m.x3470*m.b3005 <= 0) m.c3542 = Constraint(expr=m.x441*m.x441 - m.x3471*m.b3005 <= 0) m.c3543 = Constraint(expr=m.x442*m.x442 - m.x3472*m.b3005 <= 0) m.c3544 = Constraint(expr=m.x443*m.x443 - m.x3473*m.b3005 <= 0) m.c3545 = Constraint(expr=m.x444*m.x444 - m.x3474*m.b3005 <= 0) m.c3546 = Constraint(expr=m.x445*m.x445 - m.x3475*m.b3005 <= 0) m.c3547 = Constraint(expr=m.x446*m.x446 - m.x3476*m.b3005 <= 0) m.c3548 = Constraint(expr=m.x447*m.x447 - m.x3477*m.b3005 <= 0) m.c3549 = Constraint(expr=m.x448*m.x448 - m.x3478*m.b3005 <= 0) m.c3550 = Constraint(expr=m.x449*m.x449 - m.x3479*m.b3005 <= 0) m.c3551 = Constraint(expr=m.x450*m.x450 - m.x3480*m.b3005 <= 0) m.c3552 = Constraint(expr=m.x451*m.x451 - m.x3481*m.b3005 <= 0) m.c3553 = Constraint(expr=m.x452*m.x452 - m.x3482*m.b3005 <= 0) m.c3554 = Constraint(expr=m.x453*m.x453 - m.x3483*m.b3005 <= 0) m.c3555 = Constraint(expr=m.x454*m.x454 - m.x3484*m.b3005 <= 0) m.c3556 = Constraint(expr=m.x455*m.x455 - m.x3485*m.b3005 <= 0) m.c3557 = Constraint(expr=m.x456*m.x456 - m.x3486*m.b3005 <= 0) m.c3558 = Constraint(expr=m.x457*m.x457 - m.x3487*m.b3005 <= 0) m.c3559 = Constraint(expr=m.x458*m.x458 - m.x3488*m.b3005 <= 0) m.c3560 = Constraint(expr=m.x459*m.x459 - m.x3489*m.b3005 <= 0) m.c3561 = Constraint(expr=m.x460*m.x460 - m.x3490*m.b3005 <= 0) m.c3562 = Constraint(expr=m.x461*m.x461 - m.x3491*m.b3005 <= 0) m.c3563 = Constraint(expr=m.x462*m.x462 - m.x3492*m.b3005 <= 0) m.c3564 = Constraint(expr=m.x463*m.x463 - m.x3493*m.b3005 <= 0) m.c3565 = Constraint(expr=m.x464*m.x464 - m.x3494*m.b3005 <= 0) m.c3566 = Constraint(expr=m.x465*m.x465 - m.x3495*m.b3005 <= 0) m.c3567 = Constraint(expr=m.x466*m.x466 - m.x3496*m.b3005 <= 0) m.c3568 = Constraint(expr=m.x467*m.x467 - m.x3497*m.b3005 <= 0) m.c3569 = Constraint(expr=m.x468*m.x468 - m.x3498*m.b3005 <= 0) m.c3570 = Constraint(expr=m.x469*m.x469 - m.x3499*m.b3005 <= 0) m.c3571 = Constraint(expr=m.x470*m.x470 - m.x3500*m.b3005 <= 0) m.c3572 = Constraint(expr=m.x471*m.x471 - m.x3501*m.b3005 <= 0) m.c3573 = Constraint(expr=m.x472*m.x472 - m.x3502*m.b3005 <= 0) m.c3574 = Constraint(expr=m.x473*m.x473 - m.x3503*m.b3005 <= 0) m.c3575 = Constraint(expr=m.x474*m.x474 - m.x3504*m.b3005 <= 0) m.c3576 = Constraint(expr=m.x475*m.x475 - m.x3505*m.b3005 <= 0) m.c3577 = Constraint(expr=m.x476*m.x476 - m.x3506*m.b3005 <= 0) m.c3578 = Constraint(expr=m.x477*m.x477 - m.x3507*m.b3005 <= 0) m.c3579 = Constraint(expr=m.x478*m.x478 - m.x3508*m.b3005 <= 0) m.c3580 = Constraint(expr=m.x479*m.x479 - m.x3509*m.b3005 <= 0) m.c3581 = Constraint(expr=m.x480*m.x480 - m.x3510*m.b3005 <= 0) m.c3582 = Constraint(expr=m.x481*m.x481 - m.x3511*m.b3005 <= 0) m.c3583 = Constraint(expr=m.x482*m.x482 - m.x3512*m.b3005 <= 0) m.c3584 = Constraint(expr=m.x483*m.x483 - m.x3513*m.b3005 <= 0) m.c3585 = Constraint(expr=m.x484*m.x484 - m.x3514*m.b3005 <= 0) m.c3586 = Constraint(expr=m.x485*m.x485 - m.x3515*m.b3005 <= 0) m.c3587 = Constraint(expr=m.x486*m.x486 - m.x3516*m.b3005 <= 0) m.c3588 = Constraint(expr=m.x487*m.x487 - m.x3517*m.b3005 <= 0) m.c3589 = Constraint(expr=m.x488*m.x488 - m.x3518*m.b3005 <= 0) m.c3590 = Constraint(expr=m.x489*m.x489 - m.x3519*m.b3005 <= 0) m.c3591 = Constraint(expr=m.x490*m.x490 - m.x3520*m.b3005 <= 0) m.c3592 = Constraint(expr=m.x491*m.x491 - m.x3521*m.b3005 <= 0) m.c3593 = Constraint(expr=m.x492*m.x492 - m.x3522*m.b3005 <= 0) m.c3594 = Constraint(expr=m.x493*m.x493 - m.x3523*m.b3005 <= 0) m.c3595 = Constraint(expr=m.x494*m.x494 - m.x3524*m.b3005 <= 0) m.c3596 = Constraint(expr=m.x495*m.x495 - m.x3525*m.b3005 <= 0) m.c3597 = Constraint(expr=m.x496*m.x496 - m.x3526*m.b3005 <= 0) m.c3598 = Constraint(expr=m.x497*m.x497 - m.x3527*m.b3005 <= 0) m.c3599 = Constraint(expr=m.x498*m.x498 - m.x3528*m.b3005 <= 0) m.c3600 = Constraint(expr=m.x499*m.x499 - m.x3529*m.b3005 <= 0) m.c3601 = Constraint(expr=m.x500*m.x500 - m.x3530*m.b3005 <= 0) m.c3602 = Constraint(expr=m.x501*m.x501 - m.x3531*m.b3006 <= 0) m.c3603 = Constraint(expr=m.x502*m.x502 - m.x3532*m.b3006 <= 0) m.c3604 = Constraint(expr=m.x503*m.x503 - m.x3533*m.b3006 <= 0) m.c3605 = Constraint(expr=m.x504*m.x504 - m.x3534*m.b3006 <= 0) m.c3606 = Constraint(expr=m.x505*m.x505 - m.x3535*m.b3006 <= 0) m.c3607 = Constraint(expr=m.x506*m.x506 - m.x3536*m.b3006 <= 0) m.c3608 = Constraint(expr=m.x507*m.x507 - m.x3537*m.b3006 <= 0) m.c3609 = Constraint(expr=m.x508*m.x508 - m.x3538*m.b3006 <= 0) m.c3610 = Constraint(expr=m.x509*m.x509 - m.x3539*m.b3006 <= 0) m.c3611 = Constraint(expr=m.x510*m.x510 - m.x3540*m.b3006 <= 0) m.c3612 = Constraint(expr=m.x511*m.x511 - m.x3541*m.b3006 <= 0) m.c3613 = Constraint(expr=m.x512*m.x512 - m.x3542*m.b3006 <= 0) m.c3614 = Constraint(expr=m.x513*m.x513 - m.x3543*m.b3006 <= 0) m.c3615 = Constraint(expr=m.x514*m.x514 - m.x3544*m.b3006 <= 0) m.c3616 = Constraint(expr=m.x515*m.x515 - m.x3545*m.b3006 <= 0) m.c3617 = Constraint(expr=m.x516*m.x516 - m.x3546*m.b3006 <= 0) m.c3618 = Constraint(expr=m.x517*m.x517 - m.x3547*m.b3006 <= 0) m.c3619 = Constraint(expr=m.x518*m.x518 - m.x3548*m.b3006 <= 0) m.c3620 = Constraint(expr=m.x519*m.x519 - m.x3549*m.b3006 <= 0) m.c3621 = Constraint(expr=m.x520*m.x520 - m.x3550*m.b3006 <= 0) m.c3622 = Constraint(expr=m.x521*m.x521 - m.x3551*m.b3006 <= 0) m.c3623 = Constraint(expr=m.x522*m.x522
we're using # draw line between magnetic axis and the seperatrix at the outboard midplane self.obmp_pt = self.main_sep_pts[np.argmax(self.main_sep_pts, axis=0)[0]] self.ibmp_pt = self.main_sep_pts[np.argmin(self.main_sep_pts, axis=0)[0]] self.top_pt = self.main_sep_pts[np.argmax(self.main_sep_pts, axis=0)[1]] self.bot_pt = self.main_sep_pts[np.argmin(self.main_sep_pts, axis=0)[1]] rho_line = LineString([Point(self.m_axis), Point(self.obmp_pt)]) # for several points on the rho line specified above: # To get smooth gradients for use in the SOL calculation, you need around # 50-100 radial points in the far edge and around 100 or so theta points # TODO: There is almost certainly a faster way to get these gradients. rho_pts = np.concatenate((np.linspace(0, 0.95, 20, endpoint=False), np.linspace(0.95, 1, 50, endpoint=False)), axis=0) thetapts = np.linspace(0, 1, 100, endpoint=False) for i, rho in enumerate(rho_pts): # get n, T information at the point by interpolating the rho-based input file data ni_val = ni(rho) ne_val = ne(rho) Ti_kev_val = Ti_kev(rho) Te_kev_val = Te_kev(rho) # Set value to the last experimental data point if interpolators are creating negative values if ne_val <= 0.0: ne_val = self.ne_data[:, 1][-1] if ni_val <= 0.0: ni_val = self.ni_data[:, 1][-1] if Te_kev_val <= 0.0: Te_kev_val = self.Te_data[:, 1][-1] if Ti_kev_val <= 0.0: Ti_kev_val = self.Ti_data[:, 1][-1] # get R, Z coordinates of each point along the rho_line pt_coords = np.asarray(rho_line.interpolate(rho, normalized=True).coords)[0] # get psi value at that point psi_val = griddata(np.column_stack((self.R.flatten(), self.Z.flatten())), self.psi_norm.flatten(), pt_coords, method='linear') # map this n, T data to every point on the corresponding flux surface num_lines = int(len(plt.contour(self.R, self.Z, self.psi_norm, [psi_val], colors='r').collections[0].get_paths())) # num_lines = int(len(cntr.contour(self.R, self.Z, self.psi_norm).trace(psi_val))/2) if num_lines == 1: # then we're definitely dealing with a surface inside the seperatrix x, y = draw_line(self.R, self.Z, self.psi_norm, psi_val, 0) surf = LineString(np.column_stack((x, y))) else: # we need to find which of the surfaces is inside the seperatrix for j, line in enumerate( plt.contour(self.R, self.Z, self.psi_norm, [psi_val], colors='r').collections[0].get_paths()[:num_lines]): # for j, line in enumerate(cntr.contour(self.R, self.Z, self.psi_norm).trace(psi_val)[:num_lines]): # for j, line in enumerate(cntr.contour(R, Z, self.psi_norm).trace(v)): x, y = draw_line(self.R, self.Z, self.psi_norm, psi_val, j) if (np.amax(x) < np.amax(self.main_sep_pts[:, 0]) and \ np.amin(x) > np.amin(self.main_sep_pts[:, 0]) and \ np.amax(y) < np.amax(self.main_sep_pts[:, 1]) and \ np.amin(y) > np.amin(self.main_sep_pts[:, 1])): # then it's an internal flux surface surf = LineString(np.column_stack((x, y))) break for j, theta_norm in enumerate(thetapts): pt = np.asarray(surf.interpolate(theta_norm, normalized=True).coords).T self.ni_pts = np.vstack((self.ni_pts, np.append(pt, ni_val))) self.ne_pts = np.vstack((self.ne_pts, np.append(pt, ne_val))) self.Ti_kev_pts = np.vstack((self.Ti_kev_pts, np.append(pt, Ti_kev_val))) self.Te_kev_pts = np.vstack((self.Te_kev_pts, np.append(pt, Te_kev_val))) # Do seperatrix separately so we don't accidentally assign the input n, T data to the divertor legs self.ni_sep_val = self.ni_data[:, 1][-1] self.ne_sep_val = self.ne_data[:, 1][-1] self.Ti_kev_sep_val = self.Ti_data[:, 1][-1] self.Te_kev_sep_val = self.Te_data[:, 1][-1] self.Ti_J_sep_val = self.Ti_kev_sep_val * 1.0E3 * 1.6021E-19 self.Te_J_sep_val = self.Te_kev_sep_val * 1.0E3 * 1.6021E-19 for j, theta_norm in enumerate(thetapts): pt = np.asarray(self.main_sep_line.interpolate(theta_norm, normalized=False).coords, dtype='float').T self.ni_pts = np.vstack((self.ni_pts, np.append(pt, self.ni_sep_val))) self.ne_pts = np.vstack((self.ne_pts, np.append(pt, self.ne_sep_val))) self.Ti_kev_pts = np.vstack((self.Ti_kev_pts, np.append(pt, self.Ti_kev_sep_val))) self.Te_kev_pts = np.vstack((self.Te_kev_pts, np.append(pt, self.Te_kev_sep_val))) def _sol_nT(self): # Calculate n, T in SOL using Bohm diffusion, core data from radial profile input files, and input # divertor target densities and temperatures (replace with 2-pt divertor model later) # draw core line just inside the seperatrix (seperatrix would be too noisy absent SOL data, which is what we're trying to calculate) psi_val = 0.98 num_lines = int(len(plt.contour(self.R, self.Z, self.psi_norm, [psi_val]).collections[0].get_paths())) # num_lines = int(len(cntr.contour(self.R, self.Z, self.psi_norm).trace(psi_val))/2) if num_lines == 1: # then we're definitely dealing with a surface inside the seperatrix x, y = draw_line(self.R, self.Z, self.psi_norm, psi_val, 0) else: # we need to find which of the surfaces is inside the seperatrix for j, line in enumerate( plt.contour(self.R, self.Z, self.psi_norm, [psi_val]).collections[0].get_paths()[:num_lines]): # for j, line in enumerate(cntr.contour(self.R, self.Z, self.psi_norm).trace(psi_val)[:num_lines]): # for j, line in enumerate(cntr.contour(R, Z, self.psi_norm).trace(v)): x, y = draw_line(self.R, self.Z, self.psi_norm, psi_val, j) if (np.amax(x) < np.amax(self.main_sep_pts[:, 0]) and \ np.amin(x) > np.amin(self.main_sep_pts[:, 0]) and \ np.amax(y) < np.amax(self.main_sep_pts[:, 1]) and \ np.amin(y) > np.amin(self.main_sep_pts[:, 1])): # then it's an internal flux surface break # get quantities on a fairly fine R, Z grid for the purpose of taking gradients, etc. R_temp, Z_temp = np.meshgrid(np.linspace(0.95 * self.ibmp_pt[0], 1.05 * self.obmp_pt[0], 500), np.linspace(1.05 * self.top_pt[1], 1.05 * self.bot_pt[1], 500)) ni_grid = griddata(self.ni_pts[:, :-1], self.ni_pts[:, -1], (R_temp, Z_temp), method='linear', fill_value=self.ni_sep_val) ne_grid = griddata(self.ne_pts[:, :-1], self.ne_pts[:, -1], (R_temp, Z_temp), method='linear', fill_value=self.ne_sep_val) Ti_grid = griddata(self.Ti_kev_pts[:, :-1], self.Ti_kev_pts[:, -1] * 1.0E3 * 1.6021E-19, (R_temp, Z_temp), method='linear', fill_value=self.Ti_J_sep_val) Te_grid = griddata(self.Te_kev_pts[:, :-1], self.Te_kev_pts[:, -1] * 1.0E3 * 1.6021E-19, (R_temp, Z_temp), method='linear', fill_value=self.Te_J_sep_val) dnidr = -1.0 * (np.abs(np.gradient(ni_grid, Z_temp[:, 0], axis=1)) + np.abs( np.gradient(ni_grid, R_temp[0, :], axis=0))) dnedr = -1.0 * (np.abs(np.gradient(ne_grid, Z_temp[:, 0], axis=1)) + np.abs( np.gradient(ne_grid, R_temp[0, :], axis=0))) dTidr = -1.0 * (np.abs(np.gradient(Ti_grid, Z_temp[:, 0], axis=1)) + np.abs( np.gradient(Ti_grid, R_temp[0, :], axis=0))) dTedr = -1.0 * (np.abs(np.gradient(Te_grid, Z_temp[:, 0], axis=1)) + np.abs( np.gradient(Te_grid, R_temp[0, :], axis=0))) # Get densities, temperatures, and other quantities along the flux surface we just drew # note densities and temperatures on seperatrix are assumed to be constant for all theta and are # obtained above, i.e. self.ni_sep_val, etc. dnidr_sep_raw = griddata(np.column_stack((R_temp.flatten(), Z_temp.flatten())), dnidr.flatten(), np.column_stack((x, y)), method='linear' ) dnedr_sep_raw = griddata(np.column_stack((R_temp.flatten(), Z_temp.flatten())), dnedr.flatten(), np.column_stack((x, y)), method='linear' ) dTidr_sep_raw = griddata(np.column_stack((R_temp.flatten(), Z_temp.flatten())), dTidr.flatten(), np.column_stack((x, y)), method='linear' ) dTedr_sep_raw = griddata(np.column_stack((R_temp.flatten(), Z_temp.flatten())), dTedr.flatten(), np.column_stack((x, y)), method='linear' ) BT_sep_raw = griddata(np.column_stack((R_temp.flatten(), Z_temp.flatten())), (self.m_axis[0] * self.BT0 / R_temp).flatten(), np.column_stack((x, y)), method='linear' ) # Get densities, temperatures, and other quantities along the inboard divertor leg of seperatrix # doing linear interpolation in the absense of a 1D model # Get densities, temperatures, and other quantities along the outboard divertor leg of seperatrix # norm factor used to divide by the order of magnitude to facilitate easier smoothing ni_norm_factor = 1.0 # *10**(int(np.log10(np.average(dnidr_sep)))-1) ne_norm_factor = 1.0 # *10**(int(np.log10(np.average(dnedr_sep)))-1) Ti_norm_factor = 1.0 # *10**(int(np.log10(np.average(dTidr_sep)))-1) Te_norm_factor = 1.0 # *10**(int(np.log10(np.average(dTedr_sep)))-1) # specify the number of xi (parallel) points in the seperatrix region of the 2 point divertor model ni_sep = np.zeros(self.xi_sep_pts) + self.ni_sep_val ne_sep = np.zeros(self.xi_sep_pts) + self.ne_sep_val Ti_sep = np.zeros(self.xi_sep_pts) + self.Ti_J_sep_val Te_sep = np.zeros(self.xi_sep_pts) + self.Te_J_sep_val dnidr_sep = UnivariateSpline(np.linspace(0, 1, len(dnidr_sep_raw)), dnidr_sep_raw / ni_norm_factor, k=1, s=2.0)( np.linspace(self.ib_trim_off, 1.0 - self.ob_trim_off, self.xi_sep_pts)) * ni_norm_factor dnedr_sep = UnivariateSpline(np.linspace(0, 1, len(dnedr_sep_raw)), dnedr_sep_raw / ne_norm_factor, k=1, s=2.0)( np.linspace(self.ib_trim_off, 1.0 - self.ob_trim_off, self.xi_sep_pts)) * ne_norm_factor dTidr_sep = UnivariateSpline(np.linspace(0, 1, len(dTidr_sep_raw)), dTidr_sep_raw / Ti_norm_factor, k=1, s=2.0)( np.linspace(self.ib_trim_off, 1.0 - self.ob_trim_off, self.xi_sep_pts)) * Ti_norm_factor dTedr_sep = UnivariateSpline(np.linspace(0, 1, len(dTedr_sep_raw)), dTedr_sep_raw / Te_norm_factor, k=1, s=2.0)( np.linspace(self.ib_trim_off, 1.0 - self.ob_trim_off, self.xi_sep_pts)) * Te_norm_factor BT_sep = UnivariateSpline(np.linspace(0, 1, len(dnidr_sep_raw)), BT_sep_raw, k=1, s=2.0)(np.linspace(self.ib_trim_off, 1.0 - self.ob_trim_off, self.xi_sep_pts)) ni_ib_wall = self.ni_sep_val * 1.0 ni_ob_wall = self.ni_sep_val * 1.0 ni_ib = np.linspace(ni_ib_wall, self.ni_sep_val, self.xi_ib_pts, endpoint=False) ni_ob = np.linspace(self.ni_sep_val, ni_ob_wall, self.xi_ob_pts, endpoint=True) ne_ib_wall = self.ne_sep_val * 1.0 ne_ob_wall = self.ne_sep_val * 1.0 ne_ib = np.linspace(ne_ib_wall, self.ne_sep_val, self.xi_ib_pts, endpoint=False) ne_ob = np.linspace(self.ne_sep_val, ne_ob_wall, self.xi_ob_pts, endpoint=True) Ti_ib_wall = self.Ti_J_sep_val * 1.0 Ti_ob_wall = self.Ti_J_sep_val * 1.0 Ti_ib = np.linspace(Ti_ib_wall, self.Ti_J_sep_val, self.xi_ib_pts, endpoint=False) Ti_ob = np.linspace(self.Ti_J_sep_val, Ti_ob_wall, self.xi_ob_pts, endpoint=True) Te_ib_wall = self.Te_J_sep_val * 1.0 Te_ob_wall = self.Te_J_sep_val * 1.0 Te_ib = np.linspace(Te_ib_wall, self.Te_J_sep_val, self.xi_ib_pts, endpoint=False) Te_ob = np.linspace(self.Te_J_sep_val, Te_ob_wall, self.xi_ob_pts, endpoint=True) dnidr_ib_wall = dnidr_sep[0] dnidr_ob_wall = dnidr_sep[-1] dnidr_ib = np.linspace(dnidr_ib_wall, dnidr_sep[0], self.xi_ib_pts, endpoint=False) dnidr_ob = np.linspace(dnidr_sep[-1], dnidr_ob_wall, self.xi_ob_pts, endpoint=True) dnedr_ib_wall = dnedr_sep[0] dnedr_ob_wall = dnedr_sep[-1] dnedr_ib = np.linspace(dnedr_ib_wall, dnedr_sep[0], self.xi_ib_pts, endpoint=False) dnedr_ob = np.linspace(dnedr_sep[-1], dnedr_ob_wall, self.xi_ob_pts, endpoint=True) dTidr_ib_wall = dTidr_sep[0] dTidr_ob_wall = dTidr_sep[-1] dTidr_ib = np.linspace(dTidr_ib_wall, dTidr_sep[0], self.xi_ib_pts, endpoint=False) dTidr_ob = np.linspace(dTidr_sep[-1], dTidr_ob_wall, self.xi_ob_pts, endpoint=True) dTedr_ib_wall = dTedr_sep[0] dTedr_ob_wall = dTedr_sep[-1] dTedr_ib = np.linspace(dTedr_ib_wall, dTedr_sep[0], self.xi_ib_pts, endpoint=False) dTedr_ob = np.linspace(dTedr_sep[-1], dTedr_ob_wall, self.xi_ob_pts, endpoint=True) BT_ib_wall = BT_sep[0] BT_ob_wall = BT_sep[-1] BT_ib = np.linspace(BT_ib_wall, BT_sep[0], self.xi_ib_pts, endpoint=False) BT_ob = np.linspace(BT_sep[-1], BT_ob_wall, self.xi_ob_pts, endpoint=True) ni_xi = np.concatenate((ni_ib, ni_sep, ni_ob)) ne_xi = np.concatenate((ne_ib, ne_sep, ne_ob)) Ti_xi = np.concatenate((Ti_ib, Ti_sep, Ti_ob)) Te_xi = np.concatenate((Te_ib, Te_sep, Te_ob)) dnidr_xi = np.concatenate((dnidr_ib, dnidr_sep, dnidr_ob)) dnedr_xi = np.concatenate((dnedr_ib, dnedr_sep, dnedr_ob)) dTidr_xi = np.concatenate((dTidr_ib, dTidr_sep, dTidr_ob)) dTedr_xi = np.concatenate((dTedr_ib, dTedr_sep, dTedr_ob)) BT_xi = np.concatenate((BT_ib, BT_sep, BT_ob)) ib_leg_length = self.ib_div_line_cut.length ob_leg_length = self.ob_div_line_cut.length sep_length = self.main_sep_line_closed.length ib_frac = ib_leg_length / (ib_leg_length