input
stringlengths
2.65k
237k
output
stringclasses
1 value
<filename>src/microstructpy/meshing/trimesh.py """Triangle/Tetrahedron Meshing This module contains the class definition for the TriMesh class. """ # --------------------------------------------------------------------------- # # # # Import Modules # # # # --------------------------------------------------------------------------- # from __future__ import division from __future__ import print_function import meshpy.tet import meshpy.triangle import numpy as np from matplotlib import collections from matplotlib import patches from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from microstructpy import _misc __all__ = ['TriMesh'] __author__ = 'Kenneth (<NAME>' # --------------------------------------------------------------------------- # # # # TriMesh Class # # # # --------------------------------------------------------------------------- # class TriMesh(object): """Triangle/Tetrahedron mesh. The TriMesh class contains the points, facets, and elements in a triangle/ tetrahedron mesh, also called an unstructured grid. The points attribute is an Nx2 or Nx3 list of points in the mesh. The elements attribute contains the Nx3 or Nx4 list of the points at the corners of each triangle/tetrahedron. A list of facets can also be included, though it is optional and does not need to include every facet in the mesh. Attributes can also be assigned to the elements and facets, though they are also optional. Args: points (list, numpy.ndarray): List of coordinates in the mesh. elements (list, numpy.ndarray): List of indices of the points at the corners of each element. The shape should be Nx3 in 2D or Nx4 in 3D. element_attributes (list, numpy.ndarray): *(optional)* A number associated with each element. Defaults to None. facets (list, numpy.ndarray): *(optional)* A list of facets in the mesh. The shape should be Nx2 in 2D or Nx3 in 3D. Defaults to None. facet_attributes (list, numpy.ndarray): *(optional)* A number associated with each facet. Defaults to None. """ # ----------------------------------------------------------------------- # # Constructors # # ----------------------------------------------------------------------- # def __init__(self, points, elements, element_attributes=None, facets=None, facet_attributes=None): self.points = points self.elements = elements self.element_attributes = element_attributes self.facets = facets self.facet_attributes = facet_attributes @classmethod def from_file(cls, filename): """Read TriMesh from file. This function reads in a triangular mesh from a file and creates an instance from that file. Currently the only supported file type is the output from :meth:`.write` with the ``format='str'`` option. Args: filename (str): Name of file to read from. Returns: TriMesh: An instance of the class. """ with open(filename, 'r') as file: stage = 0 pts = [] elems = [] elem_atts = [] facets = [] facet_atts = [] n_eas = 0 n_facets = 0 n_fas = 0 for line in file.readlines(): if 'Mesh Points'.lower() in line.lower(): n_pts = int(line.split(':')[1]) stage = 'points' elif 'Mesh Elements'.lower() in line.lower(): n_elems = int(line.split(':')[1]) stage = 'elements' elif 'Element Attributes'.lower() in line.lower(): n_eas = int(line.split(':')[1]) stage = 'element attributes' elif 'Facets'.lower() in line.lower(): n_facets = int(line.split(':')[1]) stage = 'facets' elif 'Facet Attributes'.lower() in line.lower(): n_fas = int(line.split(':')[1]) stage = 'facet attributes' else: if stage == 'points': pts.append([float(x) for x in line.split(',')]) elif stage == 'elements': elems.append([int(kp) for kp in line.split(',')]) elif stage == 'element attributes': elem_atts.append(_misc.from_str(line)) elif stage == 'facets': facets.append([int(kp) for kp in line.split(',')]) elif stage == 'facet attributes': facet_atts.append(_misc.from_str(line)) else: pass # check the inputs assert len(pts) == n_pts assert len(elems) == n_elems assert len(elem_atts) == n_eas assert len(facets) == n_facets assert len(facet_atts) == n_fas return cls(pts, elems, elem_atts, facets, facet_atts) @classmethod def from_polymesh(cls, polymesh, phases=None, min_angle=0, max_volume=float('inf'), max_edge_length=float('inf')): """Create TriMesh from PolyMesh. This constuctor creates a triangle/tetrahedron mesh from a polygon mesh (:class:`.PolyMesh`). Polygons of the same seed number are merged and the element attribute is set to the seed number it is within. The facets between seeds are saved to the mesh and the index of the facet is stored in the facet attributes. Since the PolyMesh can include phase numbers for each region, additional information about the phases can be included as an input. The "phases" input should be a list of material phase dictionaries, formatted according to the :ref:`phase_dict_guide` guide. The minimum angle, maximum volume, and maximum edge length options provide quality controls for the mesh. The phase type option can take one of several values, described below. * **crystalline**: granular, solid * **amorphous**: glass, matrix * **void**: crack, hole The **crystalline** option creates a mesh where cells of the same seed number are merged, but cells are not merged across seeds. _This is the default material type._ The **amorphous** option creates a mesh where cells of the same phase number are merged to create an amorphous region in the mesh. Finally, the **void** option will merge neighboring void cells and treat them as holes in the mesh. Args: polymesh (PolyMesh): A polygon/polyhedron mesh. phases (list): *(optional)* A list of dictionaries containing options for each phase. Default is ``{'material_type': 'solid', 'max_volume': float('inf')}``. min_angle (float): The minimum interior angle of an element. max_volume (float): The default maximum cell volume, used if one is not set for each phase. max_edge_length (float): The maximum edge length of elements along grain boundaries. Currently only supported in 2D. """ # condition the phases input if phases is None: default_dict = {'material_type': 'solid', 'max_volume': float('inf')} n_phases = int(np.max(polymesh.phase_numbers)) + 1 phases = [default_dict for _ in range(n_phases)] # create point and facet lists kps = {} pts = [] facets = [] facet_neighs = [] facet_nums = [] for i in range(len(polymesh.facets)): facet = polymesh.facets[i] neighs = polymesh.facet_neighbors[i] if facet_check(neighs, polymesh, phases): new_facet = [] for kp_old in facet: if kp_old not in kps: kp_new = len(pts) pts.append(polymesh.points[kp_old]) kps[kp_old] = kp_new else: kp_new = kps[kp_old] new_facet.append(kp_new) facets.append(new_facet) facet_neighs.append(neighs) facet_nums.append(i + 1) # Subdivide facets n_dim = len(pts[0]) if n_dim == 2: n_subs = np.ones(len(facets), dtype='int') for i, facet in enumerate(facets): pt1 = np.array(pts[facet[0]]) pt2 = np.array(pts[facet[1]]) rel_pos = pt2 - pt1 n_float = np.linalg.norm(rel_pos) / max_edge_length n_int = max(1, np.ceil(n_float)) n_subs[i] = n_int sub_out = meshpy.triangle.subdivide_facets(n_subs, pts, facets, facet_nums) pts, facets, facet_nums = sub_out # create groups/regions pts_arr = np.array(polymesh.points) regions = [] holes = [] ungrouped = np.full(len(polymesh.regions), True, dtype='?') while np.any(ungrouped): cell_ind = np.argmax(ungrouped) # compute cell center facet_list = polymesh.regions[cell_ind] cell_kps = set() [cell_kps.update(polymesh.facets[n]) for n in facet_list] cell_cen = pts_arr[list(cell_kps)].mean(axis=0) # seed number and phase type seed_num = int(polymesh.seed_numbers[cell_ind]) phase_num = polymesh.phase_numbers[cell_ind] phase = phases[phase_num] phase_type = phase.get('material_type', 'crystalline') phase_vol = phase.get('max_volume', max_volume) # get all cell numbers in group cell_nums = set([cell_ind]) old_len = len(cell_nums) searching_front = True while searching_front: front = set() for n in cell_nums: neighs = set() for facet_num in polymesh.regions[n]: f_neighs = polymesh.facet_neighbors[facet_num] neigh_ind = [i for i in f_neighs if i != n][0] if neigh_ind < 0: continue if not facet_check(f_neighs, polymesh, phases): neighs.add(neigh_ind) assert ungrouped[list(neighs)].all() front.update(neighs) cell_nums |= front new_len = len(cell_nums) searching_front = new_len != old_len old_len = new_len ungrouped[list(cell_nums)] = False # update appropriate list if phase_type in _misc.kw_void: holes.append(cell_cen) else: regions.append(cell_cen.tolist() + [seed_num, phase_vol]) # build inputs if n_dim == 2: info = meshpy.triangle.MeshInfo() else: info = meshpy.tet.MeshInfo() info.set_points(pts) info.set_facets(facets, facet_nums) info.set_holes(holes) info.regions.resize(len(regions)) for i, r in enumerate(regions): info.regions[i] = tuple(r) # run MeshPy if n_dim == 2: tri_mesh = meshpy.triangle.build(info, attributes=True, volume_constraints=True, max_volume=max_volume, min_angle=min_angle, generate_faces=True) else: opts = meshpy.tet.Options('pq') opts.mindihedral = min_angle opts.maxvolume = max_volume opts.fixedvolume = 1 opts.regionattrib = 1 opts.facesout = 1 tri_mesh = meshpy.tet.build(info, options=opts) # return mesh tri_pts = np.array(tri_mesh.points) tri_elems = np.array(tri_mesh.elements) tri_e_atts = np.array(tri_mesh.element_attributes, dtype='int') tri_faces = np.array(tri_mesh.faces) tri_f_atts = np.array(tri_mesh.face_markers) f_mask = tri_f_atts > 0 tri_f = tri_faces[f_mask] tri_fa = tri_f_atts[f_mask] - 1 return cls(tri_pts, tri_elems, tri_e_atts, tri_f, tri_fa) # ----------------------------------------------------------------------- # # String and Representation Functions # # ----------------------------------------------------------------------- # def __str__(self): nv = len(self.points) nd = len(self.points[0]) pt_fmt = '\t' pt_fmt += ', '.join(['{pt[' + str(i) + ']: e}' for i in range(nd)]) str_str = 'Mesh Points: ' + str(nv) + '\n' str_str += ''.join([pt_fmt.format(pt=p) + '\n' for p in self.points]) str_str += 'Mesh Elements: ' + str(len(self.elements)) + '\n' str_str += '\n'.join(['\t' + str(tuple(e))[1:-1] for e in self.elements]) try: str_str += '\nElement Attributes: ' str_str += str(len(self.element_attributes)) + '\n' str_str += '\n'.join(['\t' + str(a) for a in self.element_attributes]) except TypeError: pass try: str_str += '\nFacets: ' + str(len(self.facets)) + '\n' str_str
qty, uom_id in lines: prod = get_model("product").browse(prod_id) line_vals = { "product_id": prod_id, "description": prod.description or "/", "qty": qty, "uom_id": uom_id, "unit_price": prod.purchase_price or 0, "tax_id": prod.purchase_tax_id.id, "sale_id": obj.id, } purch_vals["lines"].append(("create", line_vals)) po_id = get_model("purchase.order").create(purch_vals) po_ids.append(po_id) po_objs = get_model("purchase.order").browse(po_ids) return { "next": { "name": "purchase", "search_condition": [["ref", "=", obj.number]], }, "flash": "Purchase orders created successfully: " + ", ".join([po.number for po in po_objs]), } def copy_to_production(self, ids, context={}): order_ids = [] mfg_orders = {} for obj in self.browse(ids): for line in obj.lines: prod = line.product_id if not prod: continue if prod.procure_method != "mto" or prod.supply_method != "production": continue if line.production_id: raise Exception("Production order already created for sales order %s, product %s"%(obj.number,prod.code)) due_date=line.due_date or obj.due_date if due_date: raise Exception("Missing due date in sales order %s"%obj.number) if not prod.mfg_lead_time: raise Exception("Missing manufacturing lead time in product %s"%prod.code) k=(prod.id,due_date) mfg_orders.setdefault(k,[]).append(line.id) for (prod_id,due_date),sale_line_ids in mfg_orders.items(): prod=get_model("product").browse(prod_id) res=get_model("bom").search([["product_id","=",prod.id]]) # TODO: select bom in separate function if not res: raise Exception("BoM not found for product '%s'" % prod.name) bom_id = res[0] bom = get_model("bom").browse(bom_id) loc_id = bom.location_id.id if not loc_id: raise Exception("Missing FG location in BoM %s" % bom.number) routing = bom.routing_id if not routing: raise Exception("Missing routing in BoM %s" % bom.number) loc_prod_id = routing.location_id.id if not loc_prod_id: raise Exception("Missing production location in routing %s" % routing.number) uom = prod.uom_id mfg_qty=0 for line in get_model("sale.order.line").browse(sale_line_ids): if line.qty_stock: qty = line.qty_stock else: qty = get_model("uom").convert(line.qty, line.uom_id.id, uom.id) mfg_qty+=qty if not prod.mfg_lead_time: raise Exception("Missing manufacturing lead time for product %s"%prod.code) mfg_date=(datetime.strptime(due_date,"%Y-%m-%d")-timedelta(days=prod.mfg_lead_time)).strftime("%Y-%m-%d") order_vals = { "product_id": prod.id, "qty_planned": mfg_qty, "uom_id": uom.id, "bom_id": bom_id, "routing_id": routing.id, "production_location_id": loc_prod_id, "location_id": loc_id, "order_date": mfg_date, "due_date": due_date, "state": "waiting_confirm", } order_id = get_model("production.order").create(order_vals) get_model("production.order").create_components([order_id]) get_model("production.order").create_operations([order_id]) order_ids.append(order_id) get_model("sale.order.line").write(sale_line_ids,{"production_id":order_id}) if not order_ids: return { "flash": "No production orders to create", } get_model("production.order").copy_to_production_all(order_ids) return { "flash": "Production orders created successfully", } def get_production_status(self, ids, context={}): vals = {} for obj in self.browse(ids): num_done = 0 num_total = 0 for prod in obj.production_orders: if prod.state == "done": num_done += 1 if prod.state not in ("voided", "split"): num_total += 1 if num_total != 0: percent = num_done * 100 / num_total vals[obj.id] = { "percent": percent, "string": "%d / %d" % (num_done, num_total) } else: vals[obj.id] = None return vals def get_overdue(self, ids, context={}): vals = {} for obj in self.browse(ids): if obj.due_date: vals[obj.id] = obj.due_date < time.strftime("%Y-%m-%d") and obj.state in ("draft", "waiting", "ready") else: vals[obj.id] = False return vals def search_overdue(self, clause, context={}): return [["due_date", "<", time.strftime("%Y-%m-%d")], ["state", "in", ["draft", "waiting", "ready"]]] def get_amount_total_words(self, ids, context={}): vals = {} for obj in self.browse(ids): amount_total_words = utils.num2word(obj.amount_total) vals[obj.id] = amount_total_words return vals def approve(self, ids, context={}): if not check_permission_other("sale_approve_done"): raise Exception("Permission denied") obj = self.browse(ids)[0] user_id = get_active_user() obj.write({"approved_by_id": user_id}) return { "next": { "name": "sale", "mode": "form", "active_id": obj.id, }, "flash": "Sales order approved successfully", } def find_sale_line(self, ids, product_id, context={}): obj = self.browse(ids)[0] for line in obj.lines: if line.product_id.id == product_id: return line.id return None def onchange_sequence(self, context={}): data = context["data"] seq_id = data["sequence_id"] if not seq_id: return None while 1: num = get_model("sequence").get_next_number(seq_id, context=context) res = self.search([["number", "=", num]]) if not res: break get_model("sequence").increment_number(seq_id, context=context) data["number"] = num return data def get_state_label(self, ids, context={}): vals = {} for obj in self.browse(ids): if obj.state == "draft": s = "Draft" if obj.state == "confirmed": s = "Confirmed" elif obj.state == "done": s = "Completed" elif obj.state == "voided": s = "Voided" else: s = "/" vals[obj.id] = s return vals def get_ship_tracking(self, ids, context={}): vals = {} for obj in self.browse(ids): track_nos = [] for pick in obj.pickings: if pick.ship_tracking: track_nos.append(pick.ship_tracking) vals[obj.id] = ", ".join(track_nos) return vals def get_pickings(self, ids, context={}): vals = {} for obj in self.browse(ids): pick_ids = [] for move in obj.stock_moves: pick_ids.append(move.picking_id.id) pick_ids = sorted(list(set(pick_ids))) vals[obj.id] = pick_ids return vals def copy_to_job(self, ids, context={}): obj = self.browse(ids)[0] tmpl = obj.job_template_id if not tmpl: raise Exception("Missing service order template in sales order") job_id = tmpl.create_job(sale_id=obj.id) job = get_model("job").browse(job_id) return { "flash": "Service order %s created from sales order %s" % (job.number, obj.number), "next": { "name": "job", "mode": "form", "active_id": job_id, }, } def get_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): est_cost_total = 0 act_cost_total = 0 for cost in obj.costs: amt = cost.amount or 0 if cost.currency_id: amt = get_model("currency").convert(amt, cost.currency_id.id, obj.currency_id.id) est_cost_total += amt act_amt = cost.actual_amount or 0 if cost.currency_id: act_amt = get_model("currency").convert(act_amt, cost.currency_id.id, obj.currency_id.id) act_cost_total += act_amt est_profit = obj.amount_subtotal - est_cost_total est_profit_percent = est_profit * 100 / obj.amount_subtotal if obj.amount_subtotal else None act_profit = obj.amount_subtotal - act_cost_total act_profit_percent = act_profit * 100 / obj.amount_subtotal if obj.amount_subtotal else None vals[obj.id] = { "est_cost_total": est_cost_total, "est_profit": est_profit, "est_profit_percent": est_profit_percent, "act_cost_total": act_cost_total, "act_profit": act_profit, "act_profit_percent": act_profit_percent, } return vals def onchange_cost_product(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) prod_id = line.get("product_id") if prod_id: prod = get_model("product").browse(prod_id) line["description"] = prod.description line["unit_price"] = prod.landed_cost line["qty"] = 1 line["uom_id"] = prod.uom_id.id line["currency_id"] = prod.purchase_currency_id.id line["purchase_duty_percent"] = prod.purchase_duty_percent line["purchase_ship_percent"] = prod.purchase_ship_percent line["landed_cost"] = prod.landed_cost line["purchase_price"] = prod.purchase_price if prod.suppliers: line["supplier_id"] = prod.suppliers[0].supplier_id.id return data def get_cost_per_supplier(self, ids, context): vals = {} for obj in self.browse(ids): sup_cost = {} for line in obj.costs: sup = line.supplier_id.name if line.supplier_id else "/" sup_cost.setdefault(sup, [0, 0]) sup_cost[sup][0] += line.amount or 0 sup_cost[sup][1] += line.actual_amount or 0 data = [] for sup in sorted(sup_cost): data.append({ "name": sup, "est_cost_total": sup_cost[sup][0], "act_cost_total": sup_cost[sup][1], }) vals[obj.id] = data return vals def cancel_unpaid_order(self, num_days=7): exp_date = datetime.now() - timedelta(days=num_days) exp_date = exp_date.strftime("%Y-%m-%d") res = self.search([["date", "<", exp_date], ["state", "=", "confirmed"]]) number = "Expired Date-" + exp_date + " Order -" for obj in self.browse(res): if not obj.is_paid: number += obj.number + "-" for pick in obj.pickings: pick.void() for inv in obj.invoices: if inv.state == "waiting_payment": inv.void() obj.void() print(number) def get_est_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): cost=0 for line in obj.lines: cost+=line.est_cost_amount or 0 profit=obj.amount_subtotal-cost margin=profit*100/obj.amount_subtotal if obj.amount_subtotal else None vals[obj.id] = { "est_cost_amount": cost, "est_profit_amount": profit, "est_margin_percent": margin, } return vals def get_track_entries(self,ids,context={}): vals={} for obj in self.browse(ids): if not obj.track_id: vals[obj.id]=[] continue res=get_model("account.track.entry").search([["track_id","child_of",obj.track_id.id]]) vals[obj.id]=res return vals def write_track_entries(self,ids,field,val,context={}): for op in val: if op[0]=="create": rel_vals=op[1] for obj in self.browse(ids): if not obj.track_id: continue rel_vals["track_id"]=obj.track_id.id get_model("account.track.entry").create(rel_vals,context=context) elif op[0]=="write": rel_ids=op[1] rel_vals=op[2] get_model("account.track.entry").write(rel_ids,rel_vals,context=context) elif op[0]=="delete": rel_ids=op[1] get_model("account.track.entry").delete(rel_ids,context=context) def get_act_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): cost=0 for line in obj.track_entries: cost-=line.amount profit=obj.amount_subtotal-cost margin=profit*100/obj.amount_subtotal if obj.amount_subtotal else None vals[obj.id] = { "act_cost_amount": cost, "act_profit_amount": profit, "act_margin_percent": margin, } return vals def create_track(self,ids,context={}): obj=self.browse(ids[0]) count=0 code=obj.number res=get_model("account.track.categ").search([["code","=",code]]) if res: sale_track_id=res[0] else: sale_track_id=get_model("account.track.categ").create({ "code": code, "name": code, "type": "1", }) count+=1 obj.write({"track_id":sale_track_id}) for line in obj.lines: if not line.sequence: raise Exception("Missing sequence in sales order line") code="%s / %s"%(obj.number,line.sequence) res=get_model("account.track.categ").search([["code","=",code]]) if res: continue vals={ "code": code, "parent_id": sale_track_id, "name": obj.number, #XXX "type": "1", } get_model("account.track.categ").create(vals) count+=1 return { "next": { "name": "sale", "mode": "form", "active_id": obj.id, }, "flash": "%d tracking codes created"%count, } def create_est_costs(self,ids,context={}): obj=self.browse(ids[0]) obj.write({"est_costs":[("delete_all",)]}) for line in obj.lines: prod=line.product_id if not prod: continue if not line.sequence: continue if "bundle" == prod.type: continue vals={ "sale_id": obj.id, "sequence": line.sequence, "product_id": prod.id, "description": prod.name, "supplier_id": prod.suppliers[0].supplier_id.id if prod.suppliers else None, "list_price": prod.purchase_price, "purchase_price": prod.purchase_price, "landed_cost": prod.landed_cost, "purchase_duty_percent": prod.purchase_duty_percent, "purchase_ship_percent": prod.purchase_ship_percent, "qty": line.qty, "currency_id": prod.purchase_currency_id.id, "currency_rate": prod.purchase_currency_rate, } get_model("sale.cost").create(vals) def copy_cost_to_purchase(self, ids, context={}): obj = self.browse(ids)[0] suppliers = {} for cost in obj.est_costs: prod = line.product_id if not prod: continue if not prod.suppliers: raise Exception("Missing supplier for product '%s'" % prod.name) supplier_id = prod.suppliers[0].supplier_id.id suppliers.setdefault(supplier_id, []).append((prod.id, line.qty, line.uom_id.id)) if not suppliers: raise Exception("No purchase orders to create") po_ids = [] for supplier_id, lines in suppliers.items(): purch_vals = { "contact_id": supplier_id, "ref": obj.number, "lines": [], } for prod_id, qty, uom_id in lines: prod = get_model("product").browse(prod_id) line_vals = { "product_id": prod_id, "description": prod.description or "/", "qty": qty, "uom_id": uom_id, "unit_price": prod.purchase_price or 0, "tax_id": prod.purchase_tax_id.id, "sale_id": obj.id, } purch_vals["lines"].append(("create",
from __future__ import absolute_import, division, print_function # LIBTBX_SET_DISPATCHER_NAME phenix.model_idealization import sys, os import datetime from time import time from libtbx.utils import Sorry, multi_out, null_out from libtbx import easy_pickle, group_args import libtbx.load_env from scitbx.array_family import flex from six.moves import cStringIO as StringIO from cctbx import crystal from cctbx import xray from iotbx import reflection_file_utils from iotbx.phil import process_command_line_with_files import iotbx.ncs import iotbx.phil from cctbx import maptbx, miller from mmtbx.secondary_structure.build import ss_idealization as ssb from mmtbx.secondary_structure import manager, sec_str_master_phil import mmtbx.utils from mmtbx.building.loop_idealization import loop_idealization from mmtbx.building.cablam_idealization import cablam_idealization import mmtbx.building.loop_closure.utils from mmtbx.refinement.geometry_minimization import minimize_wrapper_for_ramachandran from mmtbx.refinement.real_space.individual_sites import minimize_wrapper_with_map import mmtbx.model import mmtbx.refinement.real_space.fit_residues import scitbx.math import mmtbx.idealized_aa_residues.rotamer_manager from elbow.command_line.ready_set import model_interface as ready_set_model_interface from phenix.programs import phi_psi_2 import six turned_on_ss = ssb.ss_idealization_master_phil_str turned_on_ss = turned_on_ss.replace("enabled = False", "enabled = True") master_params_str = """ model_file_name = None .type = path .multiple = True .short_caption = Model file .style = file_type:pdb bold input_file .expert_level = 0 map_file_name = None .type = path .help = User-provided map that will be used as reference .expert_level = 0 hkl_file_name = None .type = path .help = User-provided X-ray data to generate 2mFo-DFc map that will be used \ as reference .expert_level = 0 data_labels = None .type = str .short_caption = Data labels .help = Labels for experimental data. r_free_flags_labels = None .type = str .short_caption = Rfree labels .help = Labels for free reflections. ligands_file_name = None .type = path .multiple = True .help = User-provided ligand restraints .expert_level = 0 mask_and_he_map = False .type = bool .help = Mask and histogram equalization of the input map trim_alternative_conformations = False .type = bool .help = Leave only atoms with empty altloc .expert_level = 2 additionally_fix_rotamer_outliers = True .type = bool .help = At the late stage if rotamer is still outlier choose another one \ with minimal clash with surrounding atoms .expert_level = 2 use_ss_restraints = True .type = bool .help = Use Secondary Structure restraints .expert_level = 2 use_starting_model_for_final_gm = False .type = bool .help = Use supplied model for final geometry minimization. Otherwise just \ use self. .expert_level = 3 output_prefix = None .type = str .expert_level = 0 output_pkl = False .type = bool .expert_level = 3 output_model_h = True .type = bool .expert_level = 2 use_map_for_reference = True .type = bool .expert_level = 1 run_minimization_first = True .type = bool .expert_level = 2 run_minimization_last = True .type = bool .expert_level = 2 use_hydrogens_in_minimization = False .type = bool .expert_level = 3 reference_map_resolution = 5 .type = float .expert_level = 2 number_of_refinement_cycles = 5 .type = int .expert_level = 1 cycles_to_converge = 2 .type = int .help = Nuber of cycles of geometry optimization without considerable stat \ change before stopping .expert_level=1 ignore_ncs = False .type = bool .help = Don't use NCS even if it is present in model. .expert_level = 2 filter_input_ss = True .type = bool .help = Filter input annotation .expert_level = 3 debug = False .type = bool .help = Output all intermediate files .expert_level = 3 verbose = False .type = bool .help = More output to log nonbonded_weight=10000 .type = float apply_all_trans = True .type = bool %s include scope mmtbx.geometry_restraints.ramachandran.old_master_phil include scope mmtbx.secondary_structure.sec_str_master_phil_str include scope mmtbx.building.loop_idealization.loop_idealization_master_phil_str include scope mmtbx.building.cablam_idealization.master_phil_str """ % turned_on_ss def master_params(): return iotbx.phil.parse(master_params_str, process_includes=True) def format_usage_message(log): print("-"*79, file=log) msg = """\ phenix.model_idealization: Idealize model geometry. Usage examples: phenix.model_idealization model.pdb """ print(msg, file=log) print("-"*79, file=log) print(master_params().show(), file=log) class model_idealization(): def __init__(self, model, # shifted, with shift_manager map_data = None, # shifted map_data params=None, log=sys.stdout, verbose=True): t_0 = time() self.model = model # self.cif_objects = cif_objects self.params = params self.log = log self.verbose = verbose # self.shift_manager = self.model.get_shift_manager() self.rmsd_from_start = None self.init_model_statistics = None self.init_gm_model_statistics = None self.after_ss_idealization = None self.after_loop_idealization = None self.after_rotamer_fixing = None self.final_model_statistics = None self.user_supplied_map = map_data self.reference_map = None # Whole map for all NCS copies self.master_map = None # Map for only one NCS copy, or == reference_map if no NCS self.init_ref_map = None # separate map for initial GM. Should be tighter than the 2 above params = mmtbx.model.manager.get_default_pdb_interpretation_params() params.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None params.pdb_interpretation.peptide_link.ramachandran_restraints = True params.pdb_interpretation.peptide_link.restrain_rama_outliers = self.params.restrain_rama_outliers params.pdb_interpretation.peptide_link.restrain_rama_allowed = self.params.restrain_rama_allowed params.pdb_interpretation.peptide_link.restrain_allowed_outliers_with_emsley = self.params.restrain_allowed_outliers_with_emsley params.pdb_interpretation.peptide_link.rama_weight = self.params.rama_weight params.pdb_interpretation.peptide_link.oldfield.weight_scale=self.params.oldfield.weight_scale params.pdb_interpretation.peptide_link.oldfield.plot_cutoff=self.params.oldfield.plot_cutoff params.pdb_interpretation.peptide_link.apply_peptide_plane = True if self.params.loop_idealization.make_all_trans: params.pdb_interpretation.peptide_link.apply_all_trans = self.params.apply_all_trans params.pdb_interpretation.nonbonded_weight = self.params.nonbonded_weight params.pdb_interpretation.c_beta_restraints=True params.pdb_interpretation.max_reasonable_bond_distance = None params.pdb_interpretation.ncs_search.enabled = True params.pdb_interpretation.ncs_search.chain_max_rmsd=4.0 params.pdb_interpretation.ncs_search.chain_similarity_threshold=0.99 params.pdb_interpretation.ncs_search.residue_match_radius=999.0 params.pdb_interpretation.restraints_library.rdl = True params.pdb_interpretation.secondary_structure = self.params.secondary_structure self.params_for_model = params self.model.set_pdb_interpretation_params(params) self.model.process_input_model(make_restraints=True) self.original_hierarchy = self.model.get_hierarchy().deep_copy() # original pdb_h, without any processing self.original_boxed_hierarchy = None # original and boxed (if needed) self.filtered_ncs_restr_group_list = [] self.init_ss_annotation = self.model.get_ss_annotation() # various checks, shifts, trims self.cs = self.original_cs = self.model.crystal_symmetry() # check self.cs (copy-paste from secondary_sturcure_restraints) corrupted_cs = False if self.cs is not None: if [self.cs.unit_cell(), self.cs.space_group()].count(None) > 0: corrupted_cs = True self.cs = None elif self.cs.unit_cell().volume() < 10: corrupted_cs = True self.cs = None # couple checks if pdb_h is ok o_c = self.original_hierarchy.overall_counts() o_c.raise_duplicate_atom_labels_if_necessary() # o_c.raise_residue_groups_with_multiple_resnames_using_same_altloc_if_necessary() o_c.raise_chains_with_mix_of_proper_and_improper_alt_conf_if_necessary() o_c.raise_improper_alt_conf_if_necessary() if len(self.original_hierarchy.models()) > 1: raise Sorry("Multi model files are not supported") ca_only_present = False for c in self.original_hierarchy.only_model().chains(): if c.is_ca_only(): ca_only_present = True if ca_only_present: raise Sorry("Don't support models with chains containing only CA atoms.") self.original_boxed_hierarchy = self.model.get_hierarchy().deep_copy() self.shift_vector = None if self.cs is None: assert self.model.get_shift_manager() is None # should it happen here? if corrupted_cs: print("Symmetry information is corrupted, ", file=self.log) else: print("Symmetry information was not found, ", file=self.log) print("putting molecule in P1 box.", file=self.log) self.log.flush() from cctbx import uctbx box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=self.model.get_sites_cart(), buffer_layer=3) # Creating new xrs from box, inspired by extract_box_around_model_and_map sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = self.model.get_xray_structure().replace_sites_frac(box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) self.model.set_xray_structure(xray_structure_box) self.cs = box.crystal_symmetry() self.shift_vector = box.shift_vector if self.shift_vector is not None and self.params.debug: txt = self.model.model_as_pdb() with open("%s_boxed.pdb" % self.params.output_prefix, 'w') as f: f.write(txt) if self.params.trim_alternative_conformations: self.model.remove_alternative_conformations(always_keep_one_conformer=True) self.model = self.model.remove_hydrogens() self.model_h = None self.time_for_init = time()-t_0 def get_statistics(self, model): # should we shift here? No # should we multiply NCS here? No geometry = model.geometry_statistics().result() motifs = phi_psi_2.results_manager(model=model, log=null_out()).get_motif_count() mcounts = motifs.get_counts() res = {} # TODO is mcounts a dict ? If not consider changing back for key, value in six.iteritems(mcounts): res[key] = value.percent geometry.merge(group_args(**res)) return geometry def prepare_user_map(self): print("Preparing user map...", file=self.log) self.map_shift_manager = mmtbx.utils.shift_origin( map_data = self.user_supplied_map, xray_structure = self.model.get_xray_structure(), crystal_symmetry = self.cs) if(self.map_shift_manager.shift_cart is not None): # Need to figure out way to save the shift to shift back # and apply it to whole_pdb, master_pdb, etc. Don't forget about # boxing hierarchy when symmetry is not available or corrupted... raise Sorry("Map origin is not at (0,0,0). This is not implemented for model_idealization") map_data = self.map_shift_manager.map_data self.reference_map = map_data self.master_map = self.reference_map.deep_copy() if self.model.ncs_constraints_present(): mask = maptbx.mask( xray_structure=self.model.get_xray_structure().select(self.model.get_master_selection()), n_real=self.master_map.focus(), mask_value_inside_molecule=1, mask_value_outside_molecule=-1, solvent_radius=0, atom_radius=1.) self.master_map = self.reference_map * mask if self.params.debug: iotbx.mrcfile.write_ccp4_map( file_name="%s_3_master.map" % self.params.output_prefix, unit_cell=self.cs.unit_cell(), space_group=self.cs.space_group(), map_data=self.master_map, labels=flex.std_string([""])) iotbx.mrcfile.write_ccp4_map( file_name="%s_reference.map" % self.params.output_prefix, unit_cell=self.cs.unit_cell(), space_group=self.cs.space_group(), map_data=self.reference_map, labels=flex.std_string([""])) self.master_map = map_data def prepare_init_reference_map(self): xrs = self.model.get_xray_structure().deep_copy_scatterers() pdb_h = self.model.get_hierarchy().deep_copy() if self.user_supplied_map is not None: print("Using user-supplied map for initial GM.", file=self.log) self.init_ref_map = self.reference_map return print("Preparing map for initial GM...", file=self.log) asc = self.model.get_atom_selection_cache() outlier_selection_txt = mmtbx.building.loop_closure.utils. \ rama_score_selection(pdb_h, self.model.get_ramachandran_manager(), "outlier",1) rama_out_sel = asc.selection(outlier_selection_txt) allowed_selection_txt = mmtbx.building.loop_closure.utils. \ rama_score_selection(pdb_h, self.model.get_ramachandran_manager(), "allowed",0) rama_allowed_sel = asc.selection(allowed_selection_txt) # side_chain_no_cb_selection = ~ xrs.main_chain_selection() side_chain_no_cb_selection = ~ xrs.backbone_selection() sc_rama_out = rama_out_sel & side_chain_no_cb_selection sc_rama_allowed =rama_allowed_sel & side_chain_no_cb_selection xrs=xrs.set_b_iso(value=10) xrs = xrs.set_b_iso(value=20, selection=side_chain_no_cb_selection) xrs = xrs.set_b_iso(value=25, selection=rama_allowed_sel) xrs = xrs.set_b_iso(value=50, selection=rama_out_sel) xrs = xrs.set_b_iso(value=40, selection=sc_rama_allowed) xrs = xrs.set_b_iso(value=70, selection=rama_out_sel) crystal_gridding = maptbx.crystal_gridding( unit_cell = xrs.unit_cell(), space_group_info = xrs.space_group_info(), symmetry_flags = maptbx.use_space_group_symmetry, d_min = self.params.reference_map_resolution) fc = xrs.structure_factors(d_min = 2, algorithm = "fft").f_calc() fft_map = miller.fft_map( crystal_gridding=crystal_gridding, fourier_coefficients=fc) fft_map.apply_sigma_scaling() init_reference_map = fft_map.real_map_unpadded(in_place=False) if self.params.debug: fft_map.as_xplor_map(file_name="%s_init.map" % self.params.output_prefix) self.init_ref_map = init_reference_map def prepare_reference_map_3(self): """ with ramachandran outliers """ xrs = self.model.get_xray_structure().deep_copy_scatterers() pdb_h = self.model.get_hierarchy() print("Preparing reference map, method 3", file=self.log) outlier_selection_txt = mmtbx.building.loop_closure.utils. \ rama_score_selection(pdb_h, self.model.get_ramachandran_manager(), "outlier",1) asc = self.model.get_atom_selection_cache() # print >> self.log, "rama outlier selection:", outlier_selection_txt rama_out_sel = asc.selection(outlier_selection_txt) xrs=xrs.set_b_iso(value=50) # side_chain_no_cb_selection = ~ xrs.main_chain_selection() side_chain_no_cb_selection = ~ xrs.backbone_selection() xrs = xrs.set_b_iso(value=200, selection=side_chain_no_cb_selection) xrs = xrs.set_b_iso(value=150, selection=rama_out_sel) # xrs = xrs.set_occupancies(value=0.3, selection=rama_out_sel) crystal_gridding = maptbx.crystal_gridding( unit_cell = xrs.unit_cell(), space_group_info = xrs.space_group_info(), symmetry_flags = maptbx.use_space_group_symmetry, d_min = self.params.reference_map_resolution) fc = xrs.structure_factors( d_min = self.params.reference_map_resolution, algorithm = "direct").f_calc() fft_map = miller.fft_map( crystal_gridding=crystal_gridding, fourier_coefficients=fc) fft_map.apply_sigma_scaling() self.reference_map = fft_map.real_map_unpadded(in_place=False) if self.params.debug: fft_map.as_xplor_map(file_name="%s_3.map" % self.params.output_prefix)
# -*- coding:utf-8 -*- # # Tencent is pleased to support the open source community by making QTA available. # Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may not use this # file except in compliance with the License. You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. # '''远程控制的截屏服务 ''' from __future__ import absolute_import, print_function import Queue import threading import time import struct import subprocess import re import os import traceback import signal import argparse import atexit import sys from six.moves.socketserver import BaseRequestHandler from six.moves.socketserver import TCPServer from six.moves.socketserver import ThreadingMixIn from six.moves.urllib.request import urlopen from qt4i.driver.tools import logger as logging from qt4i.driver.util import Process DEFAULT_IP = '0.0.0.0' DEFAULT_PORT = 12306 DEFAULT_AGENT_PORT = 8100 DEFAULT_PID_FILE = '/tmp/screencapure.pid' logger = logging.get_logger() class ArgumentParser(argparse.ArgumentParser): '''Argument parser, automatically display help while error ''' def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) CMD_HELP = { "start": "start screencapure service daemon", "stop": "stop screencapure service daemon", "restart": "stop screencapure service daemon and start it again", "debug": "try to start screencapure service as a normal process for debug", } # 参数解析器 main_parser = ArgumentParser(description='QT4i screencapure program', formatter_class=argparse.RawDescriptionHelpFormatter) main_parser.add_argument('--pidfile', '-p', metavar='PIDFILE', dest='pidfile', default=DEFAULT_PID_FILE, help='the path of pid file, %s is used by default' % DEFAULT_PID_FILE) main_parser.add_argument('--udid', '-u', metavar='UDID', dest='udid', default=None, help='udid of device') main_parser.add_argument('--listen_port', '-l', metavar='LISTENPORT', dest='listen_port', default=DEFAULT_PORT, help='listening port of driver server, port %s is used by default' % DEFAULT_PORT) main_parser.add_argument('--mjpeg_port', '-m', metavar='MJPEGPORT', dest='mjpeg_port', default=DEFAULT_AGENT_PORT, help='listening port of xctest agent, port %s is used by default' % DEFAULT_AGENT_PORT) subparser_dict = {} subparsers = main_parser.add_subparsers(title='List of Commands', metavar='COMMAND') for command in CMD_HELP: subparser_dict[command] = subparsers.add_parser(command, help=CMD_HELP[command]) subparser_dict[command].set_defaults(func=command) subparser_dict['stop'].add_argument('--force', '-f', action='store_true', default=False, help='force stop driver server') class Daemon(object): """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ # Do first fork self.fork() # Decouple from parent environment self.dettach_env() # Do second fork self.fork() # Flush standart file descriptors sys.stdout.flush() sys.stderr.flush() # self.attach_stream('stdin', mode='r') self.create_pidfile() def attach_stream(self, name, mode): """ Replaces the stream with new one """ stream = open(getattr(self, name), mode) os.dup2(stream.fileno(), getattr(sys, name).fileno()) def dettach_env(self): os.chdir("/") os.setsid() os.umask(0) def fork(self): """ Spawn the child process """ try: pid = os.fork() if pid > 0: sys.exit(0) except OSError as e: sys.stderr.write("Fork failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) def create_pidfile(self): atexit.register(self.delpid) pid = str(os.getpid()) open(self.pidfile, 'w+').write("%s\n" % pid) def delpid(self): """ Removes the pidfile on process exit """ os.remove(self.pidfile) def start(self, is_daemon=True): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs pid = self.get_pid() if pid: if Process().get_process_by_pid(pid, 'screencapture.py'): message = "pidfile %s already exist. Daemon already running?\n" logger.warning(message % self.pidfile) return else: os.remove(self.pidfile) # Start the daemon if is_daemon: self.daemonize() self.run() def get_pid(self): """ Returns the PID from pidfile """ try: pf = open(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except (IOError, TypeError): pid = None return pid def stop(self, silent=False): """ Stop the daemon """ # Get the pid from the pidfile pid = self.get_pid() if not pid: if not silent: message = "pidfile %s does not exist. Daemon not running?\n" logger.error(message % self.pidfile) return # Try killing the daemon process try: while True: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: logger.error(str(err)) sys.exit(1) def restart(self): """ Restart the daemon """ self.stop(silent=True) self.start() def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ raise NotImplementedError class ThreadedTCPServer(ThreadingMixIn, TCPServer): allow_reuse_address = True request_queue_size = 16 class ScreenConsumer(BaseRequestHandler): def setup(self): self.screenqueue = Queue.Queue(24) self.screen_producer = self.server.screen_producer assert self.request.recv(10) == 'screenshot' self.screen_producer.add_client(self) def handle(self): while True: image_data = self.screenqueue.get() try: image_length = len(image_data) self.request.sendall(struct.pack("I", image_length) + image_data) except: break def finish(self): self.request.close() self.screen_producer.remove_client(self) class ScreenCaptureService(Daemon): def __init__(self, pidfile, udid, listen_port, mjpeg_port): Daemon.__init__(self, pidfile) self._udid = udid self._listen_port = listen_port self._mjpeg_port = mjpeg_port def start(self, is_daemon=True): '''启动service ''' pid = self.get_pid() if pid: process = Process().get_process_by_pid(pid, 'screencapture.py') if process: Process().kill_process_by_pid(pid) logger.warning('Kill old screencapure server process %d' % pid) else: os.remove(self.pidfile) # start damon if is_daemon: self.daemonize() self.run() def run(self): if self._udid: if self._mjpeg_port: screen_producer = ScreenProducer(self._udid, int(self._mjpeg_port)) screen_producer.start() server = ThreadedTCPServer(('localhost', int(self._listen_port)), ScreenConsumer) server.screen_producer = screen_producer server.serve_forever() def stop(self, silent=False): '''停止service ''' Daemon.stop(self, silent) class MJpegClient(object): def __init__(self, url): self.stream = urlopen(url) self.boundary = None def parse_mjpeg_boundary(self): ''' parse mjpeg stream boundary :param stream: mjpeg client stream :type stream: http.client.HTTPResponse :returns: str -- boundary ''' if self.stream.getcode() != 200: raise Exception('Invalid response from server: %d' % self.stream.status) h = self.stream.info() content_type = h.get('Content-Type', None) match = re.search(r'boundary="?(.*)"?', content_type) if match is None: raise Exception('Content-Type header does not provide boundary string') self.boundary = match.group(1) def read_mjpeg_frame(self): hdr = self._read_headers(self.boundary) clen = self._parse_content_length(hdr) if clen == 0: raise EOFError('End of stream reached') self._check_content_type(hdr, 'image/jpg') left = clen buf = '' while left > 0: tmp = self.stream.read(left) buf += tmp left -= len(tmp) return buf def close(self): self.stream.close() def _read_header_line(self): '''Read one header line within the stream. The headers come right after the boundary marker and usually contain headers like Content-Type and Content-Length which determine the type and length of the data portion. ''' return self.stream.readline().strip() def _read_headers(self, boundary): '''Read and return stream headers. Each stream data packet starts with an empty line, followed by a boundary marker, followed by zero or more headers, followed by an empty line, followed by actual data. This function reads and parses the entire header section. It returns a dictionary with all the headers. Header names are converted to lower case. Each value in the dictionary is a list of header fields values. ''' l = '' while True: l = self._read_header_line() if l != '': break if l != boundary: raise Exception('Boundary string expected, but not found') headers = {} while True: l = self._read_header_line() # An empty line indicates the end of the header section if l == '': break # Parse the header into lower case header name and header body i = l.find(':') if i == -1: raise Exception('Invalid header line: ' + l) name = l[:i].lower() body = l[i + 1:].strip() lst = headers.get(name, list()) lst.append(body) headers[name] = lst return headers def _parse_content_length(self, headers): # Parse and check Content-Length. The header must be present in # each chunk, otherwise we wouldn't know how much data to read. clen = headers.get('content-length', None) try: return int(clen[0]) except (ValueError, TypeError): raise Exception('Invalid or missing Content-Length') def _check_content_type(self, headers, expected_type): ctype = headers.get('content-type', None) if ctype is None: raise Exception('Missing Content-Type header') ctype = ctype[0] i = ctype.find(';') if i != -1: ctype = ctype[:i] if ctype != expected_type: raise Exception('Wrong Content-Type: %s' % ctype) return True class ScreenProducer(threading.Thread): def __init__(self, udid, mjpeg_port): super(ScreenProducer, self).__init__() self._clients = set() self._udid = udid self.running = True self._mutex = threading.Lock() self.no_client = True self.mjpeg_conn_event = threading.Event() self.mjpeg_conn_event.clear() if re.match(r'^[a-f0-9]+$', udid): self._is_simulator = False self._url = "http://127.0.0.1:%s" % mjpeg_port else: self._is_simulator = True @property def is_sim(self): return self._is_simulator def add_client(self, client): with self._mutex: self._clients.add(client) self.no_client = False self.mjpeg_conn_event.set() def remove_client(self, client): with self._mutex: self._clients.discard(client) if len(self._clients) == 0: self.no_client = True self.mjpeg_conn_event.clear() def process_mjpeg_stream(self, mjpeg_client): mjpeg_client.parse_mjpeg_boundary() while True: jpeg_frame = mjpeg_client.read_mjpeg_frame() with self._mutex: if len(self._clients) == 0: break for client in self._clients: if client.screenqueue.full(): continue client.screenqueue.put(jpeg_frame) def _capture_screen_by_xctestagent(self): try: if self.no_client: self.mjpeg_conn_event.wait() mjpeg_client = MJpegClient(self._url) self.process_mjpeg_stream(mjpeg_client) except EOFError: pass except Exception: logger.exception(traceback.format_exc()) finally: mjpeg_client.close() def _capture_screen_by_simctl(self): try: if self.no_client: self.mjpeg_conn_event.wait() cmd = 'xcrun simctl io %s screenshot --type=jpeg -'
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Library for Graph Attention model.""" from typing import Optional import tensorflow as tf from uncertainty_baselines.models.mpnn import get_adjacency_matrix class GraphAttentionLayer(tf.keras.layers.Layer): """A layer that implements graph attention.""" def __init__(self, node_feature_dim, out_node_feature_dim, constant_attention=False): """Construct a graph attention layer. Args: node_feature_dim: dimension (integer) of incoming node level features. An incoming tensor should have dimension of (batch_size, num_nodes, node_feature_dim). out_node_feature_dim: dimension (integer) of outcoming node level features. An outcoming tensor should have dimension of (batch_size, num_nodes, out_node_feature_dim). constant_attention: a boolean. If True, we directly use equal attention coefficients across neighbors without going through the network. Default is False. """ super().__init__() self.constant_attention = constant_attention self.w = self.add_weight( name="w", shape=(node_feature_dim, out_node_feature_dim), initializer="glorot_uniform", regularizer="l2", trainable=True) self.a = self.add_weight( name="a", shape=(2 * out_node_feature_dim, 1), initializer="glorot_uniform", regularizer="l2", trainable=True) self.leakyrelu = tf.keras.layers.LeakyReLU(alpha=0.2) def call(self, h, adj): """Forward pass computation of the layer. Args: h: An incoming tensor contains node level features and it should have dimension of (batch_size, num_nodes, node_feature_dim). adj: An incoming tensor contains adjacency matrices. Each adjacency matrix has added diagonal ones before entering the layer. It should have dimension of (batch_size, num_nodes, num_nodes). Returns: new_h: The new node level features tensor. It is aggregated from neighbours with attention and it has dimension of (batch_size, out_node_feature_dim). """ wh = tf.matmul(h, self.w) # (batch_size, num_nodes, out_node_feature_dim) # Go through attention. if self.constant_attention: attention_scores = tf.ones([tf.shape(h)[0], tf.shape(h)[1], tf.shape(h)[1] ]) # (batch_size, num_nodes, num_nodes) else: attention_inputs = self._prepare_attention_inputs( wh) # (batch_size, num_nodes, num_nodes, 2*out_node_feature_dim) attention_scores = self._calc_attention_scores( attention_inputs) # (batch_size, num_nodes, num_nodes) attention_coeffs = self._calc_attention_coeffs(attention_scores, adj) new_h = tf.matmul(attention_coeffs, wh) # (batch_size, num_nodes, out_node_feature_dim) return new_h def _prepare_attention_inputs(self, wh): """Prepare inputs for downstream attention computation. Since our downstream attention score calculation takes a pair of nodes as input, this method really is to generate a list of all possible pairs and arrange them into adjacency-matrix-like shape. Args: wh: Incoming transformed node representation. It should have dimension of (batch_size, num_nodes, out_node_feature_dim). Returns: attention_inputs: Prepared tensor to feed into attention score calculation. It has dimension of (batch_size, num_nodes, num_nodes, 2*out_node_feature_dim). """ batch_size, num_nodes = tf.shape(wh)[0], tf.shape(wh)[1] # Get wh repeats and tiles. wh_repeats = tf.repeat( wh, repeats=tf.ones(num_nodes, dtype=tf.int32) * num_nodes, axis=1) # (batch_size, num_nodes^2, out_node_feature_dim) wh_tile = tf.tile( wh, [1, num_nodes, 1]) # (batch_size, num_nodes^2, out_node_feature_dim) # Generate a list of all possible pairs of nodes. attention_inputs = tf.concat( [wh_repeats, wh_tile], axis=2) # (batch_size, num_nodes^2, 2*out_node_feature_dim) # Reshape the list into an adjacency-matrix-like tensor. attention_inputs = tf.reshape( attention_inputs, [batch_size, num_nodes, num_nodes, -1 ]) # (batch_size, num_nodes, num_nodes, 2*out_node_feature_dim) return attention_inputs def _calc_attention_scores(self, attention_inputs): """Compute attention scores. Args: attention_inputs: The incoming tensor contains pair-wise node-level representations. It has dimension of (batch_size, num_nodes, num_nodes, 2*out_node_feature_dim) Returns: attention_scores: Computed attention scores tensor with dimension of (batch_size, num_nodes, num_nodes) """ attention_scores = tf.squeeze( tf.matmul(attention_inputs, self.a), axis=[3]) # (batch_size, num_nodes, num_nodes) attention_scores = self.leakyrelu( attention_scores) # (batch_size, num_nodes, num_nodes) return attention_scores def _calc_attention_coeffs(self, attention_scores, adj): """Compute attention coefficients. The attention coefficients, at high level, are computed based on attention scores and adjacency matrix. In this current implementation, we only allow direct neighbours to have positive attention coefficients; all the non-direct neighbours may have high attention scores, but we still assign zero coefficients to them. This can be dis-regulated in the future because long-distance intra-molecular interactions are common. Args: attention_scores: An incoming tensor contains pair-wise attention scores (logits). It has dimension of (batch_size, num_nodes, num_nodes). adj: An incoming tensor contains adjacency matrices. Each adjacency matrix has added diagonal ones before entering the layer. It should have dimension of (batch_size, num_nodes, num_nodes). It's used to decide how large of a neighbourhood to consider for attention contributions. Returns: attention_coeffs: Computed attention coefficients tensor with dimension of (batch_size, num_nodes, num_nodes) """ # Create a tensor of (batch_size, num_nodes, num_nodes) # with default scores of negative infinities (-9e15). The reason is # some entries will be updated with computed attention scores # (should be much larger than negative infinities), and after going # through softmax, entries with default scores will give zero # attention coefficients. default_scores = -9e15 * tf.ones_like( attention_scores) # (batch_size, num_nodes, num_nodes) # Final scores will be same as default scores, except that those # entries for direct-neighbours (adj > 0) will be updated with # computed attention scores. whether_neighboring = tf.math.greater(adj, 0) final_scores = tf.where( whether_neighboring, attention_scores, default_scores) # (batch_size, num_nodes, num_nodes) # After softmax, those entries with default scores give zero # attention coefficients. attention_coeffs = tf.nn.softmax( final_scores, axis=2) # (batch_size, num_nodes, num_nodes) return attention_coeffs class GATModel(tf.keras.Model): """A model that implements molecule classification via graph attention. #### References [1]: <NAME>, et. al. Graph Attention Networks. ICLR 2018. https://arxiv.org/abs/1710.10903 Reference implementation: http://google3//research/biology/ether/yield_prediction/gat/models.py # END GOOGLE_INTERNAL """ def __init__( self, attention_heads, node_feature_dim, out_node_feature_dim, readout_layer_size, num_classes, constant_attention=False, kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None, dropout_rate=0.1): """Construct a graph attention model. Args: attention_heads: number (integer) of attention heads. node_feature_dim: dimension (integer) of incoming node level features. out_node_feature_dim: dimension (integer) of node level features outcoming from the attention layer. readout_layer_size: dimension (integer) of graph level features after readout layer. num_classes: number (integer) of classes for classification. constant_attention: a boolean. If True, we directly use equal attention coefficients across neighbors without going through the network. Default is False. kernel_regularizer: Regularization function for Dense layer. dropout_rate: a float regulating percent of features to turn OFF. """ super().__init__() self.dropout = tf.keras.layers.Dropout(dropout_rate) # We have three consecutive graph attention layers # before readout the graph level representations. self.attention_heads1 = [ GraphAttentionLayer(node_feature_dim, out_node_feature_dim, constant_attention) for _ in range(attention_heads) ] self.attention_heads2 = [ GraphAttentionLayer(out_node_feature_dim * attention_heads, out_node_feature_dim, constant_attention) for _ in range(attention_heads) ] self.attention_heads3 = [ GraphAttentionLayer(out_node_feature_dim * attention_heads, out_node_feature_dim, constant_attention) for _ in range(attention_heads) ] self.i_layer = tf.keras.layers.Dense( readout_layer_size, activation="sigmoid", kernel_regularizer=kernel_regularizer) self.j_layer = tf.keras.layers.Dense( readout_layer_size, kernel_regularizer=kernel_regularizer) self.classifier = tf.keras.layers.Dense( num_classes, kernel_regularizer=kernel_regularizer) self.softmax = tf.keras.layers.Softmax() def graph_representation(self, nodes, adj, training=False): """Forward pass to compute molecular graph level representation. Args: nodes: An incoming tensor contains node level features and it should have dimension of (batch_size, num_nodes, node_feature_dim). adj: An incoming tensor contains adjacency matrices. Each adjacency matrix has added diagonal ones before entering the layer. It should have dimension of (batch_size, num_nodes, num_nodes). training: A boolean indicating if the model is in training mode or not. This affects the behavior of dropout layers. Returns: x_g: The graph level features tensor. It is aggregated from neighbours with attention and it has dimension of (batch_size, out_node_feature_dim). """ # Go through graph attention 1 & 2. attention_layers = [self.attention_heads1, self.attention_heads2] nodes_under_iter = nodes for attention_heads in attention_layers: nodes_under_iter = self.dropout(nodes_under_iter, training=training) nodes_under_iter = tf.concat( [a_head(nodes_under_iter, adj) for a_head in attention_heads], axis=2) # (batch_size, num_nodes, heads * out_node_feature_dim) nodes_under_iter = tf.nn.elu( nodes_under_iter ) # (batch_size, num_nodes, heads * out_node_feature_dim) # Go through graph attention 3. nodes_under_iter = self.dropout(nodes_under_iter, training=training) if len(self.attention_heads3) > 1: nodes_under_iter = tf.keras.layers.Average()([ a_head(nodes_under_iter, adj) for a_head in self.attention_heads3 ]) # (batch_size, num_nodes, out_node_feature_dim) else: nodes_under_iter = self.attention_heads3[0](nodes_under_iter, adj) # Go though graph level aggregation. readout = tf.reduce_sum( tf.multiply( self.i_layer( tf.keras.layers.Concatenate()([nodes_under_iter, nodes])), self.j_layer(nodes_under_iter)), axis=1) # (batch_size, graph_level_features) return readout def call(self, inputs, training=False): """Forward pass computation of the model. Args: inputs: An inputs dictionary fed to the model. training: A boolean indicating if the model is in training mode or not. Returns: output: Logits tensor with dimension of (batch_size, classes) for classification. """ nodes, edges = inputs["atoms"], inputs["pairs"] adjacency_matrix = tf.cast(get_adjacency_matrix(edges), tf.int32) readout = self.graph_representation(nodes, adjacency_matrix, training) logits = self.classifier( readout, training=training) # (batch_size, classes)
_tout.stream(tl) ####################################### TestContext.TraceStream.TraceStream(std.ostream o, TraceLevel tl): _traceLevel(tl), _outputStreamPtr(o), #if defined(WIN32) and not (defined(__CYGWIN__) or defined(__MINGW32__)) _nullStream("nul") #else: _nullStream("/dev/null") #endif TestContext.TraceStream.~TraceStream() _nullStream.close() void TestContext.TraceStream.setTraceLevel(TraceLevel tl) _traceLevel = tl TestContext.TraceLevel TestContext.TraceStream.getTraceLevel() return _traceLevel std.ostream TestContext.TraceStream.stream(TestContext.TraceLevel tl) if _traceLevel >= tl : return *_outputStreamPtr return _nullStream ####################################### TestGraph TestGraph.instance() static TestGraph instance_ return instance_ TestSuite* TestGraph.root() return root_ TestSuite* TestGraph.suite( str path, TestSuite* tsuite, bool createIfNecessary) using namespace std pathComponents = list<string>() it1 = path.begin() it2 = it1 # Dissect the path into it's constituent components do while it2 not = path.end() and *it2 not = ord(".") : ++it2 # Consider a check for "" empty pathComponents.push_back( std: if (strings) else string(it1,it2) ) if it2 not = path.end() : ++it2 it1 = it2 while it2 not = path.end() : suite = return(pathComponents.begin(), pathComponents.end(), tsuite, createIfNecessary) TestSuite* TestGraph.suite( std.list<str>.iterator it, std.list<str>.iterator end, TestSuite* tsuite, bool createIfNecessary) using namespace std if not tsuite : tsuite = root() # Make sure these tie up if *it not = tsuite.name() : return 0 ++it if it == end : return tsuite child = tsuite.findChild(*it) if child : # We've found a child with the right name. But is it a # test if TestSuite* childSuite = dynamic_cast<TestSuite*>(child) if (suite) else suite = return(it, end, childSuite, createIfNecessary) # We could return 0 here, to indicate that someone is # trying to add a TestSuite named 'xxx' to a suite with a # Test already named 'xxx'. But we don't enforce uniqueness # the other way round, so we don't do it this way round # either. Carry on as normal, and create a TestSuite of # the same name if createIfNecessary is True. if createIfNecessary : childSuite = TestSuite(*it) tsuite.add(childSuite) suite = return(it, end, childSuite, createIfNecessary) return 0 TestGraph.TestGraph(): root_(TestSuite("root")) ####################################### bool TestQualifier.visitEnter( TestSuite* pSuite ) _path.append( pSuite.name() ) _path += SEPCHAR return True # Leaving a composite: Pop its name from the Path bool TestQualifier.visitLeave( TestSuite* pSuite ) # assert( _path.rfind( pSuite.name() + static_cast< char>(SEPCHAR)) # == _path.size() - pSuite.name().size() - 1) _path.erase( _path.size() - pSuite.name().size() -1 ) return True # Provide read-only access to the current qualifier str TestQualifier.currentPath() return _path ####################################### osg.Timer TestRecord.timer_ void TestRecord.start() start_ = timer_.tick() void TestRecord.stop() stop_ = timer_.tick() void TestRecord.log( TestFailureX e) stop() result_ = Failure problem_ = e.what() void TestRecord.log( TestErrorX e) stop() result_ = Error problem_ = e.what() void TestRecord.log( std.exception e) stop() result_ = Error problem_ = e.what() void TestRecord.log( str s) stop() result_ = Error problem_ = s TestRecord.TestRecord( str name): name_(name), start_(0), stop_(0), result_(Success), problem_("No problem") std.ostream operator, (std.ostream o, TestRecord tr) if tr.result_ == TestRecord.Success : o, "pass" elif tr.result_ == TestRecord.Failure : o, "fail" else o, "error" o, "\t", tr.name_ #o, tr.start_, '\t', tr.stop_, '\t', TestRecord.timer_.delta_s(tr.start_,tr.stop_) # Just print out the duration o, '\t', TestRecord.timer_.delta_s(tr.start_,tr.stop_), ord("s") if tr.result_ not = TestRecord.Success : o, '\t', tr.problem_ return o ####################################### TestRunner.TestRunner( TestContext ctx ) : _ctx( ctx ) void TestRunner.specify( str sQualifiedName ) _tests.push_back( sQualifiedName ) bool TestRunner.visitEnter( TestSuite* pSuite ) TestQualifier.visitEnter( pSuite ) return not _ctx.shouldStop() #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace osgUtx class isSpecified : pTestName_ = str() isSpecified( str s): pTestName_(s) bool operator()( str specifiedTest) return pTestName_.find(specifiedTest) == 0 operator = ( isSpecified) return *this #endif # DOXYGEN_SHOULD_SKIP_THIS bool TestRunner.visit( TestCase* pTest ) if std.find_if _tests.begin(),_tests.end(), osgUtx.isSpecified(currentPath() + pTest.name() ) : not = _tests.end() : perform( pTest ) return not _ctx.shouldStop() bool TestRunner.visitLeave( TestSuite* pSuite ) TestQualifier.visitLeave( pSuite ) return not _ctx.shouldStop() void TestRunner.perform( TestCase* pTest ) record = _db.createRecord( currentPath() + pTest.name() ) try record.start() pTest.run( _ctx ) record.stop() catch ( TestFailureX e ) record.log( e ) catch ( TestErrorX e ) record.log( e ) catch ( std.exception e ) record.log( e ) catch ( ... ) record.log( str("Unknown") ) _ctx.tout(TestContext.Results), record ####################################### TestSuite.TestSuite( str name ) : Test( name ) void TestSuite.add( Test* pTest ) _tests.push_back( pTest ) Test* TestSuite.findChild( str name) for(Tests.iterator it = _tests.begin() not = _tests.end() ++it) if *it :.name() == name : return (*it) return 0 bool TestSuite.accept( Test.Visitor v ) if v.visitEnter( this ) : end = _tests.end() for ( Tests.iterator at = _tests.begin() at not = end ++at ) if not (*at).accept( v ) : break return v.visitLeave( this ) # continue with siblings? ####################################### bool QualifiedTestPrinter.visit( TestCase* pTest ) osg.notify(osg.NOTICE), currentPath() + pTest.name() return True ####################################### # Translated from file 'UnitTestFramework.h' # -*-c++-*- #* #* OpenSceneGraph example, osgunittests. #* #* 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 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. # #ifndef OSG_UNITTESTFRAMEWORK #define OSG_UNITTESTFRAMEWORK 1 #include <osg/Export> #include <osg/Referenced> #include <osg/ref_ptr> #include <osg/Timer> #include <osg/Notify> #include <osgDB/fstream> #include <string> #include <vector> #include <list> #* # #\namespace osgUtx # #The osgUtx is a unit test framework. # namespace osgUtx TestVisitor = class() #* #Test, an abstract base class, is the Composite pattern's \em component #class for our graph of test cases, and defines the basic interface #for all Test components. It is a referent, and may be pointed #to by an osg.ref_ptr. # class Test (osg.Referenced) : typedef TestVisitor Visitor # Test is redundant Test( str sName ) : _name( sName ) def name(): return _name virtual bool accept( Visitor ) = 0 virtual ~Test() _name = str() #* #TestContext wraps up information which is passed to tests as they are run, #and may contain test-specific information or 'global' test objects, such #as an output stream for verbose output during the running of tests. # #\todo Improve the output stream code by providing a filtering stream. # class TestContext : TestContext() def shouldStop(): return False def isVerbose(): return True enum TraceLevel Off, #/< All tracing turned off Results, #/< Output results only Full #/< Full test diagnostic output setTraceLevel = void(TraceLevel tl) TraceLevel getTraceLevel() std.ostream tout(TraceLevel tl=Full) TestContext( TestContext) operator = ( TestContext) #ifndef DOXYGEN_SHOULD_SKIP_THIS class TraceStream : TraceStream(std.ostream o=osg.notify(osg.NOTICE), TraceLevel tl=Results) ~TraceStream() setTraceLevel = void(TraceLevel tl) TraceLevel getTraceLevel() stream = std.ostream(TraceLevel tl) _traceLevel = TraceLevel() _outputStreamPtr = std.ostream*() _nullStream = osgDB.ofstream() #endif # DOXYGEN_SHOULD_SKIP_THIS mutable TraceStream _tout TestSuite = class() TestCase = class() #* #Visits while maintaining the current hierarchical context. Also allows #the traversal to be short-circuited at any point during the visitation. # class TestVisitor : #..Should we enter this node and its children? virtual bool visitEnter( TestSuite* ) return True #..Returns True to continue to next Leaf virtual bool visit( TestCase* ) = 0 #..Returns True to continue to next Composite virtual bool visitLeave( TestSuite* ) return True TestVisitor() TestVisitor( TestVisitor ) virtual ~TestVisitor() #* #TestCase, supplies the interface for a Composite pattern's #\em leaf class, though it is not a leaf in itself. # class TestCase (Test) : typedef TestContext Context # Test in TestContext? is redundant TestCase( str sName ) : Test( sName ) def accept(v): return v.visit( this ) virtual void run( Context ) = 0 # Subclass OSGUTX_EXPORT Responsibility virtual ~TestCase() #* #Base class catchable for the exceptions which may be thrown to #indicate problems during the run of a TestCase. # class TestX : TestX( str s):_what(s) virtual ~TestX() def what(): return _what _what = str() #* #A TestFailureX indicates a failure in the tested component. # class TestFailureX (TestX) : TestFailureX( str s):TestX(s) #* #A TestErrorX indicates an error while testing a component, #which prevents the test from being run. It does not indicate #a problem with the component, but rather a problem during the #run which prevents the component from being tested. # class TestErrorX (TestX) : TestErrorX( str s):TestX(s) #* #TestCase_ is a class template for a leaf TestCase, which allows TestFixture #classes to be
set to true, it also calls the 'clean_up_ramdisk' method of boot interface to clean up the environment that was set for booting agent ramdisk. 3. Deletes the cleaning ports which were setup as part of cleaning. :param task: a TaskManager object containing the node :param manage_boot: If this is set to True, this method calls the 'clean_up_ramdisk' method of boot interface to boot the agent ramdisk. If False, it skips this step. :raises: NetworkError, NodeCleaningFailure if the cleaning ports cannot be removed. """ manager_utils.node_power_action(task, states.POWER_OFF) if manage_boot: task.driver.boot.clean_up_ramdisk(task) task.driver.network.remove_cleaning_network(task) def get_image_instance_info(node): """Gets the image information from the node. Get image information for the given node instance from its 'instance_info' property. :param node: a single Node. :returns: A dict with required image properties retrieved from node's 'instance_info'. :raises: MissingParameterValue, if image_source is missing in node's instance_info. Also raises same exception if kernel/ramdisk is missing in instance_info for non-glance images. """ info = {} info['image_source'] = node.instance_info.get('image_source') is_whole_disk_image = node.driver_internal_info.get('is_whole_disk_image') if not is_whole_disk_image: if not service_utils.is_glance_image(info['image_source']): info['kernel'] = node.instance_info.get('kernel') info['ramdisk'] = node.instance_info.get('ramdisk') error_msg = (_("Cannot validate image information for node %s because one " "or more parameters are missing from its instance_info") % node.uuid) check_for_missing_params(info, error_msg) return info def parse_instance_info(node): """Gets the instance specific Node deployment info. This method validates whether the 'instance_info' property of the supplied node contains the required information for this driver to deploy images to the node. :param node: a single Node. :returns: A dict with the instance_info values. :raises: MissingParameterValue, if any of the required parameters are missing. :raises: InvalidParameterValue, if any of the parameters have invalid value. """ info = node.instance_info i_info = {} i_info['image_source'] = info.get('image_source') iwdi = node.driver_internal_info.get('is_whole_disk_image') if not iwdi: if (i_info['image_source'] and not service_utils.is_glance_image( i_info['image_source'])): i_info['kernel'] = info.get('kernel') i_info['ramdisk'] = info.get('ramdisk') i_info['root_gb'] = info.get('root_gb') error_msg = _("Cannot validate driver deploy. Some parameters were missing" " in node's instance_info") check_for_missing_params(i_info, error_msg) # NOTE(vdrok): We're casting disk layout parameters to int only after # ensuring that it is possible i_info['swap_mb'] = info.get('swap_mb', 0) i_info['ephemeral_gb'] = info.get('ephemeral_gb', 0) err_msg_invalid = _("Cannot validate parameter for driver deploy. " "Invalid parameter %(param)s. Reason: %(reason)s") for param in DISK_LAYOUT_PARAMS: try: int(i_info[param]) except ValueError: reason = _("%s is not an integer value.") % i_info[param] raise exception.InvalidParameterValue(err_msg_invalid % {'param': param, 'reason': reason}) i_info['root_mb'] = 1024 * int(i_info['root_gb']) i_info['swap_mb'] = int(i_info['swap_mb']) i_info['ephemeral_mb'] = 1024 * int(i_info['ephemeral_gb']) if iwdi: if i_info['swap_mb'] > 0 or i_info['ephemeral_mb'] > 0: err_msg_invalid = _("Cannot deploy whole disk image with " "swap or ephemeral size set") raise exception.InvalidParameterValue(err_msg_invalid) i_info['ephemeral_format'] = info.get('ephemeral_format') i_info['configdrive'] = info.get('configdrive') if i_info['ephemeral_gb'] and not i_info['ephemeral_format']: i_info['ephemeral_format'] = CONF.pxe.default_ephemeral_format preserve_ephemeral = info.get('preserve_ephemeral', False) try: i_info['preserve_ephemeral'] = ( strutils.bool_from_string(preserve_ephemeral, strict=True)) except ValueError as e: raise exception.InvalidParameterValue( err_msg_invalid % {'param': 'preserve_ephemeral', 'reason': e}) # NOTE(Zhenguo): If rebuilding with preserve_ephemeral option, check # that the disk layout is unchanged. if i_info['preserve_ephemeral']: _check_disk_layout_unchanged(node, i_info) return i_info def _check_disk_layout_unchanged(node, i_info): """Check whether disk layout is unchanged. If the node has already been deployed to, this checks whether the disk layout for the node is the same as when it had been deployed to. :param node: the node of interest :param i_info: instance information (a dictionary) for the node, containing disk layout information :raises: InvalidParameterValue if the disk layout changed """ # If a node has been deployed to, this is the instance information # used for that deployment. driver_internal_info = node.driver_internal_info if 'instance' not in driver_internal_info: return error_msg = '' for param in DISK_LAYOUT_PARAMS: param_value = int(driver_internal_info['instance'][param]) if param_value != int(i_info[param]): error_msg += (_(' Deployed value of %(param)s was %(param_value)s ' 'but requested value is %(request_value)s.') % {'param': param, 'param_value': param_value, 'request_value': i_info[param]}) if error_msg: err_msg_invalid = _("The following parameters have different values " "from previous deployment:%(error_msg)s") raise exception.InvalidParameterValue(err_msg_invalid % {'error_msg': error_msg}) @METRICS.timer('build_instance_info_for_deploy') def build_instance_info_for_deploy(task): """Build instance_info necessary for deploying to a node. :param task: a TaskManager object containing the node :returns: a dictionary containing the properties to be updated in instance_info :raises: exception.ImageRefValidationFailed if image_source is not Glance href and is not HTTP(S) URL. """ def validate_image_url(url, secret=False): """Validates image URL through the HEAD request. :param url: URL to be validated :param secret: if URL is secret (e.g. swift temp url), it will not be shown in logs. """ try: image_service.HttpImageService().validate_href(url, secret) except exception.ImageRefValidationFailed as e: with excutils.save_and_reraise_exception(): LOG.error("Agent deploy supports only HTTP(S) URLs as " "instance_info['image_source'] or swift " "temporary URL. Either the specified URL is not " "a valid HTTP(S) URL or is not reachable " "for node %(node)s. Error: %(msg)s", {'node': node.uuid, 'msg': e}) node = task.node instance_info = node.instance_info iwdi = node.driver_internal_info.get('is_whole_disk_image') image_source = instance_info['image_source'] if service_utils.is_glance_image(image_source): glance = image_service.GlanceImageService(version=2, context=task.context) image_info = glance.show(image_source) LOG.debug('Got image info: %(info)s for node %(node)s.', {'info': image_info, 'node': node.uuid}) swift_temp_url = glance.swift_temp_url(image_info) validate_image_url(swift_temp_url, secret=True) instance_info['image_url'] = swift_temp_url instance_info['image_checksum'] = image_info['checksum'] instance_info['image_disk_format'] = image_info['disk_format'] instance_info['image_container_format'] = ( image_info['container_format']) instance_info['image_tags'] = image_info.get('tags', []) instance_info['image_properties'] = image_info['properties'] if not iwdi: instance_info['kernel'] = image_info['properties']['kernel_id'] instance_info['ramdisk'] = image_info['properties']['ramdisk_id'] else: validate_image_url(image_source) instance_info['image_url'] = image_source if not iwdi: instance_info['image_type'] = 'partition' i_info = parse_instance_info(node) instance_info.update(i_info) else: instance_info['image_type'] = 'whole-disk-image' return instance_info def check_interface_capability(interface, capability): """Evaluate interface to determine if capability is present. :param interface: The interface object to check. :param capability: The value representing the capability that the caller wishes to check if present. :returns: True if capability found, otherwise False. """ return capability in getattr(interface, 'capabilities', []) def get_remote_boot_volume(task): """Identify a boot volume from any configured volumes. :returns: None or the volume target representing the volume. """ targets = task.volume_targets for volume in targets: if volume['boot_index'] == 0: return volume def populate_storage_driver_internal_info(task): """Set node driver_internal_info for boot from volume parameters. :param task: a TaskManager object containing the node. :raises StorageError when a node has an iSCSI or FibreChannel boot volume defined but is not capable to support it. """ node = task.node boot_volume = get_remote_boot_volume(task) if not boot_volume: return vol_type = str(boot_volume.volume_type).lower() node_caps = driver_utils.capabilities_to_dict( node.properties.get('capabilities')) if vol_type == 'iscsi' and 'iscsi_boot' not in node_caps: # TODO(TheJulia): In order to support the FCoE and HBA boot cases, # some additional logic will be needed here to ensure we align. # The deployment, in theory, should never reach this point # if the interfaces all validated, but we shouldn't use that # as the only guard against bad configurations. raise exception.StorageError(_('Node %(node)s has an iSCSI boot ' 'volume defined and no iSCSI boot ' 'support available.') % {'node': node.uuid}) if vol_type == 'fibre_channel' and 'fibre_channel_boot' not in node_caps: raise exception.StorageError(_('Node %(node)s has a Fibre Channel ' 'boot volume defined and no Fibre ' 'Channel boot support available.') % {'node': node.uuid}) boot_capability = ("%s_volume_boot" % vol_type) deploy_capability = ("%s_volume_deploy" % vol_type) vol_uuid = boot_volume['uuid'] driver_internal_info = node.driver_internal_info if check_interface_capability(task.driver.boot, boot_capability): driver_internal_info['boot_from_volume'] = vol_uuid # NOTE(TheJulia): This would be a convenient place to check # if we need to know about deploying the volume. if (check_interface_capability(task.driver.deploy, deploy_capability) and task.driver.storage.should_write_image(task)): driver_internal_info['boot_from_volume_deploy'] = vol_uuid # NOTE(TheJulia): This is also a useful place to include a # root device hint since we should/might/be able to obtain # and supply that information to IPA if it needs to write # the image to the volume. node.driver_internal_info = driver_internal_info node.save() def tear_down_storage_configuration(task): """Clean up storage configuration. Remove entries from driver_internal_info for storage and deletes the volume targets from the database. This is done to ensure a clean state for the next boot of the machine. """ # TODO(mjturek): TheJulia mentioned that this should # possibly be configurable for the standalone case. However, # this is dangerous if IPA is not handling the cleaning. for volume in task.volume_targets: volume.destroy() LOG.info('Successfully deleted volume target %(target)s. ' 'The node associated with the target was %(node)s.', {'target': volume.uuid, 'node': task.node.uuid}) node = task.node driver_internal_info = node.driver_internal_info driver_internal_info.pop('boot_from_volume', None) driver_internal_info.pop('boot_from_volume_deploy', None) node.driver_internal_info = driver_internal_info node.save() def is_iscsi_boot(task): """Return true if booting from an iscsi volume.""" node = task.node volume = node.driver_internal_info.get('boot_from_volume') if volume: try: boot_volume = objects.VolumeTarget.get_by_uuid(
<reponame>ArdanaCLM/storevirtual-installer #!/usr/bin/python # # (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP # (c) Copyright 2017 SUSE 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 datetime import fcntl import json import os import re import shutil import socket import struct import sys import subprocess from subprocess import PIPE, Popen from netaddr import IPNetwork import logging import libvirt import vsa_excs import glob LOG = logging.getLogger() class Deployer: """ Creates necessary infrastructure like bridge, disk configuration file etc and creates VSA VM. Also, it provides other functionalities like start/stop/update VM. """ def __init__(self, connection, is_AO_capable, disk_file): self.hypervisor_conn = connection self.is_AO_enabled = is_AO_capable self.disk_file = disk_file self.CONFIG_DIR = os.environ['VSA_CONFIG_DIR'] self.VSA_PACKAGE = os.environ['VSA_IMAGE_PATH'] self.VSA_INSTALLER = os.environ['VSA_INSTALLER'] self.VSA_NETWORK_CONFIG_FILE = os.environ['VSA_NETWORK_CONFIG_FILE'] self.VSA_CONFIG_FILE = os.environ['VSA_CONFIG_FILE'] def install_vsa(self): self._pre_install_vsa() LOG.info("VSA deployment started") try: self._read_inputs() self._create_installer_input_json() self._initialize_default_json() self._create_bridge() self._create_storage_pool() self._create_vsa_vm() except vsa_excs.StoragePoolCreationFailed: LOG.error("VSA installation failed,rolling back") self._vsa_network_destroy() sys.exit(1) except vsa_excs.VMCreateFailed: LOG.error("VSA installation failed,rolling back") self._roll_back_installation() sys.exit(1) def destroy_vsa(self): """ Destroy the VSA that were created. """ try: self._read_configuration_input(self.VSA_CONFIG_FILE) self._vsa_domain_destroy() self._vsa_network_destroy() self._vsa_storage_pool_destroy() shutil.rmtree(self.pool_location, ignore_errors=True) LOG.info("VSA destroy success") except IOError as e: msg = ("Failed to destroy VSA setup %s" % e.message) LOG.error(msg) raise vsa_excs.DestroyFailed(msg) def _pre_install_vsa(self): """ Check for VSA VM status if exists :return:True: Exit the script. No VSA deployment required False: Continue with fresh deployment """ self._read_configuration_input(self.VSA_CONFIG_FILE) self.vsa_status = self._get_vsa_vm_status() if self.vsa_status == 1 or self.vsa_status == 3: msg = "The VSA vm is present on the host, exit from installation" LOG.info(msg) print "%s" % msg sys.exit(0) def _read_inputs(self): self._read_network_input() self._read_configuration_input(self.VSA_CONFIG_FILE) # # As directed, we will either read from input file or # discover disks. # try: if self.disk_file: self.vsa_disks = self._read_json(self.disk_file) self.tiered_disks = self.vsa_disks['vsa_disks'] self.disks = self._make_list_from_tiered() else: self.disks = self._discover_disks() self.total_disks = len(self.disks) LOG.info("Total disks for VSA deployment = %s" % self.total_disks) except IOError as e: msg = ("Failed to read vsa_disks.json %s" % e.message) LOG.error(msg) raise vsa_excs.DiskFileError(msg) def _create_installer_input_json(self): command = \ self.VSA_INSTALLER + " -create-default-json -disks " + \ str(self.total_disks) if self.total_disks == 0: msg = "Minimum number of disks must be 1. No disks are available" LOG.error(msg) raise vsa_excs.InvalidInputException(msg) if self.is_AO_enabled: if self.total_disks > 1: command += " -tiering" else: msg = "Cannot enable AO as only one disk is available" LOG.error(msg) raise vsa_excs.InvalidInputException(msg) resp = self._do_operation(command) if resp: raise vsa_excs.DefaultJSONCreationFailed(resp) def _initialize_default_json(self): try: data = self._read_json('default-input.json') data["HostName"] = self.host_name data["OSImageStoragePool"] = self.os_image_storagepool LOG.debug("HostName: %s\n OSImageStoragePool: %s" % (self.host_name, self.os_image_storagepool)) for network in data["Networks"]: network["DHCP"] = 0 network["IPAddress"] = self.vsa_ip LOG.debug("IPAddress: %s" % self.vsa_ip) network["Subnet"] = self.v_netmask LOG.debug("Subnet: %s" % self.v_netmask) network["Gateway"] = self.v_gateway LOG.debug("Gateway: %s" % self.v_gateway) network["NetworkInterface"] = self.v_network_name LOG.debug("NetworkInterface: %s" % self.v_network_name) counter = 0 tier_1_counter = 0 self._validate_disks() if self.is_AO_enabled: if self.disk_file: tier0count = len(self.tier0List) tier1count = len(self.tier1List) LOG.debug("tier0count: %s\t tier1count:%s" % (tier0count, tier1count)) for disk in data["Disks"]: if tier0count: disk["Location"] = self.tier0List[tier0count - 1] disk["Size"] = "" tier0count -= 1 elif tier1count > 0: disk["Location"] = self.tier1List[tier_1_counter] disk["Tier"] = "Tier 1" tier1count -= 1 tier_1_counter += 1 disk["Size"] = "" else: for disk in data["Disks"]: if self.disks[counter] == '/dev/sdb': # # /dev/sdb is considered as AO disk if disk_file # not mentioned # disk["Tier"] = "Tier 0" else: disk["Tier"] = "Tier 1" disk["Location"] = self.disks[counter] disk["Size"] = "" counter += 1 else: for disk in data["Disks"]: disk["Location"] = self.disks[counter] disk["Size"] = "" counter += 1 with open('default-input.json', 'w') as file_desc: file_desc.write(json.dumps(data, sort_keys=False, indent=4)) LOG.info("default input json initialization success") except Exception as e: msg = \ "An unknown exception during default input json initialization" LOG.error(msg + e.message) raise vsa_excs.DefaultJSONInitializationFailed(msg) def _create_bridge(self): try: with open(self.CONFIG_DIR + '/data/network_template.xml', 'r') \ as file_desc: xmlstring = file_desc.read() substitutions = {'NETWORK_NAME': self.v_network_name, 'BRIDGE_NAME': self.v_bridge_name} pattern = re.compile(r'%([^%]+)%') xmlstring = \ re.sub(pattern, lambda m: substitutions[m.group(1)], xmlstring) with open('network_vsa.xml', 'w') as file_desc: file_desc.write(xmlstring) return self._virtual_network_define('network_vsa.xml') except Exception as e: raise vsa_excs.BridgeCreationFailed(e.message) def _create_storage_pool(self): try: with open(self.CONFIG_DIR + '/data/storage_pool_template.xml', 'r') as file_desc: xmlstring = file_desc.read() substitutions = \ dict(POOL_NAME=self.os_image_storagepool, POOL_PATH=self.pool_location) pattern = re.compile(r'%([^%]+)%') xmlstring = \ re.sub(pattern, lambda m: substitutions[m.group(1)], xmlstring) with open('storage_pool_vsa.xml', 'w') as file_desc: file_desc.write(xmlstring) return self._virtual_storage_pool_define('storage_pool_vsa.xml') except Exception as e: raise vsa_excs.StoragePoolCreationFailed(e.message) def _create_vsa_vm(self): vsa_install_resp = \ self._do_operation(self.VSA_INSTALLER + " -no-prompt " + "default-input.json " + self.VSA_PACKAGE, need_output=True) if vsa_install_resp: msg = "VSA installation failed" LOG.error(msg) raise vsa_excs.VMCreateFailed(msg) LOG.info("VSA VM creation success") self._update_vsa_config() if self.autostart: # Set VSA VM autostart self._do_operation("virsh autostart " + self.host_name) LOG.info("Set VSA VM to autostart") def _read_configuration_input(self, config_file): LOG.info("Read VSA config from %s" % config_file) self.vsa_config_data = self._read_json(config_file) self.v_network_name = \ self.vsa_config_data["vsa_config"]["network_name"] self.host_name = self.vsa_config_data["vsa_config"]["hostname"] self.os_image_storagepool = \ self.vsa_config_data["vsa_config"]["os_image_storagepool"] self.pool_location = self.vsa_config_data["vsa_config"]["os_image_dir"] self.autostart = True if self.vsa_config_data["vsa_config"][ "autostart"] == 'True' else False if not os.path.exists(self.pool_location): os.makedirs(self.pool_location) def _read_network_input(self): """ This method will parse the JSON configuration file(vsa_config.json) and will consider the values as inputs for VBridge and VSA configuration @returns the json content of the vsa_config.json """ LOG.info( "Read VSA network config from %s" % self.VSA_NETWORK_CONFIG_FILE) self.network_config_data = self._read_json( self.VSA_NETWORK_CONFIG_FILE) self.v_bridge_name = self.network_config_data["virtual_bridge"]["name"] self.v_bridge_ip = \ self.network_config_data["virtual_bridge"]["ip_address"] self.v_interface = \ self.network_config_data["virtual_bridge"]["interface"] self.vsa_ip = self.network_config_data["vsa_network"]["ip_address"] LOG.debug("v_bridge_name:%s v_bridge_ip:%s v_interface:%s vsa_ip:%s" % (self.v_bridge_name, self.v_bridge_ip, self.v_interface, self.vsa_ip)) self.v_netmask = self._get_netmask_from_interface() self.v_gateway = self._compute_gateway() def _read_json(self, file_path): """ This method will parse the JSON configuration file(vsa_config.json) and will consider the values as inputs for VBridge and VSA configuration @returns the json content of the vsa_config.json """ LOG.info("Parse JSON : %s" % file_path) try: with open(file_path) as file_desc: config_data = json.load(file_desc) LOG.debug("Config data: %s" % config_data) return config_data except IOError as e: msg = ("Failed to load %s %s" % (file_path, e.message)) LOG.error(msg) raise vsa_excs.JsonParseException(msg) def _make_list_from_tiered(self): self.disks = [] self.tier0List = self.tiered_disks['Tier 0'] if any(self.tier0List): self.disks += self.tier0List LOG.info("Tier0 disks : %s" % self.tier0List) self.tier1List = self.tiered_disks['Tier 1'] if any(self.tier1List): self.disks += self.tier1List LOG.info("Tier1 disks : %s" % self.tier1List) LOG.info("Disks for VSA deployment : %s" % self.disks) return self.disks def _get_netmask_from_interface(self): """ Using socket this method retrieves the netmask details from the given interface """ try: netmask = socket.inet_ntoa(fcntl.ioctl(socket.socket( socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', str(self.v_bridge_name)))[20:24]) LOG.debug("Netmask : %s" % netmask) return netmask except Exception as e: msg = \ ("Cannot retrieve netmask from interface %s %s" % (self.v_interface, e.message)) LOG.error(msg) raise vsa_excs.NetmaskRetrieveFailed(msg) def _compute_gateway(self): """ Computes the gateway from the give vsa ip and netmask """ try: vsa_ip = IPNetwork(self.vsa_ip + '/' + self.v_netmask) gateway = vsa_ip.network + 1 LOG.debug("Gateway : %s" % gateway) return str(gateway) except Exception as e: msg = ("Computing gateway details failed %s" % e.message) LOG.error(msg) raise vsa_excs.ComputeGatewayFailed(msg) def _validate_disks(self): disks_from_host = self._discover_disks() for disk in self.disks: if disk not in disks_from_host: msg = "Invalid disk entries are present in the file" LOG.error(msg) raise vsa_excs.DeviceValidationFailed(msg) LOG.debug("Disk validation success") def _discover_disks(self): """ Gets all non-root disk. Rely on specific pattern (as per script) to determine whether disk is a root disk or not. Returns a list() containing reference of disk(s). """ disk_lists = \ Popen(self.CONFIG_DIR + "/scripts/get_devices.sh", stdout=PIPE).stdout.read().split(' ') LOG.debug("Disks in host : %s" % disk_lists) return disk_lists def _virtual_network_define(self, network_file): """ Defines and starts the virtual network from a xml file """ return_val = self._do_operation("virsh net-define " + network_file) if str(return_val) == "0": self._do_operation("virsh net-start " + self.v_network_name) self._do_operation("virsh net-autostart " + self.v_network_name) else: msg = "Creation of virtual network failed" LOG.error(msg) raise vsa_excs.BridgeCreationFailed(msg) LOG.info("VSA network creation success") def _virtual_storage_pool_define(self, pool_file): """ Defines and starts the storage pool from a xml file :type self: object """ return_val = self._do_operation("virsh pool-define " + pool_file) if str(return_val) == "0": self._do_operation("virsh pool-start " + self.os_image_storagepool) self._do_operation("virsh pool-autostart " + self.os_image_storagepool) else: msg = "Creation of virtual storage pool failed" LOG.error(msg) raise vsa_excs.StoragePoolCreationFailed(msg) LOG.info("VSA storage pool creation success") def _update_vsa_config(self): """ This method updates
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Datasets ================== Classes for dataset handling Dataset - Base class ^^^^^^^^^^^^^^^^^^^^ This is the base class, and all the specialized datasets are inherited from it. One should never use base class itself. Usage examples: .. code-block:: python :linenos: # Create class dataset = TUTAcousticScenes_2017_DevelopmentSet(data_path='data') # Initialize dataset, this will make sure dataset is downloaded, packages are extracted, and needed meta files are created dataset.initialize() # Show meta data dataset.meta.show() # Get all evaluation setup folds folds = dataset.folds() # Get all evaluation setup folds train_data_fold1 = dataset.train(fold=folds[0]) test_data_fold1 = dataset.test(fold=folds[0]) .. autosummary:: :toctree: generated/ Dataset Dataset.initialize Dataset.show_info Dataset.audio_files Dataset.audio_file_count Dataset.meta Dataset.meta_count Dataset.error_meta Dataset.error_meta_count Dataset.fold_count Dataset.scene_labels Dataset.scene_label_count Dataset.event_labels Dataset.event_label_count Dataset.audio_tags Dataset.audio_tag_count Dataset.download_packages Dataset.extract Dataset.train Dataset.test Dataset.eval Dataset.folds Dataset.file_meta Dataset.file_error_meta Dataset.file_error_meta Dataset.relative_to_absolute_path Dataset.absolute_to_relative AcousticSceneDataset ^^^^^^^^^^^^^^^^^^^^ .. autosummary:: :toctree: generated/ AcousticSceneDataset Specialized classes inherited AcousticSceneDataset: .. autosummary:: :toctree: generated/ TUTAcousticScenes_2017_DevelopmentSet TUTAcousticScenes_2016_DevelopmentSet TUTAcousticScenes_2016_EvaluationSet SoundEventDataset ^^^^^^^^^^^^^^^^^ .. autosummary:: :toctree: generated/ SoundEventDataset SoundEventDataset.event_label_count SoundEventDataset.event_labels SoundEventDataset.train SoundEventDataset.test Specialized classes inherited SoundEventDataset: .. autosummary:: :toctree: generated/ TUTRareSoundEvents_2017_DevelopmentSet TUTSoundEvents_2016_DevelopmentSet TUTSoundEvents_2016_EvaluationSet AudioTaggingDataset ^^^^^^^^^^^^^^^^^^^ .. autosummary:: :toctree: generated/ AudioTaggingDataset """ from __future__ import print_function, absolute_import import sys import os import logging import socket import zipfile import tarfile import collections import csv import numpy import hashlib import yaml from tqdm import tqdm from six import iteritems from .utils import get_parameter_hash, get_class_inheritors from .decorators import before_and_after_function_wrapper from .files import TextFile, ParameterFile, ParameterListFile, AudioFile from .containers import DottedDict from .metadata import MetaDataContainer, MetaDataItem def dataset_list(data_path, group=None): """List of datasets available Parameters ---------- data_path : str Base path for the datasets group : str Group label for the datasets, currently supported ['acoustic scene', 'sound event', 'audio tagging'] Returns ------- str Multi line string containing dataset table """ output = '' output += ' Dataset list\n' output += ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format( class_name='Class Name', group='Group', valid='Valid', files='Files' ) output += ' {class_name:<45s} + {group:20s} + {valid:5s} + {files:10s} +\n'.format( class_name='-' * 45, group='-' * 20, valid='-'*5, files='-'*10 ) def get_empty_row(): return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format( class_name='', group='', valid='', files='' ) def get_row(d): file_count = 0 if d.meta_container.exists(): file_count = len(d.meta) return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format( class_name=d.__class__.__name__, group=d.dataset_group, valid='Yes' if d.check_filelist() else 'No', files=str(file_count) if file_count else '' ) if not group or group == 'acoustic scene': for dataset_class in get_class_inheritors(AcousticSceneDataset): d = dataset_class(data_path=data_path) output += get_row(d) if not group or group == 'sound event': for dataset_class in get_class_inheritors(SoundEventDataset): d = dataset_class(data_path=data_path) output += get_row(d) if not group or group == 'audio tagging': for dataset_class in get_class_inheritors(AudioTaggingDataset): d = dataset_class(data_path=data_path) output += get_row(d) return output def dataset_factory(*args, **kwargs): """Factory to get correct dataset class based on name Parameters ---------- dataset_class_name : str Class name Default value "None" Raises ------ NameError Class does not exists Returns ------- Dataset class """ dataset_class_name = kwargs.get('dataset_class_name', None) try: return eval(dataset_class_name)(*args, **kwargs) except NameError: message = '{name}: No valid dataset given [{dataset_class_name}]'.format( name='dataset_factory', dataset_class_name=dataset_class_name ) logging.getLogger('dataset_factory').exception(message) raise NameError(message) class Dataset(object): """Dataset base class The specific dataset classes are inherited from this class, and only needed methods are reimplemented. """ def __init__(self, *args, **kwargs): """Constructor Parameters ---------- name : str storage_name : str data_path : str Basepath where the dataset is stored. (Default value='data') logger : logger Instance of logging Default value "none" show_progress_in_console : bool Show progress in console. Default value "True" log_system_progress : bool Show progress in log. Default value "False" use_ascii_progress_bar : bool Show progress bar using ASCII characters. Use this if your console does not support UTF-8 characters. Default value "False" """ self.logger = kwargs.get('logger') or logging.getLogger(__name__) self.disable_progress_bar = not kwargs.get('show_progress_in_console', True) self.log_system_progress = kwargs.get('log_system_progress', False) self.use_ascii_progress_bar = kwargs.get('use_ascii_progress_bar', True) # Dataset name self.name = kwargs.get('name', 'dataset') # Folder name for dataset self.storage_name = kwargs.get('storage_name', 'dataset') # Path to the dataset self.local_path = os.path.join(kwargs.get('data_path', 'data'), self.storage_name) # Evaluation setup folder self.evaluation_setup_folder = kwargs.get('evaluation_setup_folder', 'evaluation_setup') # Path to the folder containing evaluation setup files self.evaluation_setup_path = os.path.join(self.local_path, self.evaluation_setup_folder) # Meta data file, csv-format self.meta_filename = kwargs.get('meta_filename', 'meta.txt') # Path to meta data file self.meta_container = MetaDataContainer(filename=os.path.join(self.local_path, self.meta_filename)) if self.meta_container.exists(): self.meta_container.load() # Error meta data file, csv-format self.error_meta_filename = kwargs.get('error_meta_filename', 'error.txt') # Path to error meta data file self.error_meta_file = os.path.join(self.local_path, self.error_meta_filename) # Hash file to detect removed or added files self.filelisthash_filename = kwargs.get('filelisthash_filename', 'filelist.python.hash') # Dirs to be excluded when calculating filelist hash self.filelisthash_exclude_dirs = kwargs.get('filelisthash_exclude_dirs', []) # Number of evaluation folds self.crossvalidation_folds = 1 # List containing dataset package items # Define this in the inherited class. # Format: # { # 'remote_package': download_url, # 'local_package': os.path.join(self.local_path, 'name_of_downloaded_package'), # 'local_audio_path': os.path.join(self.local_path, 'name_of_folder_containing_audio_files'), # } self.package_list = [] # List of audio files self.files = None # List of audio error meta data dict self.error_meta_data = None # Training meta data for folds self.crossvalidation_data_train = {} # Testing meta data for folds self.crossvalidation_data_test = {} # Evaluation meta data for folds self.crossvalidation_data_eval = {} # Recognized audio extensions self.audio_extensions = {'wav', 'flac'} self.default_audio_extension = 'wav' # Reference data presence flag, by default dataset should have reference data present. # However, some evaluation dataset might not have self.reference_data_present = True # Info fields for dataset self.authors = '' self.name_remote = '' self.url = '' self.audio_source = '' self.audio_type = '' self.recording_device_model = '' self.microphone_model = '' def initialize(self): # Create the dataset path if does not exist if not os.path.isdir(self.local_path): os.makedirs(self.local_path) if not self.check_filelist(): self.download_packages() self.extract() self._save_filelist_hash() return self def show_info(self): DottedDict(self.dataset_meta).show() @property def audio_files(self): """Get all audio files in the dataset Parameters ---------- Returns ------- filelist : list File list with absolute paths """ if self.files is None: self.files = [] for item in self.package_list: path = item['local_audio_path'] if path: l = os.listdir(path) for f in l: file_name, file_extension = os.path.splitext(f) if file_extension[1:] in self.audio_extensions: if os.path.abspath(os.path.join(path, f)) not in self.files: self.files.append(os.path.abspath(os.path.join(path, f))) self.files.sort() return self.files @property def audio_file_count(self): """Get number of audio files in dataset Parameters ---------- Returns ------- filecount : int Number of audio files """ return len(self.audio_files) @property def meta(self): """Get meta data for dataset. If not already read from disk, data is read and returned. Parameters ---------- Returns ------- meta_container : list List containing meta data as dict. Raises ------- IOError meta file not found. """ if self.meta_container.empty(): if self.meta_container.exists(): self.meta_container.load() else: message = '{name}: Meta file not found [{filename}]'.format( name=self.__class__.__name__, filename=self.meta_container.filename ) self.logger.exception(message) raise IOError(message) return self.meta_container @property def meta_count(self): """Number of meta data items. Parameters ---------- Returns ------- meta_item_count : int Meta data item count """ return len(self.meta_container) @property def error_meta(self): """Get audio error meta data for dataset. If not already read from disk, data is read and returned. Parameters ---------- Raises ------- IOError: audio error meta file not found. Returns ------- error_meta_data : list List containing audio error meta data as dict. """ if self.error_meta_data is None: self.error_meta_data = MetaDataContainer(filename=self.error_meta_file) if self.error_meta_data.exists(): self.error_meta_data.load() else: message = '{name}: Error meta file not found [{filename}]'.format(name=self.__class__.__name__, filename=self.error_meta_file) self.logger.exception(message) raise IOError(message) return self.error_meta_data def error_meta_count(self): """Number of error meta data items. Parameters ---------- Returns ------- meta_item_count : int Meta data item count """ return len(self.error_meta) @property def fold_count(self): """Number of fold in the evaluation setup. Parameters ---------- Returns ------- fold_count : int Number of folds """ return self.crossvalidation_folds @property def scene_labels(self): """List of unique scene labels in the meta data. Parameters ---------- Returns ------- labels : list List of scene labels in alphabetical order. """ return self.meta_container.unique_scene_labels @property def scene_label_count(self): """Number of unique scene labels in the meta data. Parameters ---------- Returns ------- scene_label_count : int Number of unique scene labels. """ return self.meta_container.scene_label_count def event_labels(self): """List of unique event labels in the meta data. Parameters ---------- Returns ------- labels : list List of event labels in alphabetical order. """ return self.meta_container.unique_event_labels @property def event_label_count(self): """Number of unique event labels in the meta data. Parameters ---------- Returns ------- event_label_count : int Number of unique event labels """ return self.meta_container.event_label_count @property def audio_tags(self): """List of unique audio tags in the meta data. Parameters ---------- Returns ------- labels : list List of audio tags in alphabetical order. """ tags = [] for item
#!/usr/bin/env python ''' This file is part of the PyMSRPC project and is licensed under the project license. ndr.py This are the functions that provide all the NDR data types. It handles serialization and everything. I have spent a shit load of time on this and yet they are not 100%. This is usually due to structure padding or array serialization but honestly debugging it is such a beating so this is what I have for now. (c) 2007 <NAME> - BSD License - See LICENSE.txt ''' import sys, struct, random, re, copy DEBUG = False ####################################################################### # # Opcodes # ####################################################################### class ndr_opcode: def __init__(self, **kwargs): self.opnum = kwargs.get('opnum', 0x0) self.address = kwargs.get('address', 0x00000000) self.elements = kwargs.get('elements', []) self.out = kwargs.get('out', None) self.align_byte = kwargs.get('align_byte', "\xaa") def align(self, data): return self.align_byte * ((4 - (len(data) & 3)) & 3) # Allows us to set a context handle for [in] params def set_context_handle(self, handle): for elem in self.elements: if isinstance(elem, ndr_context_handle): elem.data = handle return True return False def serialize(self): serialdata = "" for elem in self.elements: s = elem.serialize() serialdata += s + self.align(s) return serialdata ####################################################################### # # NDR Parent Classes # ####################################################################### class ndr_primitive(object): def align(self, data): return self.align_byte * ((4 - (len(data) & 3)) & 3) def serialize(self): raise NotImplementedError class ndr_container(object): def align(self, data): return self.align_byte * ((4 - (len(data) & 3)) & 3) def add_static(self, obj): if DEBUG: print "[*] add_static", if not self.parent: if DEBUG: print "self" self.s.append(obj) else: if DEBUG: print "parent" self.parent.add_static(obj) def add_deferred(self, obj): if DEBUG: print "[*] add_deferred", if not self.parent: if DEBUG: print "self" self.d.append(obj) else: if DEBUG: print "parent" self.parent.add_deferred(obj) def serialize(self): raise NotImplementedError ####################################################################### # # Primitives # ####################################################################### class ndr_pad(ndr_primitive): ''' pad placeholder ''' def __init__(self): pass class ndr_byte(ndr_primitive): ''' encode: byte element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x06) self.signed = kwargs.get('signed', False) self.name = kwargs.get('name', "") self.size = 1 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<b", self.data) else: return struct.pack("<B", self.data) class ndr_small(ndr_primitive): ''' encode: small element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x00) self.signed = kwargs.get('signed', False) self.name = kwargs.get('name', "") self.size = 1 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<b", self.data) else: return struct.pack("<B", self.data) class ndr_char(ndr_primitive): ''' encode: char [*] element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x03) self.signed = kwargs.get('signed', False) self.name = kwargs.get('name', "") self.size = 1 if self.signed: raise Exception def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return chr(self.data) class ndr_wchar(ndr_primitive): ''' encode: wchar element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x42) self.signed = kwargs.get('signed', False) self.name = kwargs.get('name', "") self.size = 2 if self.signed: raise Exception def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return chr(self.data).encode("utf-16le") class ndr_void(ndr_primitive): ''' encode: void *element_1 ''' def __init__(self, **kwargs): self.data = kwargs.get('data', "") self.name = kwargs.get('name', "") self.size = 4 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return self.data class ndr_user_marshal(ndr_primitive): ''' encode: [user_marshal(4)] struct struct_12 * elem_24; Untested/Unsupported because technically ths calls a user function ''' def __init__(self, **kwargs): self.num = kwargs.get('num', 0x4) self.data = kwargs.get('data', "") self.name = kwargs.get('name', "") self.size = 0 def get_size(self): return self.size def get_packed(self): return struct.pack("<L", self.num) class ndr_range(ndr_primitive): ''' encode: [range(0,1000)] long elem_1; ''' def __init__(self, low=0x0, high=0xffffffff, data=""): self.low = kwargs.get('low', 0x0) self.high = kwargs.get('high', 0xffffffff) self.data = kwargs.get('data', "") self.size = 0 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_size(self): return self.size def serialize(self): if not self.data: self.data = ndr_long(data=random.randint(self.low, self.high)) else: if self.data.get_data() > self.high: self.data.data = self.high elif self.data.get_data() < self.low: self.data.data = self.low return self.data.serialize() class ndr_enum16(ndr_primitive): ''' encode: /* enum16 */ short element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x0004) self.signed = kwargs.get('signed', True) self.name = kwargs.get('name', "") self.size = 2 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<H", self.data) else: return struct.pack("<h", self.data) class ndr_short(ndr_primitive): ''' encode: short element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x0004) self.signed = kwargs.get('signed', True) self.name = kwargs.get('name', "") self.size = 2 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<H", self.data) else: return struct.pack("<h", self.data) class ndr_interface(ndr_primitive): ''' encode: interface(0000000c-0000-0000-c000-000000000046) ''' def __init__(self, **kwargs): self.data = kwargs.get('data', "\x89" * 20) self.name = kwargs.get('name', "") self.size = 20 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return self.data class ndr_long(ndr_primitive): ''' encode: long element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x00000002) self.signed = kwargs.get('signed', True) self.name = kwargs.get('name', "") self.size = 4 def set_data(self, new_data): self.data = new_data def get_data(self): return self.data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<l", self.data) else: return struct.pack("<L", self.data) class ndr_hyper(ndr_primitive): ''' encode: hyper (aka 64bit) element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0x0000000000000005) self.signed = kwargs.get('signed', True) self.name = kwargs.get('name', "") self.size = 8 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): if self.signed: return struct.pack("<q", self.data) else: return struct.pack("<Q", self.data) class ndr_empty(ndr_primitive): ''' used for default or empty cases in unions/unknown stuff ''' def __init__(self, **kwargs): self.data = kwargs.get('data', "") self.name = kwargs.get('name', "") self.size = 0 def get_data(self): return self.data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return "" class ndr_float(ndr_primitive): ''' encode: float element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0.0) self.name = kwargs.get('name', "") self.size = 4 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return self.size def serialize(self): return struct.pack("<f", self.data) class ndr_double(ndr_primitive): ''' encode: double element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', 0.0) self.name = kwargs.get('name', "") self.size = 8 def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def serialize(self): return struct.pack("<d", self.data) class ndr_string(ndr_primitive): ''' encode: char *element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', "Administrator") self.name = kwargs.get('name', "") self.align_byte = kwargs.get('align_byte', "\xaa") self.size = 0 def pad(self, data): return self.align_byte * ((4 - (len(data) & 3)) & 3) def get_data(self): return self.data def set_data(self, new_data): self.data = new_data def get_name(self): return self.name def get_size(self): return len(self.get_packed()) def serialize(self): # We add our null because it gets counted self.data += "\x00" length = len(self.data) # Conformance varying information return struct.pack("<L", length) \ + struct.pack("<L", 0) \ + struct.pack("<L", length) \ + self.data \ + self.pad(self.data) \ class ndr_wstring(ndr_primitive): ''' encode: wchar *element_1; ''' def __init__(self, **kwargs): self.data = kwargs.get('data', "\\\\EXCHANGE2K3") self.name = kwargs.get('name', "") self.align_byte = kwargs.get('align_byte', "\xaa") self.size = 0 def pad(self, data): return self.align_byte * ((4 - (len(data) & 3)) & 3) def set_data(self, new_data): self.data = new_data def get_data(self): return self.data def get_name(self): return self.name def get_size(self): return len(self.get_packed()) def serialize(self): # Add our wide null because it
True) if not outs: return for out in outs: if not core.is_a_shape(out): shapes = core.get_shapes(out) if shapes: out = shapes[0] if cmds.nodeType(out) == 'nRigid': slot = attr.get_available_slot('%s.inputPassive' % nucleus) cmds.connectAttr('%s.currentState' % out, '%s.inputPassive[%s]' % (nucleus, slot)) cmds.connectAttr('%s.startState' % out, '%s.inputPassiveStart[%s]' % (nucleus, slot)) def add_nCloth_to_mesh(mesh, world = False): cmds.select(mesh, r = True) pass_value = 0 if world: pass_value = 1 nodes = mel.eval('createNCloth %s;' % pass_value) if world == True: output_mesh = attr.get_attribute_outputs('%s.outputMesh' % nodes[0], node_only = True) world_mesh = cmds.rename(output_mesh, 'world_%s' % mesh) parent = cmds.listRelatives(mesh, p = True) if parent: cmds.parent(world_mesh, parent[0]) if not nodes: util.warning('No ncloth created on %s' % mesh) return parent = cmds.listRelatives(nodes[0], p = True) parent = cmds.rename(parent, 'nCloth_%s' % mesh) cmds.setAttr('%s.thickness' % parent, 0.02) return [parent] def set_active_nucleus(nucleus_name): """ This sets a global variable that is used by maya to know what nucleus to perform commands on. """ mel.eval('global string $gActiveNucleusNode;$gActiveNucleusNode = "%s";' % nucleus_name) def nConstrain_to_mesh(verts, mesh, name = None, force_passive = False,): """ Constrain an ncloth to a passive collider. Args: verts (list): The list of verts to constrain on an nCloth mesh. mesh (str): The name of a mesh to constrain to. force_passive (bool): Wether to make mesh into a passive collider. """ nodes1 = [] if force_passive: nodes1 = add_passive_collider_to_mesh(mesh) cmds.setAttr('%s.collide' % nodes1[0], 0) cmds.select(cl = True) cmds.select(verts, mesh) nodes = mel.eval('createNConstraint pointToSurface 0;') if name: parent = cmds.listRelatives(nodes[0], p = True)[0] nodes = cmds.rename(parent, 'dynamicConstraint_%s' % name) nodes = util.convert_to_sequence(nodes) return nodes + nodes1 def nConstrain_verts(verts, name = None, force_passive= False): nodes1 = [] cmds.select(cl = True) cmds.select(verts) nodes = mel.eval('createNConstraint pointToPoint 0;') if name: parent = cmds.listRelatives(nodes[0], p = True)[0] nodes = cmds.rename(parent, 'dynamicConstraint_%s' % name) nodes = util.convert_to_sequence(nodes) return nodes + nodes1 def create_cloth_input_meshes(deform_mesh, cloth_mesh, parent, attribute): final = cmds.duplicate(deform_mesh)[0] final = cmds.rename(final, 'temp') clothwrap = cmds.duplicate(deform_mesh)[0] deform_mesh_orig = deform_mesh deform_mesh = core.prefix_hierarchy(deform_mesh, 'deform')[0] clothwrap = cmds.rename(clothwrap, deform_mesh) clothwrap = core.prefix_hierarchy(clothwrap, 'clothwrap')[0] final = cmds.rename(final, deform_mesh_orig) deform_mesh = deform_mesh.split('|')[-1] clothwrap = clothwrap.split('|')[-1] deform.create_wrap(deform_mesh, cloth_mesh) deform.create_wrap(cloth_mesh, clothwrap) blend = cmds.blendShape(deform_mesh, clothwrap, final, w = [0,1], n = 'blendShape_nClothFinal')[0] attr.connect_equal_condition(attribute, '%s.%s' % (blend, deform_mesh), 0) attr.connect_equal_condition(attribute, '%s.%s' % (blend, clothwrap), 1) cmds.parent(deform_mesh , clothwrap, parent ) nodes = add_nCloth_to_mesh(cloth_mesh) return nodes #--- cMuscle class CMuscle(object): def __init__(self, muscle): self.muscle = muscle self.description = None if not cmds.objExists('%s.description' % self.muscle): cmds.addAttr(self.muscle, ln = 'description', dt = 'maya_util') def _get_control_data_indices(self): muscle_creator = self._get_muscle_creator() return attr.get_indices('%s.controlData' % muscle_creator) def _get_attach_data_indices(self): muscle_creator = self._get_muscle_creator() return attr.get_indices('%s.attachData' % muscle_creator) def _get_parent(self): rels = cmds.listRelatives(self.muscle, p = True) return rels[0] def _get_muscle_creator(self): return attr.get_attribute_input('%s.create' % self.muscle, True) def _get_muscle_shapes(self): shapes = core.get_shapes(self.muscle) deformer = None nurbs = None for shape in shapes: if cmds.nodeType(shape) == 'cMuscleObject': deformer = shape if cmds.nodeType(shape) == 'nurbsSurface': nurbs = shape return nurbs, deformer def _rename_controls(self, name): name_upper = name[0].upper() + name[1:] indices = self._get_control_data_indices() count = len(indices) muscle_creator = self._get_muscle_creator() last_xform = None for inc in range(0, count): input_value = attr.get_attribute_input('%s.controlData[%s].insertMatrix' % (muscle_creator, inc), True) input_drive = cmds.listRelatives(input_value, p = True)[0] input_xform = cmds.listRelatives(input_drive, p = True)[0] input_stretch = attr.get_attribute_input('%s.controlData[%s].curveSt' % (muscle_creator, inc), True) input_squash = attr.get_attribute_input('%s.controlData[%s].curveSq' % (muscle_creator, inc), True) input_rest = attr.get_attribute_input('%s.controlData[%s].curveRest' % (muscle_creator, inc), True) cmds.delete(input_stretch, input_squash, input_rest, ch = True) if inc == 0: cmds.rename(input_value, core.inc_name('startParent_%s' % name)) if inc == count-1: cmds.rename(input_value, core.inc_name('endParent_%s' % name)) if inc > 0 and inc < count-1: input_value = cmds.rename(input_value, core.inc_name('ctrl_%s_%s' % (inc, name))) shape = core.get_shapes(input_value) cmds.rename(shape, '%sShape' % input_value) input_stretch = cmds.listRelatives(input_stretch, p = True)[0] input_squash = cmds.listRelatives(input_squash, p = True)[0] input_rest = cmds.listRelatives(input_rest, p = True)[0] cmds.rename(input_stretch, core.inc_name('ctrl_%s_stretch%s' % (inc, name_upper))) cmds.rename(input_squash, core.inc_name('ctrl_%s_squash%s' % (inc, name_upper))) cmds.rename(input_rest, core.inc_name('ctrl_%s_rest%s' % (inc, name_upper))) cmds.rename(input_drive, 'drive_%s' % input_value) input_xform = cmds.rename(input_xform, 'xform_%s' % input_value) last_xform = input_xform parent = cmds.listRelatives(last_xform, p = True)[0] cmds.rename(parent, core.inc_name('controls_cMuscle%s' % name_upper)) def _rename_attach_controls(self, name): indices = self._get_attach_data_indices() count = len(indices) muscle_creator = self._get_muscle_creator() last_xform = None for inc in range(0, count): name_upper = name[0].upper() + name[1:] input_value = attr.get_attribute_input('%s.attachData[%s].attachMatrix' % (muscle_creator, inc), True) input_drive = cmds.listRelatives(input_value, p = True)[0] input_xform = cmds.listRelatives(input_drive, p = True)[0] input_stretch = attr.get_attribute_input('%s.attachData[%s].attachMatrixSt' % (muscle_creator, inc), True) input_squash = attr.get_attribute_input('%s.attachData[%s].attachMatrixSq' % (muscle_creator, inc), True) input_value = cmds.rename(input_value, core.inc_name('ctrl_%s_attach%s' % (inc+1, name_upper))) cmds.rename(input_stretch, core.inc_name('ctrl_%s_attachStretch%s' % (inc+1, name_upper))) cmds.rename(input_squash, core.inc_name('ctrl_%s_attachSquash%s' % (inc+1, name_upper))) cmds.rename(input_drive, 'drive_%s' % input_value) input_xform = cmds.rename(input_xform, 'xform_%s' % input_value) last_xform = input_xform parent = cmds.listRelatives(last_xform, p = True)[0] cmds.rename(parent, core.inc_name('attach_cMuscle%s' % name_upper)) def _rename_locators(self, name): muscle_creator = self._get_muscle_creator() input_start_A = attr.get_attribute_input('%s.startPointA' % muscle_creator, True) input_start_B = attr.get_attribute_input('%s.startPointB' % muscle_creator, True) input_end_A = attr.get_attribute_input('%s.endPointA' % muscle_creator, True) input_end_B = attr.get_attribute_input('%s.endPointB' % muscle_creator, True) cmds.rename(input_start_A, core.inc_name('locatorStart1_%s' % name)) cmds.rename(input_start_B, core.inc_name('locatorStart2_%s' % name)) cmds.rename(input_end_A, core.inc_name('locatorEnd1_%s' % name)) cmds.rename(input_end_B, core.inc_name('locatorEnd2_%s' % name)) def rename(self, name): nurbsSurface, muscle_object = self._get_muscle_shapes() muscle_creator = self._get_muscle_creator() self.muscle = cmds.rename(self.muscle, core.inc_name('cMuscle_%s' % name)) if cmds.objExists(nurbsSurface): cmds.rename(nurbsSurface, core.inc_name('%sShape' % self.muscle)) cmds.rename(muscle_object, core.inc_name('cMuscleObject_%sShape' % name)) cmds.rename(muscle_creator, core.inc_name('cMuscleCreator_%s' % name)) parent = self._get_parent() cmds.rename(parent, core.inc_name('cMuscle_%s_grp' % name)) self._rename_controls(name) self._rename_attach_controls(name) self._rename_locators(name) self.description = name cmds.setAttr('%s.description' % self.muscle, name, type = 'maya_util') def create_attributes(self, node = None): if not node: node = self.muscle muscle_creator = self._get_muscle_creator() description = cmds.getAttr('%s.description' % self.muscle) title = attr.MayaEnumVariable(description.upper()) title.create(node) if node == self.muscle: cmds.addAttr(node, ln = 'controlVisibility_%s' % description, at = 'bool', k = True ) cmds.connectAttr('%s.controlVisibility_%s' % (node, description), '%s.showControls' % muscle_creator) indices = self._get_attach_data_indices() count = len(indices) attributes = ['jiggle', 'jiggleX', 'jiggleY', 'jiggleZ', 'jiggleImpact', 'jiggleImpactStart', 'jiggleImpactStop', 'cycle', 'rest'] for inc in range(0, count): current = inc+1 title_name = 'muscle_section_%s' % (current) title_name = title_name.upper() title = attr.MayaEnumVariable(title_name) title.create(node) control = attr.get_attribute_input('%s.controlData[%s].insertMatrix' % (muscle_creator, current), True) for attribute in attributes: other_attribute = '%s_%s' % (attribute, current) attribute_value = cmds.getAttr('%s.%s' % (control, attribute)) cmds.addAttr(node, ln = other_attribute, at = 'double', k = True, dv = attribute_value) cmds.connectAttr('%s.%s' % (node, other_attribute), '%s.%s' % (control, attribute)) def add_muscle_to_mesh(mesh): mesh_shape = geo.get_mesh_shape(mesh, 0) if not mesh_shape: return mesh_shape_name = core.get_basename(mesh_shape) shape = cmds.createNode('cMuscleObject', n = 'cMuscleObject_%s' % mesh_shape_name, p = mesh) cmds.hide(shape) cmds.connectAttr('%s.worldMatrix' % mesh_shape, '%s.worldMatrixStart' % mesh) cmds.connectAttr('%s.worldMesh' % mesh_shape, '%s.meshIn' % shape) cmds.setAttr('%s.draw' % shape, 0) cmds.setAttr('%s.localPositionX' % shape, k = False, cb = False) cmds.setAttr('%s.localPositionY' % shape, k = False, cb = False) cmds.setAttr('%s.localPositionZ' % shape, k = False, cb = False) cmds.setAttr('%s.localScaleX' % shape, k = False, cb = False) cmds.setAttr('%s.localScaleY' % shape, k = False, cb = False) cmds.setAttr('%s.localScaleZ' % shape, k = False, cb = False) cmds.setAttr('%s.type' % shape, k = False) cmds.setAttr('%s.radius' % shape, k = False) cmds.setAttr('%s.length' % shape, k = False) cmds.setAttr('%s.capsuleAxis' % shape, k = False) cmds.setAttr('%s.userScaleX' % shape, k = False) cmds.setAttr('%s.userScaleY' % shape, k = False) cmds.setAttr('%s.userScaleZ' % shape, k = False) cmds.setAttr('%s.nSeg' % shape, k = False) cmds.setAttr('%s.nSides' % shape, k = False) return shape def add_mesh_to_keep_out(mesh, keep_out): shapes = core.get_shapes(mesh, 'cMuscleObject') if shapes: shape = shapes[0] if not shapes: shape = add_muscle_to_mesh(mesh) cmds.connectAttr('%s.muscleData' % shape, '%s.muscleData[0]' % keep_out) def create_keep_out(collide_transform = None, collide_mesh = None, name = None): """ Collide a transform with a mesh. It will generate a locator that can be used to drive an aim or an ik, or a set driven key Args: collide_transform (str): The transform that should collide with the mesh. This needs to be a point
*unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-528 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-529 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-530 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-531 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-532 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-533 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-534 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-535 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-536 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-537 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-538 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-539 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-540 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-541 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-542 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-543 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-544 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-545 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-546 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-547 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-548 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-549 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-550 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1000 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1001 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1002 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1003 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1004 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1005 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1006 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1007 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1008 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1009 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1010 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1011 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1012 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1013 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1014 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1015 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1016 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1017 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1018 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1019 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1020 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1021 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1022 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1023 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1024 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1025 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1026 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1027 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1028 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1029 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1030 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1031 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1032 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1033 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1034 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1035 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1036 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1037 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1038 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1039 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1040 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1041 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1042 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1043 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1044 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1045 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1046 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1047 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1048 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1049 *unknown*\*unknown* (8) S-1-5-82-3006700770-424185619-1745488364-794895919-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-80 and logon username 'administrator', password '<PASSWORD>' S-1-5-80-500 *unknown*\*unknown* (8) S-1-5-80-501 *unknown*\*unknown* (8) S-1-5-80-502 *unknown*\*unknown* (8) S-1-5-80-503 *unknown*\*unknown* (8) S-1-5-80-504 *unknown*\*unknown* (8) S-1-5-80-505 *unknown*\*unknown* (8) S-1-5-80-506 *unknown*\*unknown* (8) S-1-5-80-507 *unknown*\*unknown* (8) S-1-5-80-508 *unknown*\*unknown* (8) S-1-5-80-509 *unknown*\*unknown* (8) S-1-5-80-510 *unknown*\*unknown* (8) S-1-5-80-511 *unknown*\*unknown* (8) S-1-5-80-512 *unknown*\*unknown* (8) S-1-5-80-513 *unknown*\*unknown* (8) S-1-5-80-514 *unknown*\*unknown* (8) S-1-5-80-515 *unknown*\*unknown* (8) S-1-5-80-516 *unknown*\*unknown* (8) S-1-5-80-517 *unknown*\*unknown* (8) S-1-5-80-518 *unknown*\*unknown* (8) S-1-5-80-519 *unknown*\*unknown* (8) S-1-5-80-520 *unknown*\*unknown* (8) S-1-5-80-521 *unknown*\*unknown* (8) S-1-5-80-522 *unknown*\*unknown* (8) S-1-5-80-523 *unknown*\*unknown* (8) S-1-5-80-524 *unknown*\*unknown* (8) S-1-5-80-525 *unknown*\*unknown* (8) S-1-5-80-526 *unknown*\*unknown* (8) S-1-5-80-527 *unknown*\*unknown* (8) S-1-5-80-528 *unknown*\*unknown* (8) S-1-5-80-529 *unknown*\*unknown* (8) S-1-5-80-530 *unknown*\*unknown* (8) S-1-5-80-531 *unknown*\*unknown* (8) S-1-5-80-532 *unknown*\*unknown* (8) S-1-5-80-533 *unknown*\*unknown* (8) S-1-5-80-534 *unknown*\*unknown* (8) S-1-5-80-535 *unknown*\*unknown* (8) S-1-5-80-536 *unknown*\*unknown* (8) S-1-5-80-537 *unknown*\*unknown* (8) S-1-5-80-538 *unknown*\*unknown* (8) S-1-5-80-539 *unknown*\*unknown* (8) S-1-5-80-540 *unknown*\*unknown* (8) S-1-5-80-541 *unknown*\*unknown* (8) S-1-5-80-542 *unknown*\*unknown* (8) S-1-5-80-543 *unknown*\*unknown* (8) S-1-5-80-544 *unknown*\*unknown* (8) S-1-5-80-545 *unknown*\*unknown* (8) S-1-5-80-546 *unknown*\*unknown* (8) S-1-5-80-547 *unknown*\*unknown* (8) S-1-5-80-548 *unknown*\*unknown* (8) S-1-5-80-549 *unknown*\*unknown* (8) S-1-5-80-550 *unknown*\*unknown* (8) S-1-5-80-1000 *unknown*\*unknown* (8) S-1-5-80-1001 *unknown*\*unknown* (8) S-1-5-80-1002 *unknown*\*unknown* (8) S-1-5-80-1003 *unknown*\*unknown* (8) S-1-5-80-1004 *unknown*\*unknown* (8) S-1-5-80-1005 *unknown*\*unknown* (8) S-1-5-80-1006 *unknown*\*unknown* (8) S-1-5-80-1007 *unknown*\*unknown* (8) S-1-5-80-1008 *unknown*\*unknown* (8) S-1-5-80-1009 *unknown*\*unknown* (8) S-1-5-80-1010 *unknown*\*unknown* (8) S-1-5-80-1011 *unknown*\*unknown* (8) S-1-5-80-1012 *unknown*\*unknown* (8) S-1-5-80-1013 *unknown*\*unknown* (8) S-1-5-80-1014 *unknown*\*unknown* (8) S-1-5-80-1015 *unknown*\*unknown* (8) S-1-5-80-1016 *unknown*\*unknown* (8) S-1-5-80-1017 *unknown*\*unknown* (8) S-1-5-80-1018 *unknown*\*unknown* (8) S-1-5-80-1019 *unknown*\*unknown* (8) S-1-5-80-1020 *unknown*\*unknown* (8) S-1-5-80-1021 *unknown*\*unknown* (8) S-1-5-80-1022 *unknown*\*unknown* (8) S-1-5-80-1023 *unknown*\*unknown* (8) S-1-5-80-1025 *unknown*\*unknown* (8) S-1-5-80-1026 *unknown*\*unknown* (8) S-1-5-80-1027 *unknown*\*unknown* (8) S-1-5-80-1028 *unknown*\*unknown* (8) S-1-5-80-1029 *unknown*\*unknown* (8) S-1-5-80-1030 *unknown*\*unknown* (8) S-1-5-80-1031 *unknown*\*unknown* (8) S-1-5-80-1032 *unknown*\*unknown* (8) S-1-5-80-1033 *unknown*\*unknown* (8) S-1-5-80-1034 *unknown*\*unknown* (8) S-1-5-80-1035 *unknown*\*unknown* (8) S-1-5-80-1036 *unknown*\*unknown* (8) S-1-5-80-1037 *unknown*\*unknown* (8) S-1-5-80-1038 *unknown*\*unknown* (8) S-1-5-80-1039 *unknown*\*unknown* (8) S-1-5-80-1040 *unknown*\*unknown* (8) S-1-5-80-1041 *unknown*\*unknown* (8) S-1-5-80-1042 *unknown*\*unknown* (8) S-1-5-80-1043 *unknown*\*unknown* (8) S-1-5-80-1044 *unknown*\*unknown* (8) S-1-5-80-1045 *unknown*\*unknown* (8) S-1-5-80-1046 *unknown*\*unknown* (8) S-1-5-80-1047 *unknown*\*unknown* (8) S-1-5-80-1048 *unknown*\*unknown* (8) S-1-5-80-1049 *unknown*\*unknown* (8) S-1-5-80-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-80-3139157870-2983391045-3678747466-658725712 and logon username 'administrator', password '<PASSWORD>' S-1-5-80-3139157870-2983391045-3678747466-658725712-500 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-501 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-502 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-503 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-504 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-505 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-506 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-507 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-508 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-509 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-510 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-511 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-512 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-513 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-514 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-515 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-516 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-517 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-518 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-519 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-520 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-521 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-522 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-523 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-524 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-525 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-526 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-527 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-528 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-529 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-530 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-531 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-532 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-533 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-534 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-535 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-536 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-537 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-538 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-539 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-540 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-541 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-542 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-543 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-544 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-545 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-546 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-547 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-548 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-549 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-550 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1000 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1001 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1002 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1003 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1004 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1005 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1006 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1007 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1008 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1009 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1010 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1011 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1012 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1013 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1014 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1015 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1016 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1017 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1018 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1019 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1020 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1021 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1022 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1023 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1024 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1025 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1026 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1027 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1028 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1029 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1030 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1031 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1032 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1033 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1034 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1035 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1036 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1037 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1038 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1039 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1040 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1041 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1042 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1043 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1044 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1045 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1046 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1047 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1048 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1049 *unknown*\*unknown* (8) S-1-5-80-3139157870-2983391045-3678747466-658725712-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-21-833310794-1261029646-3490875958 and logon username 'administrator', password '<PASSWORD>' S-1-5-21-833310794-1261029646-3490875958-500 WIN-DUSS7GPO657\Administrator (Local User) S-1-5-21-833310794-1261029646-3490875958-501 WIN-DUSS7GPO657\Guest (Local User) S-1-5-21-833310794-1261029646-3490875958-502 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-503 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-504 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-505 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-506 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-507 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-508 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-509 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-510 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-511 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-512 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-513 WIN-DUSS7GPO657\None (Domain Group) S-1-5-21-833310794-1261029646-3490875958-514 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-515 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-516 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-517 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-518 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-519 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-520 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-521 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-522 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-523 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-524 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-525 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-526 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-527 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-528 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-529 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-530 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-531 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-532 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-533 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-534 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-535 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-537 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-538 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-539 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-540 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-541 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-542 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-543 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-544 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-545 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-546 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-547 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-548 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-549 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-550 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1000 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1001 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1002 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1003 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1004 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1005 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1006 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1007 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1008 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1009 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1010 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1011 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1012 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1013 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1014 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1015 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1016 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1017 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1018 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1019 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1020 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1021 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1022 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1023 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1024 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1025 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1026 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1027 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1028 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1029 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1030 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1031 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1032 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1033 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1034 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1035 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1036 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1037 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1038 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1039 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1040 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1041 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1042 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1043 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1044 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1045 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1046 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1047 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1048 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1049 *unknown*\*unknown* (8) S-1-5-21-833310794-1261029646-3490875958-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-32 and logon username 'administrator', password '<PASSWORD>' S-1-5-32-500 *unknown*\*unknown* (8) S-1-5-32-501 *unknown*\*unknown* (8) S-1-5-32-502 *unknown*\*unknown* (8) S-1-5-32-503 *unknown*\*unknown* (8) S-1-5-32-504 *unknown*\*unknown* (8) S-1-5-32-505 *unknown*\*unknown* (8) S-1-5-32-506 *unknown*\*unknown* (8) S-1-5-32-507 *unknown*\*unknown* (8) S-1-5-32-508 *unknown*\*unknown* (8) S-1-5-32-509 *unknown*\*unknown* (8) S-1-5-32-510 *unknown*\*unknown* (8) S-1-5-32-511 *unknown*\*unknown* (8) S-1-5-32-512 *unknown*\*unknown* (8) S-1-5-32-513 *unknown*\*unknown* (8) S-1-5-32-514 *unknown*\*unknown* (8) S-1-5-32-515 *unknown*\*unknown* (8) S-1-5-32-516 *unknown*\*unknown* (8) S-1-5-32-517 *unknown*\*unknown* (8) S-1-5-32-518 *unknown*\*unknown* (8) S-1-5-32-519 *unknown*\*unknown* (8) S-1-5-32-520 *unknown*\*unknown* (8) S-1-5-32-521 *unknown*\*unknown* (8) S-1-5-32-522 *unknown*\*unknown* (8) S-1-5-32-523 *unknown*\*unknown* (8) S-1-5-32-524 *unknown*\*unknown* (8) S-1-5-32-525 *unknown*\*unknown* (8) S-1-5-32-526 *unknown*\*unknown* (8) S-1-5-32-527 *unknown*\*unknown* (8) S-1-5-32-528 *unknown*\*unknown* (8) S-1-5-32-529 *unknown*\*unknown* (8) S-1-5-32-530 *unknown*\*unknown* (8) S-1-5-32-531 *unknown*\*unknown* (8) S-1-5-32-532 *unknown*\*unknown* (8) S-1-5-32-533 *unknown*\*unknown* (8) S-1-5-32-534 *unknown*\*unknown* (8) S-1-5-32-535 *unknown*\*unknown* (8) S-1-5-32-536 *unknown*\*unknown* (8) S-1-5-32-537 *unknown*\*unknown* (8) S-1-5-32-538 *unknown*\*unknown* (8) S-1-5-32-539 *unknown*\*unknown* (8) S-1-5-32-540 *unknown*\*unknown* (8) S-1-5-32-541 *unknown*\*unknown* (8) S-1-5-32-542 *unknown*\*unknown* (8) S-1-5-32-543 *unknown*\*unknown* (8) S-1-5-32-544 BUILTIN\Administrators (Local Group) S-1-5-32-545 BUILTIN\Users (Local Group) S-1-5-32-546 BUILTIN\Guests (Local Group) S-1-5-32-547 *unknown*\*unknown* (8) S-1-5-32-548 BUILTIN\Account Operators (Local Group) S-1-5-32-549 BUILTIN\Server Operators (Local Group) S-1-5-32-550 BUILTIN\Print Operators (Local Group) S-1-5-32-1000 *unknown*\*unknown* (8) S-1-5-32-1001 *unknown*\*unknown* (8) S-1-5-32-1002 *unknown*\*unknown* (8) S-1-5-32-1003 *unknown*\*unknown* (8) S-1-5-32-1004 *unknown*\*unknown* (8) S-1-5-32-1005 *unknown*\*unknown* (8) S-1-5-32-1006 *unknown*\*unknown* (8) S-1-5-32-1007 *unknown*\*unknown* (8) S-1-5-32-1008 *unknown*\*unknown* (8) S-1-5-32-1009 *unknown*\*unknown* (8) S-1-5-32-1010 *unknown*\*unknown* (8) S-1-5-32-1011 *unknown*\*unknown* (8) S-1-5-32-1012 *unknown*\*unknown* (8) S-1-5-32-1013 *unknown*\*unknown* (8) S-1-5-32-1014 *unknown*\*unknown* (8) S-1-5-32-1015 *unknown*\*unknown* (8) S-1-5-32-1016 *unknown*\*unknown* (8) S-1-5-32-1017 *unknown*\*unknown* (8) S-1-5-32-1018 *unknown*\*unknown* (8) S-1-5-32-1019 *unknown*\*unknown* (8) S-1-5-32-1020 *unknown*\*unknown* (8) S-1-5-32-1021 *unknown*\*unknown* (8) S-1-5-32-1022 *unknown*\*unknown* (8) S-1-5-32-1023 *unknown*\*unknown* (8) S-1-5-32-1024 *unknown*\*unknown* (8) S-1-5-32-1025 *unknown*\*unknown* (8) S-1-5-32-1026 *unknown*\*unknown* (8) S-1-5-32-1027 *unknown*\*unknown* (8) S-1-5-32-1028 *unknown*\*unknown* (8) S-1-5-32-1029 *unknown*\*unknown* (8) S-1-5-32-1030 *unknown*\*unknown* (8) S-1-5-32-1031 *unknown*\*unknown* (8) S-1-5-32-1032 *unknown*\*unknown* (8) S-1-5-32-1033 *unknown*\*unknown* (8) S-1-5-32-1034 *unknown*\*unknown* (8) S-1-5-32-1035 *unknown*\*unknown* (8) S-1-5-32-1036 *unknown*\*unknown* (8) S-1-5-32-1037 *unknown*\*unknown* (8) S-1-5-32-1038 *unknown*\*unknown* (8) S-1-5-32-1039 *unknown*\*unknown* (8) S-1-5-32-1040 *unknown*\*unknown* (8) S-1-5-32-1041 *unknown*\*unknown* (8) S-1-5-32-1042 *unknown*\*unknown* (8) S-1-5-32-1043 *unknown*\*unknown* (8) S-1-5-32-1044 *unknown*\*unknown* (8) S-1-5-32-1045 *unknown*\*unknown* (8) S-1-5-32-1046 *unknown*\*unknown* (8) S-1-5-32-1047 *unknown*\*unknown* (8) S-1-5-32-1048 *unknown*\*unknown* (8) S-1-5-32-1049 *unknown*\*unknown* (8) S-1-5-32-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-82-271721585-897601226-2024613209-625570482 and logon username 'administrator', password '<PASSWORD>' S-1-5-82-271721585-897601226-2024613209-625570482-500 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-501 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-502 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-503 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-504 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-505 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-506 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-507 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-508 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-509 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-510 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-511 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-512 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-513 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-514 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-515 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-516 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-517 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-518 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-519 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-520 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-521 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-522 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-523 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-524 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-525 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-526 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-527 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-528 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-529 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-530 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-531 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-532 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-533 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-534 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-535 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-536 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-537 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-538 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-539 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-540 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-541 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-542 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-543 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-544 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-545 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-546 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-547 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-548 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-549 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-550 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1000 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1001 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1002 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1003 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1004 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1005 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1006 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1007 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1009 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1010 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1011 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1012 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1013 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1014 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1015 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1016 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1017 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1018 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1019 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1020 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1021 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1022 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1023 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1024 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1025 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1026 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1027 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1028 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1029 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1030 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1031 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1032 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1033 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1034 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1035 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1036 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1037 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1038 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1039 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1040 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1041 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1042 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1043 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1044 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1045 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1046 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1047 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1048 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1049 *unknown*\*unknown* (8) S-1-5-82-271721585-897601226-2024613209-625570482-1050 *unknown*\*unknown* (8) [+] Enumerating users using SID S-1-5-82-3876422241-1344743610-1729199087-774402673 and logon username 'administrator', password '<PASSWORD>' S-1-5-82-3876422241-1344743610-1729199087-774402673-500 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-501 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-502 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-503 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-504 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-505 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-506 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-507 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-508 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-509 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-510 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-511 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-512 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-513 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-514 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-515 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-516 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-517 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-518 *unknown*\*unknown* (8) S-1-5-82-3876422241-1344743610-1729199087-774402673-519
<gh_stars>0 from __future__ import print_function from __future__ import absolute_import import functools import numpy as np import pandas as pds from pysat import Series, DataFrame class Orbits(object): """Determines orbits on the fly and provides orbital data in .data. Determines the locations of orbit breaks in the loaded data in inst.data and provides iteration tools and convenient orbit selection via inst.orbit[orbit num]. Parameters ---------- sat : pysat.Instrument instance instrument object to determine orbits for index : string name of the data series to use for determing orbit breaks kind : {'local time', 'longitude', 'polar', 'orbit'} kind of orbit, determines how orbital breaks are determined - local time: negative gradients in lt or breaks in inst.data.index - longitude: negative gradients or breaks in inst.data.index - polar: zero crossings in latitude or breaks in inst.data.index - orbit: uses unique values of orbit number period : np.timedelta64 length of time for orbital period, used to gauge when a break in the datetime index (inst.data.index) is large enough to consider it a new orbit Note ---- class should not be called directly by the user, use the interface provided by inst.orbits where inst = pysat.Instrument() Warning ------- This class is still under development. Examples -------- :: info = {'index':'longitude', 'kind':'longitude'} vefi = pysat.Instrument(platform='cnofs', name='vefi', tag='dc_b', clean_level=None, orbit_info=info) start = pysat.datetime(2009,1,1) stop = pysat.datetime(2009,1,10) vefi.load(date=start) vefi.bounds(start, stop) # iterate over orbits for vefi in vefi.orbits: print('Next available orbit ', vefi['dB_mer']) # load fifth orbit of first day vefi.load(date=start) vefi.orbits[5] # less convenient load vefi.orbits.load(5) # manually iterate orbit vefi.orbits.next() # backwards vefi.orbits.prev() """ def __init__(self, sat=None, index=None, kind=None, period=None): # create null arrays for storing orbit info if sat is None: raise ValueError('Must provide a pysat instrument object when ' + 'initializing orbits class.') else: # self.sat = weakref.proxy(sat) self.sat = sat if kind is None: kind = 'local time' else: kind = kind.lower() if period is None: period = pds.Timedelta(np.timedelta64(97, 'm')) self.orbit_period = pds.Timedelta(period) if (kind == 'local time') or (kind == 'lt'): self._detBreaks = functools.partial(self._equaBreaks, orbit_index_period=24.) elif (kind == 'longitude') or (kind == 'long'): self._detBreaks = functools.partial(self._equaBreaks, orbit_index_period=360.) elif kind == 'polar': self._detBreaks = self._polarBreaks elif kind == 'orbit': self._detBreaks = self._orbitNumberBreaks else: raise ValueError('Unknown kind of orbit requested.') self._orbit_breaks = [] self.num = 0 #[] self._current = 0 self.orbit_index = index @property def current(self): """Current orbit number. Returns ------- int or None None if no orbit data. Otherwise, returns orbit number, begining with zero. The first and last orbit of a day is somewhat ambiguous. The first orbit for day n is generally also the last orbit on day n - 1. When iterating forward, the orbit will be labeled as first (0). When iterating backward, orbit labeled as the last. """ if self._current > 0: return self._current - 1 else: return None def __getitem__(self, key): """Enable convenience notation for loading orbit into parent object. Examples -------- :: inst.load(date=date) inst.orbits[4] print('Orbit data ', inst.data) Note ---- A day of data must already be loaded. """ # hack included so that orbits appear to be zero indexed if key < 0: self.load(key) else: self.load(key+1) def _reset(self): # create null arrays for storing orbit info self._orbit_breaks = [] self.num = 0 #None self._current = 0 def _calcOrbits(self): """Prepares data structure for breaking data into orbits. Not intended for end user.""" # if the breaks between orbit have not been defined, define them # also, store the data so that grabbing different orbits does not # require reloads of whole dataset if len(self._orbit_breaks) == 0: # determine orbit breaks self._detBreaks() # store a copy of data self._fullDayData = self.sat.data.copy() # set current orbit counter to zero (default) self._current = 0 def _equaBreaks(self, orbit_index_period=24.): """Determine where breaks in an equatorial satellite orbit occur. Looks for negative gradients in local time (or longitude) as well as breaks in UT. Parameters ---------- orbit_index_period : float The change in value of supplied index parameter for a single orbit """ if self.orbit_index is None: raise ValueError('Orbit properties must be defined at ' + 'pysat.Instrument object instantiation.' + 'See Instrument docs.') else: try: self.sat[self.orbit_index] except ValueError: raise ValueError('Provided orbit index does not exist in ' + 'loaded data') # get difference in orbit index around the orbit lt_diff = self.sat[self.orbit_index].diff() # universal time values, from datetime index ut_vals = Series(self.sat.data.index) # UT difference ut_diff = ut_vals.diff() # get locations where orbit index derivative is less than 0 # then do some basic checks on these locations ind, = np.where((lt_diff < -0.1)) if len(ind) > 0: ind = np.hstack((ind, np.array([len(self.sat[self.orbit_index])]))) # look at distance between breaks dist = ind[1:] - ind[0:-1] # only keep orbit breaks with a distance greater than 1 # done for robustness if len(ind) > 1: if min(dist) == 1: print('There are orbit breaks right next to each other') ind = ind[:-1][dist > 1] # check for large positive gradients around the break that would # suggest not a true orbit break, but rather bad orbit_index values new_ind = [] for idx in ind: tidx, = np.where(lt_diff[idx - 5:idx + 6] > 0.1) if len(tidx) != 0: # there are large changes, suggests a false alarm # iterate over samples and check for tidx in tidx: # look at time change vs local time change if(ut_diff[idx - 5:idx + 6].iloc[tidx] < lt_diff[idx - 5:idx + 6].iloc[tidx] / orbit_index_period * self.orbit_period): # change in ut is small compared to the change in # the orbit index this is flagged as a false alarm, # or dropped from consideration pass else: # change in UT is significant, keep orbit break new_ind.append(idx) break else: # no large positive gradients, current orbit break passes # the first test new_ind.append(idx) # replace all breaks with those that are 'good' ind = np.array(new_ind) # now, assemble some orbit breaks that are not triggered by changes in # the orbit index # check if there is a UT break that is larger than orbital period, aka # a time gap ut_change_vs_period = ( ut_diff > self.orbit_period ) # characterize ut change using orbital period norm_ut = ut_diff / self.orbit_period # now, look for breaks because the length of time between samples is # too large, thus there is no break in slt/mlt/etc, lt_diff is small # but UT change is big norm_ut_vs_norm_lt = norm_ut.gt(np.abs(lt_diff.values / orbit_index_period)) # indices when one or other flag is true ut_ind, = np.where(ut_change_vs_period | (norm_ut_vs_norm_lt & (norm_ut > 0.95))) # added the or and check after or on 10/20/2014 # & lt_diff.notnull() ))# & (lt_diff != 0) ) ) # combine these UT determined orbit breaks with the orbit index orbit # breaks if len(ut_ind) > 0: ind = np.hstack((ind, ut_ind)) ind = np.sort(ind) ind = np.unique(ind) print('Time Gap') # now that most problems in orbits should have been caught, look at # the time difference between orbits (not individual orbits) orbit_ut_diff = ut_vals[ind].diff() orbit_lt_diff = self.sat[self.orbit_index][ind].diff() # look for time gaps between partial orbits. The full orbital time # period is not required between end of one orbit and begining of next # if first orbit is partial. Also provides another general test of the # orbital breaks determined. idx, = np.where((orbit_ut_diff / self.orbit_period - orbit_lt_diff.values / orbit_index_period) > 0.97) # pull out breaks that pass the test, need to make sure the first one # is always included it gets dropped via the nature of diff if len(idx) > 0: if idx[0] != 0: idx = np.hstack((0, idx)) else: idx = np.array([0]) # only keep the good indices if len(ind) > 0: ind = ind[idx] # create orbitbreak index, ensure first element is always 0 if ind[0] != 0: ind = np.hstack((np.array([0]), ind)) else: ind = np.array([0]) # number of orbits num_orbits = len(ind) # set index of orbit
60) (a *in_* Pair(a, a)) @ (21, BY_THEOREM, "left_in_pair", 0) (a *in_* Pair(c, c)) @ (22, REPLACE, 21, 20) ((a *in_* Pair(c, c)) == (a == c)) @ (23, BY_THEOREM, "element_of_singleton", 0) (a == c) @ (24, TAUTOLOGY, 23, 22) with (d == a) @ 58: (a *in_* Pair(a, a)) @ (59, BY_THEOREM, "left_in_pair", 0) (d *in_* Pair(a, a)) @ (70, REPLACE, 59, 58) ((d *in_* Pair(a, a)) == (d == a)) @ (61, BY_THEOREM, "element_of_singleton", 0) (d == a) @ (62, TAUTOLOGY, 70, 61) (c == d) @ (63, BY_EQUIVALENCE, 62, 24) (Pair(c, c) == Pair(c, d)) @ (64, REPLACE, 20, 63) (Pair(a, a) == Pair(c, d)) @ (65, BY_EQUIVALENCE, 20, 64) false @ (66, TAUTOLOGY, 65, 60) ((d == a) >> false) @ (67, DEDUCE) (d != a) @ (71, TAUTOLOGY, 67) (Pair(c, d) *in_* Pair(Pair(c, c), Pair(c, d))) @ (72, BY_THEOREM, "right_in_pair", 6, 7) (Pair(c, d) *in_* Pair(Pair(a, a), Pair(a, b))) @ (73, REPLACE, 72, 14) ((Pair(c, d) == Pair(a, a)) | (Pair(c, d) == Pair(a, b))) @ (74, BY_THEOREM, "element_of_pair", 4, 5, 73) with (Pair(c, d) == Pair(a, a)) @ 75: (Pair(a, a) == Pair(c, d)) @ (76, BY_EQUIVALENCE, 75) false @ (77, TAUTOLOGY, 76, 60) ((Pair(c, d) == Pair(a, a)) >> false) @ (78, DEDUCE) (Pair(c, d) == Pair(a, b)) @ (79, TAUTOLOGY, 78, 74) (d *in_* Pair(c, d)) @ (80, BY_THEOREM, "right_in_pair", 0) (d *in_* Pair(a, b)) @ (81, REPLACE, 80, 79) ((d == a) | (d == b)) @ (82, BY_THEOREM, "element_of_pair", 81, 0) (d == b) @ (83, TAUTOLOGY, 71, 82) (b == d) @ (84, BY_EQUIVALENCE, 83) ((a == c) & (b == d)) @ (85, TAUTOLOGY, 84, 24) ((Pair(a, a) != Pair(c, d)) >> ((a == c) & (b == d))) @ (86, DEDUCE) ((a == c) & (b == d)) @ (87, TAUTOLOGY, 86, 52) ((OrderedPair(a, b) == OrderedPair(c, d)) >> ((a == c) & (b == d))) @ (88, DEDUCE) ((Set(a) & Set(b) & Set(c) & Set(d)) >> ((OrderedPair(a, b) == OrderedPair(c, d)) >> ((a == c) & (b == d)))) @ (89, DEDUCE) (((Set(a) & Set(b) & Set(c) & Set(d)) & (OrderedPair(a, b) == OrderedPair(c, d))) >> ((a == c) & (b == d))) @ (90, TAUTOLOGY, 89) All(a_, b_, c_, d_, ((Set(a_) & Set(b_) & Set(c_) & Set(d_)) & (OrderedPair(a_, b_) == OrderedPair(c_, d_))) >> ((a_ == c_) & (b_ == d_))) @ ("comparison_of_ordered_pairs", CLOSING, 90) # arity 2 Arity2 = make_property("arity_2") All(p_, Arity2(p_) == Exist(a_, b_, (Set(a_) & Set(b_)) & (p_ == OrderedPair(a_, b_)))) @ ("arity_2", DEFINE_PROPERTY, "arity_2") # arity2 condition with ((Set(a) & Set(b)) & (p == OrderedPair(a, b))) @ 0: Exist(b_, ((Set(a) & Set(b_)) & (p == OrderedPair(a, b_)))) @ (1, FOUND, b, 0) Exist(a_, b_, (((Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_))))) @ (2, FOUND, a, 1) (Arity2(p) == Exist(a_, b_, (Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_)))) @ (3, BY_THEOREM, "arity_2") Arity2(p) @ (4, TAUTOLOGY, 2, 3) ((((Set(a) & Set(b)) & (p == OrderedPair(a, b)))) >> Arity2(p)) @ (5, DEDUCE) All(a_, b_, p_, (((Set(a_) & Set(b_)) & (p_ == OrderedPair(a_, b_)))) >> Arity2(p_)) @ ("arity_2_condition", CLOSING, 5) def arity_2(target, Seta, Setb, po): Seta = proof_history[Seta] assert Seta.is_proved() Setb = proof_history[Setb] assert Setb.is_proved() po = proof_history[po] assert po.is_proved() assert Seta.type_ == TYPE_PROPERTY assert Seta.name == "set" a0 = Seta.children[0] assert Setb.type_ == TYPE_PROPERTY assert Setb.name == "set" b0 = Setb.children[0] assert po.type_ == TYPE_PROPERTY assert po.name == "equal" p0 = po.children[0] All(b_, p_, (((Set(a0) & Set(b_)) & (p_ == OrderedPair(a0, b_)))) >> Arity2(p_)) @ (-5, PUT, a0, "arity_2_condition") All(p_, (((Set(a0) & Set(b0)) & (p_ == OrderedPair(a0, b0)))) >> Arity2(p_)) @ (-5, PUT, b0, -5) ((((Set(a0) & Set(b0)) & (p0 == OrderedPair(a0, b0)))) >> Arity2(p0)) @ (-5, PUT, p0, -5) Seta @ -6 Setb @ -7 po @ -8 Arity2(p0) @ (-5, TAUTOLOGY, -5, -6, -7, -8) return target @ (-5, TAUTOLOGY, -5) ARITY_2 = 39 callbacks[ARITY_2] = arity_2 # ordered pair is arity 2 clear() with (Set(a) & Set(b)) @ 0: (OrderedPair(a, b) == OrderedPair(a, b)) @ (1, BY_EQUIVALENCE) Set(a) @ (2, TAUTOLOGY, 0) Set(b) @ (3, TAUTOLOGY, 0) Arity2(OrderedPair(a, b)) @(4, ARITY_2, 2, 3, 1) ((Set(a) & Set(b)) >> Arity2(OrderedPair(a, b))) @ (5, DEDUCE) All(a_, b_, (Set(a_) & Set(b_)) >> Arity2(OrderedPair(a_, b_))) @ ("ordered_pair_is_arity_2", CLOSING, 5) # unique left clear() with Arity2(p) @ 0: (Arity2(p) == Exist(a_, b_, (Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_)))) @ (1, PUT, p, "arity_2") Exist(a_, b_, (Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_))) @ (2, TAUTOLOGY, 0, 1) Exist(b_, (Set(c) & Set(b_)) & (p == OrderedPair(c, b_))) @ (3, LET, c, 2) ((Set(c) & Set(d)) & (p == OrderedPair(c, d))) @ (4, LET, d, 3) Exist(b_, (Set(e) & Set(b_)) & (p == OrderedPair(e, b_))) @ (5, LET, e, 2) ((Set(e) & Set(f)) & (p == OrderedPair(e, f))) @ (6, LET, f, 5) (p == OrderedPair(c, d)) @ (7, TAUTOLOGY, 4) (p == OrderedPair(e, f)) @ (8, TAUTOLOGY, 6) (OrderedPair(c, d) == OrderedPair(e, f)) @ (9, BY_EQUIVALENCE, 7, 8) ((c == e) & (d == f)) @ (10, BY_THEOREM, "comparison_of_ordered_pairs", 4, 6, 9) (c == e) @ (11, TAUTOLOGY, 10) UniquelyExist(a_, Exist(b_, (Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_)))) @ (12, CLAIM_UNIQUE, 11) (Arity2(p) >> UniquelyExist(a_, Exist(b_, (Set(a_) & Set(b_)) & (p == OrderedPair(a_, b_))))) @ (13, DEDUCE) All(p_, Arity2(p_) >> UniquelyExist(a_, Exist(b_, (Set(a_) & Set(b_)) & (p_ == OrderedPair(a_, b_))))) @ ("unique_left", CLOSING, 13) # left clear() Left = make_function("left") All(p_, Arity2(p_) >> Exist(b_, (Set(Left(p_)) & Set(b_)) & (p_ == OrderedPair(Left(p_), b_)))) @ ("left", DEFINE_FUNCTION, "left", "unique_left") # ordered pair is set clear() with (Set(a) & Set(b)) @ 0: (OrderedPair(a, b) == Pair(Pair(a, a), Pair(a, b))) @ (1, BY_THEOREM, "ordered_pair") Set(Pair(a, a)) @ (2, BY_THEOREM, "pair_is_set", 0) Set(Pair(a, b)) @ (3, BY_THEOREM, "pair_is_set", 0) Set(Pair(Pair(a, a), Pair(a, b))) @ (4, BY_THEOREM, "pair_is_set", 2, 3) Set(OrderedPair(a, b)) @ (5, REPLACE, 4, 1) ((Set(a) & Set(b)) >> Set(OrderedPair(a, b))) @ (6, DEDUCE) All(a_, b_, ((Set(a_) & Set(b_)) >> Set(OrderedPair(a_, b_)))) @ ("ordered_pair_is_set", CLOSING, 6) # left of ordered pair clear() with (Set(a) & Set(b)) @ 0: Arity2(OrderedPair(a, b)) @ (1, BY_THEOREM, "ordered_pair_is_arity_2", 0) Set(OrderedPair(a, b)) @ (10, BY_THEOREM, "ordered_pair_is_set", 0) Exist(b_, (Set(Left(OrderedPair(a, b))) & Set(b_)) & (OrderedPair(a, b) == OrderedPair(Left(OrderedPair(a, b)), b_))) @ (2, BY_THEOREM, "left", 1) ((Set(Left(OrderedPair(a, b))) & Set(c)) & (OrderedPair(a, b) == OrderedPair(Left(OrderedPair(a, b)), c))) @ (3, LET, c, 2) ((a == Left(OrderedPair(a, b))) & (b == c)) @ (4, BY_THEOREM, "comparison_of_ordered_pairs", 3, 0, 10) (a == Left(OrderedPair(a, b))) @ (5, TAUTOLOGY, 4) ((Set(a) & Set(b)) >> (a == Left(OrderedPair(a, b)))) @ (6, DEDUCE) All(a_, b_, (Set(a_) & Set(b_)) >> (a_ == Left(OrderedPair(a_, b_)))) @ ("left_of_ordered_pair", CLOSING, 6) # unique right clear() with Arity2(p) @ 0: Exist(b_, (Set(Left(p)) & Set(b_)) & (p == OrderedPair(Left(p), b_))) @ (1, BY_THEOREM, "left", 0) ((Set(Left(p)) & Set(c)) & (p == OrderedPair(Left(p), c))) @ (2, LET, c, 1) ((Set(Left(p)) & Set(d)) & (p == OrderedPair(Left(p), d))) @ (3, LET, d, 1) (p == OrderedPair(Left(p), c)) @ (4, TAUTOLOGY, 2) (p == OrderedPair(Left(p), d)) @ (5, TAUTOLOGY, 3) (OrderedPair(Left(p), c) == OrderedPair(Left(p), d)) @ (6, BY_EQUIVALENCE, 4, 5) ((Left(p) == Left(p)) & (c == d)) @ (7, BY_THEOREM, "comparison_of_ordered_pairs", 2, 3, 6) (c == d) @ (8, TAUTOLOGY, 7) UniquelyExist(b_, (Set(Left(p)) & Set(b_)) & (p == OrderedPair(Left(p), b_))) @ (9, CLAIM_UNIQUE, 8) (Arity2(p) >> UniquelyExist(b_, (Set(Left(p)) & Set(b_)) & (p == OrderedPair(Left(p), b_)))) @ (10, DEDUCE) All(p_, Arity2(p_) >> UniquelyExist(b_, (Set(Left(p_)) & Set(b_)) & (p_ == OrderedPair(Left(p_), b_)))) @ ("unique_right", CLOSING, 10) # right clear() Right = make_function("right") All(p_, Arity2(p_) >> ((Set(Left(p_)) & Set(Right(p_))) & (p_ == OrderedPair(Left(p_), Right(p_))))) @ ("right", DEFINE_FUNCTION, "right", "unique_right") # right of ordered pair clear() with (Set(a) & Set(b)) @ 0: Arity2(OrderedPair(a, b)) @ (1, BY_THEOREM, "ordered_pair_is_arity_2", 0) Set(OrderedPair(a, b)) @ (2, BY_THEOREM, "ordered_pair_is_set", 0) ((Set(Left(OrderedPair(a, b))) & Set(Right(OrderedPair(a, b)))) & (OrderedPair(a, b) == OrderedPair(Left(OrderedPair(a, b)), Right(OrderedPair(a, b))))) @ (3, BY_THEOREM, "right", 1) ((a == Left(OrderedPair(a, b))) & (b == Right(OrderedPair(a, b)))) @ (4, BY_THEOREM, "comparison_of_ordered_pairs", 0, 3) (b == Right(OrderedPair(a, b))) @ (5, TAUTOLOGY, 4) ((Set(a) & Set(b))
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. import abc from threading import Lock from typing import cast, Dict, Iterable, Optional, TYPE_CHECKING from cdm.enums import CdmObjectType if TYPE_CHECKING: from cdm.objectmodel import CdmCorpusContext, CdmDocumentDefinition, CdmEntityAttributeDefinition from cdm.resolvedmodel import ResolvedTraitSet, ResolvedTraitSetBuilder from cdm.utilities import AttributeContextParameters, ResolveOptions class CdmObject(abc.ABC): _next_id_counter = 0 _next_id_lock = Lock() def __init__(self, ctx: 'CdmCorpusContext') -> None: # The object ID. self.id = CdmObject._next_id() # The object context. self.ctx = ctx # The object that owns or contains this object. self.owner = None # type: Optional[CdmObject] self.in_document = None # type: Optional[CdmDocumentDefinition] # internal self._declared_path = None # type: Optional[str] self._resolving_traits = False # type: bool self._trait_cache = None # type: Optional[Dict[str, ResolvedTraitSetBuilder]] self._at_corpus_path = None # type: Optional[str] @property def at_corpus_path(self) -> Optional[str]: if self.in_document is None: return 'NULL:/NULL/{}'.format(self._declared_path if self._declared_path else '') return '{}/{}'.format(self.in_document.at_corpus_path, self._declared_path if self._declared_path else '') @property @abc.abstractmethod def object_type(self) -> 'CdmObjectType': """the object type.""" raise NotImplementedError() @abc.abstractmethod def copy(self, res_opt: Optional['ResolveOptions'] = None, host: Optional['CdmObject'] = None) -> 'CdmObject': """Creates a copy of this object. host: For CDM internal use. Copies the object INTO the provided host instead of creating a new object instance. """ raise NotImplementedError() @abc.abstractmethod def create_simple_reference(self, res_opt: 'ResolveOptions') -> Optional['CdmObjectReference']: raise NotImplementedError() @abc.abstractmethod def _create_portable_reference(self, res_opt: 'ResolveOptions') -> Optional['CdmObjectReference']: raise NotImplementedError() @abc.abstractmethod def fetch_object_definition(self, res_opt: Optional['ResolveOptions'] = None) -> Optional['CdmObjectDefinition']: """Returns the resolved object reference.""" raise NotImplementedError() @abc.abstractmethod def fetch_object_definition_name(self) -> Optional[str]: raise NotImplementedError() @abc.abstractmethod def is_derived_from(self, base: str, res_opt: Optional['ResolveOptions'] = None) -> bool: raise NotImplementedError() @abc.abstractmethod def validate(self) -> bool: raise NotImplementedError() @abc.abstractmethod def visit(self, path_from: str, pre_children: 'VisitCallback', post_children: 'VisitCallback') -> bool: raise NotImplementedError() # Internal def _clear_trait_cache(self) -> None: self._trait_cache = None def _construct_resolved_attributes(self, res_opt: 'ResolveOptions', under: Optional['CdmAttributeContext'] = None) -> 'ResolvedAttributeSetBuilder': raise NotImplementedError('Not implemented in type {}'.format(self.__class__.__name__)) def _construct_resolved_traits(self, rtsb: 'ResolvedTraitSetBuilder', res_opt: 'ResolveOptions') -> None: raise NotImplementedError('Not implemented in type {}'.format(self.__class__.__name__)) def _fetch_object_from_cache(self, res_opt: 'ResolveOptions', acp_in_context: Optional['AttributeContextParameters']) -> 'ResolvedAttributeSet': kind = 'rasb' ctx = self.ctx cache_tag = ctx.corpus._create_definition_cache_tag(res_opt, self, kind, 'ctx' if acp_in_context else '') return ctx._attribute_cache.get(cache_tag) if cache_tag else None def _fetch_resolved_attributes(self, res_opt: 'ResolveOptions', acp_in_context: Optional['AttributeContextParameters'] = None) -> 'ResolvedAttributeSet': from cdm.resolvedmodel import ResolvedAttributeSet from cdm.utilities import SymbolSet from .cdm_attribute_context import CdmAttributeContext from .cdm_corpus_def import CdmCorpusDefinition from .cdm_entity_attribute_def import CdmEntityAttributeDefinition from .cdm_entity_def import CdmEntityDefinition from cdm.resolvedmodel.resolved_attribute_set_builder import ResolvedAttributeSetBuilder was_previously_resolving = self.ctx.corpus._is_currently_resolving self.ctx.corpus._is_currently_resolving = True if not res_opt: res_opt = ResolveOptions(self, self.ctx.corpus.default_resolution_directives) in_circular_reference = False was_in_circular_reference = res_opt._in_circular_reference if isinstance(self, CdmEntityDefinition): in_circular_reference = self in res_opt._currently_resolving_entities res_opt._currently_resolving_entities.add(self) res_opt._in_circular_reference = in_circular_reference # uncomment this line as a test to turn off allowing cycles #if in_circular_reference: # return ResolvedAttributeSet() current_depth = res_opt._depth_info.current_depth kind = 'rasb' ctx = self.ctx rasb_result = None rasb_cache = self._fetch_object_from_cache(res_opt, acp_in_context) # type: Optional[ResolvedAttributeSetBuilder] under_ctx = None # store the previous symbol set, we will need to add it with # children found from the constructResolvedTraits call curr_sym_ref_set = res_opt._symbol_ref_set or SymbolSet() res_opt._symbol_ref_set = SymbolSet() # if using the cache passes the maxDepth, we cannot use it if rasb_cache \ and res_opt._depth_info.max_depth \ and res_opt._depth_info.current_depth + rasb_cache._resolved_attribute_set._depth_traveled > res_opt._depth_info.max_depth: rasb_cache = None if not rasb_cache: # a new context node is needed for these attributes, # this tree will go into the cache, so we hang it off a placeholder parent # when it is used from the cache (or now), then this placeholder parent is ignored and the things under it are # put into the 'receiving' tree under_ctx = CdmAttributeContext._get_under_context_for_cache_context(res_opt, self.ctx, acp_in_context) rasb_cache = self._construct_resolved_attributes(res_opt, under_ctx) # type: ResolvedAttributeSetBuilder if rasb_cache: # register set of possible docs o_def = self.fetch_object_definition(res_opt) if o_def is not None: ctx.corpus._register_definition_reference_symbols(o_def, kind, res_opt._symbol_ref_set) if self.object_type == CdmObjectType.ENTITY_DEF: # if we just got attributes for an entity, take the time now to clean up this cached tree and prune out # things that don't help explain where the final set of attributes came from if under_ctx: scopes_for_attributes = set() # type: Set[CdmAttributeContext] under_ctx._collect_context_from_atts(rasb_cache._resolved_attribute_set, scopes_for_attributes) # the context node for every final attribute if not under_ctx._prune_to_scope(scopes_for_attributes): return None # get the new cache tag now that we have the list of docs cache_tag = ctx.corpus._create_definition_cache_tag(res_opt, self, kind, 'ctx' if acp_in_context else None) # save this as the cached version if cache_tag: ctx._attribute_cache[cache_tag] = rasb_cache # get the 'under_ctx' of the attribute set from the acp that is wired into the target tree under_ctx = rasb_cache._resolved_attribute_set.attribute_context \ ._get_under_context_from_cache_context(res_opt, acp_in_context) \ if rasb_cache._resolved_attribute_set.attribute_context else None else: # get the 'under_ctx' of the attribute set from the cache. The one stored there was build with a different # acp and is wired into the fake placeholder. so now build a new under_ctx wired into the output tree but with # copies of all cached children under_ctx = rasb_cache \ ._resolved_attribute_set.attribute_context \ ._get_under_context_from_cache_context(res_opt, acp_in_context) \ if rasb_cache._resolved_attribute_set.attribute_context else None # under_ctx._validate_lineage(res_opt) # debugging if rasb_cache: # either just built something or got from cache # either way, same deal: copy resolved attributes and copy the context tree associated with it # 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree # 2. deep copy the tree. # # 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree rasb_result = ResolvedAttributeSetBuilder() rasb_result._resolved_attribute_set = rasb_cache._resolved_attribute_set.copy() # 2. deep copy the tree and map the context references. if under_ctx: # null context? means there is no tree, probably 0 attributes came out if not under_ctx.associate_tree_copy_with_attributes(res_opt, rasb_result._resolved_attribute_set): return None if isinstance(self, CdmEntityAttributeDefinition): # if we hit the maxDepth, we are now going back up res_opt._depth_info.current_depth = current_depth # now at the top of the chain where max depth does not influence the cache if res_opt._depth_info.current_depth == 0: res_opt._depth_info.max_depth_exceeded = False if not in_circular_reference and self.object_type == CdmObjectType.ENTITY_DEF: # should be removed from the root level only # if it is in a circular reference keep it there res_opt._currently_resolving_entities.remove(self) res_opt._in_circular_reference = was_in_circular_reference # merge child reference symbols set with current curr_sym_ref_set._merge(res_opt._symbol_ref_set) res_opt._symbol_ref_set = curr_sym_ref_set self.ctx.corpus._is_currently_resolving = was_previously_resolving return rasb_result._resolved_attribute_set if rasb_result else rasb_result def _fetch_resolved_traits(self, res_opt: 'ResolveOptions') -> 'ResolvedTraitSet': from cdm.resolvedmodel import ResolvedTraitSet, ResolvedTraitSetBuilder from cdm.utilities import SymbolSet was_previously_resolving = self.ctx.corpus._is_currently_resolving self.ctx.corpus._is_currently_resolving = True if not res_opt: res_opt = ResolveOptions(self, self.ctx.corpus.default_resolution_directives) kind = 'rtsb' ctx = self.ctx cache_tag_a = ctx.corpus._create_definition_cache_tag(res_opt, self, kind) rtsb_all = None # type: ResolvedTraitSetBuilder if self._trait_cache is None: self._trait_cache = {} elif cache_tag_a: rtsb_all = self._trait_cache.get(cache_tag_a) # store the previous document set, we will need to add it with # children found from the constructResolvedTraits call curr_doc_ref_set = res_opt._symbol_ref_set if curr_doc_ref_set is None: curr_doc_ref_set = SymbolSet() res_opt._symbol_ref_set = SymbolSet() if rtsb_all is None: rtsb_all = ResolvedTraitSetBuilder() if not self._resolving_traits: self._resolving_traits = True self._construct_resolved_traits(rtsb_all, res_opt) self._resolving_traits = False obj_def = self.fetch_object_definition(res_opt) if obj_def: # register set of possible docs ctx.corpus._register_definition_reference_symbols(obj_def, kind, res_opt._symbol_ref_set) if rtsb_all.resolved_trait_set is None: # nothing came back, but others will assume there is a set in this builder rtsb_all.resolved_trait_set = ResolvedTraitSet(res_opt) # get the new cache tag now that we have the list of docs cache_tag_a = ctx.corpus._create_definition_cache_tag(res_opt, self, kind) if cache_tag_a: self._trait_cache[cache_tag_a] = rtsb_all else: # cache was found # get the SymbolSet for this cached object from .cdm_corpus_def import CdmCorpusDefinition key = CdmCorpusDefinition._fetch_cache_key_from_object(self, kind) temp_doc_ref_set = ctx.corpus._definition_reference_symbols.get(key) res_opt._symbol_ref_set = temp_doc_ref_set # merge child document set with current curr_doc_ref_set._merge(res_opt._symbol_ref_set) res_opt._symbol_ref_set = curr_doc_ref_set self.ctx.corpus._is_currently_resolving = was_previously_resolving return rtsb_all.resolved_trait_set @staticmethod def _protect_parameter_values(res_opt: 'ResolveOptions', val: 'CdmObject') -> 'CdmObject': from .cdm_entity_ref import CdmEntityReference from .cdm_constant_entity_def import CdmConstantEntityDefinition if val: # the value might be a constant entity object, need to protect the original c_ent = cast(CdmEntityReference, val).explicit_reference if isinstance(val, CdmEntityReference) else None if c_ent: # copy the constant entity AND the reference that holds it c_ent = cast(CdmConstantEntityDefinition, c_ent.copy(res_opt)) val = cast(CdmEntityReference, val).copy(res_opt) cast(CdmEntityReference, val).explicit_reference = c_ent return val @staticmethod def _next_id():
على خريطة). أدخل بعض الحروف للبحث من المواقع المتوفرة.', "The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.": "المانحون لهذا المشروع. يمكن تحديد قيم متعددة بضغط مفتاح 'المراقبةl' .", 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'عنوان البريد الإلكتروني الذي ترسل اليه طلبات الموافقة (عادة ما يكون هذا البريد لفريق بدلا من فرد). إذا كان الحقل فارغا فسوف تتم الموافقة على الطلبات تلقائيا إذا كان المجال موافقا.', 'The facility where this position is based.': 'المرفق الذي يستند هذا الموقف.', 'The first or only name of the person (mandatory).': 'الاسم الأول أو الوحيد للشخص (إلزامي).', 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'الإبلاغ عن الحوادث (Incident Reporting System) نظام يسمح للجمهور العام بتقريرالحوادث و تتبع هذه الأخيرة.', 'The language you wish the site to be displayed in.': 'اللغة التي ترغب ان يتم عرض الموقع فيها.', 'The list of Brands are maintained by the Administrators.': 'يقوم المسؤولون بالاحتفاظ بقائمة العلامات التجارية.', 'The list of Catalogs are maintained by the Administrators.': 'يقوم المسؤولون بالاحتفاظ بقائمة السجلات.', 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'موقع الشخص قد حان ، والتي يمكن أن تكون عامة (للإبلاغ) أو دقيقة (للعرض على الخريطة). أدخل عدد قليل من الأحرف للبحث عن المواقع المتوفرة.', 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'الموقع الذي يذهب اليه الشخص يمكن ان يكون عاما (للتقرير) او محددا (للعرض على خريطة). قم بإدخال بعض الحروف للبحث في المواقع المتوفرة.', 'The map will be displayed initially with this latitude at the center.': 'ابتدائيا سيتم عرض الخريطة في المركز على خط العرض هذا.', 'The map will be displayed initially with this longitude at the center.': 'سيتم عرض الخريطة في البداية مع هذا العرض في المركز.', 'The Media Library provides a catalog of digital media.': 'توفر مكتبة وسائل الإعلام كتالوج لوسائل الإعلام الرقمية.', 'The name to be used when calling for or directly addressing the person (optional).': 'استخدام الاسم عند طلبه أو مخاطبة الشخص مباشرة (اختياري)', 'The next screen will allow you to detail the number of people here & their needs.': 'الشاشة التالية سوف تسمح لك بتفصيل عدد الناس هنا واحتياجاتهم.', 'The number of beneficiaries actually reached by this activity': 'عدد المستفيدين الذين بلغها هذا النشاط', 'The number of beneficiaries targeted by this activity': 'عدد المستفيدين المستهدفين بهذا النشاط', 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'عدد وحدات القياس من العناصر البديلة التي تساوي وحدة واحدة القياس من البند', 'The post variable on the URL used for sending messages': 'البريد متغير حسب العنوان URLالمستعمل لإرسال الرسائل.', 'The post variables other than the ones containing the message and the phone number': 'متغيرات أخرى غير تلك التي تحتوي على رسالة ورقم الهاتف', 'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.': 'وحدة تعقب المشروع تتيح خلق أنشطة لسد الثغرات في عملية تقييم الاحتياجات.', 'The questionnaire is available in all SEA languages, please change the language to your need on the upper-right corner of your screen.': 'الاستبيان متاح بجميع اللغات SEA، يرجى تغيير اللغة للحاجة الخاصة بك في الزاوية العليا اليمنى من الشاشة.', 'The role of the member in the group': 'دور عضو في المجموعة', 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'المنفذ التسلسلي أين يتم توصيل المودم - / dev/ttyUSB0 ،إلخ على linux و COM2 ، COM1 ، الخ في نظام التشغيل Windows', 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'لم يستقبل الخادم إجابة في الوقت المناسب من الخادم الآخر الذي كان يسعى للوصول لملئ طلب على يد متصفح.', 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'تلقى الخادم استجابة غير صحيحة من خادم آخر أنه كان داخلا لملء طلب من المتصفح.', 'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.': 'يتبع سجل كافة الملاجئ ويخزن التفاصيل الأساسية المتعلقة بهم.بالتعاون مع وحدات أخرى لتعقب الأشخاص المتعاونين مع ملجأ أخر،و توفر الخدمات إلخ', 'The Shelter this Request is from (optional).': 'المأوى الذي جاء منه هذا الطلب (اختياري).', "The staff member's official job title": 'المسمى الوظيفي الرسمي للموظف', 'The unique identifier which identifies this instance to other instances.': 'المعرف الوحيد الذي يحدد هذه الحالة إلى حالات أخرى.', 'The uploaded Form is unreadable, please do manual data entry.': 'نموذج تم الرفع غير قابل للقراءة ، الرجاء القيام دليل إدخال البيانات.', 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': ' العنوانURL لحصول على قايلية صفحة خدمة شبكة الخريطة WMS التي تتوفر على الطبقات التي ترغب فيها عبر لوحة التصفح على الخريطة.', "The URL of the image file. If you don't upload an image file, then you must specify its location here.": 'عنوان URL لملف الصورة. إذا لم تقم بتحميل ملف صورة، فيجب عليك تحديد موقعه هنا.', 'The URL of your web gateway without the post parameters': 'عنوان مدحل موقع الويب الخاص بك دون وضع سمات أخرى', 'The URL to access the service.': 'عنوان الموقع للوصول إلى الخدمة.', "The volunteer's role": 'دور المتطوع', 'The way in which an item is normally distributed': 'الطريقة التي يتم بها عادة توزيع العنصر', 'The weight in kg.': 'الوزن بالكيلو جرام.', 'Theme': 'الموضوع', 'Theme added': 'تم اضافة نسق', 'Theme added to Activity': 'النسق المضاف إلى النشاط', 'Theme added to Project': 'النسق المضاف إلى المشروع', 'Theme added to Project Location': 'إضافة نسق إلى موقع المشروع', 'Theme deleted': 'تم حذف النسق', 'Theme Details': 'تفاصيل الموضوع', 'Theme removed from Activity': 'تمت إزالة السمة من النشاط', 'Theme removed from Project': 'تمت إزالة السمة من المشروع', 'Theme removed from Project Location': 'تمت إزالة السمة من موقع المشروع', 'Theme updated': 'تم تحديث السمة', 'Themes': 'المواضيع', 'There are errors in the form, please check your input': 'هناك أخطاء في النموذج، يرجى مراجعة الإدخال', 'There are insufficient items in the Inventory to send this shipment': 'لا توجد وحدات كافية في المخزون لإرسال هذه الشحنة', 'There are more than %(max)s results, please input more characters.': 'هناك أكثر من %(max)s النتائج ، يرجى إدخال المزيد من الحروف.', 'There are multiple records at this location': 'هناك سجلات متعددة في هذا الموقع', "There are no details for this person yet. Add Person's Details.": 'لا توجد تفاصيل لهذا الشخص حتى الان. إضافة تفاصيل الشخص.', 'There is no address for this person yet. Add new address.': 'لا يوجد أي عنوان لهذا الشخص حتى الان. إضافة عنوان جديد.', 'There is no status for this %(site_label)s yet. Add %(site_label)s Status.': 'ليس هناك وضع لهذا %(site_label)s حتى الان. حالة الإعلان %(site_label)s', 'There was a problem, sorry, please try again later.': 'كانت هناك مشكلة، آسف، يرجى المحاولة مرة أخرى في وقت لاحق.', 'These are settings for Inbound Mail.': 'هذه هي الإعدادات للبريد الوارد.', 'This appears to be a duplicate of ': 'يظهر أن هذا مكرر لـ', 'This email-address is already registered.': 'هذا البريد الالكتروني مسجل سابقا.', 'This file already exists on the server as': 'هذا الملف موجود مسبقا على الملقم (server) ك', 'This Group has no Members yet': 'لا يوجد أي أعضاء مسجلين حاليا', 'This level is not open for editing.': 'هذا المستوى غير مفتوح من أجل التحرير.', 'This person already belongs to another case group': 'هذا الشخص ينتمي بالفعل إلى مجموعة قضية أخرى', 'This person already belongs to this group': 'هذا الشخص ينتمي بالفعل إلى هذه المجموعة', 'This shipment has not been received - it has NOT been canceled because it can still be edited.': 'لم تستقبل هده الشحنة.و.لم يتم الغائهاا لان لاتزال امكانية تحريرها', 'This shipment will be confirmed as received.':
variable each. # So a line parameter is incompatible. if lines is not None: if panel_type == Panel.TYPE_TIMEHEIGHT: logToFile('Warning. Panel type is time-height but a lines argument was found in for variable ' + str(all_model_var_names[model_name]) + '. Those are not compatible. Ignoring lines.') else: for line in lines: line['calculated'] = False if (model_name + '_calc') in line.keys() and \ not self.__varnamesInDataset__(line['var_names'], dataset): plot_data, z = line[(model_name + '_calc')](dataset_override=dataset) if self.animation is None: plot = Line(plot_data, z, line_format=line_style, label=line['legend_label']) else: plot = Contour(x_data=z['time'],y_data=z['height'],c_data=plot_data, colors=Style_definitions.CONTOUR_CMAP, label=line['legend_label'], line_format=line_style) all_lines.append(plot) line['calculated'] = True if len(all_model_var_names[model_name]) > 0 and not data_was_calculated: all_lines.extend(self.__getVarLines__(all_model_var_names[model_name], dataset, conversion_factor=conversion_factors[model_name], label=label, line_format=line_style, override_panel_type=panel_type, lines=lines, model_name=model_name)) return all_lines def getTextDefiningDataset(self): """ Finds a dataset from which text names and descriptions can be pulled from. By default, it is always clubb, however if pyplotgen is not plotting clubb then it will return the first dataset it can find. :return: A list of all Dataset objects for all models """ datasets = [] if self.clubb_datasets is not None: for i in self.clubb_datasets.values(): if isinstance(i, dict): for dataset in i.values(): datasets.append(dataset) elif isinstance(i, Dataset): datasets.append(i) else: raise TypeError("getTextDefiningDataset received an unexpected format of datasets") if self.e3sm_datasets is not None: for dict_of_datasets in self.e3sm_datasets.values(): datasets.extend(dict_of_datasets.values()) if self.cam_datasets is not None: for dict_of_datasets in self.cam_datasets.values(): datasets.extend(dict_of_datasets.values()) if self.sam_datasets is not None: for dict_of_datasets in self.sam_datasets.values(): datasets.extend(dict_of_datasets.values()) if self.wrf_datasets is not None: for i in self.wrf_datasets.values(): if isinstance(i, dict): datasets.extend(i.values()) elif isinstance(i, Dataset): datasets.append(i) else: raise TypeError("getTextDefiningDataset recieved an unexpected format of datasets") if self.sam_benchmark_dataset is not None: datasets.extend(self.sam_benchmark_dataset.values()) if self.coamps_benchmark_dataset is not None: datasets.extend(self.coamps_benchmark_dataset.values()) if self.wrf_benchmark_dataset is not None: datasets.extend(self.wrf_benchmark_dataset.values()) if self.r408_datasets is not None: datasets.extend(self.r408_datasets.values()) if self.hoc_datasets is not None: datasets.extend(self.hoc_datasets.values()) if len(datasets) == 0: raise FileExistsError("No dataset could be found to pull text descriptions from") return datasets def generatePanels(self): """ Generates a set of panels from the plots stored in self. Does not return anything, simply assigns the panels into self.panels :return: None """ for variable in self.variables: # Only display a variable if we are either not doing a priority run or the priority flag has been set and is True if not self.priority_vars or (self.priority_vars and 'priority' in variable.keys() and variable['priority']): title = variable['title'] axis_label = variable['axis_title'] plotset = variable['plots'] centered = False panel_type = self.default_panel_type if self.time_height: panel_type = Panel.TYPE_TIMEHEIGHT elif 'type' in variable.keys(): panel_type = variable['type'] if 'sci_scale' in variable.keys(): sci_scale = variable['sci_scale'] else: sci_scale = None if 'centered' in variable.keys(): centered = variable['centered'] if panel_type == Panel.TYPE_TIMEHEIGHT: panel = ContourPanel(plotset, title=title, dependent_title=axis_label, panel_type=panel_type) elif self.animation is not None: panel = AnimationPanel(plotset, title=title, dependent_title=axis_label, panel_type=panel_type, sci_scale=sci_scale, centered=centered) else: panel = Panel(plotset, title=title, dependent_title=axis_label, panel_type=panel_type, sci_scale=sci_scale, centered=centered) self.panels.append(panel) def __getTitles__(self, variable_def_dict, plotted_models_varname): """ Creates and returns figure and axis titles of the panel based on panel type and panel definition in variable_def_dict :param variable_def_dict: Definition of the variable being used :param plotted_models_varname: String containing the name of the plotted variable :return: title, axis_title """ title = "Title not found" axis_title = "axis_title not found" data_reader = DataReader() var_names = variable_def_dict['var_names'] all_lines = variable_def_dict['plots'] panel_type = self.default_panel_type if self.time_height: panel_type = Panel.TYPE_TIMEHEIGHT elif 'type' in variable_def_dict.keys(): panel_type = variable_def_dict['type'] try: first_input_datasets = self.getTextDefiningDataset() except FileExistsError as e: logToFile(str(e)) return title, axis_title if 'title' not in variable_def_dict.keys(): # No title given so it must be generated from given information if panel_type == Panel.TYPE_BUDGET: source_folder = os.path.basename(Path(first_input_datasets[0].filepath()).parent) title = source_folder + ' ' + plotted_models_varname else: all_var_names = [] for model_var_names in var_names.values(): all_var_names.extend(model_var_names) # Get long name for any of the var_names given in variable_def_dict imported_title = data_reader.getLongName(first_input_datasets, all_var_names) title = imported_title else: # A title is manually defined in variable_def_dict title = variable_def_dict['title'] if 'axis_title' not in variable_def_dict.keys(): # No axis_title given so it must be generated from given information if panel_type == Panel.TYPE_BUDGET and len(all_lines) > 0: any_varname_with_budget_units = [var.label for var in all_lines] axis_title = "[" + data_reader.__getUnits__(first_input_datasets, any_varname_with_budget_units) + "]" else: all_var_names = [] for model_var_names in var_names.values(): all_var_names.extend(model_var_names) # Get axis title for any of the var_names given in variable_def_dict imported_axis_title = data_reader.getAxisTitle(first_input_datasets, all_var_names) axis_title = imported_axis_title else: # An axis_title is manually defined in variable_def_dict axis_title = variable_def_dict['axis_title'] return title, axis_title def __varnamesInDataset__(self, varnames, datasets): """ Returns True if the dataset contains a variable with one of the given varnames, False otherwise :param varnames: A list of possible variable names :param datasets: Either the dataset being investigated (NetCDF Dataset object) or a dict of datasets to be compared :return: True if a name is found, False otherwise """ if isinstance(datasets, list): for name in varnames: for dataset in datasets: if name in dataset.variables.keys(): return True elif isinstance(datasets, dict): for name in varnames: for dataset in datasets.values(): if name in dataset.variables.keys(): return True elif isinstance(datasets, Dataset): for name in varnames: if name in datasets.variables.keys(): return True else: raise ValueError("Unknown data type for dataset") return False def __getRelativeVarName__(self, var_names): """ Returns the varname for a variable relative to the models that were being plotted :param var_names: The dict of various names for the given variable. More info found in the addVariable() docstring :return: A relevant name of the given variable """ plotted_models_varname = "unknown_model_var" if self.clubb_datasets is not None and len(var_names['clubb']) > 0: plotted_models_varname = var_names['clubb'][0] elif self.clubb_datasets is None and self.wrf_datasets is not None and len(var_names['wrf']) > 0: plotted_models_varname = var_names['wrf'][0] elif self.clubb_datasets is None and self.sam_datasets is not None and len(var_names['sam']) > 0: plotted_models_varname = var_names['sam'][0] elif self.clubb_datasets is None and self.e3sm_datasets is not None and len(var_names['e3sm']) > 0: plotted_models_varname = var_names['e3sm'][0] return plotted_models_varname def __getConversionFactors__(self, variable_def_dict): """ This is a helper method that loads parameters from the variables definition and assigns them to python variables accordingly. :param variable_def_dict: Definition of the variable being used. More info found in the addVariable() docstring :return: A dict containing the various conversion factors for the inputted variable """ conv_factors = { 'les': 1, 'sam': 1, 'wrf': 1, 'coamps': 1, 'r408': 1, 'hoc': 1, 'e3sm': 1, 'cam': 1, 'clubb': 1 } if 'sam_conv_factor' in variable_def_dict.keys(): conv_factors['les'] = variable_def_dict['sam_conv_factor'] conv_factors['sam'] = variable_def_dict['sam_conv_factor'] if 'coamps_conv_factor' in variable_def_dict.keys(): conv_factors['coamps'] = variable_def_dict['coamps_conv_factor'] if 'r408_conv_factor' in variable_def_dict.keys(): conv_factors['r408'] = variable_def_dict['r408_conv_factor'] if 'hoc_conv_factor' in variable_def_dict.keys(): conv_factors['hoc'] = variable_def_dict['hoc_conv_factor'] if 'e3sm_conv_factor' in variable_def_dict.keys(): conv_factors['e3sm'] = variable_def_dict['e3sm_conv_factor'] if 'cam_conv_factor' in variable_def_dict.keys(): conv_factors['cam'] = variable_def_dict['cam_conv_factor'] if 'wrf_conv_factor' in variable_def_dict.keys(): conv_factors['wrf'] = variable_def_dict['wrf_conv_factor'] return conv_factors def __getVarLines__(self, var_names, ncdf_datasets, label="", line_format="", avg_axis=0, override_panel_type=None, lines=None, conversion_factor=1, model_name="unknown"): """ Get a list of Line objects for a specific clubb variable. If sam_benchmark_dataset is specified it will also attempt to generate Lines for the SAM equivalent variables, using the name conversions found in VarnameConversions.py. If a SAM variable needs to be calculated (uses an equation) then it will have to be created within that variable group's dataset and not here. :param var_names: A string or list of strings. More info found in the addVariable() docstring Each string is the name of the variable to be plotted, case sensitive :param ncdf_datasets: A list of Dataset objects containing clubb or sam netcdf dependent_data :param label: Label to give the base-plotAll on the legend. This is normally Style_definitions.CLUBB_LABEL, but not provided as default to help avoid debugging confusion. :param line_format: Line formatting string used by matplotlib's PyPlot :param avg_axis: Axis over which to average values. 0 - time average, 1 - height average :param override_panel_type: Override the VariableGroup's default panel type :param lines: Some plots require many lines to be plotted, such as budget plots. The lines parameter allows someone to write a dictionary containing a description of each line that needs to be plotted. For information on how to format the lines parameter, please see the config/VariableGroupBaseBudgets.py file and docs. :param conversion_factor: A multiplying factor used to scale clubb output. Defaults to 1. :param model_name: The name of the model being plotted. :return: A list of
<filename>py3avi2bdnxml.py<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Description: py3avi2bdnxml.py converts the imageTimings.srt produced by AVISubDetector to a BDN XML file that can be read by BDSup2Sub++. [AVISubDetector URL] [BDSup2Sub++URL] The idea is to rip hardsubs into BD PGS (.sup) files. Usage: python py3avi2bdnxml.py imageTimings.srt python py3avi2bdnxml.py imageTimings.srt -q 480p python py3avi2bdnxml.py imageTimings.srt -q 480p -o output.xml python py3avi2bdnxml.py imageTimings.srt -q 480p --yOffset 4 -o output.xml Current version: 0.2-alpha Last Modified: 06Mar17 License: any ##stop reading now## """ #file input (srt) to (BDN-XML/PNG format) #load libraries import argparse #used to add command line options import os.path #test if file exists import sys #end program on fail condition import io #manipulate files (open/read/write/close) from io import IOBase #test if variable is a file object (an "IOBase" object) from pathlib import Path #override file in file system with another, experimental library from PIL import Image #Pillow image library for image resolution and manipulation import pysrt #read input from subrip (.srt) files import decimal #improved precision for arithmetic operations from lxml import etree #XML datastructure + I/O import copy #to deepcopy() SRT object for fixing SRT file quirk from decimal import ROUND_DOWN #alias num=decimal.Decimal #set default options defaultPixelOffset=2 defaultDialogueXOffset=0 defaultRomajiXOffset=0 defaultKanjiYOffset=0 defaultQuality='720p' defaultOutputFilename='invalid' defaultEncodingType='utf-8' defaultFPS=num(24000/1001) defaultDropFrameStatus='false' #set static internal use variables currentVersion='v0.2 - 06Mar17' usageHelp='\n CorrectUsage: \n py3avi2bdnxml input.srt\n py3avi2bdnxml input.srt -o output.xml\n py3avi2bdnxml input.srt [-q 480p] [-yo 2] [-o output.xml]' #add command line options command_Line_parser=argparse.ArgumentParser(description='py3avi2bdnxml converts the imageTimings.srt produced by AVISubDetector \n to a BDN XML file that can be read by BDSup2Sub++.' + usageHelp) command_Line_parser.add_argument("-df", "--dialogueFile", help="specify a dialogue file as input", type=str) command_Line_parser.add_argument("-df2", "--dialogueFile2", help="specify an additional dialogue input file", type=str) command_Line_parser.add_argument("-df3", "--dialogueFile3", help="specify an additional dialogue input file", type=str) command_Line_parser.add_argument("-df4", "--dialogueFile4", help="specify an additional dialogue input file", type=str) command_Line_parser.add_argument("-rf", "--romajiFile", help="specify a Romaji file as input", type=str) command_Line_parser.add_argument("-rf2", "--romajiFile2", help="specify an additional Romaji input file", type=str) command_Line_parser.add_argument("-rf3", "--romajiFile3", help="specify an additional Romaji input file", type=str) command_Line_parser.add_argument("-rf4", "--romajiFile4", help="specify an additional Romaji input file", type=str) command_Line_parser.add_argument("-kf", "--kanjiFile", help="specify a Kanji file as input", type=str) command_Line_parser.add_argument("-kf2", "--kanjiFile2", help="specify an additional Kanji input file", type=str) command_Line_parser.add_argument("-kf3", "--kanjiFile3", help="specify an additional Kanji input file", type=str) command_Line_parser.add_argument("-kf4", "--kanjiFile4", help="specify an additional Kanji input file", type=str) command_Line_parser.add_argument("-df-xo", "--dialogueFile-xOffset", help="specify an X offset for dialogue input, default={}".format(defaultDialogueXOffset),default=defaultDialogueXOffset,type=int) command_Line_parser.add_argument("-df2-xo", "--dialogueFile2-xOffset", help="specify an X offset for dialogue input file 2, default={}".format(defaultDialogueXOffset),default=defaultDialogueXOffset,type=int) command_Line_parser.add_argument("-df3-xo", "--dialogueFile3-xOffset", help="specify an X offset for dialogue input file 3, default={}".format(defaultDialogueXOffset),default=defaultDialogueXOffset,type=int) command_Line_parser.add_argument("-df4-xo", "--dialogueFile4-xOffset", help="specify an X offset for dialogue input file 4, default={}".format(defaultDialogueXOffset),default=defaultDialogueXOffset,type=int) command_Line_parser.add_argument("-df-yo", "--dialogueFile-yOffset", help="specify how far dialogue should be from bottom, >=2 and <=video.height, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-df2-yo", "--dialogueFile2-yOffset", help="specify a Y offset for dialogue input file 2, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-df3-yo", "--dialogueFile3-yOffset", help="specify a Y offset for dialogue input file 3, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-df4-yo", "--dialogueFile4-yOffset", help="specify a Y offset for dialogue input file 4, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-rf-xo", "--romajiFile-xOffset", help="specify an X offset for romaji input, default={}".format(defaultRomajiXOffset),default=defaultRomajiXOffset,type=int) command_Line_parser.add_argument("-rf2-xo", "--romajiFile2-xOffset", help="specify an X offset for romaji input file 2, default={}".format(defaultRomajiXOffset),default=defaultRomajiXOffset,type=int) command_Line_parser.add_argument("-rf3-xo", "--romajiFile3-xOffset", help="specify an X offset for romaji input file 3, default={}".format(defaultRomajiXOffset),default=defaultRomajiXOffset,type=int) command_Line_parser.add_argument("-rf4-xo", "--romajiFile4-xOffset", help="specify an X offset for romaji input file 4, default={}".format(defaultRomajiXOffset),default=defaultRomajiXOffset,type=int) command_Line_parser.add_argument("-rf-yo", "--romajiFile-yOffset", help="specify how far romaji should be from top, >=2 and <=video.height, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-rf2-yo", "--romajiFile2-yOffset", help="specify a Y offset for romaji input file 2, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-rf3-yo", "--romajiFile3-yOffset", help="specify a Y offset for romaji input file 3, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-rf4-yo", "--romajiFile4-yOffset", help="specify a Y offset for romaji input file 4, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-kf-xo", "--kanjiFile-xOffset", help="specify how far kanji should be from left or right, >=2 and <=video.width, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-kf2-xo", "--kanjiFile2-xOffset", help="specify an X offset for kanji input file 2, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-kf3-xo", "--kanjiFile3-xOffset", help="specify an X offset for kanji input file 3, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-kf4-xo", "--kanjiFile4-xOffset", help="specify an X offset for kanji input file 4, default={}".format(defaultPixelOffset),default=defaultPixelOffset,type=int) command_Line_parser.add_argument("-kf-yo", "--kanjiFile-yOffset", help="specify a Y offset for kanji input, default={}".format(defaultKanjiYOffset),default=defaultKanjiYOffset,type=int) command_Line_parser.add_argument("-kf2-yo", "--kanjiFile2-yOffset", help="specify a Y offset for kanji input file 2, default={}".format(defaultKanjiYOffset),default=defaultKanjiYOffset,type=int) command_Line_parser.add_argument("-kf3-yo", "--kanjiFile3-yOffset", help="specify a Y offset for kanji input file 3, default={}".format(defaultKanjiYOffset),default=defaultKanjiYOffset,type=int) command_Line_parser.add_argument("-kf4-yo", "--kanjiFile4-yOffset", help="specify a Y offset for kanji input file 4, default={}".format(defaultKanjiYOffset),default=defaultKanjiYOffset,type=int) command_Line_parser.add_argument("-q", "--quality", help="specify quality 480p/720p/1080p, default={}".format(defaultQuality),default=defaultQuality,type=str) command_Line_parser.add_argument("-fps", "--framesPerSecond", help="specify conversion rate from SRT to BDN XML timecodes, default is 24000/1001",default=defaultFPS,type=str) command_Line_parser.add_argument("-pl", "--preferLast", help="when resolving duplicate file entries for a subtitle, prefer the last one list, default=First", action="store_true") command_Line_parser.add_argument("-ip", "--enableImageProcessing", help="vertically flip romaji images and rotate kanji ones clockwise, or counterclockwise", action="store_true") command_Line_parser.add_argument("-kr", "--kanjiRight", help="alignment for Kanji should be on the Right , default=Left", action="store_true") command_Line_parser.add_argument("-o", "--output", help="specify the output file name, default is to change to .xml",type=str) command_Line_parser.add_argument("-e", "--encoding", help="specify encoding for input files, default={}".format(defaultEncodingType),default=defaultEncodingType,type=str) command_Line_parser.add_argument("-d", "--debug", help="display calculated settings and other information",action="store_true") #parse command line settings command_Line_arguments=command_Line_parser.parse_args() dialogueFileXOffset=command_Line_arguments.dialogueFile_xOffset dialogueFile2XOffset=command_Line_arguments.dialogueFile2_xOffset dialogueFile3XOffset=command_Line_arguments.dialogueFile3_xOffset dialogueFile4XOffset=command_Line_arguments.dialogueFile4_xOffset dialogueFileYOffset=command_Line_arguments.dialogueFile_yOffset dialogueFile2YOffset=command_Line_arguments.dialogueFile2_yOffset dialogueFile3YOffset=command_Line_arguments.dialogueFile3_yOffset dialogueFile4YOffset=command_Line_arguments.dialogueFile4_yOffset romajiFileXOffset=command_Line_arguments.romajiFile_xOffset romajiFile2XOffset=command_Line_arguments.romajiFile2_xOffset romajiFile3XOffset=command_Line_arguments.romajiFile3_xOffset romajiFile4XOffset=command_Line_arguments.romajiFile4_xOffset romajiFileYOffset=command_Line_arguments.romajiFile_yOffset romajiFile2YOffset=command_Line_arguments.romajiFile2_yOffset romajiFile3YOffset=command_Line_arguments.romajiFile3_yOffset romajiFile4YOffset=command_Line_arguments.romajiFile4_yOffset kanjiFileXOffset=command_Line_arguments.kanjiFile_xOffset kanjiFile2XOffset=command_Line_arguments.kanjiFile2_xOffset kanjiFile3XOffset=command_Line_arguments.kanjiFile3_xOffset kanjiFile4XOffset=command_Line_arguments.kanjiFile4_xOffset kanjiFileYOffset=command_Line_arguments.kanjiFile_yOffset kanjiFile2YOffset=command_Line_arguments.kanjiFile2_yOffset kanjiFile3YOffset=command_Line_arguments.kanjiFile3_yOffset kanjiFile4YOffset=command_Line_arguments.kanjiFile4_yOffset #check to make sure any dialogue.srt, romaji.srt, and kanji.srt files specified actually exist if command_Line_arguments.dialogueFile == None: if command_Line_arguments.romajiFile == None: if command_Line_arguments.kanjiFile == None: sys.exit('\n Error: Please specify at least one input file. '+ usageHelp) specifiedFiles=[] #specifiedFiles[i]=[dialogueFilePath,typeOfInput,fileXOffset,fileYOffset] if command_Line_arguments.dialogueFile != None: dialogueFilePath=command_Line_arguments.dialogueFile specifiedFiles.append([dialogueFilePath,'dialogue',dialogueFileXOffset,dialogueFileYOffset]) if os.path.isfile(dialogueFilePath) != True: sys.exit('\n Error: Unable to find SRT file "' + dialogueFilePath + '"' + usageHelp) if command_Line_arguments.dialogueFile2 != None: dialogueFile2Path=command_Line_arguments.dialogueFile2 specifiedFiles.append([dialogueFile2Path,'dialogue',dialogueFile2XOffset,dialogueFile2YOffset]) if os.path.isfile(dialogueFile2Path) != True: sys.exit('\n Error: Unable to find SRT file "' + dialogueFile2Path + '"' + usageHelp) if command_Line_arguments.dialogueFile3 != None: dialogueFile3Path=command_Line_arguments.dialogueFile3 specifiedFiles.append([dialogueFile3Path,'dialogue',dialogueFile3XOffset,dialogueFile3YOffset]) if os.path.isfile(dialogueFile3Path) != True: sys.exit('\n Error: Unable to find SRT file "' + dialogueFile3Path + '"' + usageHelp) if command_Line_arguments.dialogueFile4 != None: dialogueFile4Path=command_Line_arguments.dialogueFile4 specifiedFiles.append([dialogueFile4Path,'dialogue',dialogueFile4XOffset,dialogueFile4YOffset]) if os.path.isfile(dialogueFile4Path) != True: sys.exit('\n Error: Unable to find SRT file "' + dialogueFile4Path + '"' + usageHelp) if command_Line_arguments.romajiFile != None: romajiFilePath=command_Line_arguments.romajiFile specifiedFiles.append([romajiFilePath,'romaji',romajiFileXOffset,romajiFileYOffset]) if os.path.isfile(romajiFilePath) != True: sys.exit('\n Error: Unable to find SRT file "' + romajiFilePath + '"' + usageHelp) if command_Line_arguments.romajiFile2 != None: romajiFile2Path=command_Line_arguments.romajiFile2 specifiedFiles.append([romajiFile2Path,'romaji',romajiFile2XOffset,romajiFile2YOffset]) if os.path.isfile(romajiFile2Path) != True: sys.exit('\n Error: Unable to find SRT file "' + romajiFile2Path + '"' + usageHelp) if command_Line_arguments.romajiFile3 != None: romajiFile3Path=command_Line_arguments.romajiFile3 specifiedFiles.append([romajiFile3Path,'romaji',romajiFile3XOffset,romajiFile3YOffset]) if os.path.isfile(romajiFile3Path) != True: sys.exit('\n Error: Unable to find SRT file "' + romajiFile3Path + '"' + usageHelp) if command_Line_arguments.romajiFile4 != None: romajiFile4Path=command_Line_arguments.romajiFile4 specifiedFiles.append([romajiFile4Path,'romaji',romajiFile4XOffset,romajiFile4YOffset]) if os.path.isfile(romajiFile4Path) != True: sys.exit('\n Error: Unable to find SRT file "' + romajiFile4Path + '"' + usageHelp) if command_Line_arguments.kanjiFile != None: kanjiFilePath=command_Line_arguments.kanjiFile specifiedFiles.append([kanjiFilePath,'kanji',kanjiFileXOffset,kanjiFileYOffset]) if os.path.isfile(kanjiFilePath) != True: sys.exit('\n Error: Unable to find SRT file "' + kanjiFilePath + '"' + usageHelp) if command_Line_arguments.kanjiFile2 != None: kanjiFile2Path=command_Line_arguments.kanjiFile2 specifiedFiles.append([kanjiFile2Path,'kanji',kanjiFile2XOffset,kanjiFile2YOffset]) if os.path.isfile(kanjiFile2Path) != True: sys.exit('\n Error: Unable to find SRT file "' + kanjiFile2Path + '"' + usageHelp) if command_Line_arguments.kanjiFile3 != None: kanjiFile3Path=command_Line_arguments.kanjiFile3 specifiedFiles.append([kanjiFile3Path,'kanji',kanjiFile3XOffset,kanjiFile3YOffset]) if os.path.isfile(kanjiFile3Path) != True: sys.exit('\n Error: Unable to find SRT file "' + kanjiFile3Path + '"' + usageHelp) if command_Line_arguments.kanjiFile4 != None: kanjiFile4Path=command_Line_arguments.kanjiFile4 specifiedFiles.append([kanjiFile4Path,'kanji',kanjiFile4XOffset,kanjiFile4YOffset]) if os.path.isfile(kanjiFile4Path) != True: sys.exit('\n Error: Unable to find SRT file "' + kanjiFile4Path + '"' + usageHelp) if len(specifiedFiles) == 0: sys.exit('\n Error: Please specify at least one input file. '+ usageHelp) quality=command_Line_arguments.quality fpsRate=encodingType=command_Line_arguments.framesPerSecond preferLast=command_Line_arguments.preferLast processImages=command_Line_arguments.enableImageProcessing kanjiRight=command_Line_arguments.kanjiRight if command_Line_arguments.output != None: outputFileName=command_Line_arguments.output else: outputFileName=os.path.splitext(specifiedFiles[0][0])[0]+ ".xml" encodingType=command_Line_arguments.encoding debug=command_Line_arguments.debug dropFrameStatus=defaultDropFrameStatus if debug == True: #print("inputFileName="+inputFileName) print("quality="+str(quality)) #print("yOffset="+str(yOffset)) print("outputFileName="+outputFileName) print("fpsRate="+str(fpsRate)) #check quality qualityValid=False if quality == '480p': qualityValid=True videoWidth=848 videoHeight=480 if quality == '480': quality='480p' qualityValid=True videoWidth=848 videoHeight=480 if quality == '480p_43': quality='480p' qualityValid=True videoWidth=640 videoHeight=480 if quality == '480_43': quality='480p' qualityValid=True videoWidth=640 videoHeight=480 if quality == '720p': qualityValid=True videoWidth=1280 videoHeight=720 if quality == '720': quality='720p' qualityValid=True videoWidth=1280 videoHeight=720 if quality == '720p_43': quality='720p' qualityValid=True videoWidth=960 videoHeight=720 if quality == '720_43': quality='720p' qualityValid=True videoWidth=960 videoHeight=720 if quality == '1080p': qualityValid=True videoWidth=1920 videoHeight=1080 if quality == '1080': quality='1080p' qualityValid=True videoWidth=1920 videoHeight=1080 if quality == '1080p_43': quality='1080p' qualityValid=True videoWidth=1440 videoHeight=1080 if quality == '1080_43': quality='1080p' qualityValid=True videoWidth=1440 videoHeight=1080 if qualityValid!=True: sys.exit('\n Error: The following quality setting is invalid: "' + quality + '"' + usageHelp) try: fpsRate=num(fpsRate) except decimal.InvalidOperation: #occurs when converting string with / to decimal ('24000/1001'-> decimal) #print(sys.exc_info()[0]) #print('pie') if '/' in fpsRate: #print(fpsRate.split(sep='/')[0]) #print(fpsRate.split(sep='/')[0] + ' ' + fpsRate.split(sep='/')[1]) fpsRate=num(fpsRate.split(sep='/')[0])/num(fpsRate.split(sep='/')[1]) elif '\\' in fpsRate: fpsRate=num(fpsRate.split(sep='\\')[0])/num(fpsRate.split(sep='\\')[1]) #except ValueError: #occurs when converting string with / to float ('24000/1001'-> float) # print(fpsRate + 'raised a value error') for i in range(len(specifiedFiles)): if specifiedFiles[i][1] == 'dialogue': #check yOffset # valid range is [2-1076] for a 2 pixel height image # invalid if (yOffset + imageHeight +2 >= videoHeight) #ends too high # invalid if (yOffset is < 2) #starts too low if specifiedFiles[i][3] < 2: sys.exit('\n Error: yOffset setting is out of [2,{}] range: "'.format(videoHeight-4) + str(specifiedFiles[i][3]) + '"' + usageHelp) if specifiedFiles[i][3] + 2 >= videoHeight: sys.exit('\n Error: yOffset setting is out of [2,{}] range: "'.format(videoHeight-4) + str(specifiedFiles[i][3]) + '"' + usageHelp) if specifiedFiles[i][1] == 'romaji': if specifiedFiles[i][3] < 2: sys.exit('\n Error: yOffset setting is out of [2,{}] range: "'.format(videoHeight-4) + str(specifiedFiles[i][3]) + '"' + usageHelp) if specifiedFiles[i][3] + 2 >= videoHeight: sys.exit('\n Error: yOffset setting is out of [2,{}] range: "'.format(videoHeight-4) + str(specifiedFiles[i][3]) + '"' + usageHelp) if specifiedFiles[i][1] == 'kanji': #for Kanji mode, check
= 0x49A3 MediaGaugeD164 = 0x49A4 MediaGaugeD165 = 0x49A5 MediaGaugeD166 = 0x49A6 MediaGaugeD167 = 0x49A7 MediaGaugeD168 = 0x49A8 MediaGaugeD169 = 0x49A9 MediaGaugeD170 = 0x49AA MediaGaugeD171 = 0x49AB MediaGaugeD172 = 0x49AC MediaGaugeD173 = 0x49AD MediaGaugeD174 = 0x49AE MediaGaugeD175 = 0x49AF MediaGaugeD176 = 0x49B0 MediaGaugeD177 = 0x49B1 MediaGaugeD178 = 0x49B2 MediaGaugeD179 = 0x49B3 MediaGaugeD180 = 0x49B4 MediaGaugeD181 = 0x49B5 MediaGaugeD182 = 0x49B6 MediaGaugeD183 = 0x49B7 MediaGaugeD184 = 0x49B8 MediaGaugeD185 = 0x49B9 MediaGaugeD186 = 0x49BA MediaGaugeD187 = 0x49BB MediaGaugeD188 = 0x49BC MediaGaugeD189 = 0x49BD MediaGaugeD190 = 0x49BE MediaGaugeD191 = 0x49BF MediaGaugeD192 = 0x49C0 MediaGaugeD193 = 0x49C1 MediaGaugeD194 = 0x49C2 MediaGaugeD195 = 0x49C3 MediaGaugeD196 = 0x49C4 MediaGaugeD197 = 0x49C5 MediaGaugeD198 = 0x49C6 MediaGaugeD199 = 0x49C7 MediaGaugeD200 = 0x49C8 MediaGaugeD201 = 0x49C9 MediaGaugeD202 = 0x49CA MediaGaugeD203 = 0x49CB MediaGaugeD204 = 0x49CC MediaGaugeD205 = 0x49CD MediaGaugeD206 = 0x49CE MediaGaugeD207 = 0x49CF MediaGaugeD208 = 0x49D0 MediaGaugeD209 = 0x49D1 MediaGaugeD210 = 0x49D2 MediaGaugeD211 = 0x49D3 MediaGaugeD212 = 0x49D4 MediaGaugeD213 = 0x49D5 MediaGaugeD214 = 0x49D6 MediaGaugeD215 = 0x49D7 MediaGaugeD216 = 0x49D8 MediaGaugeD217 = 0x49D9 MediaGaugeD218 = 0x49DA MediaGaugeD219 = 0x49DB MediaGaugeD220 = 0x49DC MediaGaugeD221 = 0x49DD MediaGaugeD222 = 0x49DE MediaGaugeD223 = 0x49DF MediaGaugeD224 = 0x49E0 MediaGaugeD225 = 0x49E1 MediaGaugeD226 = 0x49E2 MediaGaugeD227 = 0x49E3 MediaGaugeD228 = 0x49E4 MediaGaugeD229 = 0x49E5 MediaGaugeD230 = 0x49E6 MediaGaugeD231 = 0x49E7 MediaGaugeD232 = 0x49E8 MediaGaugeD233 = 0x49E9 MediaGaugeD234 = 0x49EA MediaGaugeD235 = 0x49EB MediaGaugeD236 = 0x49EC MediaGaugeD237 = 0x49ED MediaGaugeD238 = 0x49EE MediaGaugeD239 = 0x49EF MediaGaugeD240 = 0x49F0 MediaGaugeD241 = 0x49F1 MediaGaugeD242 = 0x49F2 MediaGaugeD243 = 0x49F3 MediaGaugeD244 = 0x49F4 MediaGaugeD245 = 0x49F5 MediaGaugeD246 = 0x49F6 MediaGaugeD247 = 0x49F7 MediaGaugeD248 = 0x49F8 MediaGaugeD249 = 0x49F9 MediaGaugeD250 = 0x49FA MediaGaugeD251 = 0x49FB MediaGaugeD252 = 0x49FC MediaGaugeD253 = 0x49FD MediaGaugeD254 = 0x49FE MediaGaugeD255 = 0x49FF # MediaThermometer List MediaThermometer0 = 0x4A00 MediaThermometer1 = 0x4A01 MediaThermometer2 = 0x4A02 MediaThermometer3 = 0x4A03 MediaThermometer4 = 0x4A04 MediaThermometer5 = 0x4A05 MediaThermometer6 = 0x4A06 MediaThermometer7 = 0x4A07 MediaThermometer8 = 0x4A08 MediaThermometer9 = 0x4A09 MediaThermometer10 = 0x4A0A MediaThermometer11 = 0x4A0B MediaThermometer12 = 0x4A0C MediaThermometer13 = 0x4A0D MediaThermometer14 = 0x4A0E MediaThermometer15 = 0x4A0F MediaThermometer16 = 0x4A10 MediaThermometer17 = 0x4A11 MediaThermometer18 = 0x4A12 MediaThermometer19 = 0x4A13 MediaThermometer20 = 0x4A14 MediaThermometer21 = 0x4A15 MediaThermometer22 = 0x4A16 MediaThermometer23 = 0x4A17 MediaThermometer24 = 0x4A18 MediaThermometer25 = 0x4A19 MediaThermometer26 = 0x4A1A MediaThermometer27 = 0x4A1B MediaThermometer28 = 0x4A1C MediaThermometer29 = 0x4A1D MediaThermometer30 = 0x4A1E MediaThermometer31 = 0x4A1F MediaThermometer32 = 0x4A20 MediaThermometer33 = 0x4A21 MediaThermometer34 = 0x4A22 MediaThermometer35 = 0x4A23 MediaThermometer36 = 0x4A24 MediaThermometer37 = 0x4A25 MediaThermometer38 = 0x4A26 MediaThermometer39 = 0x4A27 MediaThermometer40 = 0x4A28 MediaThermometer41 = 0x4A29 MediaThermometer42 = 0x4A2A MediaThermometer43 = 0x4A2B MediaThermometer44 = 0x4A2C MediaThermometer45 = 0x4A2D MediaThermometer46 = 0x4A2E MediaThermometer47 = 0x4A2F MediaThermometer48 = 0x4A30 MediaThermometer49 = 0x4A31 MediaThermometer50 = 0x4A32 MediaThermometer51 = 0x4A33 MediaThermometer52 = 0x4A34 MediaThermometer53 = 0x4A35 MediaThermometer54 = 0x4A36 MediaThermometer55 = 0x4A37 MediaThermometer56 = 0x4A38 MediaThermometer57 = 0x4A39 MediaThermometer58 = 0x4A3A MediaThermometer59 = 0x4A3B MediaThermometer60 = 0x4A3C MediaThermometer61 = 0x4A3D MediaThermometer62 = 0x4A3E MediaThermometer63 = 0x4A3F MediaThermometer64 = 0x4A40 MediaThermometer65 = 0x4A41 MediaThermometer66 = 0x4A42 MediaThermometer67 = 0x4A43 MediaThermometer68 = 0x4A44 MediaThermometer69 = 0x4A45 MediaThermometer70 = 0x4A46 MediaThermometer71 = 0x4A47 MediaThermometer72 = 0x4A48 MediaThermometer73 = 0x4A49 MediaThermometer74 = 0x4A4A MediaThermometer75 = 0x4A4B MediaThermometer76 = 0x4A4C MediaThermometer77 = 0x4A4D MediaThermometer78 = 0x4A4E MediaThermometer79 = 0x4A4F MediaThermometer80 = 0x4A50 MediaThermometer81 = 0x4A51 MediaThermometer82 = 0x4A52 MediaThermometer83 = 0x4A53 MediaThermometer84 = 0x4A54 MediaThermometer85 = 0x4A55 MediaThermometer86 = 0x4A56 MediaThermometer87 = 0x4A57 MediaThermometer88 = 0x4A58 MediaThermometer89 = 0x4A59 MediaThermometer90 = 0x4A5A MediaThermometer91 = 0x4A5B MediaThermometer92 = 0x4A5C MediaThermometer93 = 0x4A5D MediaThermometer94 = 0x4A5E MediaThermometer95 = 0x4A5F MediaThermometer96 = 0x4A60 MediaThermometer97 = 0x4A61 MediaThermometer98 = 0x4A62 MediaThermometer99 = 0x4A63 MediaThermometer100 = 0x4A64 MediaThermometer101 = 0x4A65 MediaThermometer102 = 0x4A66 MediaThermometer103 = 0x4A67 MediaThermometer104 = 0x4A68 MediaThermometer105 = 0x4A69 MediaThermometer106 = 0x4A6A MediaThermometer107 = 0x4A6B MediaThermometer108 = 0x4A6C MediaThermometer109 = 0x4A6D MediaThermometer110 = 0x4A6E MediaThermometer111 = 0x4A6F MediaThermometer112 = 0x4A70 MediaThermometer113 = 0x4A71 MediaThermometer114 = 0x4A72 MediaThermometer115 = 0x4A73 MediaThermometer116 = 0x4A74 MediaThermometer117 = 0x4A75 MediaThermometer118 = 0x4A76 MediaThermometer119 = 0x4A77 MediaThermometer120 = 0x4A78 MediaThermometer121 = 0x4A79 MediaThermometer122 = 0x4A7A MediaThermometer123 = 0x4A7B MediaThermometer124 = 0x4A7C MediaThermometer125 = 0x4A7D MediaThermometer126 = 0x4A7E MediaThermometer127 = 0x4A7F MediaThermometer128 = 0x4A80 MediaThermometer129 = 0x4A81 MediaThermometer130 = 0x4A82 MediaThermometer131 = 0x4A83 MediaThermometer132 = 0x4A84 MediaThermometer133 = 0x4A85 MediaThermometer134 = 0x4A86 MediaThermometer135 = 0x4A87 MediaThermometer136 = 0x4A88 MediaThermometer137 = 0x4A89 MediaThermometer138 = 0x4A8A MediaThermometer139 = 0x4A8B MediaThermometer140 = 0x4A8C MediaThermometer141 = 0x4A8D MediaThermometer142 = 0x4A8E MediaThermometer143 = 0x4A8F MediaThermometer144 = 0x4A90 MediaThermometer145 = 0x4A91 MediaThermometer146 = 0x4A92 MediaThermometer147 = 0x4A93 MediaThermometer148 = 0x4A94 MediaThermometer149 = 0x4A95 MediaThermometer150 = 0x4A96 MediaThermometer151 = 0x4A97 MediaThermometer152 = 0x4A98 MediaThermometer153 = 0x4A99 MediaThermometer154 = 0x4A9A MediaThermometer155 = 0x4A9B MediaThermometer156 = 0x4A9C MediaThermometer157 = 0x4A9D MediaThermometer158 = 0x4A9E MediaThermometer159 = 0x4A9F MediaThermometer160 = 0x4AA0 MediaThermometer161 = 0x4AA1 MediaThermometer162 = 0x4AA2 MediaThermometer163 = 0x4AA3 MediaThermometer164 = 0x4AA4 MediaThermometer165 = 0x4AA5 MediaThermometer166 = 0x4AA6 MediaThermometer167 = 0x4AA7 MediaThermometer168 = 0x4AA8 MediaThermometer169 = 0x4AA9 MediaThermometer170 = 0x4AAA MediaThermometer171 = 0x4AAB MediaThermometer172 = 0x4AAC MediaThermometer173 = 0x4AAD MediaThermometer174 = 0x4AAE MediaThermometer175 = 0x4AAF MediaThermometer176 = 0x4AB0 MediaThermometer177 = 0x4AB1 MediaThermometer178 = 0x4AB2 MediaThermometer179 = 0x4AB3 MediaThermometer180 = 0x4AB4 MediaThermometer181 = 0x4AB5 MediaThermometer182 = 0x4AB6 MediaThermometer183 = 0x4AB7 MediaThermometer184 = 0x4AB8 MediaThermometer185 = 0x4AB9 MediaThermometer186 = 0x4ABA MediaThermometer187 = 0x4ABB MediaThermometer188 = 0x4ABC MediaThermometer189 = 0x4ABD MediaThermometer190 = 0x4ABE MediaThermometer191 = 0x4ABF MediaThermometer192 = 0x4AC0 MediaThermometer193 = 0x4AC1 MediaThermometer194 = 0x4AC2 MediaThermometer195 = 0x4AC3 MediaThermometer196 = 0x4AC4 MediaThermometer197 = 0x4AC5 MediaThermometer198 = 0x4AC6 MediaThermometer199 = 0x4AC7 MediaThermometer200 = 0x4AC8 MediaThermometer201 = 0x4AC9 MediaThermometer202 = 0x4ACA MediaThermometer203 = 0x4ACB MediaThermometer204 = 0x4ACC MediaThermometer205 = 0x4ACD MediaThermometer206 = 0x4ACE MediaThermometer207 = 0x4ACF MediaThermometer208 = 0x4AD0 MediaThermometer209 = 0x4AD1 MediaThermometer210 = 0x4AD2 MediaThermometer211 = 0x4AD3 MediaThermometer212 = 0x4AD4 MediaThermometer213 = 0x4AD5 MediaThermometer214 = 0x4AD6 MediaThermometer215 = 0x4AD7 MediaThermometer216 = 0x4AD8 MediaThermometer217 = 0x4AD9 MediaThermometer218 = 0x4ADA MediaThermometer219 = 0x4ADB MediaThermometer220 = 0x4ADC MediaThermometer221 = 0x4ADD MediaThermometer222 = 0x4ADE MediaThermometer223 = 0x4ADF MediaThermometer224 = 0x4AE0 MediaThermometer225 = 0x4AE1 MediaThermometer226 = 0x4AE2 MediaThermometer227 = 0x4AE3 MediaThermometer228 = 0x4AE4 MediaThermometer229 = 0x4AE5 MediaThermometer230 = 0x4AE6 MediaThermometer231 = 0x4AE7 MediaThermometer232 = 0x4AE8 MediaThermometer233 = 0x4AE9 MediaThermometer234 = 0x4AEA MediaThermometer235 = 0x4AEB MediaThermometer236 = 0x4AEC MediaThermometer237 = 0x4AED MediaThermometer238 = 0x4AEE MediaThermometer239 = 0x4AEF MediaThermometer240 = 0x4AF0 MediaThermometer241 = 0x4AF1 MediaThermometer242 = 0x4AF2 MediaThermometer243 = 0x4AF3 MediaThermometer244 = 0x4AF4 MediaThermometer245 = 0x4AF5 MediaThermometer246 = 0x4AF6 MediaThermometer247 = 0x4AF7 MediaThermometer248 = 0x4AF8 MediaThermometer249 = 0x4AF9 MediaThermometer250 = 0x4AFA MediaThermometer251 = 0x4AFB MediaThermometer252 = 0x4AFC MediaThermometer253 = 0x4AFD MediaThermometer254 = 0x4AFE MediaThermometer255 = 0x4AFF # LedSpectrum List LedSpectrum0 = 0x4B00 LedSpectrum1 = 0x4B01 LedSpectrum2 = 0x4B02 LedSpectrum3 = 0x4B03 LedSpectrum4 = 0x4B04 LedSpectrum5 = 0x4B05 LedSpectrum6 = 0x4B06 LedSpectrum7 = 0x4B07 LedSpectrum8 = 0x4B08 LedSpectrum9 = 0x4B09 LedSpectrum10 = 0x4B0A LedSpectrum11 = 0x4B0B LedSpectrum12 = 0x4B0C LedSpectrum13 = 0x4B0D LedSpectrum14 = 0x4B0E LedSpectrum15 = 0x4B0F LedSpectrum16 = 0x4B10 LedSpectrum17 = 0x4B11 LedSpectrum18 = 0x4B12 LedSpectrum19 = 0x4B13 LedSpectrum20 = 0x4B14 LedSpectrum21 = 0x4B15 LedSpectrum22 = 0x4B16 LedSpectrum23 = 0x4B17 LedSpectrum24 = 0x4B18 LedSpectrum25 = 0x4B19 LedSpectrum26 = 0x4B1A LedSpectrum27 = 0x4B1B LedSpectrum28 = 0x4B1C LedSpectrum29 = 0x4B1D LedSpectrum30 = 0x4B1E LedSpectrum31 = 0x4B1F LedSpectrum32 = 0x4B20 LedSpectrum33 = 0x4B21 LedSpectrum34 = 0x4B22 LedSpectrum35 = 0x4B23 LedSpectrum36 = 0x4B24 LedSpectrum37 = 0x4B25 LedSpectrum38 = 0x4B26 LedSpectrum39 = 0x4B27 LedSpectrum40 = 0x4B28 LedSpectrum41 = 0x4B29 LedSpectrum42 = 0x4B2A LedSpectrum43 = 0x4B2B LedSpectrum44 = 0x4B2C LedSpectrum45 = 0x4B2D LedSpectrum46 = 0x4B2E LedSpectrum47 = 0x4B2F LedSpectrum48 = 0x4B30 LedSpectrum49 = 0x4B31 LedSpectrum50 = 0x4B32 LedSpectrum51 = 0x4B33 LedSpectrum52 = 0x4B34 LedSpectrum53 = 0x4B35 LedSpectrum54 = 0x4B36 LedSpectrum55 = 0x4B37 LedSpectrum56 = 0x4B38 LedSpectrum57 = 0x4B39 LedSpectrum58 = 0x4B3A LedSpectrum59 = 0x4B3B LedSpectrum60 = 0x4B3C LedSpectrum61 = 0x4B3D LedSpectrum62 = 0x4B3E LedSpectrum63 = 0x4B3F LedSpectrum64 = 0x4B40 LedSpectrum65 = 0x4B41 LedSpectrum66 = 0x4B42 LedSpectrum67 = 0x4B43 LedSpectrum68 = 0x4B44 LedSpectrum69 = 0x4B45 LedSpectrum70 = 0x4B46 LedSpectrum71 = 0x4B47 LedSpectrum72 = 0x4B48 LedSpectrum73 = 0x4B49 LedSpectrum74 = 0x4B4A LedSpectrum75 = 0x4B4B
IRIs. :return: Server response that is a nested dictionary format >>> self.update_entity( \ ilx_id='ilx_0101431', \ label='Brain', \ type='term', # options: term, pde, fde, cde, annotation, or relationship \ definition='Official definition for entity.', \ comment='Additional casual notes for the next person.', \ subThingOf='ilx_1234567', \ add_synonyms=[{ \ 'literal': 'Better Brains', # label of synonym \ 'type': 'obo:hasExactSynonym', # Often predicate defined in ref ontology. \ }], \ delete_synonyms=[{ \ 'literal': 'Brains', # label of synonym \ 'type': 'obo:hasExactSynonym', # Often predicate defined in ref ontology. \ }], \ add_existing_ids=[{ \ 'iri': 'http://purl.obolibrary.org/obo/UBERON_0000956', \ 'curie': 'UBERON:0000956', # Obeys prefix:id structure. \ 'preferred': '1', # Can be 0 or 1 with a type of either str or int. \ }], \ delet_existing_ids=[{ \ 'iri': 'http://purl.obolibrary.org/obo/UBERON_0000955', \ 'curie': 'UBERON:0000955', # Obeys prefix:id structure. \ }], \ predicates_to_add={ \ # Annotation \ 'http://uri.interlex.org/base/ilx_0101432': 'sample_annotation_value', \ # Relationship \ 'http://uri.interlex.org/base/ilx_0101435': 'http://uri.interlex.org/base/ilx_0101434', \ }, \ predicates_to_withdraw={ \ # Annotation \ 'http://uri.interlex.org/base/ilx_0101432': 'sample_annotation_value', \ # Relationship \ 'http://uri.interlex.org/base/ilx_0101435': 'http://uri.interlex.org/base/ilx_0101434', \ }, \ cid='504', # SPARC Community, \ status='0', # remove delete \ ) """ resp = self.ilx_cli.update_entity( ilx_id=ilx_id, label=label, type=type, superclass=subThingOf, definition=definition, comment=comment, add_synonyms=add_synonyms, delete_synonyms=delete_synonyms, add_existing_ids=add_existing_ids, delete_existing_ids=delete_existing_ids, cid=cid, status=status, # predicates=tresp, ) tresp = None # todo test if tresp is good enough to be put into out_predicates if predicates_to_add: trep = self.add_predicates(ilx_curieoriri=resp['ilx'], predicates=predicates_to_add) tresp = None if predicates_to_withdraw: trep = self.delete_predicates(ilx_curieoriri=resp['ilx'], predicates=predicates_to_withdraw) out_predicates = {} if 'comment' in resp: # filtering of missing fields is done in the client out_predicates['comment'] = resp['comment'] result = self.QueryResult( query_args={}, iri='http://uri.interlex.org/base/' + resp['ilx'], curie=self._fix_fragment(resp['ilx']), label=resp['label'], labels=tuple(), # abbrev=None, # TODO # acronym=None, # TODO definition=resp['definition'], synonyms=tuple([d['literal'] for d in resp['synonyms']]), # deprecated=None, # prefix=None, # category=None, predicates=out_predicates, # _graph=None, source=self, ) return result def add_triple(self, subject, predicate, object): """ Triple of curied or full iris to add to graph. Subject should be an interlex """ def filter_ontid(ontid): if ontid.startswith('http://'): pass elif ontid.prefix == 'ILXTEMP': ontid = 'tmp_' + ontid.suffix else: ontid = 'ilx_' + ontid.suffix return ontid # this split between annotations and relationships is severely annoying # because you have to know before hand which one it is (sigh) s = self.OntId(subject) p = self.OntId(predicate) o = self._get_type(object) if type(o) == str: func = self.ilx_cli.add_annotation elif type(o) == self.OntId: func = self.ilx_cli.add_relationship o = filter_ontid(o) else: raise TypeError(f'what are you giving me?! {object!r}') s = filter_ontid(s) p = filter_ontid(p) resp = func(s, p, o) return resp def delete_triple(self, subject, predicate, object): """ Triple of curied or full iris to add to graph. Subject should be an interlex """ # TODO : TROY : should move this to a global change since this is fluid def filter_ontid(ontid): if ontid.startswith('http://'): pass elif ontid.prefix == 'ILXTEMP': ontid = 'tmp_' + ontid.suffix elif ontid.prefix == 'ILX.CDE': ontid = 'cde_' + ontid.suffix elif ontid.prefix == 'ILX.SET': ontid = 'set_' + ontid.suffix elif ontid.prefix == 'ILX.PDE': ontid = 'pde_' + ontid.suffix else: ontid = 'ilx_' + ontid.suffix return ontid # this split between annotations and relationships is severely annoying # because you have to know before hand which one it is (sigh) s = self.OntId(subject) p = self.OntId(predicate) o = self._get_type(object) if type(o) == str: func = self.ilx_cli.withdraw_annotation elif type(o) == self.OntId: func = self.ilx_cli.withdraw_relationship o = filter_ontid(o) else: raise TypeError(f'what are you giving me?! {object!r}') s = filter_ontid(s) p = filter_ontid(p) # TODO: check if add_relationship works resp = func(s, p, o) return resp def _get_type(self, entity): try: return self.OntId(entity) except self.OntId.Error: return entity @property def _is_dev_endpoint(self): return bool(self.port) def query(self, iri=None, curie=None, label=None, term=None, predicates=tuple(), prefix=tuple(), exclude_prefix=tuple(), limit=10, **_): kwargs = cullNone(iri=iri, curie=curie, label=label, term=term, predicates=predicates) if iri: oiri = self.OntId(iri=iri) icurie = oiri.curie if curie and icurie and icurie != curie: raise ValueError(f'curie and curied iri do not match {curie} {icurie}') else: curie = icurie elif curie: iri = self.OntId(curie).iri if self._is_dev_endpoint: res = self._dev_query(kwargs, iri, curie, label, predicates, prefix, exclude_prefix) if res is not None: yield res elif hasattr(self, 'ilx_cli'): if not self.api_first and (iri or curie): res = self._dev_query(kwargs, iri, curie, label, predicates, prefix, exclude_prefix) if res is not None: yield res return res = self._scicrunch_api_query( kwargs=kwargs, iri=iri, curie=curie, label=label, term=term, predicates=predicates, limit=limit) yield from res else: # can only get by iri directly and it must be an ilx id res = self._dev_query(kwargs, iri, curie, label, predicates, prefix, exclude_prefix) if res is not None: yield res def _scicrunch_api_query(self, kwargs, iri, curie, label, term, predicates, limit): resp = None if iri: try: resp: dict = self.ilx_cli.get_entity(iri) except: pass if resp is None and curie: try: resp: dict = self.ilx_cli.get_entity_from_curie(curie) except (requests.exceptions.HTTPError, self.ilx_cli.Error) as e: log.debug(e) resp = None if resp is None or resp['id'] is None: # FIXME should error before we have to check this # sometimes a remote curie does not match ours try: resp: dict = self.ilx_cli.get_entity_from_curie(self.OntId(iri).curie) except (requests.exceptions.HTTPError, self.ilx_cli.Error) as e: log.debug(e) return if resp['id'] is None: return elif label: try: resp: list = self.ilx_cli.query_elastic(label=label, size=limit) except (requests.exceptions.HTTPError, self.ilx_cli.Error) as e: log.debug(e) resp = None elif term: try: resp: list = self.ilx_cli.query_elastic(term=term, size=limit) except (requests.exceptions.HTTPError, self.ilx_cli.Error) as e: log.debug(e) resp = None else: pass # querying on iri or curie through ilx cli is ok if not resp: return resps = [resp] if isinstance(resp, dict) else resp # FIXME this is really a temp hack until we can get the # next version of the alt resolver up and running with # since iirc it can resolve curies for resp in resps: _frag = resp['ilx'] if _frag is None: log.warning(resp) continue _ilx = 'http://uri.interlex.org/base/' + _frag if iri is None: _iri = _ilx else: _iri = iri if curie is None: _curie = self._fix_fragment(resp['ilx']) else: _curie = curie # TODO if predicates is not None then need calls to get annotations and relations predicates = self._proc_api(resp) yield self.QueryResult( query_args=kwargs, iri=_iri, curie=_curie, label=resp['label'], labels=tuple(), # abbrev=None, # TODO # acronym=None, # TODO definition=resp['definition'], synonyms=tuple(resp['synonyms']), # deprecated=None, # prefix=None, # category=None, predicates=predicates, # _graph=None, _blob=resp, source=self, ) def _proc_api(self, resp): preferred, existing, = self._proc_existing(resp) ilx_id = 'http://uri.interlex.org/base/' + resp['ilx'] predicates = { 'ilxr:type': self.OntId('ilx.type:' + resp['type']), 'ilxtr:hasExistingId': existing, 'ilxtr:hasIlxId': self.OntId(ilx_id), } if preferred: # FIXME this should never happen but can ... thanks mysql predicates['TEMP:preferredId'] = preferred sub_thing_of = self._proc_sto(resp) predicates.update(sub_thing_of) return predicates def _proc_existing(self, resp): preferred, existing = None, tuple() for blob_id in resp['existing_ids']: i = self.OntId(blob_id['iri']) existing += i, if blob_id['preferred'] == '1': preferred = i return preferred, existing def _proc_sto(self, resp): if resp['type'] == 'term': p = 'rdfs:subClassOf' elif resp['type'] in ('annotation', 'relationship'): p = 'rdfs:subPropertyOf' elif resp['type'] in ('cde', 'fde', 'pde', 'TermSet'): # none of these have a meaningful subClassOf relation, # though it may be present in the interface # XXX TODO for cde the modelling is incorrect, but the # edge represents what is probably a partOf relationship # or something similar p = 'meaningless-superclass' else: raise NotImplementedError(f'how to sub thing of {resp["type"]}?') out = {p:tuple()} for blob_id in resp['superclasses']: i = self.OntId(self._fix_fragment(blob_id['ilx'])) out[p] += i, return out def _dev_query(self, kwargs, iri, curie, label, predicates, prefix, exclude_prefix): def get(url, headers={'Accept':'application/n-triples'}): # FIXME extremely slow? with requests.Session() as s: s.headers.update(headers) resp = s.get(url, allow_redirects=False) while resp.is_redirect and resp.status_code < 400: # FIXME redirect loop issue # using send means that our headers don't show up in every request resp = s.get(resp.next.url, allow_redirects=False) if not resp.is_redirect: break return resp class NoOnt(Exception): pass class NoAbout(Exception): pass def isAbout(g): try: ontid, *r1 = g[:self.RDF.type:self.OWL.Ontology] except ValueError as e: raise NoOnt('oops!') from e try: o, *r2 = g[ontid:self.URIRef('http://purl.obolibrary.org/obo/IAO_0000136')] except ValueError as e: raise NoAbout('oops!') from e if r1 or r2: raise ValueError(f'NonUnique value for ontology {r1} or about {r2}') return o if curie: if curie.startswith('ILX:') and iri: # FIXME hack, can replace once the new resolver is up url = iri.replace('uri.interlex.org', self.host_port) else: url = f'http://{self.host_port}/base/curies/{curie}?local=True' elif label:
<reponame>albertlee0622/AddHansModelToFRE import os import sys import csv import time import numpy as np import pandas as pd import random import json from system.utility.config import ClientConfig from system.sim_trading.network import PacketTypes, Packet from system.market_data.fre_market_data import EODMarketData from system.database.fre_database import FREDatabase from queue import Queue from system.utility.helpers import usd from system.sim_trading import sim_demo_model as sdm sys.path.append('../') client_config = ClientConfig() database = FREDatabase() eod_market_data = EODMarketData(os.environ.get("EOD_API_KEY"), None) #to only use get_intraday_data() def client_receive(q=None, e=None): total_server_response = b'' while not client_config.receiver_stop: try: server_response = client_config.client_socket.recv(client_config.BUF_SIZE) total_server_response += server_response msgSize = len(total_server_response) while msgSize > 0: if msgSize > 12: server_packet = Packet() server_packet.deserialize(total_server_response) if msgSize > 12 and server_packet.m_data_size <= msgSize: data = json.loads(server_packet.m_data) q.put([server_packet.m_type, data]) total_server_response = total_server_response[server_packet.m_data_size:] msgSize = len(total_server_response) if server_packet.m_type == PacketTypes.END_RSP.value or \ server_packet.m_type == PacketTypes.SERVER_DOWN_RSP.value: client_config.receiver_stop = True else: server_response = client_config.client_socket.recv(client_config.BUF_SIZE) total_server_response += server_response msgSize = len(total_server_response) if not q.empty() and e.isSet(): e.clear() except (OSError, Exception): print("Client Receiver exited\n") sys.exit(0) def logon(client_packet, symbols): client_packet.m_type = PacketTypes.CONNECTION_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Logon', 'Symbol': symbols}) return client_packet def get_client_list(client_packet): client_packet.m_type = PacketTypes.CLIENT_LIST_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Client List'}) return client_packet def get_stock_list(client_packet): client_packet.m_type = PacketTypes.STOCK_LIST_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Stock List'}) return client_packet def get_market_status(client_packet): client_packet.m_type = PacketTypes.MARKET_STATUS_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Market Status'}) return client_packet def get_order_book(client_packet, symbol): client_packet.m_type = PacketTypes.BOOK_INQUIRY_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Book Inquiry', 'Symbol': symbol}) return client_packet def enter_a_new_order(client_packet, order_id, symbol, order_type, side, price, qty): if order_type == "Mkt": price = 0 client_packet.m_type = PacketTypes.NEW_ORDER_REQ.value client_packet.m_data = json.dumps( {'Client': client_config.client_id, 'OrderIndex': order_id, 'Status': 'New Order', 'Symbol': symbol, 'Type': order_type, 'Side': side, 'Price': price, 'Qty': qty}) return client_packet def quit_connection(client_packet): client_packet.m_type = PacketTypes.END_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Client Quit'}) return client_packet def server_down(client_packet): client_packet.m_type = PacketTypes.SERVER_DOWN_REQ.value client_packet.m_data = json.dumps({'Client': client_config.client_id, 'Status': 'Server Down'}) return client_packet def send_msg(client_packet): client_config.client_socket.send(client_packet.serialize()) data = json.loads(client_packet.m_data) print(data) return data def get_response(q): msg_type, msg_data = q.get() print(msg_data) if msg_data is not None: if msg_type == PacketTypes.END_RSP.value or msg_type == PacketTypes.SERVER_DOWN_RSP.value or \ (msg_type == PacketTypes.CONNECTION_RSP.value and msg_data["Status"] == "Rejected"): client_config.client_socket.close() sys.exit(0) return msg_data def set_event(e): e.set() def wait_for_an_event(e): while e.isSet(): continue def join_trading_network(q, e): try: client_packet = Packet() set_event(e) send_msg(logon(client_packet, client_config.client_symbols)) wait_for_an_event(e) get_response(q) set_event(e) send_msg(get_client_list(client_packet)) wait_for_an_event(e) get_response(q) set_event(e) send_msg(get_stock_list(client_packet)) wait_for_an_event(e) stock_data = get_response(q) market_stock_list = stock_data['Stock List'].split(',') # print(market_stock_list) client_packet = Packet() set_event(e) send_msg(get_market_status(client_packet)) wait_for_an_event(e) mkstatus = get_response(q) market_end_date = mkstatus['Market_End_Date'] current_date = mkstatus['Market_Period'] print(market_end_date) selected_stocks, _ = sdm.BBDmodelStockSelector.select_highvol_stock(pd.to_datetime(current_date), market_stock_list) # initialize StkInfo Dict StockInfoDict = sdm.BBDmodelStockSelector.bollingerbands_stkinfo_init(selected_stocks) # print(StockInfoDict) base_filled_orderid = [] # Get market period same as server side # end_date = datetime.datetime.today() # # end_date = datetime.datetime.today() - datetime.timedelta(days = 1) # yesterday # start_date = end_date + datetime.timedelta(-29) # trading_calendar = mcal.get_calendar('NYSE') # market_periods = trading_calendar.schedule( # start_date=start_date.strftime("%Y-%m-%d"), # end_date=end_date.strftime("%Y-%m-%d")).index.strftime("%Y-%m-%d").tolist()[:-1] OrderIndex = 0 # outer loop while True: # inner loop while True: client_packet = Packet() set_event(e) send_msg(get_market_status(client_packet)) wait_for_an_event(e) # when not empty while not q.empty(): data = get_response(q) if data['Status'] not in ['Open', 'Pending Closing', 'Market Closed', 'Pending Open', 'Not Open']: client_config.orders.append(data) else: mkt_status = data print("mkt_status", mkt_status) # wait till mkt open if mkt_status["Status"] == 'Open' or mkt_status["Status"] == 'Pending Closing': break if mkt_status['Market_Period'] == market_end_date and mkt_status["Status"] == "Market Closed": # print(market_end_date) # print(client_config.orders) # PnL Calculation Logic At last day print('PnL Calculation Logic') PnL_dict = {} for stk in StockInfoDict: stkbuy_order = [order for order in client_config.orders if (order['Symbol'] == stk) & (order['Side'] == 'Buy')] print(stkbuy_order) stkbuy_price = [order['Price'] for order in stkbuy_order] print(stkbuy_price) stkbuy_qty = [int(order['Qty']) for order in stkbuy_order] print(stkbuy_qty) stksell_order = [order for order in client_config.orders if (order['Symbol'] == stk) & (order['Side'] == 'Sell')] print(stksell_order) stksell_price = [order['Price'] for order in stksell_order] print(stksell_price) stksell_qty = [int(order['Qty']) for order in stksell_order] print(stksell_qty) stkPnL = sum([P * Q for P, Q in zip(stksell_price, stksell_qty)]) - sum( [P * Q for P, Q in zip(stkbuy_price, stkbuy_qty)]) print(stkPnL) PnL_dict.update({stk: stkPnL}) client_config.PnL = sum(PnL_dict.values()) client_config.Ticker_PnL = {stk: usd(PnL_dict[stk]) for stk in PnL_dict} # complete the sim_trade client_config.trade_complete = True break time.sleep(0.5) if client_config.trade_complete: break # close every day's position in Pending Close if mkt_status["Status"] == "Pending Closing": for stk in StockInfoDict: stkInfo_object = StockInfoDict[stk] stkInfo_object.MA = 'null' stkInfo_object.Std = 'null' stkInfo_object.price_queue = Queue(int(stkInfo_object.H / 5)) # reset the members if stkInfo_object.position != 0: client_packet = Packet() OrderIndex += 1 client_order_id = client_config.client_id + '_' + str(OrderIndex) # if longing if stkInfo_object.position > 0: enter_a_new_order(client_packet, client_order_id, stk, 'Mkt', 'Sell', 100, stkInfo_object.Qty) print("Close Trade in: ", stk, "With postion: Sell", "With Qty: ", stkInfo_object.Qty) print("Because: Close at Pending Close.") set_event(e) send_msg(client_packet) wait_for_an_event(e) # close trade logic response_list = [] while not q.empty(): response_data = get_response(q) response_list.append(response_data) client_config.orders.append(response_data) stkInfo_object.Qty = 0 stkInfo_object.position = 0 # if shorting else: enter_a_new_order(client_packet, client_order_id, stk, 'Mkt', 'Buy', 100, stkInfo_object.Qty) print("Close Trade in: ", stk, "With postion: Buy", "With Qty: ", stkInfo_object.Qty) print("Because: Close at Pending Close.") set_event(e) send_msg(client_packet) wait_for_an_event(e) # close trade logic response_list = [] while not q.empty(): response_data = get_response(q) response_list.append(response_data) client_config.orders.append(response_data) stkInfo_object.Qty = 0 stkInfo_object.position = 0 # re-enter into checking "Open" while-loop continue # BBD Trading Logic client_packet = Packet() set_event(e) client_msg = get_order_book(client_packet, ','.join(selected_stocks)) send_msg(client_msg) wait_for_an_event(e) # when not empty or bad message while True: data = get_response(q) if type(data) == dict: if data['Status'] != 'Done': client_config.orders.append(data) else: break book_data = json.loads(data) order_book = book_data["data"] filled_order_book = [fill_orders for fill_orders in order_book if fill_orders['Status'] in ['Filled']] # print(filled_order_book) filled_orderid = [order['OrderIndex'] for order in filled_order_book] # print(filled_orderid) standing_order_book = [standing_orders for standing_orders in order_book if standing_orders['Status'] in ['New', 'Partial Filled']] # print(filled_order_book, file = sample) # print(standing_order_book, file = sample) # print('test3') # print(StockInfoDict) for stk in StockInfoDict: print(stk) standing_buy_price_list = [order['Price'] for order in standing_order_book if (order['Symbol'] == stk) & (order['Side'] == 'Buy')] standing_sell_price_list = [order['Price'] for order in standing_order_book if (order['Symbol'] == stk) & (order['Side'] == 'Sell')] StockInfoDict[stk].current_price_sell = min(standing_sell_price_list) StockInfoDict[stk].current_price_buy = max(standing_buy_price_list) # print('test2') # store current price in price queue and use it to calculate MA and std for stk in StockInfoDict: stkInfo_object = StockInfoDict[stk] # current price is based on filled_order_book if len(base_filled_orderid) == 0: current_price = (stkInfo_object.current_price_buy + stkInfo_object.current_price_sell) / 2 base_filled_orderid = filled_orderid else: try: newly_filled_orderid = [orderid for orderid in filled_orderid if orderid not in base_filled_orderid] base_filled_orderid = filled_orderid newly_filled_order = [order for order in filled_order_book if order['OrderIndex'] in newly_filled_orderid] filled_price_list = [order['Price'] for order in newly_filled_order] filled_qty_list = [int(order['OrigQty']) for order in newly_filled_order] current_price = sum([P * Q for P, Q in zip(filled_price_list, filled_qty_list)]) / sum( filled_qty_list) # print('test1') except: # when no newly filled # print('test') current_price = (stkInfo_object.current_price_buy + stkInfo_object.current_price_sell) / 2 # print("current price for", stk, "P= " current_price) if not stkInfo_object.price_queue.full(): stkInfo_object.price_queue.put(current_price) if stkInfo_object.price_queue.full(): stkInfo_object.MA = np.array(stkInfo_object.price_queue.queue).mean() stkInfo_object.Std = np.array(stkInfo_object.price_queue.queue).std() / np.sqrt(5) else: # already full popout = stkInfo_object.price_queue.get() stkInfo_object.price_queue.put(current_price) stkInfo_object.MA = np.array(stkInfo_object.price_queue.queue).mean() stkInfo_object.Std = np.array(stkInfo_object.price_queue.queue).std() / np.sqrt(5) for stk in StockInfoDict: stkInfo_object = StockInfoDict[stk] K1 = stkInfo_object.K1 MA = stkInfo_object.MA Std = stkInfo_object.Std Notional = stkInfo_object.Notional if MA == 'null': continue current_buy = stkInfo_object.current_price_buy current_sell = stkInfo_object.current_price_sell # current_p = (current_buy + current_sell) / 2 # print("K1: ",K1) # print("MA: ",MA) # print("Std: ",Std) # print("sell p:",current_sell) # print("buy p:",current_buy) if stkInfo_object.position == 0: # not yet open position, could open if current_sell <= MA - K1 * Std: # below lower band, go long stkInfo_object.position = 1 client_packet = Packet() OrderIndex += 1 client_order_id = client_config.client_id + '_' + str(OrderIndex) stkInfo_object.Qty = int(Notional / current_sell) enter_a_new_order(client_packet, client_order_id, stk, 'Mkt', 'Buy', 100, stkInfo_object.Qty) print("Open Trade in: ", stk, "With postion: Buy", "at Price:", current_sell, "With Qty:", stkInfo_object.Qty) print("Because: Price below lower band:", usd(MA - K1 * Std)) set_event(e) send_msg(client_packet) wait_for_an_event(e) # open logic response_list = [] while not q.empty(): response_data = get_response(q) response_list.append(response_data) client_config.orders.append(response_data) # Trade_object = Trade(stk, response_list) # stkInfo_object.Tradelist.append(Trade_object) elif current_buy >= MA + K1 * Std: # above upper band, go short stkInfo_object.position = -1 client_packet = Packet() OrderIndex += 1 client_order_id = client_config.client_id + '_' + str(OrderIndex) stkInfo_object.Qty = int(Notional / current_buy) enter_a_new_order(client_packet, client_order_id, stk, 'Mkt', 'Sell', 100, stkInfo_object.Qty) print("Open Trade in: ",
<reponame>joaomcm/Klampt """Klampt kinematics AD functions: ==================== ============= ====================================== Function Derivative Notes ==================== ============= ====================================== WorldPosition 1,2 wp[link,localPos](q) -> R^3 WorldDirection 1,2 wd[link,localDir](q) -> R^3 WorldOrientation 1,2 wo[link](q) -> SO(3) WorldTransform 1,2 wt[link,*localPos](q) -> SE(3) WorldVelocity 1 wv[link,localPos](q,dq) -> R^3 WorldAngularVelocity 1 ww[link](q,dq) -> R^3 #LocalPosition 1 lp[link,worldPos](q) -> R^3 #LocalDirection 1 ld[link,worldDir](q) -> R^3 #LocalOrientation 1 lo[link](q) -> SO(3) DriversToLinks Y d2l[robot](qdriver) -> R^numLinks() DriverDerivsToLinks Y d2l'[robot](vdriver) -> R^numLinks() LinksToDrivers Y l2d[robot](q) -> R^numDrivers() LinkDerivsToDrivers Y l2d'[robot](vdriver) -> R^numLinks() ConfigInterpolate N qinterp[robot](a,b,u) -> R^n ==================== ============= ====================================== Note that each call to WorldX or LocalX will recompute the forward kinematics of the robot, which can be rather expensive if many of these will be called. Also, see the :class:`KinematicsBuilder` class which creates the computational graph for a robot's forward kinematics, which allows you to reuse subexpressions for multiple forward kinematics calls. """ import numpy as np from .ad import ADFunctionInterface,ADFunctionCall,ADTerminal,sum_ from . import math_ad,so3_ad,se3_ad from .. import vectorops,so3,se3 from ...robotsim import RobotModel,RobotModelLink class WorldPosition(ADFunctionInterface): """Autodiff wrapper of the link.getWorldPosition() function as a function of robot configuration q. """ def __init__(self,link,localPos): self.robot = link.robot() self.link = link self.localPos = localPos def __str__(self): return "kinematics.WorldPosition[%s,%s]"%(self.link.getName(),str(self.localPos)) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 3 def eval(self,q): self.robot.setConfig(q.tolist()) return np.array(self.link.getWorldPosition(self.localPos)) def derivative(self,arg,q): assert arg == 0 self.robot.setConfig(q.tolist()) return np.array(self.link.getPositionJacobian(self.localPos)) def gen_derivative(self,arg,q): if len(arg) == 1: return self.derivative(arg,q) elif len(arg) == 2: self.robot.setConfig(q.tolist()) Hx,Hy,Hz = self.link.getPositionHessian(self.localPos) return np.array([Hx,Hy,Hz]) else: raise NotImplementedError() class WorldDirection(ADFunctionInterface): """Autodiff wrapper of the link.getWorldDirection() function as a function of robot configuration q. """ def __init__(self,link,localDir): self.robot = link.robot() self.link = link self.localDir = localDir def __str__(self): return "kinematics.WorldDirection[%s,%s]"%(self.link.getName(),str(self.localDir)) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 3 def eval(self,q): self.robot.setConfig(q.tolist()) return np.array(self.link.getWorldDirection(self.localDir)) def derivative(self,arg,q): assert arg == 0 self.robot.setConfig(q.tolist()) Jo = self.link.getOrientationJacobian() for i in range(3): Jo[i] = np.array(Jo[i]) return np.array(vectorops.cross(Jo,self.localDir)) def gen_derivative(self,arg,q): if len(arg) == 1: return self.derivative(arg[0],q) elif len(arg) == 2: self.robot.setConfig(q.tolist()) Hx,Hy,Hz = self.link.getOrientationHessian() Hx = np.array(Hx) Hy = np.array(Hy) Hz = np.array(Hz) return np.array(vectorops.cross([Hx,Hy,Hz],self.localDir)) else: raise NotImplementedError() class WorldOrientation(ADFunctionInterface): """Autodiff wrapper of the link.getTransform()[0] function as a function of robot configuration q. """ def __init__(self,link): self.robot = link.robot() self.link = link def __str__(self): return "kinematics.WorldOrientation[%s]"%(self.link.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 9 def eval(self,q): self.robot.setConfig(q.tolist()) return np.array(self.link.getTransform()[0]) def derivative(self,arg,q): assert arg == 0 self.robot.setConfig(q.tolist()) Jo = self.link.getOrientationJacobian() return _cross_product_twiddle(Jo) def gen_derivative(self,arg,q): if len(arg) == 1: return self.derivative(arg[0],q) elif len(arg) == 2: self.robot.setConfig(q.tolist()) Hx,Hy,Hz = self.link.getOrientationHessian() return _cross_product_twiddle([Hx,Hy,Hz]) else: raise NotImplementedError() class WorldTransform(ADFunctionInterface): """Autodiff wrapper of the link.getTransform() function as a function of robot configuration q. """ def __init__(self,link,localPos=None): self.robot = link.robot() self.link = link self.localPos = localPos def __str__(self): if self.localPos is not None: return "kinematics.WorldTransform[%s,%s]"%(self.link.getName(),self.localPos) return "kinematics.WorldTransform[%s]"%(self.link.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 12 def eval(self,q): self.robot.setConfig(q.tolist()) T = self.link.getTransform() if self.localPos is not None: T = (T[0],vectorops.add(so3.apply(T[0],self.localPos),T[1])) return np.array(T[0]+T[1]) def derivative(self,arg,q): assert arg == 0 self.robot.setConfig(q.tolist()) J = self.link.getJacobian([0]*3 if self.localPos is None else self.localPos) return np.vstack([_cross_product_twiddle(J[:3])]+[J[3:]]) def gen_derivative(self,arg,q): if len(arg) == 1: return self.derivative(arg[0],q) elif len(arg) == 2: self.robot.setConfig(q.tolist()) Hx,Hy,Hz = self.link.getPositionHessian([0]*3 if self.localPos is None else self.localPos) Hox,Hoy,Hoz = self.link.getOrientationHessian() Hox = np.array(Hox) Hoy = np.array(Hoy) Hoz = np.array(Hoz) return np.vstack([_cross_product_twiddle([Hox,Hoy,Hoz])]+[[Hx,Hy,Hz]]) else: raise NotImplementedError() class WorldVelocity(ADFunctionInterface): """Autodiff wrapper of the link.getPointVelocity() function as a function of robot configuration q and velocity dq. """ def __init__(self,link,localPos): self.robot = link.robot() self.link = link self.localPos = localPos def __str__(self): return "kinematics.WorldVelocity[%s,%s]"%(self.link.getName(),str(self.localPos)) def n_args(self): return 2 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 3 def eval(self,q,dq): self.robot.setConfig(q.tolist()) self.robot.setVelocity(dq.tolist()) return np.array(self.link.getPointVelocity(self.localPos)) def derivative(self,arg,q,dq): if arg == 1: self.robot.setConfig(q.tolist()) return np.array(self.link.getPositionJacobian(self.localPos)) else: self.robot.setVelocity(dq.tolist()) Hx,Hy,Hz = self.link.getPositionHessian(self.localPos) return np.row_stack([np.dot(Hx,dq),np.dot(Hy,dq),np.dot(Hz,dq)]) class WorldAngularVelocity(ADFunctionInterface): """Autodiff wrapper of the link.getAngularVelocity() function, as a function of robotconfiguration q and velocity dq. """ def __init__(self,link): self.robot = link.robot() self.link = link def __str__(self): return "kinematics.WorldAngularVelocity[%s]"%(self.link.getName(),) def n_args(self): return 2 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return 3 def eval(self,q,dq): self.robot.setConfig(q.tolist()) self.robot.setVelocity(dq.tolist()) return np.array(self.link.getAngularVelocity()) def derivative(self,arg,q,dq): if arg == 1: self.robot.setConfig(q.tolist()) return np.array(self.link.getOrientationJacobian()) else: self.robot.setVelocity(dq.tolist()) Hx,Hy,Hz = self.link.getOrientationHessian() return np.row_stack([np.dot(Hx,dq),np.dot(Hy,dq),np.dot(Hz,dq)]) class DriversToLinks(ADFunctionInterface): """Autodiff function to convert driver values to link values.""" def __init__(self,robot): self.robot = robot self.drivers = [robot.driver(i) for i in robot.numDrivers()] def __str__(self): return "kinematics.DriversToLinks[%s]"%(self.robot.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numDrivers() def n_out(self): return self.robot.numLinks() def eval(self,qdriver): for driver,q in zip(self.drivers,qdriver): driver.setValue(q) return np.array(self.robot.getConfig()) def jvp(self,arg,dqdriver,qdriver): for driver,q,v in zip(self.drivers,qdriver,dqdriver): driver.setValue(q) driver.setVelocity(v) return np.array(self.robot.getVelocity()) class DriverDerivsToLinks(ADFunctionInterface): """Autodiff function to convert driver velocities to link velocities.""" def __init__(self,robot): self.robot = robot self.drivers = [robot.driver(i) for i in robot.numDrivers()] def __str__(self): return "kinematics.DriverDerivsToLinks[%s]"%(self.robot.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numDrivers() def n_out(self): return self.robot.numLinks() def eval(self,vdriver): for driver,v in zip(self.drivers,vdriver): driver.setVelocity(v) return np.array(self.robot.getConfig()) def jvp(self,arg,dvdriver,vdriver): for driver,q,v in zip(self.drivers,vdriver,dvdriver): driver.setVelocity(v) return np.array(self.robot.getVelocity()) class LinksToDrivers(ADFunctionInterface): """Autodiff function to convert link values to driver values.""" def __init__(self,robot): self.robot = robot self.drivers = [robot.driver(i) for i in robot.numDrivers()] def __str__(self): return "kinematics.LinksToDrivers[%s]"%(self.robot.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return self.robot.numDrivers() def eval(self,q): self.robot.setConfig(q) return np.array([driver.getValue() for driver in self.drivers]) def jvp(self,arg,dq,q): self.robot.setConfig(q) self.robot.setVelocity(dq) return np.array([driver.getVelocity() for driver in self.drivers]) class LinkDerivsToDrivers(ADFunctionInterface): """Autodiff function to convert link velocities to driver velocities.""" def __init__(self,robot): self.robot = robot self.drivers = [robot.driver(i) for i in robot.numDrivers()] def __str__(self): return "kinematics.LinkDerivsToDrivers[%s]"%(self.robot.getName(),) def n_args(self): return 1 def n_in(self,arg): return self.robot.numLinks() def n_out(self): return self.robot.numDrivers() def eval(self,v): self.robot.setVelocity(v) return np.array([driver.getVelocity() for driver in self.drivers]) def jvp(self,arg,dv,v): self.robot.setVelocity(dv) return np.array([driver.getVelocity() for driver in self.drivers]) class ConfigInterpolate(ADFunctionInterface): """Autodiff wrapper of the RobotModel.interpolate function""" def __init__(self,robot): self.robot = robot def __str__(self): return "kinematics.ConfigInterpolate[%s]"%(self.robot.getName(),) def n_args(self): return 3 def n_in(self,arg): if arg <= 1: return self.robot.numLinks() return 1 def n_out(self): return self.robot.numLinks() def eval(self,a,b,u): return np.array(self.robot.interpolate(a,b,u)) def _cross_product_twiddle(J): """Does the same thing as so3.cross_product, but with a matrix""" assert len(J) == 3 n = len(J[0]) J = [np.asarray(row) for row in J] res = np.empty((9,)+J[0].shape,dtype=float) res[0,:] = 0 res[1,:] = J[2] res[2,:] = -J[1] res[3,:] = -J[2] res[4,:] = 0 res[5,:] = J[0] res[6,:] = J[1] res[7,:] = -J[0] res[8,:] = 0 return res class KinematicsBuilder: """A class that computes the entire computation graph of forward kinematics and caches it so that multiple queries are auto-diffable and share the same intermediate computations. Args: robot (RobotModel): the robot configuration (array, AD expression, or list of expressions, optional): the robot's configuration, either as a fixed configuration or a variable. By default, this is fixed at the robot's configuration. velocity (array, AD expression, or list of expressions, optional): if given, the X_velocity methods are available. This gives the robot's velocity, either as a fixed vector or a variable. By default, no velocity expression tree is created. relative_transform (array or list of AD so3 expressions, optional): if given, the relative transforms of the robot's links. By default these are taken from the robot model. axes (array or list of AD R^3 expressions, optional): if given, the axes relative transforms of the robot's links. By default these are taken from the robot model. Example:: kb = KinematicsBuilder(robot,'q','dq') print(kb.world_position(robot.numLinks()-1)) print(kb.world_velocity(robot.numLinks()-1)) """ def __init__(self,robot,configuration='fixed',velocity=None,relative_transforms='fixed',axes='fixed'): if configuration == 'fixed': configuration = robot.getConfig() else: if isinstance(configuration,str): configuration = ADTerminal(configuration) if not isinstance(configuration,ADTerminal) and not isinstance(configuration,ADFunctionCall): assert len(configuration) == robot.numLinks() if relative_transforms == 'fixed': relative_transforms = [] for i in range(robot.numLinks()): T = robot.link(i).getParentTransform() relative_transforms.append(np.array(T[0] + T[1])) else: assert len(relative_transforms) == robot.numLinks() if axes == 'fixed': axes = [np.array(robot.link(i).getAxis()) for i in range(robot.numLinks())] else: assert len(axes) == robot.numLinks() self.robot = robot self.axes = axes self.link_transforms = [] self.link_rotations = [] self.link_positions = [] self.link_inv_transforms = [] self.link_inv_rotations = [] for i in range(robot.numLinks()): link = robot.link(i) p = link.getParent() q = configuration[i] axis = axes[i] Trel = relative_transforms[i] if link.isPrismatic(): link_t = Trel[9:] + q*axis link_R = Trel[:9] else: link_t = Trel[9:] Rq = so3_ad.from_axis_angle(axis,q) link_R = so3_ad.mul(Trel[:9],Rq) assert p < i if p < 0: self.link_positions.append(link_t) self.link_rotations.append(link_R) self.link_transforms.append(se3_ad.join(self.link_rotations[-1],self.link_positions[-1])) else: self.link_positions.append(se3_ad.apply(self.link_transforms[p],link_t)) self.link_rotations.append(so3_ad.mul(self.link_rotations[p],link_R)) self.link_transforms.append(se3_ad.mul(self.link_transforms[p],se3_ad.join(link_R,link_t))) self.link_inv_transforms.append(se3_ad.inv(self.link_transforms[-1])) self.link_inv_rotations.append(so3_ad.inv(self.link_rotations[-1]))
#!/usr/bin/python import math import sys import os import re import subprocess import numpy as np import pandas as pd import argparse import operator import mxnet as mx import struct import cv2 from collections import namedtuple import scipy.io import matplotlib.pyplot as plt import matplotlib as mpl import pylab import textwrap def parse_args(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\ Dump featuremaps at a given layer, side-by-side with input image Example usage: ~/investigation_tools/colorspace/dump_featuremaps.py --image_dir_root /home/data/images/Colorspace/imagenet/png/val --image_list_file /home/data/images/Colorspace/imagenet/db/ColorSpace_val_short.lst --checkpoint_path ~/exps/resnet34/checkpoint --epoch 22 --layer_name _plus2_output ''')) parser.add_argument('--image_dir_root', metavar = '<String>', help = "A directory with subdirs '601' and '709'", required = True, type = str) parser.add_argument('--image_list_file', metavar = '<String>', help = "Image list file, like those used to build RecordIO databases", required = True, type = str) parser.add_argument('--checkpoint_path', metavar = '<String>', help = "Path of scheckpoint folder", required = True, type = str) parser.add_argument('--epoch', metavar = '<Number>', help = "epoch number to be listed", required = True, type = int) parser.add_argument('--layer_name', metavar = '<String>', help = "Name of the layer to dump, e.g. _plus12_output", required = True, type = str) args = parser.parse_args() return args def load_image(input_filename, color=3): if color == 3: img = mx.image.imread(input_filename) else: img = mx.image.imread(input_filename, flag=0) img = img.transpose((2,0,1)) img = img.expand_dims(axis=0) img = img.asnumpy() img = mx.nd.array(img) #coolimg = coolimg.asnumpy() #newcoolimg = coolimg #newcoolimg[:,:,0] = coolimg[:,:,0] #newcoolimg[:,:,1] = coolimg[:,:,2] #newcoolimg[:,:,2] = coolimg[:,:,0] #coolimgconv = cv2.cvtColor(newcoolimg, cv2.COLOR_YCR_CB2RGB) #cv2.imwrite("heresyuvimage.png", newcoolimg) #cv2.imwrite("givemeimage.png", coolimgconv) return img args = parse_args() # Dump the activations at the output of a given layer # Could use this to dump a fully connected layer (one-dimensional vector) # and use for exploring clustering. checkpoint_dir = args.checkpoint_path + "/checkpoint" checkpoint_num = args.epoch image_dir_root = args.image_dir_root image_list_file = args.image_list_file layer_name = args.layer_name fd = open( image_list_file, "r" ) Batch = namedtuple('Batch', ['data']) sym, arg_params, aux_params = mx.model.load_checkpoint(checkpoint_dir, checkpoint_num) #for key in arg_params: # print(key) wgts = arg_params['fc1_weight'] print("WEIGHTS SHAPE: {}".format(wgts.shape)) wgts_shape = wgts.shape #print("WEIGHTS: {}".format(wgts)) sd = open("fcweights.txt","w") best601 = np.zeros(10) position601 = np.zeros(10) best709 = np.zeros(10) position709 = np.zeros(10) wgts = wgts.asnumpy() counts = 0 fd = open( image_list_file, "r" ) all_layers = sym.get_internals() outs = all_layers.list_outputs() outs.sort() #for elt in outs: #print( elt ) # Symbol e.g. _plus8 sym = all_layers[layer_name] # Create module by given symbol mod = mx.mod.Module(symbol = sym, label_names = None, context=mx.gpu()) mod.bind(for_training=False, data_shapes=[('data', (1,3,256,256))]) mod.set_params(arg_params, aux_params) # pattern must be changed to fit image names #0 0.000000 601/ILSVRC2012_val_00000002-601.png #26 0.000000 601/suzie00027-601-scaled.png pattern = "([0-9]+)\s+([0-9\.]+)\s+([67]0[19])(/.*\-)([67]0[19])(.*)(\.png|\.bmp)" #0 0.000000 601/n01440764_10183-601.png # Bike_Ride00007-601.bmp #pattern = "(.*\.)(png|bmp)" #fd_out = open( "_plus12_output.csv", "w" ) gain = 1 count = 0 # Create dictionaries for each class, m based on pattern arrangement # In our case, our classes are for Rec. 601 and Rec. 709 dict601 = {} dict709 = {} while 1: line = fd.readline() if line == "": break m = re.search( pattern, line ) if (m): item_num = int(m.group(1)) classval = float(m.group(2)) coldir = m.group(3) guts = m.group(4) colspace = m.group(5) jazz = m.group(6) ext = m.group(7) #guts = m.group(1) #ext = m.group(2) #print( item_num, classval, colspace, ext ) img_name = image_dir_root+"/"+coldir+guts+colspace+jazz+ext #print(colspace) #print(guts) #print(bgr_img.shape) #img_name = image_dir_root+"/"+guts+ext #print(img_name) if (classval < 1): dict601[guts] = img_name else: dict709[guts] = img_name #activations = np.array([]) #max_act = np.array([]) for the_key in sorted(dict601): for colspace in ( "601", "709" ): if colspace == "601": print(colspace) print(the_key) if the_key in dict601: img_name = dict601[the_key] elif colspace == "709": print(colspace) print(the_key) if the_key in dict709: img_name = dict709[the_key] img = load_image(img_name) #print ("Loaded " + img_name) yuv_img = cv2.imread(img_name) rgb_img = cv2.cvtColor(yuv_img, cv2.COLOR_YCR_CB2RGB) img_shape = img.shape img_hgt = img_shape[2] img_wid = img_shape[3] mod.forward(Batch([mx.nd.array(img)])) out = mod.get_outputs()[0] out = out.asnumpy() out_shape = out.shape #sys.stderr.write("out.shape=") #sys.stderr.write(str(out_shape) + "\n") ##print(out_shape) # out.shape is (1, 256, 16, 16) num_maps = out_shape[1] hgt = out_shape[2] wid = out_shape[3] tile_cols = int(math.ceil(math.sqrt(num_maps))) tile_rows = int(math.ceil(float(num_maps)/tile_cols)) padded_hgt = hgt + 2 padded_wid = wid + 2 border_color = 192 #print( tile_rows, padded_hgt, tile_cols, padded_wid ) alloc_hgt = max(img_hgt, tile_rows * padded_hgt) alloc_wid = img_hgt + tile_cols * padded_wid montage = np.zeros((alloc_hgt, alloc_wid)) montage = montage.astype(np.uint8) img_lum = img[0,2,:,:] img_lum = img_lum.asnumpy() montage[0:img_hgt, (tile_cols * padded_wid):alloc_wid] = img_lum; feature_count = 0 res = cv2.resize(rgb_img,(64,64)) print('out: {}'.format(count)) # Create and print montage of feature maps for each image at selected layer if (count == 0): ftrstore = np.zeros((tile_rows,tile_cols,9,hgt,wid)) imgstore = np.zeros((tile_rows,tile_cols,9,64,64,3)) cv2.imwrite("firstimg.png", res) #print(res.shape) #print(hgt) #print(wid) for tile_row in range(tile_rows): for tile_col in range(tile_cols): # Write borders for col_off in range (padded_wid): montage[tile_row * padded_hgt, tile_col * padded_wid + col_off] = border_color montage[(tile_row+1) * padded_hgt - 1, tile_col * padded_wid + col_off] = border_color for row_off in range (padded_hgt): montage[tile_row * padded_hgt + row_off, tile_col * padded_wid] = border_color montage[tile_row * padded_hgt + row_off, (tile_col+1) * padded_wid - 1] = border_color tile_idx = tile_row * tile_cols + tile_col if tile_idx < num_maps: tile = np.around(gain * np.squeeze(out[0,tile_idx,:,:]) ) tile = np.clip( tile, 0, 255 ) tile = tile.astype(np.uint8) ##activations = np.append(activations,np.amax(np.squeeze(out[0,tile_idx,:,:]))) if (tile_row == 0) and (tile_col == 2): print(np.amax(np.squeeze(out[0,tile_idx,:,:]))) #print('feature: {}\tactivations: {}'.formatftrstore(feature_count,np.sum(tile))) feature_count += 1 #print("out: {}\tfeature map: {}\tactivations: {}".format(pic_count,feature_count,np.sum(tile))) #print( tile.shape ) montage[tile_row * padded_hgt + 1:tile_row * padded_hgt + 1 + hgt, tile_col * padded_wid + 1:tile_col * padded_wid + 1 + wid] = tile tile_shape = tile.shape pixelcount = 0 #for row in range(tile_shape[0]): # for col in range(tile_shape[1]): # if tile[row][col] > 0: # pixelcount += 1 img_vals = np.array([]) for i in range(0,9): #print('ROWS: {}'.format(tile_row)) #print('COLUMNS: {}'.format(tile_col)) #print(ftrstore.shape) img_vals = np.append(img_vals,np.amax(ftrstore[tile_row][tile_col][i])) if (tile_row == 0) and (tile_col == 2): print('TOP NINE:') print(img_vals) print('MINIMUM: {} VS TILE: {}'.format(np.amax(ftrstore[tile_row][tile_col][np.argmin(img_vals)]),np.amax(np.squeeze(out[0,tile_idx,:,:])))) if (np.amin(img_vals) < np.amax(np.squeeze(out[0,tile_idx,:,:]))): ftrstore[tile_row][tile_col][np.argmin(img_vals)] = np.squeeze(out[0,tile_idx,:,:]) imgstore[tile_row][tile_col][np.argmin(img_vals)] = res # Sort new vals placements = np.argsort(-img_vals) placeholder_ftr = np.zeros((9,hgt,wid)) placeholder_img = np.zeros((9,64,64,3)) placecount = 0 for key in placements: placeholder_ftr[placecount] = ftrstore[tile_row][tile_col][key] placeholder_img[placecount] = imgstore[tile_row][tile_col][key] placecount += 1 ftrstore[tile_row][tile_col] = placeholder_ftr imgstore[tile_row][tile_col] = placeholder_img if (tile_row == 0) and (tile_col == 2): print(placements) print(img_vals) #plt.imshow(montage, cmap='gray') #plt.show() cv2.imwrite("out_%04d.png" % count, montage) #for i in range(out.shape[1]): # fd_out.write( "%12.9f," % out[0,i] ) #fd_out.write("\n") count = count + 1 sys.stderr.write(".") ##activations.shape = (count,feature_count) #for feature in range(feature_count): # print('Feature Map: {}'.format(feature)) # perf = np.array([]) # for out in range(count): #print('count: {} feature: {}'.format(out,feature)) #perf = np.append(perf,activations[out][feature]) #for img in range(0,9): # top = np.argmax(perf) # max_act = np.append(max_act,top) # print('Best Out: {}\tActivations: {}'.format(top,np.amax(perf))) #perf[top] = 0 #print(activations[5]) #max_act.shape = (feature_count,9) #print(max_act[9]) #print(max_act[10]) #print(max_act[11]) # Create and print montage of 16 best images and activations for each feature map feature_shape = ftrstore.shape pic_shape = imgstore.shape num_tiles_rows = feature_shape[0] num_tiles_cols = feature_shape[1] num_maps = feature_shape[2] ftr_hgt = feature_shape[3] ftr_wid = feature_shape[4] num_pics = pic_shape[2] pic_hgt = pic_shape[3] pic_wid = pic_shape[4] padded_ftr_hgt = int(ftr_hgt + (ftr_hgt / 4)) padded_ftr_wid = int(ftr_wid + (ftr_wid / 4)) padded_pic_hgt = int(pic_hgt + (pic_hgt / 4)) padded_pic_wid = int(pic_wid + (pic_wid / 4)) tile_cols = int(math.ceil(math.sqrt(num_maps))) tile_rows = int(math.ceil(float(num_maps)/tile_cols)) border_color = 192 alloc_ftr_hgt = ftr_hgt * 4 alloc_ftr_wid = ftr_wid * 4 alloc_pic_hgt = pic_hgt * 4 alloc_pic_wid = pic_wid * 4 newpad_ftr_hgt = alloc_ftr_hgt + 2 newpad_ftr_wid = alloc_ftr_wid + 2 newpad_pic_hgt = alloc_pic_hgt + 2 newpad_pic_wid = alloc_pic_wid + 2 new_hgt = num_tiles_rows * newpad_ftr_hgt new_wid = num_tiles_cols * newpad_ftr_wid new_pic_hgt = num_tiles_rows * newpad_pic_hgt new_pic_wid = num_tiles_cols * newpad_pic_wid #print(alloc_ftr_hgt) #print(alloc_ftr_wid) #print(montage.shape) #img_lum = img[0,2,:,:] #img_lum = img_lum.asnumpy() #acttage[0:img_hgt, (tile_cols * padded_ftr_wid):alloc_ftr_wid] = img_lum; ftrtage = np.zeros((new_hgt, new_wid)) ftrtage = ftrtage.astype(np.uint8) imgtage = np.zeros((new_pic_hgt, new_pic_wid, 3)) imgtage = imgtage.astype(np.uint8) for num_tile_row in range(num_tiles_rows): for num_tile_col in range(num_tiles_cols): acttage = np.zeros((alloc_ftr_hgt, alloc_ftr_wid)) acttage = acttage.astype(np.uint8) pictage = np.zeros((alloc_pic_hgt, alloc_pic_wid, 3)) pictage = pictage.astype(np.uint8) for tile_row in range(tile_rows): for tile_col in range(tile_cols): # Write borders for col_off in range (padded_ftr_wid): acttage[tile_row * padded_ftr_hgt, tile_col * padded_ftr_wid + col_off] = border_color acttage[(tile_row+1) * padded_ftr_hgt - 1, tile_col * padded_ftr_wid + col_off] = border_color for row_off in range (padded_ftr_hgt): acttage[tile_row * padded_ftr_hgt + row_off, tile_col * padded_ftr_wid] = border_color acttage[tile_row * padded_ftr_hgt + row_off, (tile_col+1) * padded_ftr_wid - 1] = border_color for col_off in range (padded_pic_wid): pictage[tile_row * padded_pic_hgt, tile_col * padded_pic_wid + col_off] = border_color pictage[(tile_row+1) * padded_pic_hgt - 1, tile_col * padded_pic_wid + col_off] = border_color for row_off in range (padded_pic_hgt): pictage[tile_row * padded_pic_hgt + row_off, tile_col * padded_pic_wid] = border_color pictage[tile_row * padded_pic_hgt + row_off, (tile_col+1) * padded_pic_wid - 1] = border_color tile_idx = tile_row * tile_cols + tile_col if tile_idx < num_maps: tile = np.around(gain * np.squeeze(ftrstore[num_tile_row,num_tile_col,tile_idx,:,:])) pic = np.around(gain
annotation_meta=None): image.data = cv2.flip(image.data, self.mode) image.metadata.setdefault( 'geometric_operations', []).append(GeometricOperationMetadata('flip', {'mode': self.mode})) return image class Crop(Preprocessor): __provider__ = 'crop' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'size': NumberField( value_type=int, optional=True, min_value=1, description="Destination size for cropping both dimensions." ), 'dst_width': NumberField( value_type=int, optional=True, min_value=1, description="Destination width for image cropping respectively." ), 'dst_height': NumberField( value_type=int, optional=True, min_value=1, description="Destination height for image cropping respectively." ), 'use_pillow': BoolField( optional=True, default=False, description="Parameter specifies usage of Pillow library for cropping." ), 'central_fraction' : NumberField( value_type=float, min_value=0, max_value=1, optional=True, description="Central Fraction." ) }) return parameters def configure(self): self.use_pillow = self.get_value_from_config('use_pillow') self.dst_height, self.dst_width = get_size_from_config(self.config, allow_none=True) self.central_fraction = self.get_value_from_config('central_fraction') if self.dst_height is None and self.dst_width is None and self.central_fraction is None: raise ConfigError('sizes for crop or central_fraction should be provided') if self.dst_height and self.dst_width and self.central_fraction: raise ConfigError('both sizes and central fraction provided for cropping') if not self.central_fraction: if self.dst_height is None or self.dst_width is None: raise ConfigError('one from crop dimentions is not provided') def process(self, image, annotation_meta=None): is_simple_case = not isinstance(image.data, list) # otherwise -- pyramid, tiling, etc data = image.data def process_data(data, dst_height, dst_width, central_fraction, use_pillow): height, width = data.shape[:2] if not central_fraction: new_height = dst_height new_width = dst_width else: new_height = int(height * central_fraction) new_width = int(width * central_fraction) if use_pillow: i = int(round((height - new_height) / 2.)) j = int(round((width - new_width) / 2.)) cropped_data = Image.fromarray(data).crop((j, i, j + new_width, i + new_height)) return np.array(cropped_data) if width < new_width or height < new_height: resized = np.array([width, height]) if resized[0] < new_width: resized = resized * new_width / resized[0] if resized[1] < new_height: resized = resized * new_height / resized[1] data = cv2.resize(data, tuple(np.ceil(resized).astype(int))) height, width = data.shape[:2] start_height = (height - new_height) // 2 start_width = (width - new_width) // 2 if is_simple_case: # support GeometricOperationMetadata array for simple case only -- without tiling, pyramids, etc image.metadata.setdefault('geometric_operations', []).append(GeometricOperationMetadata('crop', {})) return data[start_height:start_height + new_height, start_width:start_width + new_width] image.data = process_data( data, self.dst_height, self.dst_width, self.central_fraction, self.use_pillow ) if not isinstance(data, list) else [ process_data( fragment, self.dst_height, self.dst_width, self.central_fraction, self.use_pillow ) for fragment in image.data ] return image class CropRect(Preprocessor): __provider__ = 'crop_rect' def process(self, image, annotation_meta=None): rect = annotation_meta.get('rect') if not rect: return image rows, cols = image.data.shape[:2] rect_x_min, rect_y_min, rect_x_max, rect_y_max = rect start_width, start_height = max(0, rect_x_min), max(0, rect_y_min) width = min(start_width + (rect_x_max - rect_x_min), cols) height = min(start_height + (rect_y_max - rect_y_min), rows) image.data = image.data[start_height:height, start_width:width] image.metadata.setdefault('geometric_operations', []).append(GeometricOperationMetadata('crop_rect', {})) return image class ExtendAroundRect(Preprocessor): __provider__ = 'extend_around_rect' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'augmentation_param' : NumberField( value_type=float, optional=True, default=0, description="Scale factor for augmentation." ) }) return parameters def configure(self): self.augmentation_param = self.get_value_from_config('augmentation_param') def process(self, image, annotation_meta=None): rect = annotation_meta.get('rect') rows, cols = image.data.shape[:2] rect_x_left, rect_y_top, rect_x_right, rect_y_bottom = rect or (0, 0, cols, rows) rect_x_left = max(0, rect_x_left) rect_y_top = max(0, rect_y_top) rect_x_right = min(rect_x_right, cols) rect_y_bottom = min(rect_y_bottom, rows) rect_w = rect_x_right - rect_x_left rect_h = rect_y_bottom - rect_y_top width_extent = (rect_x_right - rect_x_left + 1) * self.augmentation_param height_extent = (rect_y_bottom - rect_y_top + 1) * self.augmentation_param rect_x_left = rect_x_left - width_extent border_left = abs(min(0, rect_x_left)) rect_x_left = int(max(0, rect_x_left)) rect_y_top = rect_y_top - height_extent border_top = abs(min(0, rect_y_top)) rect_y_top = int(max(0, rect_y_top)) rect_y_bottom += border_top rect_y_bottom = int(rect_y_bottom + height_extent + 0.5) border_bottom = abs(max(0, rect_y_bottom - rows)) rect_x_right += border_left rect_x_right = int(rect_x_right + width_extent + 0.5) border_right = abs(max(0, rect_x_right - cols)) image.data = cv2.copyMakeBorder( image.data, int(border_top), int(border_bottom), int(border_left), int(border_right), cv2.BORDER_REPLICATE ) rect = ( int(rect_x_left), int(rect_y_top), int(rect_x_left) + int(rect_w + width_extent * 2), int(rect_y_top) + int(rect_h + height_extent * 2) ) annotation_meta['rect'] = rect image.metadata.setdefault('geometric_operations', []).append( GeometricOperationMetadata('extend_around_rect', {}) ) return image class PointAligner(Preprocessor): __provider__ = 'point_alignment' ref_landmarks = np.array([ 30.2946 / 96, 51.6963 / 112, 65.5318 / 96, 51.5014 / 112, 48.0252 / 96, 71.7366 / 112, 33.5493 / 96, 92.3655 / 112, 62.7299 / 96, 92.2041 / 112 ], dtype=np.float64).reshape(5, 2) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'draw_points': BoolField(optional=True, default=False, description="Allows visualize points."), 'normalize': BoolField( optional=True, default=True, description="Allows to use normalization for keypoints."), 'size': NumberField( value_type=int, optional=True, min_value=1, description="Destination size for keypoints resizing for both destination dimentions." ), 'dst_width': NumberField( value_type=int, optional=True, min_value=1, description="Destination width for keypoints resizing." ), 'dst_height': NumberField( value_type=int, optional=True, min_value=1, description="Destination height for keypoints resizing." ), }) return parameters def configure(self): self.draw_points = self.get_value_from_config('draw_points') self.normalize = self.get_value_from_config('normalize') self.dst_height, self.dst_width = get_size_from_config(self.config) def process(self, image, annotation_meta=None): keypoints = annotation_meta.get('keypoints') image.data = self.align(image.data, keypoints) image.metadata.setdefault('geometric_operations', []).append(GeometricOperationMetadata('point_alignment', {})) return image def align(self, img, points): if not points: return img points_number = len(points) // 2 points = np.array(points).reshape(points_number, 2) inp_shape = [1., 1.] if self.normalize: inp_shape = img.shape keypoints = points.copy().astype(np.float64) keypoints[:, 0] *= (float(self.dst_width) / inp_shape[1]) keypoints[:, 1] *= (float(self.dst_height) / inp_shape[0]) keypoints_ref = np.zeros((points_number, 2), dtype=np.float64) keypoints_ref[:, 0] = self.ref_landmarks[:, 0] * self.dst_width keypoints_ref[:, 1] = self.ref_landmarks[:, 1] * self.dst_height transformation_matrix = self.transformation_from_points(np.array(keypoints_ref), np.array(keypoints)) img = cv2.resize(img, (self.dst_width, self.dst_height)) if self.draw_points: for point in keypoints: cv2.circle(img, (int(point[0]), int(point[1])), 5, (255, 0, 0), -1) return cv2.warpAffine(img, transformation_matrix, (self.dst_width, self.dst_height), flags=cv2.WARP_INVERSE_MAP) @staticmethod def transformation_from_points(points1, points2): points1 = np.matrix(points1.astype(np.float64)) points2 = np.matrix(points2.astype(np.float64)) c1 = np.mean(points1, axis=0) c2 = np.mean(points2, axis=0) points1 -= c1 points2 -= c2 s1 = np.std(points1) s2 = np.std(points2) points1 /= np.maximum(s1, np.finfo(np.float64).eps) points2 /= np.maximum(s1, np.finfo(np.float64).eps) points_std_ratio = s2 / np.maximum(s1, np.finfo(np.float64).eps) u, _, vt = np.linalg.svd(points1.T * points2) r = (u * vt).T return np.hstack((points_std_ratio * r, c2.T - points_std_ratio * r * c1.T)) def center_padding(dst_width, dst_height, width, height): pad = [int(math.floor((dst_height - height) / 2.0)), int(math.floor((dst_width - width) / 2.0))] pad.extend([dst_height - height - pad[0], dst_width - width - pad[1]]) return pad def right_bottom_padding(dst_width, dst_height, width, height): return [0, 0, dst_height - height, dst_width - width] def left_top_padding(dst_width, dst_height, width, height): return [dst_height - height, dst_width - width, 0, 0] padding_func = { 'center': center_padding, 'left_top': left_top_padding, 'right_bottom': right_bottom_padding } class Padding(Preprocessor): __provider__ = 'padding' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'stride': NumberField( value_type=int, min_value=1, optional=True, default=1, description="Stride for padding." ), 'pad_value': StringField( optional=True, default='0,0,0', description="Value for filling space around original image." ), 'size': NumberField( value_type=int, optional=True, min_value=1, description="Destination size for padded image for both dimensions."), 'dst_width': NumberField( value_type=int, optional=True, min_value=1, description="Destination width for padded image." ), 'dst_height': NumberField( value_type=int, optional=True, min_value=1, description="Destination height for padded image." ), 'pad_type': StringField( choices=padding_func.keys(), optional=True, default='center', description="Padding space location. Supported: {}".format(', '.join(padding_func)) ), 'use_numpy': BoolField( optional=True, default=False, description="Allow to use numpy for padding instead default OpenCV." ) }) return parameters def configure(self): self.stride = self.get_value_from_config('stride') pad_val = self.get_value_from_config('pad_value') if isinstance(pad_val, int): self.pad_value = (pad_val, pad_val, pad_val) if isinstance(pad_val, str): self.pad_value = string_to_tuple(pad_val, int) self.dst_height, self.dst_width = get_size_from_config(self.config, allow_none=True) self.pad_func = padding_func[self.get_value_from_config('pad_type')] self.use_numpy = self.get_value_from_config('use_numpy') def process(self, image, annotation_meta=None): height, width, _ = image.data.shape pref_height = self.dst_height or image.metadata.get('preferable_height', height) pref_width = self.dst_width or image.metadata.get('preferable_width', width) height = min(height, pref_height) pref_height = math.ceil(pref_height / float(self.stride)) * self.stride pref_width = max(pref_width, width) pref_width = math.ceil(pref_width / float(self.stride)) * self.stride pad = self.pad_func(pref_width, pref_height, width, height) image.metadata['padding'] = pad padding_realization_func = self._opencv_padding if not self.use_numpy else self._numpy_padding image.data = padding_realization_func(image.data, pad) image.metadata.setdefault('geometric_operations', []).append( GeometricOperationMetadata('padding', { 'pad': pad, 'dst_width': self.dst_width, 'dst_height': self.dst_height, 'pref_width': pref_width, 'pref_height': pref_height, 'width': width, 'height': height })) return image def _opencv_padding(self, image, pad): return cv2.copyMakeBorder( image, pad[0], pad[2], pad[1], pad[3], cv2.BORDER_CONSTANT, value=self.pad_value ) def _numpy_padding(self, image, pad): pad_values = ( (self.pad_value[0], self.pad_value[0]), (self.pad_value[1], self.pad_value[1]), (self.pad_value[2], self.pad_value[2]) ) return np.pad( image, ((pad[0], pad[2]), (pad[1], pad[3]), (0, 0)), mode='constant', constant_values=pad_values ) class Tiling(Preprocessor): __provider__ = 'tiling' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'margin': NumberField(value_type=int, min_value=1, description="Margin for tiled fragment of image."), 'size': NumberField( value_type=int, optional=True, min_value=1, description="Destination size of tiled fragment for both dimentions." ), 'dst_width' : NumberField( value_type=int, optional=True, min_value=1, description="Destination width of tiled fragment." ), 'dst_height' : NumberField( value_type=int, optional=True, min_value=1, description="Destination height of tiled fragment." ), }) return parameters def configure(self): self.dst_height, self.dst_width = get_size_from_config(self.config) self.margin = self.get_value_from_config('margin') def process(self, image, annotation_meta=None): data = image.data image_size = data.shape output_height = self.dst_height
<filename>pybluez/macos/_obexcommon.py # Copyright (c) 2009 <NAME>. All rights reserved. # # This file is part of LightBlue. # # LightBlue 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. # # LightBlue 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 LightBlue. If not, see <http://www.gnu.org/licenses/>. from . import _lightbluecommon __all__ = ('OBEXResponse', 'OBEXError', 'CONTINUE', 'OK', 'CREATED', 'ACCEPTED', 'NON_AUTHORITATIVE_INFORMATION', 'NO_CONTENT', 'RESET_CONTENT', 'PARTIAL_CONTENT', 'MULTIPLE_CHOICES', 'MOVED_PERMANENTLY', 'MOVED_TEMPORARILY', 'SEE_OTHER', 'NOT_MODIFIED', 'USE_PROXY', 'BAD_REQUEST', 'UNAUTHORIZED', 'PAYMENT_REQUIRED', 'FORBIDDEN', 'NOT_FOUND', 'METHOD_NOT_ALLOWED', 'NOT_ACCEPTABLE', 'PROXY_AUTHENTICATION_REQUIRED', 'REQUEST_TIME_OUT', 'CONFLICT', 'GONE', 'LENGTH_REQUIRED', 'PRECONDITION_FAILED', 'REQUESTED_ENTITY_TOO_LARGE', 'REQUEST_URL_TOO_LARGE', 'UNSUPPORTED_MEDIA_TYPE', 'INTERNAL_SERVER_ERROR', 'NOT_IMPLEMENTED', 'BAD_GATEWAY', 'SERVICE_UNAVAILABLE', 'GATEWAY_TIMEOUT', 'HTTP_VERSION_NOT_SUPPORTED', 'DATABASE_FULL', 'DATABASE_LOCKED') class OBEXError(_lightbluecommon.BluetoothError): """ Generic exception raised for OBEX-related errors. """ pass class OBEXResponse: """ Contains the OBEX response received from an OBEX server. When an OBEX client sends a request, the OBEX server sends back a response code (to indicate whether the request was successful) and a set of response headers (to provide other useful information). For example, if a client sends a 'Get' request to retrieve a file, the client might get a response like this: >>> import lightblue >>> client = lightblue.obex.OBEXClient("aa:bb:cc:dd:ee:ff", 10) >>> response = client.get({"name": "file.txt"}, file("file.txt", "w")) >>> print response <OBEXResponse reason='OK' code=0x20 (0xa0) headers={'length': 35288}> You can get the response code and response headers in different formats: >>> print response.reason 'OK' # a string description of the response code >>> print response.code 32 # the response code (e.g. this is 0x20) >>> print response.headers {'length': 35288} # the headers, with string keys >>> print response.rawheaders {195: 35288} # the headers, with raw header ID keys >>> Note how the 'code' attribute does not have the final bit set - e.g. for OK/Success, the response code is 0x20, not 0xA0. The lightblue.obex module defines constants for response code values (e.g. lightblue.obex.OK, lightblue.obex.FORBIDDEN, etc.). """ def __init__(self, code, rawheaders): self.__code = code self.__reason = _OBEX_RESPONSES.get(code, "Unknown response code") self.__rawheaders = rawheaders self.__headers = None code = property(lambda self: self.__code, doc='The response code, without the final bit set.') reason = property(lambda self: self.__reason, doc='A string description of the response code.') rawheaders = property(lambda self: self.__rawheaders, doc='The response headers, as a dictionary with header ID (unsigned byte) keys.') def getheader(self, header, default=None): ''' Returns the response header value for the given header, which may either be a string (not case-sensitive) or the raw byte value of the header ID. Returns the specified default value if the header is not present. ''' if isinstance(header, str): return self.headers.get(header.lower(), default) return self.__rawheaders.get(header, default) def __getheaders(self): if self.__headers is None: self.__headers = {} for headerid, value in list(self.__rawheaders.items()): if headerid in _HEADER_IDS_TO_STRINGS: self.__headers[_HEADER_IDS_TO_STRINGS[headerid]] = value else: self.__headers["0x%02x" % headerid] = value return self.__headers headers = property(__getheaders, doc='The response headers, as a dictionary with string keys.') def __repr__(self): return "<OBEXResponse reason='%s' code=0x%02x (0x%02x) headers=%s>" % \ (self.__reason, self.__code, (self.__code | 0x80), str(self.headers)) try: import datetime # as from python docs example class UTC(datetime.tzinfo): """UTC""" def utcoffset(self, dt): return datetime.timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return datetime.timedelta(0) except: pass # no datetime on pys60 _LOCAL_TIME_FORMAT = "%Y%m%dT%H%M%S" _UTC_TIME_FORMAT = _LOCAL_TIME_FORMAT + "Z" def _datetimefromstring(s): import time if s[-1:] == "Z": # add UTC() instance as tzinfo args = (time.strptime(s, _UTC_TIME_FORMAT)[0:6]) + (0, UTC()) return datetime.datetime(*args) else: return datetime.datetime(*(time.strptime(s, _LOCAL_TIME_FORMAT)[0:6])) _HEADER_STRINGS_TO_IDS = { "count": 0xc0, "name": 0x01, "type": 0x42, "length": 0xc3, "time": 0x44, "description": 0x05, "target": 0x46, "http": 0x47, "who": 0x4a, "connection-id": 0xcb, "application-parameters": 0x4c, "authentication-challenge": 0x4d, "authentication-response": 0x4e, "creator-id": 0xcf, "wan-uuid": 0x50, "object-class": 0x51, "session-parameters": 0x52, "session-sequence-number": 0x93 } _HEADER_IDS_TO_STRINGS = {} for key, value in list(_HEADER_STRINGS_TO_IDS.items()): _HEADER_IDS_TO_STRINGS[value] = key assert len(_HEADER_IDS_TO_STRINGS) == len(_HEADER_STRINGS_TO_IDS) # These match the associated strings in httplib.responses, since OBEX response # codes are matched to HTTP status codes (except for 0x60 and 0x61). # Note these are the responses *without* the final bit set. _OBEX_RESPONSES = { 0x10: "Continue", 0x20: "OK", 0x21: "Created", 0x22: "Accepted", 0x23: "Non-Authoritative Information", 0x24: "No Content", 0x25: "Reset Content", 0x26: "Partial Content", 0x30: "Multiple Choices", 0x31: "Moved Permanently", 0x32: "Moved Temporarily", # but is 'Found' (302) in httplib.response??? 0x33: "See Other", 0x34: "Not Modified", 0x35: "Use Proxy", 0x40: "Bad Request", 0x41: "Unauthorized", 0x42: "Payment Required", 0x43: "Forbidden", 0x44: "Not Found", 0x45: "Method Not Allowed", 0x46: "Not Acceptable", 0x47: "Proxy Authentication Required", 0x48: "Request Timeout", 0x49: "Conflict", 0x4A: "Gone", 0x48: "Length Required", 0x4C: "Precondition Failed", 0x4D: "Request Entity Too Large", 0x4E: "Request-URI Too Long", 0x4F: "Unsupported Media Type", 0x50: "Internal Server Error", 0x51: "Not Implemented", 0x52: "Bad Gateway", 0x53: "Service Unavailable", 0x54: "Gateway Timeout", 0x55: "HTTP Version Not Supported", 0x60: "Database Full", 0x61: "Database Locked" } _obexclientclassdoc = \ """ An OBEX client class. (Note this is not available on Python for Series 60.) For example, to connect to an OBEX server and send a file: >>> import lightblue >>> client = lightblue.obex.OBEXClient("aa:bb:cc:dd:ee:ff", 10) >>> client.connect() <OBEXResponse reason='OK' code=0x20 (0xa0) headers={}> >>> client.put({"name": "photo.jpg"}, file("photo.jpg", "rb")) <OBEXResponse reason='OK' code=0x20 (0xa0) headers={}> >>> client.disconnect() <OBEXResponse reason='OK' code=0x20 (0xa0) headers={}> >>> A client must call connect() to establish a connection before it can send any other requests. The connect(), disconnect(), put(), delete(), get() and setpath() methods all accept the request headers as a dictionary of header-value mappings. The request headers are used to provide the server with additional information for the request. For example, this sends a Put request that includes Name, Type and Length headers in the request headers, to provide details about the transferred file: >>> f = file("file.txt") >>> client.put({"name": "file.txt", "type": "text/plain", ... "length": 5192}, f) >>> Here is a list of all the different string header keys that you can use in the request headers, and the expected type of the value for each header: - "name" -> a string - "type" -> a string - "length" -> an int - "time" -> a datetime object from the datetime module - "description" -> a string - "target" -> a string or buffer - "http" -> a string or buffer - "who" -> a string or buffer - "connection-id" -> an int - "application-parameters" -> a string or buffer - "authentication-challenge" -> a string or buffer - "authentication-response" -> a string or buffer - "creator-id" -> an int - "wan-uuid" -> a string or buffer - "object-class" -> a string or buffer - "session-parameters" -> a string or buffer - "session-sequence-number" -> an int less than 256 (The string header keys are not case-sensitive.) Alternatively, you can use raw header ID values instead of the above convenience strings. So, the previous example can be rewritten as: >>> client.put({0x01: "file.txt", 0x42: "text/plain", 0xC3: 5192}, ... fileobject) >>> This is also useful for inserting custom headers. For example, a PutImage request for a Basic Imaging client requires the Img-Descriptor (0x71) header: >>> client.put({"type": "x-bt/img-img", ... "name": "photo.jpg", ... 0x71: '<image-descriptor version="1.0"><image encoding="JPEG" pixel="160*120" size="37600"/></image-descriptor>'}, ... file('photo.jpg', 'rb')) >>> Notice that the connection-id header is not sent, because this is automatically included by OBEXClient in the request headers if a connection-id was received in a previous Connect response. See the included src/examples/obex_ftp_client.py for an example of using OBEXClient to implement a File Transfer client for browsing the files on a remote device. """ _obexclientdocs = { "__init__": """ Creates an OBEX client. Arguments: - address: the address of the remote device - channel: the RFCOMM channel of the remote OBEX service """, "connect": """ Establishes the Bluetooth connection to the remote OBEX server and sends a Connect request to open the OBEX session. Returns an OBEXResponse instance containing the server response. Raises lightblue.obex.OBEXError if the session is already connected, or
+ "..." cbdebug(_msg, True) self.get_network_list(vmc_name, vm_defaults) _prov_netname_found = False _run_netname_found = False if _prov_netname in self.networks_attr_list : _net_model = self.networks_attr_list[_prov_netname]["model"] _net_type = self.networks_attr_list[_prov_netname]["model"] if _net_model != "external" : _prov_netname_found = True if _net_type == _net_model : _net_str = _net_type else : _net_str = _net_type + ' ' + _net_model _msg = "done. This " + _net_str + " will be used as the default for provisioning." cbdebug(_msg) else: _msg = "\nERROR! The default provisioning network (" _msg += _prov_netname + ") cannot be an external network" cberr(_msg, True) if _run_netname in self.networks_attr_list : _net_model = self.networks_attr_list[_run_netname]["model"] _net_type = self.networks_attr_list[_run_netname]["model"] if _net_model != "external" : _run_netname_found = True if _net_type == _net_model : _net_str = _net_type else : _net_str = _net_type + ' ' + _net_model _msg = "a " + _net_type + ' ' + _net_model + " will be used as the default for running." cbdebug(_msg) else: _msg = "ERROR! The default running network (" _msg += _run_netname + ") cannot be an external network" cberr(_msg, True) if not (_run_netname_found and _prov_netname_found) : _msg = "ERROR! Please make sure that the " + _net_str + " can be found" _msg += " VMC " + vmc_name _fmsg = _msg cberr(_msg, True) return _prov_netname_found, _run_netname_found @trace def check_images(self, vmc_name, vm_defaults, vm_templates) : ''' TBD ''' self.common_messages("IMG", { "name": vmc_name }, "checking", 0, '') _map_name_to_id = {} _map_id_to_name = {} # _registered_image_list = self.oskconncompute[vmc_name].glance.list() _registered_image_list = self.oskconnimage[vmc_name].images.list() _registered_imageid_list = [] for _registered_image in _registered_image_list : if "hypervisor_type" in vm_defaults : if str(vm_defaults["hypervisor_type"]).lower() != "fake" : if "hypervisor_type" in _registered_image._info : if _registered_image._info["hypervisor_type"] == vm_defaults["hypervisor_type"] : _registered_imageid_list.append(_registered_image.id) _map_name_to_id[_registered_image.name] = _registered_image.id else : _registered_imageid_list.append(_registered_image.id) _map_name_to_id[_registered_image.name] = _registered_image.id else : _registered_imageid_list.append(_registered_image.id) _map_name_to_id[_registered_image.name] = _registered_image.id for _vm_role in list(vm_templates.keys()) : _imageid = str2dic(vm_templates[_vm_role])["imageid1"] if _imageid != "to_replace" : if _imageid in _map_name_to_id and _map_name_to_id[_imageid] != _imageid : vm_templates[_vm_role] = vm_templates[_vm_role].replace(_imageid, _map_name_to_id[_imageid]) else : _map_name_to_id[_imageid] = _imageid vm_templates[_vm_role] = vm_templates[_vm_role].replace(_imageid, _map_name_to_id[_imageid]) _map_id_to_name[_map_name_to_id[_imageid]] = _imageid _detected_imageids = self.base_check_images(vmc_name, vm_templates, _registered_imageid_list, _map_id_to_name, vm_defaults) return _detected_imageids @trace def discover_hosts(self, obj_attr_list, start) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" self.connect(obj_attr_list["access"], \ obj_attr_list["credentials"], \ obj_attr_list["name"], {}, False, False, obj_attr_list["name"]) obj_attr_list["hosts"] = '' obj_attr_list["host_list"] = {} self.build_host_map(obj_attr_list["name"]) _host_list = list(self.host_map.keys()) obj_attr_list["host_count"] = len(_host_list) for _host in _host_list : self.add_host(obj_attr_list, _host, start) obj_attr_list["hosts"] = obj_attr_list["hosts"][:-1] self.additional_host_discovery (obj_attr_list) self.populate_interface(obj_attr_list) _status = 0 except CldOpsException as obj : _status = int(obj.status) _fmsg = str(obj.msg) except Exception as e : _status = 23 _fmsg = str(e) finally : self.disconnect() _status, _msg = self.common_messages("HOST", obj_attr_list, "discovered", _status, _fmsg) return _status, _msg @trace def vmccleanup(self, obj_attr_list) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" self.connect(obj_attr_list["access"], \ obj_attr_list["credentials"], \ obj_attr_list["name"], {"use_cinderclient" : str(obj_attr_list["use_cinderclient"])}, \ False, \ False, \ obj_attr_list["name"]) _curr_tries = 0 _max_tries = int(obj_attr_list["update_attempts"]) _wait = int(obj_attr_list["update_frequency"]) sleep(_wait) self.common_messages("VMC", obj_attr_list, "cleaning up vms", 0, '') _running_instances = True while _running_instances and _curr_tries < _max_tries : _running_instances = False _criteria = {} _criteria["all_tenants"] = int(obj_attr_list["all_tenants"]) _vmc_name = obj_attr_list["name"] _instances = self.oskconncompute[_vmc_name].servers.list(search_opts = _criteria) for _instance in _instances : if _instance.name.count("cb-" + obj_attr_list["username"] + '-' + obj_attr_list["cloud_name"]) \ and not _instance.name.count("jumphost") : _instance_metadata = _instance.metadata if "cloud_floating_ip_uuid" in _instance_metadata : _msg = " Deleting floating IP " + _instance_metadata["cloud_floating_ip_uuid"] _msg += ", associated with instance " _msg += _instance.id + " (" + _instance.name + ")" cbdebug(_msg, True) self.oskconnnetwork[_vmc_name].delete_floatingip(_instance_metadata["cloud_floating_ip_uuid"]) # self.oskconncompute.floating_ips.delete(_instance_metadata["cloud_floating_ip_uuid"]) _running_instances = True if _instance.status == "ACTIVE" : _msg = "Terminating instance: " _msg += _instance.id + " (" + _instance.name + ")" cbdebug(_msg, True) _volume_attached = getattr(_instance, 'os-extended-volumes:volumes_attached') self.retriable_instance_delete({}, _instance) if _instance.status == "BUILD" : _msg = "Will wait for instance " _msg += _instance.id + "\"" _msg += " (" + _instance.name + ") to " _msg += "start and then destroy it." cbdebug(_msg, True) sleep(_wait) _curr_tries += 1 if _curr_tries > _max_tries : _status = 1077 _fmsg = "Some instances on VMC \"" + obj_attr_list["name"] + "\"" _fmsg += " could not be removed because they never became active" _fmsg += ". They will have to be removed manually." cberr(_msg, True) else : _status = 0 if self.oskconnstorage and self.use_cinderclient == "true" : self.common_messages("VMC", obj_attr_list, "cleaning up vvs", 0, '') _volumes = self.oskconnstorage[_vmc_name].volumes.list() for _volume in _volumes : if "display_name" in dir(_volume) : _volume_name = str(_volume.display_name) else : _volume_name = str(_volume.name) if _volume_name.count("cb-" + obj_attr_list["username"] + '-' + obj_attr_list["cloud_name"]) : _volume.delete() except CldOpsException as obj : _status = int(obj.status) _fmsg = str(obj.msg) except Exception as e : _status = 23 _fmsg = str(e) finally : self.disconnect() _status, _msg = self.common_messages("VMC", obj_attr_list, "cleaned up", _status, _fmsg) return _status, _msg @trace def vmcregister(self, obj_attr_list) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" _time_mark_prs = int(time()) obj_attr_list["mgt_002_provisioning_request_sent"] = _time_mark_prs - int(obj_attr_list["mgt_001_provisioning_request_originated"]) if "cleanup_on_attach" in obj_attr_list and obj_attr_list["cleanup_on_attach"] == "True" : _status, _fmsg = self.vmccleanup(obj_attr_list) else : _status = 0 if not _status : _x, _y, _hostname = self.connect(obj_attr_list["access"], \ obj_attr_list["credentials"], \ obj_attr_list["name"], obj_attr_list, \ False, \ True, \ obj_attr_list["name"]) obj_attr_list["cloud_hostname"] = _hostname if "access_from_rc" in obj_attr_list : _actual_access = obj_attr_list["access_from_rc"] else : _actual_access = obj_attr_list["access"] _resolve = _actual_access.split(':')[1].replace('//','') _resolve = _resolve.split('/')[0] _resolve = _resolve.replace("_dash_","-") _x, obj_attr_list["cloud_ip"] = hostname2ip(_resolve, True) obj_attr_list["arrival"] = int(time()) if str(obj_attr_list["discover_hosts"]).lower() == "true" : _status, _fmsg = self.discover_hosts(obj_attr_list, _time_mark_prs) else : obj_attr_list["hosts"] = '' obj_attr_list["host_list"] = {} obj_attr_list["host_count"] = "NA" _status = 0 if not _status : self.get_network_list(obj_attr_list["name"], obj_attr_list) _networks = {} for _net in list(self.networks_attr_list.keys()) : if "type" in self.networks_attr_list[_net] : _type = self.networks_attr_list[_net]["type"] obj_attr_list["network_" + _net] = _type _time_mark_prc = int(time()) obj_attr_list["mgt_003_provisioning_request_completed"] = _time_mark_prc - _time_mark_prs except CldOpsException as obj : _status = obj.status _fmsg = str(obj.msg) except Exception as e : _status = 23 _fmsg = str(e) finally : self.disconnect() _status, _msg = self.common_messages("VMC", obj_attr_list, "registered", _status, _fmsg) return _status, _msg @trace def vmcunregister(self, obj_attr_list) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" _time_mark_drs = int(time()) if "mgt_901_deprovisioning_request_originated" not in obj_attr_list : obj_attr_list["mgt_901_deprovisioning_request_originated"] = _time_mark_drs obj_attr_list["mgt_902_deprovisioning_request_sent"] = _time_mark_drs - int(obj_attr_list["mgt_901_deprovisioning_request_originated"]) if "cleanup_on_detach" in obj_attr_list and str(obj_attr_list["cleanup_on_detach"]).lower() == "true" : _status, _fmsg = self.vmccleanup(obj_attr_list) _time_mark_prc = int(time()) obj_attr_list["mgt_903_deprovisioning_request_completed"] = _time_mark_prc - _time_mark_drs _status = 0 except CldOpsException as obj : _status = obj.status _fmsg = str(obj.msg) except Exception as e : _status = 23 _fmsg = str(e) finally : _status, _msg = self.common_messages("VMC", obj_attr_list, "unregistered", _status, _fmsg) return _status, _msg @trace def vmcount(self, obj_attr_list): ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" _nr_instances = 0 for _vmc_uuid in self.osci.get_object_list(obj_attr_list["cloud_name"], "VMC") : _vmc_attr_list = self.osci.get_object(obj_attr_list["cloud_name"], \ "VMC", False, _vmc_uuid, \ False) self.connect(obj_attr_list["access"], obj_attr_list["credentials"], \ _vmc_attr_list["name"], {}, False, False, _vmc_attr_list["name"]) _instances = self.oskconncompute[_vmc_attr_list["name"]].servers.list() for _instance in _instances : if _instance.name.count("cb-" + obj_attr_list["username"] + '-' + obj_attr_list["cloud_name"]) \ and not _instance.name.count("jumphost") : if _instance.status == "ACTIVE" : _nr_instances += 1 except Exception as e : _status = 23 _nr_instances = "NA" _fmsg = "(While counting instance(s) through API call \"list\") " + str(e) finally : return _nr_instances @trace def get_ssh_keys(self, vmc_name, key_name, key_contents, key_fingerprint, registered_key_pairs, internal, connection) : ''' TBD ''' for _key_pair in self.oskconncompute[vmc_name].keypairs.list() : registered_key_pairs[_key_pair.name] = _key_pair.fingerprint + "-NA" #self.oskconncompute.keypairs.delete(_key_pair) return True @trace def get_security_groups(self, vmc_name, security_group_name, registered_security_groups) : ''' TBD ''' if vmc_name in self.oskconnnetwork : for _security_group in self.oskconnnetwork[vmc_name].list_security_groups()["security_groups"] : if _security_group["name"] not in registered_security_groups
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # LightNet++: Boosted Light-weighted Networks for Real-time Semantic Segmentation # ---------------------------------------------------------------------------------------------------------------- # # Compute Metrics for Semantic Segmentation # class: # > BootstrappedCrossEntropy2D # > DiceLoss2D # ---------------------------------------------------------------------------------------------------------------- # # Author: <NAME>. # Date: 10.10.2018 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # import torch.nn.functional as F import scipy.ndimage as nd import torch.nn as nn import numpy as np import torch # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Bootstrapped CrossEntropy2D # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # class BootstrappedCrossEntropy2D(nn.Module): def __init__(self, top_k=128, ignore_index=-100): """ Bootstrapped CrossEntropy2D: The pixel-bootstrapped cross entropy loss :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given, has to be a Tensor of size C, where C = number of classes. :param ignore_index: <int, optional> Specifies a target value that is ignored and does not contribute to the input gradient. """ super(BootstrappedCrossEntropy2D, self).__init__() self.weight = torch.FloatTensor([0.05570516, 0.32337477, 0.08998544, 1.03602707, 1.03413147, 1.68195437, 5.58540548, 3.56563995, 0.12704978, 1., 0.46783719, 1.34551528, 5.29974114, 0.28342531, 0.9396095, 0.81551811, 0.42679146, 3.6399074, 2.78376194]).cuda() self.top_k = top_k self.ignore_index = ignore_index def _update_topk(self, top_k): self.top_k = top_k def forward(self, predictions, targets): """ :param predictions: <torch.FloatTensor> Network Predictions of size [N, C, H, W], where C = number of classes :param targets: <torch.LongTensor> Ground Truth label of size [N, H, W] :param top_k: <int> Top-K worst predictions :return: <torch.Tensor> loss """ loss_fuse = 0.0 if isinstance(predictions, tuple): for predict in predictions: batch_size, channels, feat_h, feat_w = predict.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction # ------------------------------------------------------------------------ # # target_mask = (targets >= 0) * (targets != self.ignore_index) # targets = targets[target_mask] batch_loss = F.cross_entropy(input=predict, target=targets, weight=None, ignore_index=self.ignore_index, reduction='none') # ------------------------------------------------------------------------ # # 2. Bootstrap from each image not entire batch # For each element in the batch, collect the top K worst predictions # ------------------------------------------------------------------------ # loss = 0.0 for idx in range(batch_size): single_loss = batch_loss[idx].view(feat_h*feat_w) topk_loss, _ = single_loss.topk(self.top_k) loss += topk_loss.sum() / self.top_k loss_fuse += loss / float(batch_size) else: batch_size, channels, feat_h, feat_w = predictions.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction # ------------------------------------------------------------------------ # # target_mask = (targets >= 0) * (targets != self.ignore_index) # targets = targets[target_mask] batch_loss = F.cross_entropy(input=predictions, target=targets, weight=None, ignore_index=self.ignore_index, reduction='none') # ------------------------------------------------------------------------ # # 2. Bootstrap from each image not entire batch # For each element in the batch, collect the top K worst predictions # ------------------------------------------------------------------------ # loss = 0.0 for idx in range(batch_size): single_loss = batch_loss[idx].view(feat_h * feat_w) topk_loss, _ = single_loss.topk(self.top_k) loss += topk_loss.sum() / self.top_k loss_fuse += loss / float(batch_size) return loss_fuse class CriterionDSN(nn.Module): ''' DSN : We need to consider two supervision for the model. ''' def __init__(self, top_k=512*512, ignore_index=255): super(CriterionDSN, self).__init__() self.ignore_index = ignore_index self.criterion = BootstrappedCrossEntropy2D(top_k=top_k, ignore_index=ignore_index) def _update_topk(self, top_k): self.criterion._update_topk(top_k) def forward(self, predictions, targets): loss1 = self.criterion(predictions[0], targets) loss2 = self.criterion(predictions[1], targets) return loss1 + loss2 * 0.4 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Bootstrapped CrossEntropy2D # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # class OHEMBootstrappedCrossEntropy2D(nn.Module): def __init__(self, factor=8.0, thresh=0.7, min_kept=100000, top_k=128, ignore_index=-100): """ Bootstrapped CrossEntropy2D: The pixel-bootstrapped cross entropy loss :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given, has to be a Tensor of size C, where C = number of classes. :param ignore_index: <int, optional> Specifies a target value that is ignored and does not contribute to the input gradient. """ super(OHEMBootstrappedCrossEntropy2D, self).__init__() self.weight = torch.FloatTensor([0.05570516, 0.32337477, 0.08998544, 1.03602707, 1.03413147, 1.68195437, 5.58540548, 3.56563995, 0.12704978, 1., 0.46783719, 1.34551528, 5.29974114, 0.28342531, 0.9396095, 0.81551811, 0.42679146, 3.6399074, 2.78376194]) self.top_k = top_k self.ignore_index = ignore_index self.factor = factor self.thresh = thresh self.min_kept = int(min_kept) def find_threshold(self, np_predict, np_target): # downsample 1/8 factor = self.factor predict = nd.zoom(np_predict, (1.0, 1.0, 1.0 / factor, 1.0 / factor), order=1) target = nd.zoom(np_target, (1.0, 1.0 / factor, 1.0 / factor), order=0) n, c, h, w = predict.shape min_kept = self.min_kept // (factor * factor) # int(self.min_kept_ratio * n * h * w) input_label = target.ravel().astype(np.int32) input_prob = np.rollaxis(predict, 1).reshape((c, -1)) valid_flag = input_label != self.ignore_index valid_inds = np.where(valid_flag)[0] label = input_label[valid_flag] num_valid = valid_flag.sum() threshold = 1.0 if min_kept >= num_valid: threshold = 1.0 elif num_valid > 0: prob = input_prob[:, valid_flag] pred = prob[label, np.arange(len(label), dtype=np.int32)] threshold = self.thresh if min_kept > 0: k_th = min(len(pred), int(min_kept)) - 1 new_array = np.partition(pred, int(k_th)) new_threshold = new_array[k_th] if new_threshold > self.thresh: threshold = new_threshold return threshold def generate_new_target(self, predict, target): np_predict = predict.data.cpu().numpy() np_target = target.data.cpu().numpy() n, c, h, w = np_predict.shape threshold = self.find_threshold(np_predict, np_target) input_label = np_target.ravel().astype(np.int32) input_prob = np.rollaxis(np_predict, 1).reshape((c, -1)) valid_flag = input_label != self.ignore_index valid_inds = np.where(valid_flag)[0] label = input_label[valid_flag] num_valid = valid_flag.sum() if num_valid > 0: prob = input_prob[:, valid_flag] pred = prob[label, np.arange(len(label), dtype=np.int32)] kept_flag = pred <= threshold valid_inds = valid_inds[kept_flag] # print('Labels: {} {}'.format(len(valid_inds), threshold)) label = input_label[valid_inds].copy() input_label.fill(self.ignore_index) input_label[valid_inds] = label new_target = torch.from_numpy(input_label.reshape(target.size())).long().cuda(target.get_device()) return new_target def _update_topk(self, top_k): self.top_k = top_k def forward(self, predictions, targets): """ :param predictions: <torch.FloatTensor> Network Predictions of size [N, C, H, W], where C = number of classes :param targets: <torch.LongTensor> Ground Truth label of size [N, H, W] :param top_k: <int> Top-K worst predictions :return: <torch.Tensor> loss """ loss_fuse = 0.0 if isinstance(predictions, tuple): for predict in predictions: batch_size, channels, feat_h, feat_w = predict.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction # ------------------------------------------------------------------------ # # target_mask = (targets >= 0) * (targets != self.ignore_index) # targets = targets[target_mask] input_prob = F.softmax(predict, dim=1) targets = self.generate_new_target(input_prob, targets) batch_loss = F.cross_entropy(input=predict, target=targets, weight=self.weight.cuda(predictions.get_device()), ignore_index=self.ignore_index, reduction='none') # ------------------------------------------------------------------------ # # 2. Bootstrap from each image not entire batch # For each element in the batch, collect the top K worst predictions # ------------------------------------------------------------------------ # loss = 0.0 for idx in range(batch_size): single_loss = batch_loss[idx].view(feat_h*feat_w) topk_loss, _ = single_loss.topk(self.top_k) loss += topk_loss.sum() / self.top_k loss_fuse += loss / float(batch_size) else: batch_size, channels, feat_h, feat_w = predictions.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction # ------------------------------------------------------------------------ # # target_mask = (targets >= 0) * (targets != self.ignore_index) # targets = targets[target_mask] input_prob = F.softmax(predictions, dim=1) targets = self.generate_new_target(input_prob, targets) batch_loss = F.cross_entropy(input=predictions, target=targets, weight=self.weight.cuda(predictions.get_device()), ignore_index=self.ignore_index, reduction='none') # ------------------------------------------------------------------------ # # 2. Bootstrap from each image not entire batch # For each element in the batch, collect the top K worst predictions # ------------------------------------------------------------------------ # loss = 0.0 for idx in range(batch_size): single_loss = batch_loss[idx].view(feat_h * feat_w) topk_loss, _ = single_loss.topk(self.top_k) loss += topk_loss.sum() / self.top_k loss_fuse += loss / float(batch_size) return loss_fuse # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Focal Loss # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # class FocalLoss2D(nn.Module): """ Focal Loss, which is proposed in: "Focal Loss for Dense Object Detection (https://arxiv.org/abs/1708.02002v2)" """ def __init__(self, top_k=128, ignore_label=250, alpha=0.25, gamma=2): """ Loss(x, class) = - \alpha (1-softmax(x)[class])^gamma \log(softmax(x)[class]) :param ignore_label: <int> ignore label :param alpha: <torch.Tensor> the scalar factor :param gamma: <float> gamma > 0; reduces the relative loss for well-classified examples (probabilities > .5), putting more focus on hard, mis-classified examples """ super(FocalLoss2D, self).__init__() self.weight = torch.FloatTensor([0.05570516, 0.32337477, 0.08998544, 1.03602707, 1.03413147, 1.68195437, 5.58540548, 3.56563995, 0.12704978, 1., 0.46783719, 1.34551528, 5.29974114, 0.28342531, 0.9396095, 0.81551811, 0.42679146, 3.6399074, 2.78376194]) self.alpha = alpha self.gamma = gamma self.top_k = top_k self.ignore_label = ignore_label self.one_hot = torch.eye(self.num_classes) def _update_topk(self, top_k): self.top_k = top_k def forward(self, predictions, targets): """ :param predictions: <torch.FloatTensor> Network Predictions of size [N, C, H, W], where C = number of classes :param targets: <torch.LongTensor> Ground Truth label of size [N, H, W] :return: <torch.Tensor> loss """ assert not targets.requires_grad loss_fuse = 0.0 if isinstance(predictions, tuple): for predict in predictions: batch_size, channels, feat_h, feat_w = predict.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction # ------------------------------------------------------------------------ # batch_loss = F.cross_entropy(input=predict, target=targets, weight=self.weight.cuda(predictions.get_device()), ignore_index=self.ignore_index, reduction='none') # ------------------------------------------------------------------------ # # 2. Bootstrap from each image not entire batch # For each element in the batch, collect the top K worst predictions # ------------------------------------------------------------------------ # loss = 0.0 for idx in range(batch_size): single_loss = batch_loss[idx].view(feat_h * feat_w) topk_loss, _ = single_loss.topk(self.top_k) loss += topk_loss.sum() / self.top_k loss_fuse += loss / float(batch_size) else: batch_size, channels, feat_h, feat_w = predictions.size() # ------------------------------------------------------------------------ # # 1. Compute CrossEntropy Loss without Reduction #
Optional[bool]: pass @mark_no_op def visit_BitAnd_whitespace_before(self, node: "BitAnd") -> None: pass @mark_no_op def leave_BitAnd_whitespace_before(self, node: "BitAnd") -> None: pass @mark_no_op def visit_BitAnd_whitespace_after(self, node: "BitAnd") -> None: pass @mark_no_op def leave_BitAnd_whitespace_after(self, node: "BitAnd") -> None: pass @mark_no_op def visit_BitAndAssign(self, node: "BitAndAssign") -> Optional[bool]: pass @mark_no_op def visit_BitAndAssign_whitespace_before(self, node: "BitAndAssign") -> None: pass @mark_no_op def leave_BitAndAssign_whitespace_before(self, node: "BitAndAssign") -> None: pass @mark_no_op def visit_BitAndAssign_whitespace_after(self, node: "BitAndAssign") -> None: pass @mark_no_op def leave_BitAndAssign_whitespace_after(self, node: "BitAndAssign") -> None: pass @mark_no_op def visit_BitInvert(self, node: "BitInvert") -> Optional[bool]: pass @mark_no_op def visit_BitInvert_whitespace_after(self, node: "BitInvert") -> None: pass @mark_no_op def leave_BitInvert_whitespace_after(self, node: "BitInvert") -> None: pass @mark_no_op def visit_BitOr(self, node: "BitOr") -> Optional[bool]: pass @mark_no_op def visit_BitOr_whitespace_before(self, node: "BitOr") -> None: pass @mark_no_op def leave_BitOr_whitespace_before(self, node: "BitOr") -> None: pass @mark_no_op def visit_BitOr_whitespace_after(self, node: "BitOr") -> None: pass @mark_no_op def leave_BitOr_whitespace_after(self, node: "BitOr") -> None: pass @mark_no_op def visit_BitOrAssign(self, node: "BitOrAssign") -> Optional[bool]: pass @mark_no_op def visit_BitOrAssign_whitespace_before(self, node: "BitOrAssign") -> None: pass @mark_no_op def leave_BitOrAssign_whitespace_before(self, node: "BitOrAssign") -> None: pass @mark_no_op def visit_BitOrAssign_whitespace_after(self, node: "BitOrAssign") -> None: pass @mark_no_op def leave_BitOrAssign_whitespace_after(self, node: "BitOrAssign") -> None: pass @mark_no_op def visit_BitXor(self, node: "BitXor") -> Optional[bool]: pass @mark_no_op def visit_BitXor_whitespace_before(self, node: "BitXor") -> None: pass @mark_no_op def leave_BitXor_whitespace_before(self, node: "BitXor") -> None: pass @mark_no_op def visit_BitXor_whitespace_after(self, node: "BitXor") -> None: pass @mark_no_op def leave_BitXor_whitespace_after(self, node: "BitXor") -> None: pass @mark_no_op def visit_BitXorAssign(self, node: "BitXorAssign") -> Optional[bool]: pass @mark_no_op def visit_BitXorAssign_whitespace_before(self, node: "BitXorAssign") -> None: pass @mark_no_op def leave_BitXorAssign_whitespace_before(self, node: "BitXorAssign") -> None: pass @mark_no_op def visit_BitXorAssign_whitespace_after(self, node: "BitXorAssign") -> None: pass @mark_no_op def leave_BitXorAssign_whitespace_after(self, node: "BitXorAssign") -> None: pass @mark_no_op def visit_BooleanOperation(self, node: "BooleanOperation") -> Optional[bool]: pass @mark_no_op def visit_BooleanOperation_left(self, node: "BooleanOperation") -> None: pass @mark_no_op def leave_BooleanOperation_left(self, node: "BooleanOperation") -> None: pass @mark_no_op def visit_BooleanOperation_operator(self, node: "BooleanOperation") -> None: pass @mark_no_op def leave_BooleanOperation_operator(self, node: "BooleanOperation") -> None: pass @mark_no_op def visit_BooleanOperation_right(self, node: "BooleanOperation") -> None: pass @mark_no_op def leave_BooleanOperation_right(self, node: "BooleanOperation") -> None: pass @mark_no_op def visit_BooleanOperation_lpar(self, node: "BooleanOperation") -> None: pass @mark_no_op def leave_BooleanOperation_lpar(self, node: "BooleanOperation") -> None: pass @mark_no_op def visit_BooleanOperation_rpar(self, node: "BooleanOperation") -> None: pass @mark_no_op def leave_BooleanOperation_rpar(self, node: "BooleanOperation") -> None: pass @mark_no_op def visit_Break(self, node: "Break") -> Optional[bool]: pass @mark_no_op def visit_Break_semicolon(self, node: "Break") -> None: pass @mark_no_op def leave_Break_semicolon(self, node: "Break") -> None: pass @mark_no_op def visit_Call(self, node: "Call") -> Optional[bool]: pass @mark_no_op def visit_Call_func(self, node: "Call") -> None: pass @mark_no_op def leave_Call_func(self, node: "Call") -> None: pass @mark_no_op def visit_Call_args(self, node: "Call") -> None: pass @mark_no_op def leave_Call_args(self, node: "Call") -> None: pass @mark_no_op def visit_Call_lpar(self, node: "Call") -> None: pass @mark_no_op def leave_Call_lpar(self, node: "Call") -> None: pass @mark_no_op def visit_Call_rpar(self, node: "Call") -> None: pass @mark_no_op def leave_Call_rpar(self, node: "Call") -> None: pass @mark_no_op def visit_Call_whitespace_after_func(self, node: "Call") -> None: pass @mark_no_op def leave_Call_whitespace_after_func(self, node: "Call") -> None: pass @mark_no_op def visit_Call_whitespace_before_args(self, node: "Call") -> None: pass @mark_no_op def leave_Call_whitespace_before_args(self, node: "Call") -> None: pass @mark_no_op def visit_ClassDef(self, node: "ClassDef") -> Optional[bool]: pass @mark_no_op def visit_ClassDef_name(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_name(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_body(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_body(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_bases(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_bases(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_keywords(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_keywords(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_decorators(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_decorators(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_lpar(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_lpar(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_rpar(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_rpar(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_leading_lines(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_leading_lines(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_lines_after_decorators(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_lines_after_decorators(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_whitespace_after_class(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_whitespace_after_class(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_whitespace_after_name(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_whitespace_after_name(self, node: "ClassDef") -> None: pass @mark_no_op def visit_ClassDef_whitespace_before_colon(self, node: "ClassDef") -> None: pass @mark_no_op def leave_ClassDef_whitespace_before_colon(self, node: "ClassDef") -> None: pass @mark_no_op def visit_Colon(self, node: "Colon") -> Optional[bool]: pass @mark_no_op def visit_Colon_whitespace_before(self, node: "Colon") -> None: pass @mark_no_op def leave_Colon_whitespace_before(self, node: "Colon") -> None: pass @mark_no_op def visit_Colon_whitespace_after(self, node: "Colon") -> None: pass @mark_no_op def leave_Colon_whitespace_after(self, node: "Colon") -> None: pass @mark_no_op def visit_Comma(self, node: "Comma") -> Optional[bool]: pass @mark_no_op def visit_Comma_whitespace_before(self, node: "Comma") -> None: pass @mark_no_op def leave_Comma_whitespace_before(self, node: "Comma") -> None: pass @mark_no_op def visit_Comma_whitespace_after(self, node: "Comma") -> None: pass @mark_no_op def leave_Comma_whitespace_after(self, node: "Comma") -> None: pass @mark_no_op def visit_Comment(self, node: "Comment") -> Optional[bool]: pass @mark_no_op def visit_Comment_value(self, node: "Comment") -> None: pass @mark_no_op def leave_Comment_value(self, node: "Comment") -> None: pass @mark_no_op def visit_CompFor(self, node: "CompFor") -> Optional[bool]: pass @mark_no_op def visit_CompFor_target(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_target(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_iter(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_iter(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_ifs(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_ifs(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_inner_for_in(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_inner_for_in(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_asynchronous(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_asynchronous(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_whitespace_before(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_whitespace_before(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_whitespace_after_for(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_whitespace_after_for(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_whitespace_before_in(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_whitespace_before_in(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompFor_whitespace_after_in(self, node: "CompFor") -> None: pass @mark_no_op def leave_CompFor_whitespace_after_in(self, node: "CompFor") -> None: pass @mark_no_op def visit_CompIf(self, node: "CompIf") -> Optional[bool]: pass @mark_no_op def visit_CompIf_test(self, node: "CompIf") -> None: pass @mark_no_op def leave_CompIf_test(self, node: "CompIf") -> None: pass @mark_no_op def visit_CompIf_whitespace_before(self, node: "CompIf") -> None: pass @mark_no_op def leave_CompIf_whitespace_before(self, node: "CompIf") -> None: pass @mark_no_op def visit_CompIf_whitespace_before_test(self, node: "CompIf") -> None: pass @mark_no_op def leave_CompIf_whitespace_before_test(self, node: "CompIf") -> None: pass @mark_no_op def visit_Comparison(self, node: "Comparison") -> Optional[bool]: pass @mark_no_op def visit_Comparison_left(self, node: "Comparison") -> None: pass @mark_no_op def leave_Comparison_left(self, node: "Comparison") -> None: pass @mark_no_op def visit_Comparison_comparisons(self, node: "Comparison") -> None: pass @mark_no_op def leave_Comparison_comparisons(self, node: "Comparison") -> None: pass @mark_no_op def visit_Comparison_lpar(self, node: "Comparison") -> None: pass @mark_no_op def leave_Comparison_lpar(self, node: "Comparison") -> None: pass @mark_no_op def visit_Comparison_rpar(self, node: "Comparison") -> None: pass @mark_no_op def leave_Comparison_rpar(self, node: "Comparison") -> None: pass @mark_no_op def visit_ComparisonTarget(self, node: "ComparisonTarget") -> Optional[bool]: pass @mark_no_op def visit_ComparisonTarget_operator(self, node: "ComparisonTarget") -> None: pass @mark_no_op def leave_ComparisonTarget_operator(self, node: "ComparisonTarget") -> None: pass @mark_no_op def visit_ComparisonTarget_comparator(self, node: "ComparisonTarget") -> None: pass @mark_no_op def leave_ComparisonTarget_comparator(self, node: "ComparisonTarget") -> None: pass @mark_no_op def visit_ConcatenatedString(self, node: "ConcatenatedString") -> Optional[bool]: pass @mark_no_op def visit_ConcatenatedString_left(self, node: "ConcatenatedString") -> None: pass @mark_no_op def leave_ConcatenatedString_left(self, node: "ConcatenatedString") -> None: pass @mark_no_op def visit_ConcatenatedString_right(self, node: "ConcatenatedString") -> None: pass @mark_no_op def leave_ConcatenatedString_right(self, node: "ConcatenatedString") -> None: pass @mark_no_op def visit_ConcatenatedString_lpar(self, node: "ConcatenatedString") -> None: pass @mark_no_op def leave_ConcatenatedString_lpar(self, node: "ConcatenatedString") -> None: pass @mark_no_op def visit_ConcatenatedString_rpar(self, node: "ConcatenatedString") -> None: pass @mark_no_op def leave_ConcatenatedString_rpar(self, node: "ConcatenatedString") -> None: pass @mark_no_op def visit_ConcatenatedString_whitespace_between( self, node: "ConcatenatedString" ) -> None: pass @mark_no_op def leave_ConcatenatedString_whitespace_between( self, node: "ConcatenatedString" ) -> None: pass @mark_no_op def visit_Continue(self, node: "Continue") -> Optional[bool]: pass @mark_no_op def visit_Continue_semicolon(self, node: "Continue") -> None: pass @mark_no_op def leave_Continue_semicolon(self, node: "Continue") -> None: pass @mark_no_op def visit_Decorator(self, node: "Decorator") -> Optional[bool]: pass @mark_no_op def visit_Decorator_decorator(self, node: "Decorator") -> None: pass @mark_no_op def leave_Decorator_decorator(self, node: "Decorator") -> None: pass @mark_no_op def visit_Decorator_leading_lines(self, node: "Decorator") -> None: pass @mark_no_op def leave_Decorator_leading_lines(self, node: "Decorator") -> None: pass @mark_no_op def visit_Decorator_whitespace_after_at(self, node: "Decorator") -> None: pass @mark_no_op def leave_Decorator_whitespace_after_at(self, node: "Decorator") -> None: pass @mark_no_op def visit_Decorator_trailing_whitespace(self, node: "Decorator") -> None: pass @mark_no_op def
<gh_stars>1-10 import math from enum import Enum from numpy.random.mtrand import randint from pydesim import Model, Statistic, Trace from pycsmaca.simulations.modules import NetworkPacket class PDUBase: class Type(Enum): DATA = 0 ACK = 1 @property def size(self): raise NotImplementedError @property def type(self): raise NotImplementedError @property def sender_address(self): raise NotImplementedError @property def receiver_address(self): raise NotImplementedError def __repr__(self): return str(self) class DataPDU(PDUBase): def __init__( self, packet, header_size, seqn, sender_address=None, receiver_address=None, ): assert isinstance(packet, NetworkPacket) self.__packet = packet self.__sender = ( sender_address if sender_address is not None else packet.sender_address ) self.__receiver = ( receiver_address if receiver_address is not None else packet.receiver_address ) self.__header_size = header_size self.__seqn = seqn @property def packet(self): return self.__packet @property def header_size(self): return self.__header_size @property def size(self): return self.header_size + self.packet.size @property def type(self): return self.Type.DATA @property def sender_address(self): return self.__sender @property def receiver_address(self): return self.__receiver @property def seqn(self): return self.__seqn def __str__(self): link = f'{self.sender_address}=>{self.receiver_address}' size = math.ceil(self.size) return f'PDU{{{link}, seqn:{self.seqn}, {size:d}b}}' class AckPDU(PDUBase): def __init__(self, header_size, ack_size, sender_address, receiver_address): self.__header_size = header_size self.__ack_size = ack_size self.__sender_address = sender_address self.__receiver_address = receiver_address @property def size(self): return self.__header_size + self.__ack_size @property def type(self): return self.Type.ACK @property def sender_address(self): return self.__sender_address @property def receiver_address(self): return self.__receiver_address def __str__(self): link = f'{self.sender_address}=>{self.receiver_address}' size = f'{self.size}' return f'ACK{{{link}, {size}b}}' class ChannelState(Model): """Stores the channel state and informs transmitter about updates. """ def __init__(self, sim): super().__init__(sim) self._is_busy = False @property def transmitter(self): return self.connections['transmitter'].module def set_ready(self): self._is_busy = False self.transmitter.channel_ready() def set_busy(self): self._is_busy = True self.transmitter.channel_busy() @property def is_busy(self): return self._is_busy def __str__(self): return f'{self.parent}.channel' class Transmitter(Model): """Models transmitter module at MAC layer. Connections: - `'channel'`: mandatory, to `Channel` instance; - `'radio'`: mandatory, to `Radio` module - `'queue'`: optional, to `Queue` module """ class State(Enum): IDLE = 0 BUSY = 1 BACKOFF = 2 TX = 3 WAIT_ACK = 4 def __init__( self, sim, address=None, phy_header_size=None, mac_header_size=None, ack_size=None, bitrate=None, preamble=None, max_propagation=0, ): super().__init__(sim) # Properties: self.__address = address self.__phy_header_size = ( phy_header_size if phy_header_size is not None else sim.params.phy_header_size ) self.__mac_header_size = ( mac_header_size if mac_header_size is not None else sim.params.mac_header_size ) self.__bitrate = bitrate if bitrate is not None else sim.params.bitrate self.__preamble = ( preamble if preamble is not None else sim.params.preamble ) self.__max_propagation = max_propagation self.__ack_size = ( ack_size if ack_size is not None else sim.params.ack_size ) # State variables: self.timeout = None self.cw = 65536 self.backoff = -1 self.num_retries = None self.pdu = None self.__state = Transmitter.State.IDLE self.__seqn = 0 # Statistics: self.backoff_vector = Statistic() self.__start_service_time = None self.service_time = Statistic() self.num_sent = 0 self.num_retries_vector = Statistic() self.__busy_trace = Trace() self.__busy_trace.record(sim.stime, 0) # Initialize: sim.schedule(0, self.start) @property def state(self): return self.__state @state.setter def state(self, state): if self.state != state: self.sim.logger.debug( f'{self.state.name} -> {state.name}', src=self ) self.__state = state @property def address(self): return self.__address @address.setter def address(self, address): self.__address = address @property def phy_header_size(self): return self.__phy_header_size @property def mac_header_size(self): return self.__mac_header_size @property def ack_size(self): return self.__ack_size @property def bitrate(self): return self.__bitrate @property def preamble(self): return self.__preamble @property def max_propagation(self): return self.__max_propagation @property def busy_trace(self): return self.__busy_trace @property def channel(self): return self.connections['channel'].module @property def radio(self): return self.connections['radio'].module @property def queue(self): return self.connections['queue'].module def start(self): self.queue.get_next(self) def handle_message(self, packet, connection=None, sender=None): if connection.name == 'queue': assert self.state == Transmitter.State.IDLE self.cw = self.sim.params.cwmin self.backoff = randint(0, self.cw) self.num_retries = 1 # # Create the PDU: # self.pdu = DataPDU( packet, seqn=self.__seqn, header_size=self.phy_header_size + self.mac_header_size, sender_address=self.address, receiver_address=packet.receiver_address ) self.__seqn += 1 self.__start_service_time = self.sim.stime self.backoff_vector.append(self.backoff) self.__busy_trace.record(self.sim.stime, 1) self.sim.logger.debug( f'backoff={self.backoff}; CW={self.cw},NR={self.num_retries}', src=self ) if self.channel.is_busy: self.state = Transmitter.State.BUSY else: self.state = Transmitter.State.BACKOFF self.timeout = self.sim.schedule( self.sim.params.difs, self.handle_backoff_timeout ) else: raise RuntimeError( f'unexpected handle_message({packet}, connection={connection}, ' f'sender={sender}) call' ) def channel_ready(self): if self.state == Transmitter.State.BUSY: self.timeout = self.sim.schedule( self.sim.params.difs, self.handle_backoff_timeout ) self.state = Transmitter.State.BACKOFF def channel_busy(self): if self.state == Transmitter.State.BACKOFF: self.sim.cancel(self.timeout) self.state = Transmitter.State.BUSY def finish_transmit(self): if self.state == Transmitter.State.TX: self.sim.logger.debug('TX finished', src=self) ack_duration = ( (self.ack_size + self.mac_header_size + self.phy_header_size) / self.bitrate + self.preamble + 6 * self.max_propagation ) self.timeout = self.sim.schedule( self.sim.params.sifs + ack_duration, self.handle_ack_timeout ) self.state = Transmitter.State.WAIT_ACK def acknowledged(self): if self.state == Transmitter.State.WAIT_ACK: self.sim.logger.debug('received ACK', src=self) self.sim.cancel(self.timeout) self.pdu = None self.state = Transmitter.State.IDLE self.num_sent += 1 self.service_time.append(self.sim.stime - self.__start_service_time) self.__start_service_time = None self.num_retries_vector.append(self.num_retries) self.num_retries = None self.__busy_trace.record(self.sim.stime, 0) # # IMPORTANT: Informing the queue that we can handle the next packet # self.queue.get_next(self) def handle_ack_timeout(self): assert self.state == Transmitter.State.WAIT_ACK self.num_retries += 1 self.cw = min(2 * self.cw, self.sim.params.cwmax) self.backoff = randint(0, self.cw) self.backoff_vector.append(self.backoff) self.sim.logger.debug( f'backoff={self.backoff}; CW={self.cw}, NR={self.num_retries})', src=self ) if self.channel.is_busy: self.state = Transmitter.State.BUSY else: self.state = Transmitter.State.BACKOFF self.timeout = self.sim.schedule( self.sim.params.difs, self.handle_backoff_timeout ) def handle_backoff_timeout(self): if self.backoff == 0: self.state = Transmitter.State.TX self.sim.logger.debug(f'transmitting {self.pdu}', src=self) self.radio.transmit(self.pdu) else: assert self.backoff > 0 self.backoff -= 1 self.timeout = self.sim.schedule( self.sim.params.slot, self.handle_backoff_timeout ) self.sim.logger.debug(f'backoff := {self.backoff}', src=self) def __str__(self): prefix = f'{self.parent}.' if self.parent else '' return f'{prefix}transmitter' class Receiver(Model): """Module simulating MAC (+PHY) DCF receiver. Connections: - `'radio'`: - `'channel'`: - `'transmitter'` - `'up'`: """ class State(Enum): IDLE = 0 RX = 1 TX1 = 2 TX2 = 3 COLLIDED = 4 WAIT_SEND_ACK = 5 SEND_ACK = 6 def __init__( self, sim, address=None, sifs=None, phy_header_size=None, ack_size=None, ): super().__init__(sim) # Properties: self.__address = address self.__sifs = sifs if sifs is not None else sim.params.sifs self.__phy_header_size = ( phy_header_size if phy_header_size is not None else sim.params.phy_header_size ) self.__ack_size = ( ack_size if ack_size is not None else sim.params.ack_size ) # State variables: self.__state = Receiver.State.IDLE self.__rxbuf = set() self.__cur_tx_pdu = None # Statistics: self.__num_collisions = 0 self.__num_received = 0 self.__busy_trace = Trace() self.__busy_trace.record(sim.stime, 0) @property def state(self): return self.__state @state.setter def state(self, state): if state != self.__state: if self.__state == Receiver.State.IDLE: self.__busy_trace.record(self.sim.stime, 1) elif state == Receiver.State.IDLE: self.__busy_trace.record(self.sim.stime, 0) self.sim.logger.debug( f'{self.__state.name} -> {state.name}', src=self ) if state is Receiver.State.COLLIDED: self.__num_collisions += 1 self.__state = state @property def address(self): return self.__address @address.setter def address(self, address): self.__address = address @property def sifs(self): return self.__sifs @property def phy_header_size(self): return self.__phy_header_size @property def ack_size(self): return self.__ack_size @property def num_received(self): return self.__num_received @property def num_collisions(self): return self.__num_collisions @property def collision_ratio(self): num_ops = self.__num_received + self.__num_collisions if num_ops > 0: return self.__num_collisions / num_ops return 0 @property def busy_trace(self): return self.__busy_trace @property def radio(self): return self.connections['radio'].module @property def channel(self): return self.connections['channel'].module @property def transmitter(self): return self.connections['transmitter'].module @property def up(self): return self.connections['up'].module @property def collision_probability(self): if self.num_received > 0 or self.num_collisions > 0: return self.num_collisions / ( self.num_collisions + self.num_received) return 0 def start_receive(self, pdu): if pdu in self.__rxbuf: self.sim.logger.error( f"PDU {pdu} is already in the buffer:\n{self.__rxbuf}", src=self ) raise RuntimeError(f'PDU is already in the buffer, PDU={pdu}') if self.state is Receiver.State.IDLE and not self.__rxbuf: self.state = Receiver.State.RX self.channel.set_busy() elif (self.state is Receiver.State.RX or ( self.state is Receiver.State.IDLE and self.__rxbuf)): self.state = Receiver.State.COLLIDED self.__rxbuf.add(pdu) # In all other states (e.g. TX2, WAIT_SEND_ACK, SEND_ACK) we just add # the packet to RX buffer. def finish_receive(self, pdu): assert pdu in self.__rxbuf self.__rxbuf.remove(pdu) if self.state is Receiver.State.RX: assert not self.__rxbuf if pdu.receiver_address == self.address: if pdu.type is DataPDU.Type.DATA: self.state = Receiver.State.WAIT_SEND_ACK self.__cur_tx_pdu = pdu self.sim.schedule(self.sifs, self.handle_timeout) elif pdu.type is DataPDU.Type.ACK: self.transmitter.acknowledged() self.state = Receiver.State.IDLE self.channel.set_ready() else: raise RuntimeError(f'unsupported packet type {pdu.type}') else: self.state = Receiver.State.IDLE self.channel.set_ready() elif self.state is Receiver.State.COLLIDED: if not self.__rxbuf: self.state = Receiver.State.IDLE self.channel.set_ready() # Otherwise stay in COLLIDED state # In all other states (e.g. IDLE, TX1, TX2, ...) we just purge the # packet from the RX buffer. def start_transmit(self): if self.state is Receiver.State.IDLE: self.state = Receiver.State.TX1 elif self.state in (Receiver.State.RX, Receiver.State.COLLIDED): self.state = Receiver.State.TX2 assert self.state is not self.state.WAIT_SEND_ACK def finish_transmit(self): if self.state is Receiver.State.TX1: if self.__rxbuf: self.channel.set_busy() self.state = Receiver.State.COLLIDED else: self.state = Receiver.State.IDLE elif self.state is Receiver.State.TX2: if self.__rxbuf: self.state = Receiver.State.COLLIDED else: self.channel.set_ready() self.state = Receiver.State.IDLE elif self.state is Receiver.State.SEND_ACK: payload = self.__cur_tx_pdu.packet self.connections['up'].send(payload) self.__num_received += 1 self.__cur_tx_pdu = None self.channel.set_ready() self.state = Receiver.State.IDLE def handle_timeout(self): assert self.state is Receiver.State.WAIT_SEND_ACK ack = AckPDU( header_size=self.phy_header_size, ack_size=self.ack_size, sender_address=self.address, receiver_address=self.__cur_tx_pdu.sender_address, ) self.state = Receiver.State.SEND_ACK self.radio.transmit(ack) def __str__(self): prefix = f'{self.parent}.' if self.parent else ''
* (x - x0) ** 2 / sigma_x ** 3 dydy0 = value * (y - y0) / sigma_x ** 2 return np.vstack((dydamp, dydx0, dydy0, dydsigmax, np.ones_like(value))).T # new_params = np.insert(params, 4, 0) # new_params = np.insert(new_params, 4, params[3]) # return np.delete(cls.gauss2D_jac(new_params, xdata), (4, 5), axis=0) @classmethod def model_jac(cls, xdata_tuple, *params): """Chooses the correct model jacobian function to use based on the number of arguments passed to it Parameters ---------- xdata_tuple : tuple of ndarrays (xx, yy) The independent data Returns ------- modeldata : Other Parameters ---------------- *args : model parameters """ num_args = len(params) if num_args == 5: return cls.gauss2D_sym_jac(params, xdata_tuple) elif num_args == 6: return cls.gauss2D_norot_jac(params, xdata_tuple) elif num_args == 7: return cls.gauss2D_jac(params, xdata_tuple) else: raise RuntimeError("len(params) = {}, number out of range!".format(num_args)) @classmethod def gen_model(cls, data, *args): """ A helper method to generate a fit if needed, useful for generating residuals Parameters ---------- *args : tuple passed directly to `model` Returns ------- out : ndarray Fit generated by the model. """ # generate data grid yy, xx = np.indices(data.shape) xdata_tuple = (xx, yy) # return model return cls.model(xdata_tuple, *args) @property def fit_model(self): """ Generate the model from this instance, if the fit hasn't been performed yet an error will be raised """ return self.gen_model(self._data, *self._popt) def area(self, **kwargs): """ A function for calculating the area of the model peak Area = 2*amp*np.pi*sigma_x*sigma_y*np.sqrt(1-rho**2) Parameters ---------- kwargs : dictionary key word arguments to pass to `optimize_params`, only used if `opt_params` has not been caculated yet. Returns ------- Area of the peak based on fit parameters. """ # this is for convenience so that the area can # be returned quickly, i.e. a = Gauss2D(data).area() if self._popt is None: self.optimize_params(**kwargs) # extract the optimal parameters opt_params = self.opt_params num_params = len(opt_params) # depending on the specified model the area is calculated if num_params == 7: return abs( 2 * np.pi * opt_params[0] * opt_params[3] * opt_params[4] * np.sqrt(1 - opt_params[5] ** 2) ) elif num_params == 6: return abs(2 * np.pi * opt_params[0] * opt_params[3] * opt_params[4]) else: return abs(2 * np.pi * opt_params[0] * opt_params[3] ** 2) def optimize_params( self, guess_params=None, modeltype="norot", quiet=False, bounds=None, checkparams=True, detrenddata=False, fittype="ls", ): """ A function that will optimize the parameters for a 2D Gaussian model using either a least squares or maximum likelihood method Parameters ---------- guess_params : numeric sequence, or dict (optional) The initial guesses for the model parameters. The number of parameters determines the modeltype (see notes). If no guesses are provided they will be estimated from the data. The estimation is only valid for positive data modeltype : {'sym', 'norot', 'full'}, default 'norot' Determines the model to guess parameters for fittype : {'ls', 'mle'}, default 'ls' Specifies if a least squares fit ('ls') or maximum likelihood estimation ('mle') should be performed quiet : bool Determines the verbosity of the output bounds : (-np.inf, np.inf) See `scipy.optimize.curve_fit` for details, if modeltype is 'full' then the bounds for $\rho$ are automatically set to (-1, 1) while the rest are left as is checkparams : bool Checks the parameters for validity after the fit, maybe replaced in the future by more intelligent default bounding detrenddata : bool Determines if the data should be detrended before parameter estimation, may be removed in the future. Returns ------- opt_params : ndarray The optimized parameters from the fit. If the fit wasn't successful a series of np.nan's will be returned. Notes ----- This function will call scipy.optimize to optimize the parameters of the model function MLE is for poisson noise model while LS is for gaussian noise model. """ # Test if we've been provided guess parameters # Need to test if the variable is good or not. if guess_params is None: # if not we generate them guess_params = self.estimate_params(detrenddata=detrenddata) if modeltype.lower() == "sym": guess_params = np.delete(guess_params, (4, 5)) elif modeltype.lower() == "norot": guess_params = np.delete(guess_params, 5) elif modeltype.lower() == "full": pass else: raise RuntimeError("modeltype is not one of: 'sym', 'norot', 'full'") # handle the case where the user passes a dictionary of values. if isinstance(guess_params, dict): guess_params = self.dict_to_params(guess_params) self._guess_params = guess_params # pull the data attribute for use data = self._data # We need to generate the x an y coordinates for the fit # remember that image data generally has the higher dimension first # as do most python objects yy, xx = np.indices(data.shape) # define our function for fitting def model_ravel(*args): return self.model(*args).ravel() # TODO: We also need a function to clear nan values from data and the # associated xx and yy points. # Here we fit the data but we catch any errors and instead set the # optimized parameters to nan. # full_output is an undocumented key word of `curve_fit` if set to true # it returns the same output as leastsq's would, if False, as it is by # default it returns only popt and pcov. # we need to set the bounds if rho is available if bounds is None: # TODO: we can make better defaults, keep sigma_x/sigma_y positive, # make sure amp is positive, etc... # set to default for all params if len(guess_params) == 7: # make sure rho is restricted ub = np.array((np.inf,) * 5 + (1, np.inf)) bounds = (-1 * ub, ub) else: bounds = (-np.inf, np.inf) with warnings.catch_warnings(): # we'll catch this error later and alert the user with a printout warnings.simplefilter("ignore", OptimizeWarning) if fittype.lower() == "mle": meth = "mle" elif fittype.lower() == "ls": # default to scipy meth = None else: raise RuntimeError("fittype is not one of: 'ls', 'mle'") try: popt, pcov, infodict, errmsg, ier = curve_fit( model_ravel, (xx, yy), data.ravel(), p0=guess_params, bounds=bounds, full_output=True, jac=self.model_jac, method=meth, ) except RuntimeError as e: # print(e) # now we need to re-parse the error message to set all the # flags pull the message self.errmsg = e.args[0].replace("Optimal parameters not found: ", "") # run through possibilities for failure errors = { 0: "Improper", 5: "maxfev", 6: "ftol", 7: "xtol", 8: "gtol", "unknown": "Unknown", } # set the error flag correctly for k, v in errors.items(): if v in self.errmsg: self.ier = k except ValueError as e: # This except is for bounds checking gone awry self.errmsg = str(e) self.ier = -1 else: # if we save the infodict as well then we'll start using a lot # of memory # self.infodict = infodict self.errmsg = errmsg self.ier = ier if checkparams: self._check_params(popt) # check to see if the covariance is bunk if not np.isfinite(pcov).all(): self.errmsg = """ Covariance of the parameters could not be estimated """ self.ier = 9 # save parameters for later use # if the error flag is good, proceed if self.ier in [1, 2, 3, 4]: # make sure sigmas are positive # if popt.size > 5: # popt[3:5] = abs(popt[3:5]) # else: # popt[3] = abs(popt[3]) self._popt = popt self._pcov = pcov else: if not quiet: logger.warning("Fitting error: " + self.errmsg) self._popt = guess_params * np.nan self._pcov = np.zeros((len(guess_params), len(guess_params))) * np.nan if not self.error: # if no fitting error calc residuals and noise self.residuals = self.data - self.fit_model self.noise = self.residuals.std() else: # if there is an error set the noise to nan self.noise = np.nan return self.opt_params def _check_params(self, popt): """ A method that checks if optimized parameters are valid and sets the fit flag """ data = self.data # check to see if the gaussian is bigger than its fitting window by a # large amount, generally the user is advised to enlarge the fitting # window or disregard the results of the fit. sigma_msg = "Sigma larger than ROI" max_s = max(data.shape) if len(popt) < 6: if abs(popt[3]) > max_s: self.errmsg = sigma_msg self.ier = 10 else: if abs(popt[3]) > max_s or
"""EnrollmentTerms API Version 1.0. This API client was generated using a template. Make sure this code is valid before using it. """ import logging from datetime import date, datetime from .base import BaseCanvasAPI from .base import BaseModel class EnrollmentTermsAPI(BaseCanvasAPI): """EnrollmentTerms API Version 1.0.""" def __init__(self, *args, **kwargs): """Init method for EnrollmentTermsAPI.""" super(EnrollmentTermsAPI, self).__init__(*args, **kwargs) self.logger = logging.getLogger("py3canvas.EnrollmentTermsAPI") def create_enrollment_term( self, account_id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_overrides_enrollment_type_end_at=None, enrollment_term_overrides_enrollment_type_start_at=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None, ): """ Create enrollment term. Create a new enrollment term for the specified account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ ID """ path["account_id"] = account_id # OPTIONAL - enrollment_term[name] """ The name of the term. """ if enrollment_term_name is not None: data["enrollment_term[name]"] = enrollment_term_name # OPTIONAL - enrollment_term[start_at] """ The day/time the term starts. Accepts times in ISO 8601 format, e.g. 2015-01-10T18:48:00Z. """ if enrollment_term_start_at is not None: if issubclass(enrollment_term_start_at.__class__, str): enrollment_term_start_at = self._validate_iso8601_string( enrollment_term_start_at ) elif issubclass(enrollment_term_start_at.__class__, date) or issubclass( enrollment_term_start_at.__class__, datetime ): enrollment_term_start_at = enrollment_term_start_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) data["enrollment_term[start_at]"] = enrollment_term_start_at # OPTIONAL - enrollment_term[end_at] """ The day/time the term ends. Accepts times in ISO 8601 format, e.g. 2015-01-10T18:48:00Z. """ if enrollment_term_end_at is not None: if issubclass(enrollment_term_end_at.__class__, str): enrollment_term_end_at = self._validate_iso8601_string( enrollment_term_end_at ) elif issubclass(enrollment_term_end_at.__class__, date) or issubclass( enrollment_term_end_at.__class__, datetime ): enrollment_term_end_at = enrollment_term_end_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) data["enrollment_term[end_at]"] = enrollment_term_end_at # OPTIONAL - enrollment_term[sis_term_id] """ The unique SIS identifier for the term. """ if enrollment_term_sis_term_id is not None: data["enrollment_term[sis_term_id]"] = enrollment_term_sis_term_id # OPTIONAL - enrollment_term[overrides][enrollment_type][start_at] """ The day/time the term starts, overridden for the given enrollment type. *enrollment_type* can be one of StudentEnrollment, TeacherEnrollment, TaEnrollment, or DesignerEnrollment """ if enrollment_term_overrides_enrollment_type_start_at is not None: if issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, str ): enrollment_term_overrides_enrollment_type_start_at = ( self._validate_iso8601_string( enrollment_term_overrides_enrollment_type_start_at ) ) elif issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, date ) or issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, datetime ): enrollment_term_overrides_enrollment_type_start_at = ( enrollment_term_overrides_enrollment_type_start_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) ) data[ "enrollment_term[overrides][enrollment_type][start_at]" ] = enrollment_term_overrides_enrollment_type_start_at # OPTIONAL - enrollment_term[overrides][enrollment_type][end_at] """ The day/time the term ends, overridden for the given enrollment type. *enrollment_type* can be one of StudentEnrollment, TeacherEnrollment, TaEnrollment, or DesignerEnrollment """ if enrollment_term_overrides_enrollment_type_end_at is not None: if issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, str ): enrollment_term_overrides_enrollment_type_end_at = ( self._validate_iso8601_string( enrollment_term_overrides_enrollment_type_end_at ) ) elif issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, date ) or issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, datetime ): enrollment_term_overrides_enrollment_type_end_at = ( enrollment_term_overrides_enrollment_type_end_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) ) data[ "enrollment_term[overrides][enrollment_type][end_at]" ] = enrollment_term_overrides_enrollment_type_end_at self.logger.debug( "POST /api/v1/accounts/{account_id}/terms with query params: {params} and form data: {data}".format( params=params, data=data, **path ) ) return self.generic_request( "POST", "/api/v1/accounts/{account_id}/terms".format(**path), data=data, params=params, single_item=True, ) def update_enrollment_term( self, account_id, id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_overrides_enrollment_type_end_at=None, enrollment_term_overrides_enrollment_type_start_at=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None, ): """ Update enrollment term. Update an existing enrollment term for the specified account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ ID """ path["account_id"] = account_id # REQUIRED - PATH - id """ ID """ path["id"] = id # OPTIONAL - enrollment_term[name] """ The name of the term. """ if enrollment_term_name is not None: data["enrollment_term[name]"] = enrollment_term_name # OPTIONAL - enrollment_term[start_at] """ The day/time the term starts. Accepts times in ISO 8601 format, e.g. 2015-01-10T18:48:00Z. """ if enrollment_term_start_at is not None: if issubclass(enrollment_term_start_at.__class__, str): enrollment_term_start_at = self._validate_iso8601_string( enrollment_term_start_at ) elif issubclass(enrollment_term_start_at.__class__, date) or issubclass( enrollment_term_start_at.__class__, datetime ): enrollment_term_start_at = enrollment_term_start_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) data["enrollment_term[start_at]"] = enrollment_term_start_at # OPTIONAL - enrollment_term[end_at] """ The day/time the term ends. Accepts times in ISO 8601 format, e.g. 2015-01-10T18:48:00Z. """ if enrollment_term_end_at is not None: if issubclass(enrollment_term_end_at.__class__, str): enrollment_term_end_at = self._validate_iso8601_string( enrollment_term_end_at ) elif issubclass(enrollment_term_end_at.__class__, date) or issubclass( enrollment_term_end_at.__class__, datetime ): enrollment_term_end_at = enrollment_term_end_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) data["enrollment_term[end_at]"] = enrollment_term_end_at # OPTIONAL - enrollment_term[sis_term_id] """ The unique SIS identifier for the term. """ if enrollment_term_sis_term_id is not None: data["enrollment_term[sis_term_id]"] = enrollment_term_sis_term_id # OPTIONAL - enrollment_term[overrides][enrollment_type][start_at] """ The day/time the term starts, overridden for the given enrollment type. *enrollment_type* can be one of StudentEnrollment, TeacherEnrollment, TaEnrollment, or DesignerEnrollment """ if enrollment_term_overrides_enrollment_type_start_at is not None: if issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, str ): enrollment_term_overrides_enrollment_type_start_at = ( self._validate_iso8601_string( enrollment_term_overrides_enrollment_type_start_at ) ) elif issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, date ) or issubclass( enrollment_term_overrides_enrollment_type_start_at.__class__, datetime ): enrollment_term_overrides_enrollment_type_start_at = ( enrollment_term_overrides_enrollment_type_start_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) ) data[ "enrollment_term[overrides][enrollment_type][start_at]" ] = enrollment_term_overrides_enrollment_type_start_at # OPTIONAL - enrollment_term[overrides][enrollment_type][end_at] """ The day/time the term ends, overridden for the given enrollment type. *enrollment_type* can be one of StudentEnrollment, TeacherEnrollment, TaEnrollment, or DesignerEnrollment """ if enrollment_term_overrides_enrollment_type_end_at is not None: if issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, str ): enrollment_term_overrides_enrollment_type_end_at = ( self._validate_iso8601_string( enrollment_term_overrides_enrollment_type_end_at ) ) elif issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, date ) or issubclass( enrollment_term_overrides_enrollment_type_end_at.__class__, datetime ): enrollment_term_overrides_enrollment_type_end_at = ( enrollment_term_overrides_enrollment_type_end_at.strftime( "%Y-%m-%dT%H:%M:%S+00:00" ) ) data[ "enrollment_term[overrides][enrollment_type][end_at]" ] = enrollment_term_overrides_enrollment_type_end_at self.logger.debug( "PUT /api/v1/accounts/{account_id}/terms/{id} with query params: {params} and form data: {data}".format( params=params, data=data, **path ) ) return self.generic_request( "PUT", "/api/v1/accounts/{account_id}/terms/{id}".format(**path), data=data, params=params, single_item=True, ) def delete_enrollment_term(self, account_id, id): """ Delete enrollment term. Delete the specified enrollment term. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ ID """ path["account_id"] = account_id # REQUIRED - PATH - id """ ID """ path["id"] = id self.logger.debug( "DELETE /api/v1/accounts/{account_id}/terms/{id} with query params: {params} and form data: {data}".format( params=params, data=data, **path ) ) return self.generic_request( "DELETE", "/api/v1/accounts/{account_id}/terms/{id}".format(**path), data=data, params=params, single_item=True, ) def list_enrollment_terms(self, account_id, include=None, workflow_state=None): """ List enrollment terms. An object with a paginated list of all of the terms in the account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ ID """ path["account_id"] = account_id # OPTIONAL - workflow_state """ If set, only returns terms that are in the given state. Defaults to 'active'. """ if workflow_state is not None: self._validate_enum(workflow_state, ["active", "deleted", "all"]) params["workflow_state"] = workflow_state # OPTIONAL - include """ Array of additional information to include. "overrides":: term start/end dates overridden for different enrollment types """ if include is not None: self._validate_enum(include, ["overrides"]) params["include"] = include self.logger.debug( "GET /api/v1/accounts/{account_id}/terms with query params: {params} and form data: {data}".format( params=params, data=data, **path ) ) return self.generic_request( "GET", "/api/v1/accounts/{account_id}/terms".format(**path), data=data, params=params, single_item=True, ) def retrieve_enrollment_term(self, account_id, id): """ Retrieve enrollment term. Retrieves the details for an enrollment term in the account. Includes overrides by default. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ ID """ path["account_id"] = account_id # REQUIRED - PATH - id """ ID """ path["id"] = id self.logger.debug( "GET /api/v1/accounts/{account_id}/terms/{id} with query params: {params} and form data: {data}".format( params=params, data=data, **path ) ) return self.generic_request( "GET", "/api/v1/accounts/{account_id}/terms/{id}".format(**path), data=data, params=params, single_item=True, ) class Enrollmentterm(BaseModel): """Enrollmentterm Model.""" def __init__( self, id=None, sis_term_id=None, sis_import_id=None, name=None, start_at=None, end_at=None, workflow_state=None, overrides=None, ): """Init method for Enrollmentterm class.""" self._id = id self._sis_term_id = sis_term_id self._sis_import_id = sis_import_id self._name = name self._start_at = start_at self._end_at = end_at self._workflow_state = workflow_state self._overrides = overrides self.logger = logging.getLogger("py3canvas.Enrollmentterm") @property def id(self): """The unique identifier for the enrollment term.""" return self._id @id.setter def id(self, value): """Setter for id property.""" self.logger.warn( "Setting values on id will NOT update the remote Canvas instance." ) self._id = value @property def sis_term_id(self): """The SIS id of the term. Only included if the user has permission to view SIS information.""" return self._sis_term_id @sis_term_id.setter def sis_term_id(self, value): """Setter for sis_term_id property.""" self.logger.warn( "Setting values on sis_term_id will NOT update the remote Canvas instance." ) self._sis_term_id = value @property def sis_import_id(self): """the unique identifier for the SIS import. This field is only included if the user has permission to manage SIS information.""" return self._sis_import_id @sis_import_id.setter def sis_import_id(self, value): """Setter for sis_import_id property.""" self.logger.warn( "Setting values on sis_import_id will NOT update the remote Canvas instance." ) self._sis_import_id = value @property def name(self): """The name of the term.""" return self._name @name.setter def name(self, value): """Setter for name property.""" self.logger.warn( "Setting values on name will NOT update the remote Canvas instance." ) self._name = value @property def start_at(self): """The datetime of the start of the term.""" return self._start_at @start_at.setter def start_at(self, value): """Setter for start_at property.""" self.logger.warn( "Setting values on start_at will NOT update the remote Canvas instance." ) self._start_at = value @property def end_at(self): """The datetime of the end
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import ast import functools import imp import importlib import inspect import itertools import logging import os import pkg_resources import re import sys import time import types import unittest import threading from operator import itemgetter from os.path import join as opj import odoo import odoo.tools as tools import odoo.release as release from odoo import SUPERUSER_ID, api MANIFEST_NAMES = ('__manifest__.py', '__openerp__.py') README = ['README.rst', 'README.md', 'README.txt'] _logger = logging.getLogger(__name__) # addons path as a list ad_paths = [] hooked = False # Modules already loaded loaded = [] class AddonsHook(object): """ Makes modules accessible through openerp.addons.* and odoo.addons.* """ def find_module(self, name, path=None): if name.startswith(('odoo.addons.', 'openerp.addons.'))\ and name.count('.') == 2: return self def load_module(self, name): assert name not in sys.modules # get canonical names odoo_name = re.sub(r'^openerp.addons.(\w+)$', r'odoo.addons.\g<1>', name) openerp_name = re.sub(r'^odoo.addons.(\w+)$', r'openerp.addons.\g<1>', odoo_name) assert odoo_name not in sys.modules assert openerp_name not in sys.modules # get module name in addons paths _1, _2, addon_name = name.split('.') # load module f, path, (_suffix, _mode, type_) = imp.find_module(addon_name, ad_paths) if f: f.close() # TODO: fetch existing module from sys.modules if reloads permitted # create empty odoo.addons.* module, set name new_mod = types.ModuleType(odoo_name) new_mod.__loader__ = self # module top-level can only be a package assert type_ == imp.PKG_DIRECTORY, "Odoo addon top-level must be a package" modfile = opj(path, '__init__.py') new_mod.__file__ = modfile new_mod.__path__ = [path] new_mod.__package__ = odoo_name # both base and alias should be in sys.modules to handle recursive and # corecursive situations sys.modules[odoo_name] = sys.modules[openerp_name] = new_mod # execute source in context of module *after* putting everything in # sys.modules, so recursive import works execfile(modfile, new_mod.__dict__) # people import openerp.addons and expect openerp.addons.<module> to work setattr(odoo.addons, addon_name, new_mod) return sys.modules[name] # need to register loader with setuptools as Jinja relies on it when using # PackageLoader pkg_resources.register_loader_type(AddonsHook, pkg_resources.DefaultProvider) class OdooHook(object): """ Makes odoo package also available as openerp """ def find_module(self, name, path=None): # openerp.addons.<identifier> should already be matched by AddonsHook, # only framework and subdirectories of modules should match if re.match(r'^openerp\b', name): return self def load_module(self, name): assert name not in sys.modules canonical = re.sub(r'^openerp(.*)', r'odoo\g<1>', name) if canonical in sys.modules: mod = sys.modules[canonical] else: # probable failure: canonical execution calling old naming -> corecursion mod = importlib.import_module(canonical) # just set the original module at the new location. Don't proxy, # it breaks *-import (unless you can find how `from a import *` lists # what's supposed to be imported by `*`, and manage to override it) sys.modules[name] = mod return sys.modules[name] def initialize_sys_path(): """ Setup an import-hook to be able to import OpenERP addons from the different addons paths. This ensures something like ``import crm`` (or even ``import odoo.addons.crm``) works even if the addons are not in the PYTHONPATH. """ global ad_paths global hooked dd = tools.config.addons_data_dir if os.access(dd, os.R_OK) and dd not in ad_paths: ad_paths.append(dd) for ad in tools.config['addons_path'].split(','): ad = os.path.abspath(tools.ustr(ad.strip())) if ad not in ad_paths: ad_paths.append(ad) # add base module path base_path = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'addons')) if base_path not in ad_paths: ad_paths.append(base_path) # add odoo.addons.__path__ for ad in __import__('odoo.addons').addons.__path__: ad = os.path.abspath(ad) if ad not in ad_paths: ad_paths.append(ad) if not hooked: sys.meta_path.append(AddonsHook()) sys.meta_path.append(OdooHook()) hooked = True def get_module_path(module, downloaded=False, display_warning=True): """Return the path of the given module. Search the addons paths and return the first path where the given module is found. If downloaded is True, return the default addons path if nothing else is found. """ initialize_sys_path() for adp in ad_paths: files = [opj(adp, module, manifest) for manifest in MANIFEST_NAMES] +\ [opj(adp, module + '.zip')] if any(os.path.exists(f) for f in files): return opj(adp, module) if downloaded: return opj(tools.config.addons_data_dir, module) if display_warning: _logger.warning('module %s: module not found', module) return False def get_module_filetree(module, dir='.'): path = get_module_path(module) if not path: return False dir = os.path.normpath(dir) if dir == '.': dir = '' if dir.startswith('..') or (dir and dir[0] == '/'): raise Exception('Cannot access file outside the module') files = odoo.tools.osutil.listdir(path, True) tree = {} for f in files: if not f.startswith(dir): continue if dir: f = f[len(dir)+int(not dir.endswith('/')):] lst = f.split(os.sep) current = tree while len(lst) != 1: current = current.setdefault(lst.pop(0), {}) current[lst.pop(0)] = None return tree def get_resource_path(module, *args): """Return the full path of a resource of the given module. :param module: module name :param list(str) args: resource path components within module :rtype: str :return: absolute path to the resource TODO make it available inside on osv object (self.get_resource_path) """ mod_path = get_module_path(module) if not mod_path: return False resource_path = opj(mod_path, *args) if os.path.isdir(mod_path): # the module is a directory - ignore zip behavior if os.path.exists(resource_path): return resource_path return False # backwards compatibility get_module_resource = get_resource_path def get_resource_from_path(path): """Tries to extract the module name and the resource's relative path out of an absolute resource path. If operation is successfull, returns a tuple containing the module name, the relative path to the resource using '/' as filesystem seperator[1] and the same relative path using os.path.sep seperators. [1] same convention as the resource path declaration in manifests :param path: absolute resource path :rtype: tuple :return: tuple(module_name, relative_path, os_relative_path) if possible, else None """ resource = False for adpath in ad_paths: # force trailing separator adpath = os.path.join(adpath, "") if os.path.commonprefix([adpath, path]) == adpath: resource = path.replace(adpath, "", 1) break if resource: relative = resource.split(os.path.sep) if not relative[0]: relative.pop(0) module = relative.pop(0) return (module, '/'.join(relative), os.path.sep.join(relative)) return None def get_module_icon(module): iconpath = ['static', 'description', 'icon.png'] if get_module_resource(module, *iconpath): return ('/' + module + '/') + '/'.join(iconpath) return '/base/' + '/'.join(iconpath) def module_manifest(path): """Returns path to module manifest if one can be found under `path`, else `None`.""" if not path: return None for manifest_name in MANIFEST_NAMES: if os.path.isfile(opj(path, manifest_name)): return opj(path, manifest_name) def get_module_root(path): """ Get closest module's root begining from path # Given: # /foo/bar/module_dir/static/src/... get_module_root('/foo/bar/module_dir/static/') # returns '/foo/bar/module_dir' get_module_root('/foo/bar/module_dir/') # returns '/foo/bar/module_dir' get_module_root('/foo/bar') # returns None @param path: Path from which the lookup should start @return: Module root path or None if not found """ while not module_manifest(path): new_path = os.path.abspath(opj(path, os.pardir)) if path == new_path: return None path = new_path return path def load_information_from_description_file(module, mod_path=None): """ :param module: The name of the module (sale, purchase, ...) :param mod_path: Physical path of module, if not providedThe name of the module (sale, purchase, ...) """ if not mod_path: mod_path = get_module_path(module, downloaded=True) manifest_file = module_manifest(mod_path) if manifest_file: # default values for descriptor info = { 'application': False, 'author': '<NAME>.', 'auto_install': False, 'category': 'Uncategorized', 'depends': [], 'description': '', 'icon': get_module_icon(module), 'installable': True, 'license': 'LGPL-3', 'post_load': None, 'version': '1.0', 'web': False, 'website': 'https://www.odoo.com', 'sequence': 100, 'summary': '', } info.update(itertools.izip( 'depends data demo test init_xml update_xml demo_xml'.split(), iter(list, None))) f = tools.file_open(manifest_file) try: info.update(ast.literal_eval(f.read())) finally: f.close() if not info.get('description'): readme_path = [opj(mod_path, x) for x in README if os.path.isfile(opj(mod_path, x))] if readme_path: readme_text = tools.file_open(readme_path[0]).read() info['description'] = readme_text if 'active' in info: # 'active' has been renamed 'auto_install' info['auto_install'] = info['active'] info['version'] = adapt_version(info['version']) return info _logger.debug('module %s: no manifest file found %s', module, MANIFEST_NAMES) return {} def load_openerp_module(module_name): """ Load an OpenERP module, if not already loaded. This loads the module and register all of its models, thanks to either the MetaModel metaclass, or the explicit instantiation of the model. This is also used to load server-wide module (i.e. it is also used when there is no model to register). """ global loaded if module_name in loaded: return initialize_sys_path() try: __import__('odoo.addons.' + module_name) # Call the module's post-load hook. This can done before any model or # data has been initialized. This is ok as the post-load hook is for # server-wide (instead of registry-specific) functionalities. info = load_information_from_description_file(module_name) if info['post_load']: getattr(sys.modules['odoo.addons.' + module_name], info['post_load'])() except Exception, e: msg = "Couldn't load module %s" % (module_name) _logger.critical(msg) _logger.critical(e) raise else: loaded.append(module_name) def get_modules(): """Returns the list of module names """ def listdir(dir): def clean(name): name = os.path.basename(name) if name[-4:] == '.zip': name = name[:-4] return name def is_really_module(name): for mname in MANIFEST_NAMES: if os.path.isfile(opj(dir, name, mname)): return True return map(clean, filter(is_really_module, os.listdir(dir))) plist =
rest)) return base, symlink, rest if index == len(relfile): break index += 1 return relfile, None, None def kill_children_processes(root): """Not yet implemented on posix.""" # pylint: disable=unused-argument return False def relpath(path, root): """os.path.relpath() that keeps trailing os.path.sep.""" out = os.path.relpath(path, root) if path.endswith(os.path.sep): out += os.path.sep return out def safe_relpath(filepath, basepath): """Do not throw on Windows when filepath and basepath are on different drives. Different than relpath() above since this one doesn't keep the trailing os.path.sep and it swallows exceptions on Windows and return the original absolute path in the case of different drives. """ try: return os.path.relpath(filepath, basepath) except ValueError: assert sys.platform == 'win32' return filepath def normpath(path): """os.path.normpath() that keeps trailing os.path.sep.""" out = os.path.normpath(path) if path.endswith(os.path.sep): out += os.path.sep return out def posix_relpath(path, root): """posix.relpath() that keeps trailing slash. It is different from relpath() since it can be used on Windows. """ out = posixpath.relpath(path, root) if path.endswith('/'): out += '/' return out def is_url(path): """Returns True if it looks like an HTTP url instead of a file path.""" return bool(re.match(r'^https?://.+$', path)) def path_starts_with(prefix, path): """Returns true if the components of the path |prefix| are the same as the initial components of |path| (or all of the components of |path|). The paths must be absolute. """ #assert os.path.isabs(prefix) and os.path.isabs(path) prefix = os.path.normpath(prefix) path = os.path.normpath(path) #assert prefix == get_native_path_case(prefix), prefix #assert path == get_native_path_case(path), path prefix = prefix.rstrip(os.path.sep) + os.path.sep path = path.rstrip(os.path.sep) + os.path.sep return path.startswith(prefix) @tools.profile def fix_native_path_case(root, path): """Ensures that each component of |path| has the proper native case. It does so by iterating slowly over the directory elements of |path|. The file must exist. """ native_case_path = root for raw_part in path.split(os.sep): if not raw_part or raw_part == '.': break part = find_item_native_case(native_case_path, raw_part) if not part: raise OSError( 'File %s doesn\'t exist' % os.path.join(native_case_path, raw_part)) native_case_path = os.path.join(native_case_path, part) return os.path.normpath(native_case_path) def ensure_command_has_abs_path(command, cwd): """Ensures that an isolate command uses absolute path. This is needed since isolate can specify a command relative to 'cwd' and subprocess.call doesn't consider 'cwd' when searching for executable. """ if not os.path.isabs(command[0]): command[0] = os.path.abspath(os.path.join(cwd, command[0])) def is_same_filesystem(path1, path2): """Returns True if both paths are on the same filesystem. This is required to enable the use of hardlinks. """ assert os.path.isabs(path1), path1 assert os.path.isabs(path2), path2 if sys.platform == 'win32': # If the drive letter mismatches, assume it's a separate partition. # TODO(maruel): It should look at the underlying drive, a drive letter could # be a mount point to a directory on another drive. assert re.match(r'^[a-zA-Z]\:\\.*', path1), path1 assert re.match(r'^[a-zA-Z]\:\\.*', path2), path2 if path1[0].lower() != path2[0].lower(): return False return fs.stat(path1).st_dev == fs.stat(path2).st_dev def get_free_space(path): """Returns the number of free bytes. On POSIX platforms, this returns the free space as visible by the current user. On some systems, there's a percentage of the free space on the partition that is only accessible as the root user. """ if sys.platform == 'win32': free_bytes = ctypes.c_ulonglong(0) windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes)) return free_bytes.value # For OSes other than Windows. f = fs.statvfs(path) # pylint: disable=E1101 return f.f_bavail * f.f_frsize ### Write file functions. def hardlink(source, link_name): """Hardlinks a file. Add support for os.link() on Windows. """ assert isinstance(source, six.text_type), source assert isinstance(link_name, six.text_type), link_name if sys.platform == 'win32': if not windll.kernel32.CreateHardLinkW( fs.extend(link_name), fs.extend(source), 0): raise OSError() else: fs.link(source, link_name) def readable_copy(outfile, infile): """Makes a copy of the file that is readable by everyone.""" fs.copy2(infile, outfile) fs.chmod( outfile, fs.stat(outfile).st_mode | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) def set_read_only(path, read_only): """Sets or resets the write bit on a file or directory. Zaps out access to 'group' and 'others'. """ orig_mode = fs.lstat(path).st_mode mode = orig_mode # TODO(maruel): Stop removing GO bits. if read_only: mode &= stat.S_IRUSR|stat.S_IXUSR # 0500 else: mode |= stat.S_IRUSR|stat.S_IWUSR # 0600 if sys.platform != 'win32' and stat.S_ISDIR(mode): mode |= stat.S_IXUSR # 0100 if hasattr(os, 'lchmod'): fs.lchmod(path, mode) # pylint: disable=E1101 else: if stat.S_ISLNK(orig_mode): # Skip symlink without lchmod() support. return # TODO(maruel): Implement proper DACL modification on Windows. fs.chmod(path, mode) def set_read_only_swallow(path, read_only): """Returns if an OSError exception occurred.""" try: set_read_only(path, read_only) except OSError as e: return e return None def remove(filepath): """Removes a file, even if it is read-only.""" # TODO(maruel): Not do it unless necessary since it slows this function # down. if sys.platform == 'win32': # Deleting a read-only file will fail if it is read-only. set_read_only(filepath, False) else: # Deleting a read-only file will fail if the directory is read-only. set_read_only(os.path.dirname(filepath), False) fs.remove(filepath) def try_remove(filepath): """Removes a file without crashing even if it doesn't exist. Returns: True if the removal succeeded. """ try: remove(filepath) return True except OSError: return False def link_file(outfile, infile, action): """Links a file. The type of link depends on |action|. Returns: True if the action was carried on, False if fallback was used. """ if action < 1 or action > COPY: raise ValueError('Unknown mapping action %s' % action) # TODO(maruel): Skip these checks. if not fs.isfile(infile): raise OSError('%s is missing' % infile) if fs.isfile(outfile): raise OSError( '%s already exist; insize:%d; outsize:%d' % (outfile, fs.stat(infile).st_size, fs.stat(outfile).st_size)) if action == COPY: readable_copy(outfile, infile) return True if action in (SYMLINK, SYMLINK_WITH_FALLBACK): try: fs.symlink(infile, outfile) # pylint: disable=E1101 return True except OSError: if action == SYMLINK: raise logging.warning( 'Failed to symlink, falling back to copy %s to %s' % ( infile, outfile)) # Signal caller that fallback copy was used. readable_copy(outfile, infile) return False # HARDLINK or HARDLINK_WITH_FALLBACK. try: hardlink(infile, outfile) return True except OSError as e: if action == HARDLINK: raise OSError('Failed to hardlink %s to %s: %s' % (infile, outfile, e)) # Probably a different file system. logging.warning( 'Failed to hardlink, falling back to copy %s to %s' % ( infile, outfile)) readable_copy(outfile, infile) # Signal caller that fallback copy was used. return False def atomic_replace(path, body): """Atomically replaces content of the file at given path. 'body' will be written to the file as is (as in open(..., 'wb') mode). Does not preserve file attributes. Raises OSError or IOError on errors (e.g. in case the file is locked on Windows). The caller may retry a bunch of times in such cases before giving up. """ assert path and path[-1] != os.sep, path path = os.path.abspath(path) dir_name, base_name = os.path.split(path) fd, tmp_name = tempfile.mkstemp(dir=dir_name, prefix=base_name+'_') try: with os.fdopen(fd, 'wb') as f: f.write(body) f.flush() os.fsync(fd) if sys.platform != 'win32': os.rename(tmp_name, path) else: # Flags are MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH. MoveFileEx(six.text_type(tmp_name), six.text_type(path), 0x1 | 0x8) tmp_name = None # no need to remove it in 'finally' block anymore finally: if tmp_name: try: os.remove(tmp_name) except OSError as e: logging.warning( 'Failed to delete temp file %s in replace_file_content: %s', tmp_name, e) ### Write directory functions. def ensure_tree(path, perm=0o777): """Ensures a directory exists.""" if not fs.isdir(path): try: fs.makedirs(path, perm) except OSError as e: # Do not raise if directory exists. if e.errno != errno.EEXIST or not fs.isdir(path): raise def make_tree_files_read_only(root): """Makes all the files in the directories read only but not the directories themselves. This means files can be created or deleted. """ logging.debug('make_tree_files_read_only(%s)', root) if sys.platform != 'win32': set_read_only(root, False) for dirpath, dirnames, filenames in fs.walk(root, topdown=True): for filename in filenames: set_read_only(os.path.join(dirpath, filename), True) if sys.platform != 'win32': # It must not be done on Windows. for dirname in dirnames: set_read_only(os.path.join(dirpath, dirname), False) def make_tree_deleteable(root): """Changes the appropriate permissions so the files in the directories can be deleted. On Windows, the files are modified. On other platforms, modify the directory. It only does the minimum so the files can be deleted safely. Warning on Windows: since file permission is modified, the file node is modified. This means that for hard-linked files, every directory entry for the file node has its file permission modified. """ logging.debug('file_path.make_tree_deleteable(%s)', root) err = None sudo_failed = False def try_sudo(p): if sys.platform in ('darwin', 'linux2', 'linux') and not sudo_failed: # Try passwordless sudo, just in case. In practice, it is preferable # to use linux capabilities. with open(os.devnull, 'rb') as
i64.trunc_f32_u """ # TODO: in theory this should be solvable in ir-code. opcode = instruction.opcode self._runtime_call(opcode) def gen_const_instruction(self, instruction): """ Generate code for i32.const and friends. """ opcode = instruction.opcode value = self.emit( ir.Const(instruction.args[0], "const", self.get_ir_type(opcode)) ) self.push_value(value) def gen_local_set(self, instruction): opcode = instruction.opcode ty, local_var = self.locals[instruction.args[0].index] value = self.pop_value(ir_typ=ty) self.emit(ir.Store(value, local_var)) if opcode == "local.tee": self.push_value(value) def gen_local_get(self, instruction): ty, local_var = self.locals[instruction.args[0].index] value = self.emit(ir.Load(local_var, "local_get", ty)) self.push_value(value) def gen_global_get(self, instruction): ty, addr = self.globalz[instruction.args[0].index] value = self.emit(ir.Load(addr, "global_get", ty)) self.push_value(value) def gen_global_set(self, instruction): ty, addr = self.globalz[instruction.args[0].index] value = self.pop_value(ir_typ=ty) self.emit(ir.Store(value, addr)) def gen_floor_instruction(self, instruction): opcode = instruction.opcode self._runtime_call(opcode) # TODO: this does not work for all cases: # ir_typ = self.get_ir_type(opcode) # value = self.pop_value(ir_typ) # value = self.emit(ir.Cast(value, 'cast', ir.u64)) # value = self.emit(ir.Cast(value, 'cast', ir_typ)) # self.push_value(value) # Someday we may have a Unary op for this, # or a call into a native runtime lib? # value = self.emit( # ir.Unop('floor', self.pop_value(ir_typ), 'floor', ir_typ)) # self.push_value(value) def gen_neg_instruction(self, instruction): """ Generate code for (f32|f64).neg """ ir_typ = self.get_ir_type(instruction.opcode) value = self.emit(ir.Unop("-", self.pop_value(ir_typ), "neg", ir_typ)) self.push_value(value) def gen_binop(self, instruction): """ Generate code for binary operator """ opcode = instruction.opcode itype, opname = opcode.split(".") op_map = { "add": "+", "sub": "-", "mul": "*", "div": "/", "div_s": "/", "div_u": "/", "rem_s": "%", "rem_u": "%", "and": "&", "or": "|", "xor": "^", "shl": "<<", "shr_u": ">>", "shr_s": ">>", } op = op_map[opname] name = "op_{}".format(opname) ir_typ = self.get_ir_type(itype) b = self.pop_value(ir_typ=ir_typ) a = self.pop_value(ir_typ=ir_typ) do_unsigned = "_u" in opname if do_unsigned: # Unsigned operation, first cast to unsigned: u_ir_typ = {ir.i32: ir.u32, ir.i64: ir.u64}[ir_typ] a = self.emit(ir.Cast(a, "cast", u_ir_typ)) b = self.emit(ir.Cast(b, "cast", u_ir_typ)) value = self.emit(ir.Binop(a, op, b, name, u_ir_typ)) value = self.emit(ir.Cast(value, "cast", ir_typ)) else: value = self.emit(ir.Binop(a, op, b, name, ir_typ)) self.push_value(value) def gen_cmpop(self, instruction): """ Generate code for a comparison operation """ opcode = instruction.opcode itype, opname = opcode.split(".") ir_typ = self.get_ir_type(itype) if opname in ["eqz"]: b = self.emit(ir.Const(0, "zero", ir_typ)) a = self.pop_value(ir_typ=ir_typ) else: b = self.pop_value(ir_typ=ir_typ) a = self.pop_value(ir_typ=ir_typ) is_unsigned = "_u" in opcode if is_unsigned: # Cast to unsigned u_ir_typ = {ir.i32: ir.u32, ir.i64: ir.u64}[ir_typ] a = self.emit(ir.Cast(a, "cast", u_ir_typ)) b = self.emit(ir.Cast(b, "cast", u_ir_typ)) op = self.OPMAP[opname] self.push_value((op, a, b)) # todo: hack; we assume this is the only test in an if def gen_load(self, instruction): """ Generate code for load instruction """ itype, load_op = instruction.opcode.split(".") ir_typ = self.get_ir_type(itype) _, offset = instruction.args address = self.get_memory_address(offset) if load_op == "load": value = self.emit(ir.Load(address, "load", ir_typ)) else: # Load different data-type and cast: load_ir_typ = { "load8_u": ir.u8, "load8_s": ir.i8, "load16_u": ir.u16, "load16_s": ir.i16, "load32_u": ir.u32, "load32_s": ir.i32, }[load_op] value = self.emit(ir.Load(address, "load", load_ir_typ)) value = self.emit(ir.Cast(value, "casted_load", ir_typ)) self.push_value(value) def gen_store(self, instruction): """ Generate code for store instruction """ itype, store_op = instruction.opcode.split(".") ir_typ = self.get_ir_type(itype) # ACHTUNG: alignment and offset are swapped in text: _, offset = instruction.args value = self.pop_value(ir_typ=ir_typ) address = self.get_memory_address(offset) if store_op == "store": self.emit(ir.Store(value, address)) else: store_ir_typ = { "store8": ir.i8, "store16": ir.i16, "store32": ir.i32, }[store_op] value = self.emit(ir.Cast(value, "casted_value", store_ir_typ)) self.emit(ir.Store(value, address)) def get_memory_address(self, offset): """ Emit code to retrieve a memory address """ base = self.pop_value() if base.ty is not ir.ptr: base = self.emit(ir.Cast(base, "cast", ir.ptr)) offset = self.emit(ir.Const(offset, "offset", ir.ptr)) address = self.emit(ir.add(base, offset, "address", ir.ptr)) mem0 = self.emit(ir.Load(self.memory_base_address, "mem0", ir.ptr)) address = self.emit(ir.add(mem0, address, "address", ir.ptr)) return address @property def is_reachable(self): """ Determine if the current position is reachable """ # Attention: # Since block implements iter, one cannot check for bool(block) if # the block is empty.. So we have to check for None here: return self.builder.block is not None def gen_block_instruction(self, instruction): """ Generate start of block """ stack_start = len(self.stack) if self.is_reachable: self.logger.debug("start of block") param_phis, result_phis = self.get_phis(instruction) inner_block = self.new_block() continue_block = self.new_block() self.fill_phis(param_phis) self.emit(ir.Jump(inner_block)) self.builder.set_block(inner_block) for phi in param_phis: self.emit(phi) self.push_value(phi) else: self.logger.debug("start of unreachable block") param_phis = [] result_phis = [] inner_block = None continue_block = None self.block_stack.append( BlockLevel( "block", continue_block, inner_block, param_phis, result_phis, stack_start, ) ) def gen_loop_instruction(self, instruction): """ Generate code for a loop start """ stack_start = len(self.stack) if self.is_reachable: param_phis, result_phis = self.get_phis(instruction) inner_block = self.new_block() continue_block = self.new_block() self.fill_phis(param_phis) self.emit(ir.Jump(inner_block)) self.builder.set_block(inner_block) for phi in param_phis: self.emit(phi) self.push_value(phi) else: param_phis = [] result_phis = None inner_block = None continue_block = None self.block_stack.append( BlockLevel( "loop", continue_block, inner_block, param_phis, result_phis, stack_start, ) ) def gen_end_instruction(self): """ Generate code for end instruction. This is a more or less complex task. It has to deal with unreachable code as well. """ block = self.pop_block() # If we are not unreachable: if self.is_reachable: assert block.continue_block is not None self.emit(ir.Jump(block.continue_block)) if block.typ == "if" and block.inner_block is not None: # We should connect empty else to end block. self.builder.set_block(block.inner_block) # Shortcut-circuit param arguments to result phis: assert len(block.param_phis) == len(block.result_phis) for param_value, result_phi in zip( block.param_phis, block.result_phis ): result_phi.set_incoming(block.inner_block, param_value) self.emit(ir.Jump(block.continue_block)) self.builder.set_block(block.continue_block) # if we close a block that yields values # introduce a phi values for each created value. for phi in block.result_phis: self.logger.debug("Put %s on stack", phi) self.emit(phi) self.push_value(phi) def gen_if_instruction(self, instruction): """ Generate code for an if start """ if self.is_reachable: # todo: we assume that the test is a comparison op, a, b = self.pop_condition() true_block = self.new_block() continue_block = self.new_block() else_block = self.new_block() stack_start = len(self.stack) param_phis, result_phis = self.get_phis(instruction) param_values = [ self.pop_value(ir_typ=phi.ty) for phi in reversed(param_phis) ] param_values.reverse() # Restore stack: for value in param_values: self.push_value(value) # prepare values for then block: for param_value in param_values: self.push_value(param_value) self.emit(ir.CJump(a, op, b, true_block, else_block)) self.builder.set_block(true_block) else: continue_block = None else_block = None param_values = [] result_phis = [] stack_start = len(self.stack) # Store else block as inner block to allow break: self.block_stack.append( BlockLevel( "if", continue_block, else_block, param_values, result_phis, stack_start, ) ) def gen_else_instruction(self): """ Generate code for else instruction """ if_block = self.pop_block() assert if_block.typ == "if" # else_block was stored in inner block else_block = if_block.inner_block continue_block = if_block.continue_block for param_value in if_block.param_phis: self.push_value(param_value) if self.is_reachable: self.emit(ir.Jump(continue_block)) self.builder.set_block(else_block) self.block_stack.append( BlockLevel( "else", continue_block, None, if_block.param_phis, if_block.result_phis, if_block.stack_start, ) ) def gen_call_instruction(self, instruction): """ Generate a function call """ # Call another function! idx = instruction.args[0].index ir_function, signature = self.functions[idx] self._gen_call_helper(ir_function, signature) def gen_call_indirect_instruction(self, instruction): """ Call another function by pointer! """ type_id = instruction.args[0].index signature = self.wasm_types[type_id] func_index = self.pop_value() ptr_size = self.emit(ir.Const(self.ptr_info.size, "ptr_size", ir.i32)) element_offset = self.emit( ir.Cast( self.emit( ir.mul(func_index, ptr_size, "element_offset", ir.i32) ), "element_offset", ir.ptr, ) ) element_address = self.emit( ir.add(self.table_var, element_offset, "element_address", ir.ptr) ) func_ptr = self.emit(ir.Load(element_address, "func_ptr", ir.ptr)) # TODO: how to check function type during runtime? self._gen_call_helper(func_ptr, signature) def _gen_call_helper(self, target, signature): """ Common function calling logic """ self.logger.debug( "Calling function %s with signature %s", target, signature.to_string(), ) args = [self.pop_value() for _ in range(len(signature.params))] # Note that the top of the stack contains the last argument: args.reverse() for arg, arg_type in zip(args, signature.params): ir_typ = self.get_ir_type(arg_type[1]) assert arg.ty is ir_typ if signature.results: if len(signature.results) == 1: ir_typ = self.get_ir_type(signature.results[0]) value = self.emit( ir.FunctionCall(target, args, "call", ir_typ) ) self.push_value(value) else: assert len(signature.results) > 1 # allocate a memory slab, and inject a pointer to it as first argument. data_area_size = len(signature.results) * 8 data_area_alignment = 8 data_area = self.emit( ir.Alloc( "return_values_area", data_area_size, data_area_alignment, ) ) multi_return_ptr = self.emit( ir.AddressOf(data_area, "return_values_ptr") ) args.append(multi_return_ptr) # Invoke function: self.emit(ir.ProcedureCall(target, args)) # Unpack the multiple return values: inc = self.emit(ir.Const(8, "inc", ir.ptr)) for nr, result in enumerate(signature.results): ir_typ = self.get_ir_type(result) value = self.emit( ir.Load( multi_return_ptr, "return_value_{}".format(nr), ir_typ, ) ) self.push_value(value) multi_return_ptr = self.emit( ir.add(multi_return_ptr, inc, "inc", ir.ptr) ) else: self.emit(ir.ProcedureCall(target, args)) def gen_select_instruction(self, instruction): """ Generate code for the select wasm instruction """ # This is roughly equivalent to C-style: a ? b : c op, a, b = self.pop_condition() nein_value, ja_value = self.pop_value(), self.pop_value() ja_block =
<filename>moto/route53/responses.py """Handles Route53 API requests, invokes method and returns response.""" from functools import wraps from urllib.parse import parse_qs, urlparse from jinja2 import Template import xmltodict from moto.core.responses import BaseResponse from moto.route53.exceptions import Route53ClientError, InvalidChangeBatch from moto.route53.models import route53_backend XMLNS = "https://route53.amazonaws.com/doc/2013-04-01/" def error_handler(f): @wraps(f) def _wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Route53ClientError as e: return e.code, e.get_headers(), e.get_body() return _wrapper class Route53(BaseResponse): """Handler for Route53 requests and responses.""" @error_handler def list_or_create_hostzone_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) # Set these here outside the scope of the try/except # so they're defined later when we call create_hosted_zone() vpcid = None vpcregion = None if request.method == "POST": elements = xmltodict.parse(self.body) zone_request = elements["CreateHostedZoneRequest"] if "HostedZoneConfig" in zone_request: zone_config = zone_request["HostedZoneConfig"] comment = zone_config["Comment"] private_zone = zone_config.get("PrivateZone", False) else: comment = None private_zone = False # It is possible to create a Private Hosted Zone without # associating VPC at the time of creation. if private_zone == "true": if zone_request.get("VPC", None) is not None: vpcid = zone_request["VPC"].get("VPCId", None) vpcregion = zone_request["VPC"].get("VPCRegion", None) name = zone_request["Name"] if name[-1] != ".": name += "." delegation_set_id = zone_request.get("DelegationSetId") new_zone = route53_backend.create_hosted_zone( name, comment=comment, private_zone=private_zone, vpcid=vpcid, vpcregion=vpcregion, delegation_set_id=delegation_set_id, ) template = Template(CREATE_HOSTED_ZONE_RESPONSE) return 201, headers, template.render(zone=new_zone) elif request.method == "GET": all_zones = route53_backend.list_hosted_zones() template = Template(LIST_HOSTED_ZONES_RESPONSE) return 200, headers, template.render(zones=all_zones) def list_hosted_zones_by_name_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) query_params = parse_qs(parsed_url.query) dnsname = query_params.get("dnsname") dnsname, zones = route53_backend.list_hosted_zones_by_name(dnsname) template = Template(LIST_HOSTED_ZONES_BY_NAME_RESPONSE) return 200, headers, template.render(zones=zones, dnsname=dnsname, xmlns=XMLNS) def list_hosted_zones_by_vpc_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) query_params = parse_qs(parsed_url.query) vpc_id = query_params.get("vpcid")[0] vpc_region = query_params.get("vpcregion")[0] zones = route53_backend.list_hosted_zones_by_vpc(vpc_id, vpc_region) template = Template(LIST_HOSTED_ZONES_BY_VPC_RESPONSE) return 200, headers, template.render(zones=zones, xmlns=XMLNS) def get_hosted_zone_count_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) num_zones = route53_backend.get_hosted_zone_count() template = Template(GET_HOSTED_ZONE_COUNT_RESPONSE) return 200, headers, template.render(zone_count=num_zones, xmlns=XMLNS) @error_handler def get_or_delete_hostzone_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) zoneid = parsed_url.path.rstrip("/").rsplit("/", 1)[1] if request.method == "GET": the_zone = route53_backend.get_hosted_zone(zoneid) template = Template(GET_HOSTED_ZONE_RESPONSE) return 200, headers, template.render(zone=the_zone) elif request.method == "DELETE": route53_backend.delete_hosted_zone(zoneid) return 200, headers, DELETE_HOSTED_ZONE_RESPONSE @error_handler def rrset_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) method = request.method zoneid = parsed_url.path.rstrip("/").rsplit("/", 2)[1] if method == "POST": elements = xmltodict.parse(self.body) change_list = elements["ChangeResourceRecordSetsRequest"]["ChangeBatch"][ "Changes" ]["Change"] if not isinstance(change_list, list): change_list = [ elements["ChangeResourceRecordSetsRequest"]["ChangeBatch"][ "Changes" ]["Change"] ] # Enforce quotas https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-requests-changeresourcerecordsets # - A request cannot contain more than 1,000 ResourceRecord elements. When the value of the Action element is UPSERT, each ResourceRecord element is counted twice. effective_rr_count = 0 for value in change_list: record_set = value["ResourceRecordSet"] if ( "ResourceRecords" not in record_set or not record_set["ResourceRecords"] ): continue resource_records = list(record_set["ResourceRecords"].values())[0] effective_rr_count += len(resource_records) if value["Action"] == "UPSERT": effective_rr_count += len(resource_records) if effective_rr_count > 1000: raise InvalidChangeBatch error_msg = route53_backend.change_resource_record_sets(zoneid, change_list) if error_msg: return 400, headers, error_msg return 200, headers, CHANGE_RRSET_RESPONSE elif method == "GET": querystring = parse_qs(parsed_url.query) template = Template(LIST_RRSET_RESPONSE) start_type = querystring.get("type", [None])[0] start_name = querystring.get("name", [None])[0] max_items = int(querystring.get("maxitems", ["300"])[0]) if start_type and not start_name: return 400, headers, "The input is not valid" ( record_sets, next_name, next_type, is_truncated, ) = route53_backend.list_resource_record_sets( zoneid, start_type=start_type, start_name=start_name, max_items=max_items, ) template = template.render( record_sets=record_sets, next_name=next_name, next_type=next_type, max_items=max_items, is_truncated=is_truncated, ) return 200, headers, template def health_check_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) method = request.method if method == "POST": json_body = xmltodict.parse(self.body)["CreateHealthCheckRequest"] caller_reference = json_body["CallerReference"] config = json_body["HealthCheckConfig"] health_check_args = { "ip_address": config.get("IPAddress"), "port": config.get("Port"), "type": config["Type"], "resource_path": config.get("ResourcePath"), "fqdn": config.get("FullyQualifiedDomainName"), "search_string": config.get("SearchString"), "request_interval": config.get("RequestInterval"), "failure_threshold": config.get("FailureThreshold"), "health_threshold": config.get("HealthThreshold"), "measure_latency": config.get("MeasureLatency"), "inverted": config.get("Inverted"), "disabled": config.get("Disabled"), "enable_sni": config.get("EnableSNI"), "children": config.get("ChildHealthChecks", {}).get("ChildHealthCheck"), } health_check = route53_backend.create_health_check( caller_reference, health_check_args ) template = Template(CREATE_HEALTH_CHECK_RESPONSE) return 201, headers, template.render(health_check=health_check, xmlns=XMLNS) elif method == "DELETE": health_check_id = parsed_url.path.split("/")[-1] route53_backend.delete_health_check(health_check_id) template = Template(DELETE_HEALTH_CHECK_RESPONSE) return 200, headers, template.render(xmlns=XMLNS) elif method == "GET": template = Template(LIST_HEALTH_CHECKS_RESPONSE) health_checks = route53_backend.list_health_checks() return ( 200, headers, template.render(health_checks=health_checks, xmlns=XMLNS), ) def not_implemented_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) action = "" if "tags" in full_url: action = "tags" elif "trafficpolicyinstances" in full_url: action = "policies" raise NotImplementedError( f"The action for {action} has not been implemented for route 53" ) def list_or_change_tags_for_resource_request(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) id_ = parsed_url.path.split("/")[-1] type_ = parsed_url.path.split("/")[-2] if request.method == "GET": tags = route53_backend.list_tags_for_resource(id_) template = Template(LIST_TAGS_FOR_RESOURCE_RESPONSE) return ( 200, headers, template.render(resource_type=type_, resource_id=id_, tags=tags), ) if request.method == "POST": tags = xmltodict.parse(self.body)["ChangeTagsForResourceRequest"] if "AddTags" in tags: tags = tags["AddTags"] elif "RemoveTagKeys" in tags: tags = tags["RemoveTagKeys"] route53_backend.change_tags_for_resource(id_, tags) template = Template(CHANGE_TAGS_FOR_RESOURCE_RESPONSE) return 200, headers, template.render() def get_change(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": parsed_url = urlparse(full_url) change_id = parsed_url.path.rstrip("/").rsplit("/", 1)[1] template = Template(GET_CHANGE_RESPONSE) return 200, headers, template.render(change_id=change_id, xmlns=XMLNS) @error_handler def list_or_create_query_logging_config_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "POST": json_body = xmltodict.parse(self.body)["CreateQueryLoggingConfigRequest"] hosted_zone_id = json_body["HostedZoneId"] log_group_arn = json_body["CloudWatchLogsLogGroupArn"] query_logging_config = route53_backend.create_query_logging_config( self.region, hosted_zone_id, log_group_arn ) template = Template(CREATE_QUERY_LOGGING_CONFIG_RESPONSE) headers["Location"] = query_logging_config.location return ( 201, headers, template.render(query_logging_config=query_logging_config, xmlns=XMLNS), ) elif request.method == "GET": hosted_zone_id = self._get_param("hostedzoneid") next_token = self._get_param("nexttoken") max_results = self._get_int_param("maxresults") # The paginator picks up named arguments, returns tuple. # pylint: disable=unbalanced-tuple-unpacking (all_configs, next_token,) = route53_backend.list_query_logging_configs( hosted_zone_id=hosted_zone_id, next_token=next_token, max_results=max_results, ) template = Template(LIST_QUERY_LOGGING_CONFIGS_RESPONSE) return ( 200, headers, template.render( query_logging_configs=all_configs, next_token=next_token, xmlns=XMLNS, ), ) @error_handler def get_or_delete_query_logging_config_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) query_logging_config_id = parsed_url.path.rstrip("/").rsplit("/", 1)[1] if request.method == "GET": query_logging_config = route53_backend.get_query_logging_config( query_logging_config_id ) template = Template(GET_QUERY_LOGGING_CONFIG_RESPONSE) return ( 200, headers, template.render(query_logging_config=query_logging_config, xmlns=XMLNS), ) elif request.method == "DELETE": route53_backend.delete_query_logging_config(query_logging_config_id) return 200, headers, "" def reusable_delegation_sets(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": delegation_sets = route53_backend.list_reusable_delegation_sets() template = self.response_template(LIST_REUSABLE_DELEGATION_SETS_TEMPLATE) return ( 200, {}, template.render( delegation_sets=delegation_sets, marker=None, is_truncated=False, max_items=100, ), ) elif request.method == "POST": elements = xmltodict.parse(self.body) root_elem = elements["CreateReusableDelegationSetRequest"] caller_reference = root_elem.get("CallerReference") hosted_zone_id = root_elem.get("HostedZoneId") delegation_set = route53_backend.create_reusable_delegation_set( caller_reference=caller_reference, hosted_zone_id=hosted_zone_id, ) template = self.response_template(CREATE_REUSABLE_DELEGATION_SET_TEMPLATE) return ( 201, {"Location": delegation_set.location}, template.render(delegation_set=delegation_set), ) @error_handler def reusable_delegation_set(self, request, full_url, headers): self.setup_class(request, full_url, headers) parsed_url = urlparse(full_url) ds_id = parsed_url.path.rstrip("/").rsplit("/")[-1] if request.method == "GET": delegation_set = route53_backend.get_reusable_delegation_set( delegation_set_id=ds_id ) template = self.response_template(GET_REUSABLE_DELEGATION_SET_TEMPLATE) return 200, {}, template.render(delegation_set=delegation_set) if request.method == "DELETE": route53_backend.delete_reusable_delegation_set(delegation_set_id=ds_id) template = self.response_template(DELETE_REUSABLE_DELEGATION_SET_TEMPLATE) return 200, {}, template.render() LIST_TAGS_FOR_RESOURCE_RESPONSE = """ <ListTagsForResourceResponse xmlns="https://route53.amazonaws.com/doc/2015-01-01/"> <ResourceTagSet> <ResourceType>{{resource_type}}</ResourceType> <ResourceId>{{resource_id}}</ResourceId> <Tags> {% for key, value in tags.items() %} <Tag> <Key>{{key}}</Key> <Value>{{value}}</Value> </Tag> {% endfor %} </Tags> </ResourceTagSet> </ListTagsForResourceResponse> """ CHANGE_TAGS_FOR_RESOURCE_RESPONSE = """<ChangeTagsForResourceResponse xmlns="https://route53.amazonaws.com/doc/2015-01-01/"> </ChangeTagsForResourceResponse> """ LIST_RRSET_RESPONSE = """<?xml version="1.0" encoding="UTF-8"?> <ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <ResourceRecordSets> {% for record in record_sets %} <ResourceRecordSet> <Name>{{ record.name }}</Name> <Type>{{ record.type_ }}</Type> {% if record.set_identifier %} <SetIdentifier>{{ record.set_identifier }}</SetIdentifier> {% endif %} {% if record.weight %} <Weight>{{ record.weight }}</Weight> {% endif %} {% if record.region %} <Region>{{ record.region }}</Region> {% endif %} {% if record.ttl %} <TTL>{{ record.ttl }}</TTL> {% endif %} {% if record.failover %} <Failover>{{ record.failover }}</Failover> {% endif %} {% if record.geo_location %} <GeoLocation> {% for geo_key in ['ContinentCode','CountryCode','SubdivisionCode'] %} {% if record.geo_location[geo_key] %}<{{ geo_key }}>{{ record.geo_location[geo_key] }}</{{ geo_key }}>{% endif %} {% endfor %} </GeoLocation> {% endif %} {% if record.alias_target %} <AliasTarget> <HostedZoneId>{{ record.alias_target['HostedZoneId'] }}</HostedZoneId> <DNSName>{{ record.alias_target['DNSName'] }}</DNSName> <EvaluateTargetHealth>{{ record.alias_target['EvaluateTargetHealth'] }}</EvaluateTargetHealth> </AliasTarget> {% else %} <ResourceRecords> {% for resource in record.records %} <ResourceRecord> <Value><![CDATA[{{ resource }}]]></Value> </ResourceRecord> {% endfor %} </ResourceRecords> {% endif %} {% if record.health_check %} <HealthCheckId>{{ record.health_check }}</HealthCheckId> {% endif %} </ResourceRecordSet> {% endfor %} </ResourceRecordSets> {% if is_truncated %}<NextRecordName>{{ next_name }}</NextRecordName>{% endif %} {% if is_truncated %}<NextRecordType>{{ next_type }}</NextRecordType>{% endif %} <MaxItems>{{ max_items }}</MaxItems> <IsTruncated>{{ 'true' if is_truncated else 'false' }}</IsTruncated> </ListResourceRecordSetsResponse>""" CHANGE_RRSET_RESPONSE = """<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <ChangeInfo> <Status>INSYNC</Status> <SubmittedAt>2010-09-10T01:36:41.958Z</SubmittedAt> <Id>/change/C2682N5HXP0BZ4</Id> </ChangeInfo> </ChangeResourceRecordSetsResponse>""" DELETE_HOSTED_ZONE_RESPONSE = """<DeleteHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <ChangeInfo> </ChangeInfo> </DeleteHostedZoneResponse>""" GET_HOSTED_ZONE_COUNT_RESPONSE = """<GetHostedZoneCountResponse> xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <HostedZoneCount>{{ zone_count }}</HostedZoneCount> </GetHostedZoneCountResponse>""" GET_HOSTED_ZONE_RESPONSE = """<GetHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <HostedZone> <Id>/hostedzone/{{ zone.id }}</Id> <Name>{{ zone.name }}</Name> <ResourceRecordSetCount>{{ zone.rrsets|count }}</ResourceRecordSetCount> <Config> {% if zone.comment %} <Comment>{{ zone.comment }}</Comment> {% endif %} <PrivateZone>{{ zone.private_zone }}</PrivateZone> </Config> </HostedZone> <DelegationSet> <Id>{{ zone.delegation_set.id }}</Id> <NameServers> {% for name in zone.delegation_set.name_servers %}<NameServer>{{ name }}</NameServer>{% endfor %} </NameServers> </DelegationSet> <VPCs> <VPC> <VPCId>{{zone.vpcid}}</VPCId> <VPCRegion>{{zone.vpcregion}}</VPCRegion> </VPC> </VPCs> </GetHostedZoneResponse>""" CREATE_HOSTED_ZONE_RESPONSE = """<CreateHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> <HostedZone> <Id>/hostedzone/{{ zone.id }}</Id> <Name>{{ zone.name }}</Name> <ResourceRecordSetCount>0</ResourceRecordSetCount> <Config> {% if zone.comment %} <Comment>{{ zone.comment }}</Comment> {% endif %}
# -*- coding: utf-8 -*- # # Copyright 2018 Data61, CSIRO # # 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. """ GAT tests """ from stellargraph.core.graph import StellarGraph from stellargraph.mapper.node_mappers import ( FullBatchNodeGenerator, GraphSAGENodeGenerator, ) from stellargraph.layer import * import keras import keras.backend as K from keras.layers import Input import numpy as np import networkx as nx import pytest import scipy.sparse as sps def example_graph_1(feature_size=None): G = nx.Graph() elist = [(1, 2), (2, 3), (1, 4), (3, 2)] G.add_nodes_from([1, 2, 3, 4], label="default") G.add_edges_from(elist, label="default") # Add example features if feature_size is not None: for v in G.nodes(): G.node[v]["feature"] = np.ones(feature_size) return StellarGraph(G, node_features="feature") else: return StellarGraph(G) class Test_GraphAttention: """ Tests of GraphAttention layer """ N = 10 F_in = 5 F_out = 2 attn_heads = 8 activation = "relu" layer = GraphAttention def get_inputs(self): x_inp = [ Input(batch_shape=(1, self.N, self.F_in)), Input(batch_shape=(1, None), dtype="int32"), Input(batch_shape=(1, self.N, self.N)), ] # For dense matrix, remove batch dimension A_mat = keras.layers.Lambda(lambda A: K.squeeze(A, 0))(x_inp[2]) layer_inp = x_inp[:2] + [A_mat] return x_inp, layer_inp def get_matrix(self, edges=[]): # adjacency matrix with self-loops only A = np.eye(self.N) for e, v in edges: A[e[0], e[1]] = v return [A[None, :, :]] def test_constructor(self): # attn_heads_reduction = "concat": layer = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="concat", activation=self.activation, ) assert layer.units == self.F_out assert layer.attn_heads == self.attn_heads assert layer.output_dim == self.F_out * self.attn_heads assert layer.activation == keras.activations.get(self.activation) # attn_heads_reduction = "average": layer = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="average", activation=self.activation, ) assert layer.output_dim == self.F_out # attn_heads_reduction = "ave": with pytest.raises(ValueError): self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="ave", activation=self.activation, ) def test_apply_concat(self): gat = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="concat", activation=self.activation, kernel_initializer="ones", ) x_inp, layer_inp = self.get_inputs() # Instantiate layer with squeezed matrix x_out = gat(layer_inp) model = keras.Model(inputs=x_inp, outputs=x_out) assert model.output_shape[-1] == self.F_out * self.attn_heads As = self.get_matrix() X = np.ones((1, self.N, self.F_in)) # features all_indices = np.arange(self.N)[None, :] expected = np.ones((self.N, self.F_out * self.attn_heads)) * self.F_in actual = model.predict([X, all_indices] + As) assert np.allclose(actual.squeeze(), expected) def test_apply_average(self): gat = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="average", activation=self.activation, kernel_initializer="ones", attn_kernel_initializer="zeros", bias_initializer="zeros", final_layer=False, ) x_inp, layer_inp = self.get_inputs() # Instantiate layer with squeezed matrix x_out = gat(layer_inp) model = keras.Model(inputs=x_inp, outputs=x_out) assert model.output_shape[-1] == self.F_out X = np.ones((1, self.N, self.F_in)) # features for i in range(self.N): X[:, i, :] = i + 1 As = self.get_matrix() all_indices = np.arange(self.N)[None, :] expected = (X * self.F_in)[..., : self.F_out] actual = model.predict([X, all_indices] + As) assert np.allclose(actual.squeeze(), expected) def test_apply_average_with_neighbours(self): gat_saliency = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="average", activation=self.activation, kernel_initializer="ones", attn_kernel_initializer="zeros", bias_initializer="zeros", final_layer=False, saliency_map_support=True, ) gat_origin = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="average", activation=self.activation, kernel_initializer="ones", attn_kernel_initializer="zeros", bias_initializer="zeros", final_layer=False, saliency_map_support=False, ) x_inp, layer_inp = self.get_inputs() # Instantiate layer with squeezed matrix x_out_saliency = gat_saliency(layer_inp) x_out_origin = gat_origin(layer_inp) model_origin = keras.Model(inputs=x_inp, outputs=x_out_origin) model_saliency = keras.Model(inputs=x_inp, outputs=x_out_saliency) assert model_origin.output_shape[-1] == self.F_out assert model_saliency.output_shape[-1] == self.F_out X = np.zeros((1, self.N, self.F_in)) # features for i in range(self.N): X[:, i, :] = i As = self.get_matrix([((0, 1), 1), ((1, 0), 1)]) all_indices = np.arange(self.N)[None, :] expected = (X * self.F_in)[..., : self.F_out] expected[:, :2] = self.F_in / 2 actual_origin = model_origin.predict([X, all_indices] + As) actual_saliency = model_saliency.predict([X, all_indices] + As) assert np.allclose(expected, actual_origin) assert np.allclose(expected, actual_saliency) def test_layer_config(self): layer = self.layer( units=self.F_out, attn_heads=self.attn_heads, attn_heads_reduction="concat", activation=self.activation, ) conf = layer.get_config() assert conf["units"] == self.F_out assert conf["attn_heads"] == self.attn_heads assert conf["attn_heads_reduction"] == "concat" assert conf["activation"] == self.activation assert conf["use_bias"] == True assert conf["kernel_initializer"]["class_name"] == "VarianceScaling" assert conf["kernel_initializer"]["config"]["distribution"] == "uniform" assert conf["bias_initializer"]["class_name"] == "Zeros" assert conf["kernel_regularizer"] == None assert conf["bias_regularizer"] == None assert conf["kernel_constraint"] == None assert conf["bias_constraint"] == None class Test_GraphAttentionSparse(Test_GraphAttention): """ Tests of GraphAttentionSparse layer """ N = 10 F_in = 5 F_out = 2 attn_heads = 8 activation = "relu" layer = GraphAttentionSparse def get_inputs(self): x_inp = [ Input(batch_shape=(1, self.N, self.F_in)), Input(batch_shape=(1, None), dtype="int32"), Input(batch_shape=(1, None, 2), dtype="int64"), Input(batch_shape=(1, None), dtype="float32"), ] # Test with final_layer=False A_mat = SqueezedSparseConversion(shape=(self.N, self.N))(x_inp[2:]) # For dense matrix, remove batch dimension layer_inp = x_inp[:2] + [A_mat] return x_inp, layer_inp def get_matrix(self, edges=[]): # adjacency matrix with self-loops + edges A_sparse = sps.eye(self.N, format="lil") for e, v in edges: A_sparse[e[0], e[1]] = v # Extract indices & values to feed to tensorflow A_sparse = A_sparse.tocoo() A_indices = np.expand_dims( np.hstack((A_sparse.row[:, None], A_sparse.col[:, None])), 0 ) A_values = np.expand_dims(A_sparse.data, 0) return [A_indices, A_values] class Test_GAT: """ Tests of GAT class """ N = 10 F_in = 5 F_out = 2 attn_heads = 8 layer_sizes = [4, 16] activations = ["relu", "linear"] sparse = False method = "gat" def test_constructor(self): G = example_graph_1(feature_size=self.F_in) gen = FullBatchNodeGenerator(G, sparse=self.sparse, method=self.method) # test error if no activations are passed: with pytest.raises(TypeError): gat = GAT(layer_sizes=self.layer_sizes, generator=gen, bias=True) # test error where layer_sizes is not a list: with pytest.raises(TypeError): gat = GAT( layer_sizes=10, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, ) # test error where layer_sizes values are not valid with pytest.raises(ValueError): gat = GAT( layer_sizes=[4, 0], activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, ) # test for incorrect length of att_heads list: with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=[8, 8, 1], generator=gen, bias=True, ) # test for invalid values in att_heads list: with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=[8, 0], generator=gen, bias=True, ) # test for invalid type of att_heads argument: with pytest.raises(TypeError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=8.0, generator=gen, bias=True, ) # test error where activations is not a list: with pytest.raises(TypeError): gat = GAT( layer_sizes=self.layer_sizes, activations="relu", generator=gen, bias=True, ) # test attn_heads_reduction errors: with pytest.raises(TypeError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, attn_heads_reduction="concat", generator=gen, bias=True, ) with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, attn_heads_reduction=["concat", "concat", "average"], generator=gen, bias=True, ) with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, attn_heads_reduction=["concat", "sum"], generator=gen, bias=True, ) # test error where len(activations) is not equal to len(layer_sizes): with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=["relu"], generator=gen, bias=True, ) # Default attention heads reductions: gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, ) assert gat.activations == self.activations assert gat.attn_heads_reduction == ["concat", "average"] assert gat.generator == gen # User-specified attention heads reductions: gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, attn_heads_reduction=["concat", "concat"], generator=gen, bias=True, ) assert gat.attn_heads_reduction == ["concat", "concat"] def test_gat_node_model_constructor(self): G = example_graph_1(feature_size=self.F_in) gen = FullBatchNodeGenerator(G, sparse=self.sparse, method=self.method) gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, ) assert len(gat.node_model()) == 2 x_in, x_out = gat.node_model() assert len(x_in) == 4 if self.sparse else 3 assert int(x_in[0].shape[-1]) == self.F_in assert K.int_shape(x_in[-1]) == (1, G.number_of_nodes(), G.number_of_nodes()) assert int(x_out.shape[-1]) == self.layer_sizes[-1] def test_gat_sparse_node_model_constructor(self): G = example_graph_1(feature_size=self.F_in) gen = FullBatchNodeGenerator(G, sparse=self.sparse, method=self.method) gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, ) assert len(gat.node_model()) == 2 x_in, x_out = gat.node_model() assert len(x_in) == 4 if self.sparse else 3 assert int(x_in[0].shape[-1]) == self.F_in assert int(x_out.shape[-1]) == self.layer_sizes[-1] def test_gat_node_model_constructor_no_generator(self): G = example_graph_1(feature_size=self.F_in) gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, bias=True, ) assert gat.use_sparse == False with pytest.raises(RuntimeError): x_in, x_out = gat.node_model() x_in, x_out = gat.node_model(num_nodes=1000, feature_size=self.F_in) assert len(x_in) == 4 if self.sparse else 3 assert int(x_in[0].shape[-1]) == self.F_in assert int(x_out.shape[-1]) == self.layer_sizes[-1] def test_gat_node_model_constructor_wrong_generator(self): G = example_graph_1(feature_size=self.F_in) gen = GraphSAGENodeGenerator(G, self.N, [5, 10]) # test error where generator is of the wrong type for GAT: with pytest.raises(ValueError): gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, bias=True, generator=gen, ) def test_gat_node_model_l2norm(self): G = example_graph_1(feature_size=self.F_in) gen = FullBatchNodeGenerator(G, sparse=self.sparse, method=self.method) gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True, normalize="l2", ) gat._layers[1].kernel_initializer = keras.initializers.get("ones") gat._layers[1].attn_kernel_initializer = keras.initializers.get("ones") gat._layers[3].kernel_initializer = keras.initializers.get("ones") gat._layers[3].attn_kernel_initializer = keras.initializers.get("ones") x_in, x_out = gat.node_model() model = keras.Model(inputs=x_in, outputs=x_out) ng = gen.flow(G.nodes()) actual = model.predict_generator(ng) expected = np.ones((G.number_of_nodes(), self.layer_sizes[-1])) * ( 1.0 / G.number_of_nodes() ) assert np.allclose(expected, actual[0]) def test_gat_node_model_no_norm(self): G = example_graph_1(feature_size=self.F_in) gen = FullBatchNodeGenerator(G, sparse=self.sparse, method=self.method) gat = GAT( layer_sizes=self.layer_sizes, activations=self.activations, attn_heads=self.attn_heads, generator=gen, bias=True,
import numpy def assign2D(C, maximize=False): # ASSIGN2D: # Solve the two-dimensional assignment problem with a rectangular # cost matrix C, scanning row-wise. The problem being solved can # be formulated as minimize (or maximize): # \sum_{i=1}^{numRow}\sum_{j=1}^{numCol}C_{i,j}*x_{i,j} # subject to: # \sum_{j=1}^{numCol}x_{i,j}<=1 for all i # \sum_{i=1}^{numRow}x_{i,j}=1 for all j # x_{i,j}=0 or 1. # Assuming that numCol<=numRow. If numCol>numRow, then the # inequality and inequality conditions are switched. A modified # Jonker-Volgenant algorithm is used. # # INPUTS: # C A numRowXnumCol 2D numpy array or matrix matrix that does # not contain any NaNs. Forbidden assignments can be given costs # of +Inf for minimization and -Inf for maximization. # maximize A boolean value. If true, the minimization problem is # transformed into a maximization problem. The default # if this parameter is omitted or an empty matrix # is passed is false. # # OUTPUTS: # gain The sum of the values of the assigned elements in C. If the # problem is infeasible, this is -1. # col4row A length numRow numpy array where the entry in each # element is an assignment of the element in that row to # a column. 0 entries signify unassigned rows. If the # problem is infeasible, this is an empty matrix. # row4col A length numCol numpy array where the entry in each # element is an assignment of the element in that column # to a row. 0 entries signify unassigned columns. If the # problem is infeasible, this is an empty matrix. # # If the number of rows is <= the number of columns, then every row is # assigned to one column; otherwise every column is assigned to one # row. The assignment minimizes the sum of the assigned elements (the # gain). During minimization, assignments can be forbidden by placing # Inf in elements. During maximization, assignment can be forbidden by # placing -Inf in elements. The cost matrix can not contain any -Inf # elements during minimization nor any +Inf elements during # maximization to try to force an assignment. If no complete # assignment can be made with finite cost, then gain, col4row, and # row4col are returned as numpy.empty(0) values. # # The algorithm is described in detail in [1] and [2]. This is a Python # translation of the C and Matlab functions in the # Tracker Component Library of # https://github.com/USNavalResearchLaboratory/TrackerComponentLibrary # # EXAMPLE 1: # import numpy # import assignAlgs # Inf=numpy.inf # C=numpy.array([[Inf, 2, Inf, Inf, 3], # [ 7, Inf, 23, Inf, Inf], # [ 17, 24, Inf, Inf, Inf], # [ Inf, 6, 13, 20, Inf]]) # maximize=False # gain, col4row, row4col=assignAlgs.assign2D(C,maximize) # print(gain) # One will get an optimal assignment having a gain of 47 # # EXAMPLE 2: # This is the example used in [3]. Here, we demonstrate how to form # assignment tuples (index from 1, not 0) from col4row. # import numpy # import assignAlgs # C=numpy.array([[7, 51, 52, 87, 38, 60, 74, 66, 0, 20], # [50, 12, 0, 64, 8, 53, 0, 46, 76, 42], # [27, 77, 0, 18, 22, 48, 44, 13, 0, 57], # [62, 0, 3, 8, 5, 6, 14, 0, 26, 39], # [0, 97, 0, 5, 13, 0, 41, 31, 62, 48], # [79, 68, 0, 0, 15, 12, 17, 47, 35, 43], # [76, 99, 48, 27, 34, 0, 0, 0, 28, 0], # [0, 20, 9, 27, 46, 15, 84, 19, 3, 24], # [56, 10, 45, 39, 0, 93, 67, 79, 19, 38], # [27, 0, 39, 53, 46, 24, 69, 46, 23, 1]]) # maximize=False # gain, col4row, row4col=assignAlgs.assign2D(C,maximize) # tuples=numpy.empty((2,10),dtype=int) # for curRow in range(0,10): # tuples[0,curRow]=curRow+1 # tuples[1,curRow]=col4row[curRow]+1 # print(gain) # print(tuples) # One will see that the gain is 0 and the assigned tuples match what # is in [3]. However, the assigned tuples is NOT obtained by attaching # col4row to row4col. # # REFERENCES: # [1] <NAME>, "On Implementing 2D Rectangular Assignment # Algorithms," IEEE Transactions on Aerospace and Electronic # Systems, vol. 52, no. 4, pp. 1679-1696, Aug. 2016. # [2] <NAME>, "Advances in displaying uncertain estimates of # multiple targets," in Proceedings of SPIE: Signal Processing, # Sensor Fusion, and Target Recognition XXII, vol. 8745, # Baltimore, MD, Apr. 2013. # [3] <NAME>. "An algorithm for ranking all the assignments in # order of increasing cost," Operations Research, vol. 16, no. 3, # pp. 682-687, May-Jun. 1968. # # May 2018 <NAME>, Naval Research Laboratory, Washington D.C. # (UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. # This work was supported by the Office of Naval Research through the # Naval Research Laboratory 6.1 Base Program numRow = C.shape[0] numCol = C.shape[1] totalNumElsInC = C.size didFlip = False if numCol > numRow: C = C.T temp = numRow numRow = numCol numCol = temp didFlip = True # The cost matrix must have all non-negative elements for the # assignment algorithm to work. This forces all of the elements to be # positive. The delta is added back in when computing the gain in the # end. if not maximize: CDelta = numpy.inf idxs = numpy.unravel_index([i for i in range(totalNumElsInC)], C.shape) for i in range(0, totalNumElsInC): idx = (idxs[0][i], idxs[1][i]) if C[idx] < CDelta: CDelta = C[idx] # If C is all positive, do not shift. if CDelta > 0: CDelta = 0 for i in range(0, totalNumElsInC): idx = (idxs[0][i], idxs[1][i]) C[idx] = C[idx] - CDelta else: CDelta = -numpy.inf idxs = numpy.unravel_index([i for i in range(totalNumElsInC)], C.shape) for i in range(0, totalNumElsInC): idx = (idxs[0][i], idxs[1][i]) if C[idx] > CDelta: CDelta = C[idx] # If C is all negative, do not shift. if CDelta < 0: CDelta = 0 for i in range(0, totalNumElsInC): idx = (idxs[0][i], idxs[1][i]) C[idx] = -C[idx] + CDelta CDelta = CDelta * numCol gain, col4row, row4col = assign2DBasic(C) if gain == -1: # The problem is infeasible emptyMat = numpy.empty(0) return emptyMat, emptyMat, emptyMat else: # The problem is feasible. Adjust for the shifting of the elements # in C. if not maximize: gain = gain + CDelta else: gain = -gain + CDelta # If a transposed matrix was used if didFlip: temp = col4row col4row = row4col row4col = temp return gain, col4row, row4col def assign2DBasic(C): numRow = C.shape[0] numCol = C.shape[1] col4row = numpy.full(numRow, -1, dtype=int) row4col = numpy.full(numCol, -1, dtype=int) u = numpy.zeros(numCol) v = numpy.zeros(numRow) ScannedColIdx = numpy.empty(numCol, dtype=int) pred = numpy.empty(numRow, dtype=int) Row2Scan = numpy.empty(numRow, dtype=int) shortestPathCost = numpy.empty(numRow) for curUnassignedCol in range(0, numCol): # First, find the shortest augmenting path starting at # curUnassignedCol. # Mark everything as not yet scanned. A 1 will be placed in each # row entry as it is scanned. numColsScanned = 0 scannedRows = numpy.zeros(numRow, dtype=bool) for curRow in range(0, numRow): Row2Scan[curRow] = curRow # Initially, the cost of the shortest path to each row is not # known and will be made infinite. shortestPathCost[curRow] = numpy.inf # All rows need to be scanned numRow2Scan = numRow # pred will be used to keep track of the shortest path. # sink will hold the final index of the shortest augmenting path. # If the problem is not feasible, then sink will remain -1. sink = -1 delta = 0 curCol = curUnassignedCol while sink == -1: # Mark the current column as having been visited. ScannedColIdx[numColsScanned] = curCol numColsScanned = numColsScanned + 1 minVal = numpy.inf for curRowScan in range(0, numRow2Scan): curRow = Row2Scan[curRowScan] reducedCost = \ delta + C[curRow, curCol] - u[curCol] - v[curRow] if reducedCost < shortestPathCost[curRow]: pred[curRow] = curCol shortestPathCost[curRow] = reducedCost if shortestPathCost[curRow] < minVal: minVal = shortestPathCost[curRow] closestRowScan
<reponame>dperl-sol/cctbx_project<gh_stars>0 from __future__ import absolute_import, division, print_function import cctbx.array_family.flex # import dependency import boost_adaptbx.boost.python as bp from six.moves import zip from six.moves import range ext = bp.import_ext("mmtbx_ncs_ext") from scitbx.array_family import flex from cctbx import sgtbx from libtbx import adopt_init_args from scitbx import lbfgsb import math import scitbx.math from scitbx.math import matrix import sys from scitbx.math import superpose import mmtbx.alignment from libtbx.test_utils import approx_equal from boost_adaptbx import graph from boost_adaptbx.graph import connected_component_algorithm import iotbx.pdb class groups(object): def __init__(self, pdb_hierarchy, crystal_symmetry, angular_difference_threshold_deg=5., sequence_identity_threshold=90., quiet=False): h = pdb_hierarchy superposition_threshold = 2*sequence_identity_threshold - 100. n_atoms_all = h.atoms_size() s_str = "altloc ' ' and (protein or nucleotide)" h = h.select(h.atom_selection_cache().selection(s_str)) h1 = iotbx.pdb.hierarchy.root() h1.append_model(h.models()[0].detached_copy()) unit_cell = crystal_symmetry.unit_cell() result = {} if not quiet: print("Find groups of chains related by translational NCS") # double loop over chains to find matching pairs related by pure translation for c1 in h1.chains(): c1.parent().remove_chain(c1) nchains = len(h1.models()[0].chains()) if([c1.is_protein(), c1.is_na()].count(True)==0): continue r1 = list(c1.residues()) c1_seq = "".join(c1.as_sequence()) sc_1_tmp = c1.atoms().extract_xyz() h1_p1 = h1.expand_to_p1(crystal_symmetry=crystal_symmetry) for (ii,c2) in enumerate(h1_p1.chains()): orig_c2 = h1.models()[0].chains()[ii%nchains] r2 = list(c2.residues()) c2_seq = "".join(c2.as_sequence()) sites_cart_1, sites_cart_2 = None,None sc_2_tmp = c2.atoms().extract_xyz() # chains are identical if(c1_seq==c2_seq and sc_1_tmp.size()==sc_2_tmp.size()): sites_cart_1 = sc_1_tmp sites_cart_2 = sc_2_tmp p_identity = 100. # chains are not identical, do alignment else: align_obj = mmtbx.alignment.align(seq_a = c1_seq, seq_b = c2_seq) alignment = align_obj.extract_alignment() matches = alignment.matches() equal = matches.count("|") total = len(alignment.a) - alignment.a.count("-") p_identity = 100.*equal/max(1,total) if(p_identity>superposition_threshold): sites_cart_1 = flex.vec3_double() sites_cart_2 = flex.vec3_double() for i1, i2, match in zip(alignment.i_seqs_a, alignment.i_seqs_b, matches): if(i1 is not None and i2 is not None and match=="|"): r1i, r2i = r1[i1], r2[i2] assert r1i.resname==r2i.resname, [r1i.resname,r2i.resname,i1,i2] for a1 in r1i.atoms(): for a2 in r2i.atoms(): if(a1.name == a2.name): sites_cart_1.append(a1.xyz) sites_cart_2.append(a2.xyz) break # superpose two sequence-aligned chains if([sites_cart_1,sites_cart_2].count(None)==0): lsq_fit_obj = superpose.least_squares_fit( reference_sites = sites_cart_1, other_sites = sites_cart_2) angle = lsq_fit_obj.r.rotation_angle() t_frac = unit_cell.fractionalize((sites_cart_1-sites_cart_2).mean()) t_frac = [math.modf(t)[0] for t in t_frac] # put into [-1,1] radius = flex.sum(flex.sqrt((sites_cart_1- sites_cart_1.mean()).dot()))/sites_cart_1.size()*4./3. fracscat = min(c1.atoms_size(),c2.atoms_size())/n_atoms_all result.setdefault( frozenset([c1,orig_c2]), [] ).append( [p_identity,[lsq_fit_obj.r, t_frac, angle, radius, fracscat]] ) else: result.setdefault( frozenset([c1,orig_c2]), [] ).append( [p_identity,None] ) # Build graph g = graph.adjacency_list() vertex_handle = {} for key in result: seqid = result[key][0][0] sup = min( result[key],key=lambda s:0 if s[1] is None else s[1][2])[1] result[key] = [seqid,sup] if ((seqid > sequence_identity_threshold) and (sup[2] < angular_difference_threshold_deg)): (c1,c2) = key if (c1 not in vertex_handle): vertex_handle[c1] = g.add_vertex(label=c1) if (c2 not in vertex_handle): vertex_handle[c2] = g.add_vertex(label=c2) g.add_edge(vertex1=vertex_handle[c1],vertex2=vertex_handle[c2]) # Do connected component analysis and compose final tNCS pairs object components = connected_component_algorithm.connected_components(g) import itertools self.ncs_pairs = [] self.tncsresults = [ 0, "", [], 0.0 ] for (i,group) in enumerate(components): chains = [g.vertex_label(vertex=v) for v in group] fracscats = [] radii = [] for pair in itertools.combinations(chains,2): sup = result[frozenset(pair)][1] fracscats.append(sup[-1]) radii.append(sup[-2]) fs = sum(fracscats)/len(fracscats) self.tncsresults[3] = fs # store fracscat in array rad = sum(radii)/len(radii) #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) ) maxorder = 1 vectors = [] previous_id = next(itertools.combinations(chains,2))[0].id for pair in itertools.combinations(chains,2): sup = result[frozenset(pair)][1] ncs_pair = ext.pair( r = sup[0], t = sup[1], radius = rad, radius_estimate = rad, fracscat = fs, rho_mn = flex.double(), # rho_mn undefined, needs to be set later id = i) self.ncs_pairs.append(ncs_pair) # show tNCS pairs in group fmt="group %d chains %s <> %s angle: %4.2f trans.vect.: (%s) fracscat: %5.3f" t = ",".join([("%6.3f"%t_).strip() for t_ in sup[1]]).strip() if not quiet: print(fmt%(i, pair[0].id, pair[1].id, sup[2], t, fs)) if pair[0].id == previous_id: maxorder += 1 orthoxyz = unit_cell.orthogonalize( sup[1] ) vectors.append(( sup[1], orthoxyz, sup[2] )) else: previous_id = pair[0].id maxorder = 1 vectors = [] if maxorder > self.tncsresults[0]: self.tncsresults[0] = maxorder self.tncsresults[1] = previous_id self.tncsresults[2] = vectors if not quiet: print("Largest TNCS order, peptide chain, fracvector, orthvector, angle, fracscat = ", \ str(self.tncsresults)) #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) ) def initialize_rho_mn(ncs_pairs, d_spacings_data, binner, rms=0.5): """ Initialize rho_mn rhoMN = exp(-(2*pi^2/3)*(rms/d)^2, and rms=0.4-0.8 is probably a good guess. """ n_bins = binner.n_bins_used() rho_mn_initial = flex.double(n_bins, 0) cntr=0 for i_bin in binner.range_used(): sel_bin = binner.selection(i_bin) if(sel_bin.count(True)>0): arg = (2*math.pi**2/3)*(rms/flex.mean(d_spacings_data.select(sel_bin)))**2 rho_mn_initial[cntr] = math.exp(-1*arg) cntr+=1 for p in ncs_pairs: p.set_rhoMN(rho_mn_initial) def lbfgs_run(target_evaluator, use_bounds, lower_bound, upper_bound, max_iterations=None): minimizer = lbfgsb.minimizer( n = target_evaluator.n, #factr=1.e+1, XXX Affects speed significantly l = lower_bound, # lower bound u = upper_bound, # upper bound nbd = flex.int(target_evaluator.n, use_bounds)) # flag to apply both bounds minimizer.error = None try: icall = 0 while 1: icall += 1 x, f, g = target_evaluator() #print "x,f:", ",".join(["%6.3f"%x_ for x_ in x]), f, icall have_request = minimizer.process(x, f, g) if(have_request): requests_f_and_g = minimizer.requests_f_and_g() continue assert not minimizer.requests_f_and_g() if(minimizer.is_terminated()): break # XXX temp fix for python3 failure (run_lbfgs in tncs) # Failure is that max_iterations is None # temp fix is to break if max_iterations is None or icall>max_iterations #if(icall>max_iterations): break if ((max_iterations is None) or (icall>max_iterations)): break except RuntimeError as e: minimizer.error = str(e) minimizer.n_calls = icall return minimizer class minimizer(object): def __init__(self, potential, use_bounds, lower_bound, upper_bound, initial_values): adopt_init_args(self, locals()) self.x = initial_values self.n = self.x.size() def run(self): self.minimizer = lbfgs_run( target_evaluator=self, use_bounds=self.use_bounds, lower_bound = self.lower_bound, upper_bound = self.upper_bound) self() return self def __call__(self): self.potential.update(x = self.x) self.f = self.potential.target() self.g = self.potential.gradient() return self.x, self.f, self.g class potential(object): def __init__(self, f_obs, ncs_pairs, reflections_per_bin): adopt_init_args(self, locals()) # Create bins f_obs.setup_binner(reflections_per_bin = reflections_per_bin) self.binner = f_obs.binner() n_bins = self.binner.n_bins_used() self.n_bins = n_bins self.SigmaN = None self.update_SigmaN() # self.rbin = flex.int(f_obs.data().size(), -1) for i_bin in self.binner.range_used(): for i_seq in self.binner.array_indices(i_bin): self.rbin[i_seq] = i_bin-1 # i_bin starts with 1, not 0 ! assert flex.min(self.rbin)==0 assert flex.max(self.rbin)==n_bins-1 # Extract symmetry matrices self.sym_matrices = [] for m_as_string in f_obs.space_group().smx(): o = sgtbx.rt_mx(symbol=str(m_as_string), t_den=f_obs.space_group().t_den()) m_as_double = o.r().as_double() self.sym_matrices.append(m_as_double) self.gradient_evaluator = None self.target_and_grads = ext.tncs_eps_factor_refinery( tncs_pairs = self.ncs_pairs, f_obs = self.f_obs.data(), sigma_f_obs = self.f_obs.sigmas(), rbin = self.rbin, SigmaN = self.SigmaN, space_group = self.f_obs.space_group(), miller_indices = self.f_obs.indices(), fractionalization_matrix = self.f_obs.unit_cell().fractionalization_matrix(), sym_matrices = self.sym_matrices) self.update() def update(self, x=None): if(self.gradient_evaluator=="rhoMN"): size = len(self.ncs_pairs) for i, ncs_pair in enumerate(self.ncs_pairs): ncs_pair.set_rhoMN(x[i*self.n_bins:(i+1)*self.n_bins]) self.target_and_grads.update_pairs(self.ncs_pairs) elif(self.gradient_evaluator=="radius"): for ncs_pair, x_ in zip(self.ncs_pairs, x): ncs_pair.set_radius(x_) self.target_and_grads = ext.tncs_eps_factor_refinery( tncs_pairs = self.ncs_pairs, f_obs = self.f_obs.data(), sigma_f_obs = self.f_obs.sigmas(), rbin = self.rbin, SigmaN = self.SigmaN, space_group = self.f_obs.space_group(), miller_indices = self.f_obs.indices(), fractionalization_matrix = self.f_obs.unit_cell().fractionalization_matrix(), sym_matrices = self.sym_matrices) self.target_and_grads.set_compute_gradients_radius() def update_SigmaN(self): if(self.SigmaN is None): eps = self.f_obs.epsilons().data().as_double() else: eps = self.target_and_grads.tncs_epsfac() self.SigmaN = flex.double(self.f_obs.data().size(), 0) for i_bin in self.binner.range_used(): bin_sel = self.f_obs.binner().selection(i_bin) f_obs_bin = self.f_obs.select(bin_sel) f_obs_bin_data = f_obs_bin.data() f_obs_bin_data_size = f_obs_bin_data.size() if(f_obs_bin_data_size>0): eps_bin = eps.select(bin_sel) sn = flex.sum(f_obs_bin_data*f_obs_bin_data/eps_bin)/f_obs_bin_data_size self.SigmaN = self.SigmaN.set_selected(bin_sel, sn) assert self.SigmaN.all_gt(0) def set_refine_radius(self): self.gradient_evaluator = "radius" self.target_and_grads.set_compute_gradients_radius() return self def set_refine_rhoMN(self): self.gradient_evaluator = "rhoMN" self.target_and_grads.set_compute_gradients_rho_mn() return self def target(self): return self.target_and_grads.target() def gradient(self): if(self.gradient_evaluator=="rhoMN"): return self.target_and_grads.gradient_rhoMN() elif(self.gradient_evaluator=="radius"): return self.target_and_grads.gradient_radius() else: assert 0 def finite_differences_grad_radius(ncs_pairs, f_obs, reflections_per_bin, tolerance): reflections_per_bin = min(f_obs.data().size(), reflections_per_bin) f_obs.setup_binner(reflections_per_bin = reflections_per_bin) binner = f_obs.binner() n_bins = binner.n_bins_used() # radii = flex.double() for ncs_pair in ncs_pairs: radii.append(ncs_pair.radius) # pot = potential(f_obs = f_obs, ncs_pairs = ncs_pairs, reflections_per_bin = reflections_per_bin) pot = pot.set_refine_radius() t = pot.target() g_exact = pot.gradient() #print "Exact:", list(g_exact) # eps = 1.e-4 # g_fd = [] for i, rad in enumerate(radii): radii_p = radii.deep_copy() radii_m = radii.deep_copy() radii_p[i] = radii[i]+eps radii_m[i] = radii[i]-eps # pot.update(x = flex.double(radii_p)) t1 = pot.target() # pot.update(x = flex.double(radii_m)) t2 = pot.target() # g_fd_ = (t1-t2)/(2*eps) g_fd.append(g_fd_) #print "Finite diff.:",g_fd relative_error = flex.double() for g1,g2 in zip(g_exact, g_fd): #print "exact: %10.6f fd: %10.6f"%(g1,g2) relative_error.append( abs((g1-g2)/(g1+g2))*2.*100. ) mmm = relative_error.min_max_mean().as_tuple() print("min/max/mean of |(g_exact-g_fd)/(g_exact+g_fd)|*100.*2:",\ "%6.4f %6.4f %6.4f"%mmm) # assert approx_equal(mmm, [0,0,0], tolerance) # reinstate after proper constraints def finite_differences_rho_mn(ncs_pairs, f_obs, reflections_per_bin, tolerance): reflections_per_bin = min(f_obs.data().size(), reflections_per_bin) f_obs.setup_binner(reflections_per_bin = reflections_per_bin) binner = f_obs.binner() n_bins = binner.n_bins_used() # pot = potential(f_obs = f_obs, ncs_pairs = ncs_pairs, reflections_per_bin = reflections_per_bin) pot = pot.set_refine_rhoMN() t = pot.target() g_exact = pot.gradient() # rho_mn = flex.double() for p in ncs_pairs: rho_mn.extend(p.rho_mn) # eps = 1.e-6 # g_fd = [] for i, rho_mn_i in enumerate(rho_mn): rho_mn_p = rho_mn.deep_copy() rho_mn_p[i] = rho_mn_i + eps rho_mn_m = rho_mn.deep_copy() rho_mn_m[i] = rho_mn_i - eps # pot.update(x = rho_mn_p) t1 = pot.target() # pot.update(x = rho_mn_m) t2 = pot.target() # g_fd_ = (t1-t2)/(2*eps) g_fd.append(g_fd_)
from swsscommon import swsscommon import os import sys import time import json import pytest from distutils.version import StrictVersion def create_entry(tbl, key, pairs): fvs = swsscommon.FieldValuePairs(pairs) tbl.set(key, fvs) # FIXME: better to wait until DB create them time.sleep(1) def remove_entry_tbl(db, table, key): tbl = swsscommon.Table(db, table) tbl._del(key) # FIXME: better to wait until DB create them time.sleep(1) def create_entry_tbl(db, table, key, pairs): tbl = swsscommon.Table(db, table) create_entry(tbl, key, pairs) def how_many_entries_exist(db, table): tbl = swsscommon.Table(db, table) return len(tbl.getKeys()) def test_negativeFDB(dvs, testlog): dvs.setup_db() #dvs.runcmd("sonic-clear fdb all") time.sleep(2) #Find switch_id switch_id = dvs.getSwitchOid() print("Switch_id="+str(switch_id)) vlan_before = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_VLAN") bp_before = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT") vm_before = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_VLAN_MEMBER") # create vlan dvs.create_vlan("2") dvs.create_vlan_member("2", "Ethernet0") dvs.create_vlan_member("2", "Ethernet4") # Find the vlan_oid_2 to be used in DB communications vlan_oid_2 = dvs.getVlanOid("2") assert vlan_oid_2 is not None, "Could not find Vlan_oid" print("VLan-2 vlan_oid="+str(vlan_oid_2)) # create vlan dvs.create_vlan("4") dvs.create_vlan_member("4", "Ethernet8") # Find the vlan_oid_4 to be used in DB communications vlan_oid_4 = dvs.getVlanOid("4") assert vlan_oid_4 is not None, "Could not find Vlan_oid" print("VLan-4 vlan_oid="+str(vlan_oid_4)) dvs.create_vlan("10") dvs.create_vlan_member("10", "Ethernet12") # Find the vlan_oid_10 to be used in DB communications vlan_oid_10 = dvs.getVlanOid("10") assert vlan_oid_10 is not None, "Could not find Vlan_oid" print("VLan-10 vlan_oid="+str(vlan_oid_10)) # check that the vlan information was propagated vlan_after = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_VLAN") bp_after = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT") vm_after = how_many_entries_exist(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_VLAN_MEMBER") assert vlan_after - vlan_before == 3, "The Vlan2/Vlan4 wasn't created" assert bp_after - bp_before == 4, "The bridge port wasn't created" assert vm_after - vm_before == 4, "The vlan member wasn't added" # Get mapping between interface name and its bridge port_id iface_2_bridge_port_id = dvs.get_map_iface_bridge_port_id(dvs.adb) #dvs.runcmd("swssloglevel -l DEBUG -c orchagent") #dvs.runcmd("swssloglevel -l DEBUG -c vlanmgrd") print("NEG1 - Add MAC address to an out of range vlan and later delete it") mac = "52:54:00:25:06:E9" #dvs.runcmd("config mac add " + mac.lower() + " 3 Ethernet0") print("ACTION: Creating static FDB Vlan33333|"+mac.lower()+"|Ethernet0 in CONFIG-DB") create_entry_tbl( dvs.cdb, "FDB", "Vlan33333|"+mac.lower(), [ ("port", "Ethernet0"), ] ) time.sleep(2) # check that the FDB entry was added in Config DB print("CHECK: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is created in Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan33333\|"+mac.lower(), [("port", "Ethernet0")] ) assert mac1_found, str(extra) print("CONFIRM: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is created in Config-DB") # check that the FDB entry was not added in APP DB print("CHECK: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is not created in APP-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.pdb, "FDB_TABLE", "Vlan33333:"+mac.lower(), [("port", "Ethernet0"), ("type", "static"), ] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is not created in APP-DB") print("ACTION: Deleting Static FDB Vlan33333:"+mac.lower()+":Ethernet0") remove_entry_tbl(dvs.cdb, "FDB", "Vlan33333|"+mac.lower()) time.sleep(2) #Check the mac is removed from config-db print("CHECK: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is deleted from Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan33333\|"+mac.lower(), [("port", "Ethernet0")] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan33333:"+mac.lower()+":Ethernet0 is deleted from Config-DB") print("NEG2 - Add MAC address to a vlan which does not exist and later delete it") mac = "52:54:00:25:06:E9" #dvs.runcmd("config mac add " + mac.lower() + " 3 Ethernet0") print("ACTION: Creating static FDB Vlan3:"+mac.lower()+":Ethernet0 in CONFIG-DB") create_entry_tbl( dvs.cdb, "FDB", "Vlan3|"+mac.lower(), [ ("port", "Ethernet0"), ] ) time.sleep(2) # check that the FDB entry was added in Config DB print("CHECK: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is created in Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan3\|"+mac.lower(), [("port", "Ethernet0")] ) assert mac1_found, str(extra) print("CONFIRM: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is created in Config-DB") # check that the FDB entry was added in APP DB print("CHECK: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is created in APP-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.pdb, "FDB_TABLE", "Vlan3:"+mac.lower(), [("port", "Ethernet0"), ("type", "static"), ] ) assert mac1_found, str(extra) print("CONFIRM: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is created in APP-DB") # check that the FDB entry is not inserted into ASIC DB print("CHECK: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is not created in ASIC-DB") ok, extra = dvs.is_fdb_entry_exists(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_FDB_ENTRY", [("mac", mac.lower())], [("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_STATIC")] ) assert ok == False, str(extra) print("CONFIRM: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is not created in ASIC-DB") print("ACTION: Deleting Static FDB Vlan3:"+mac.lower()+"Ethernet0") remove_entry_tbl(dvs.cdb, "FDB", "Vlan3|"+mac.lower()) time.sleep(2) #Check the mac is removed from config-db print("CHECK: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is deleted from Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan3\|"+mac.lower(), [("port", "Ethernet0")] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is deleted from Config-DB") # check that the FDB entry is removed from APP DB print("CHECK: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is deleted from APP-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.pdb, "FDB_TABLE", "Vlan3:"+mac.lower(), [("port", "Ethernet0"), ("type", "static"), ] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan3:"+mac.lower()+":Ethernet0 is deleted from APP-DB") print("NEG3 - Add MAC address to an invalid port which does not exist and later delete it") mac = "52:54:00:25:06:E9" #dvs.runcmd("config mac add " + mac.lower() + " 3 Ethernet0") print("ACTION: Creating static FDB Vlan2:"+mac.lower()+":Port0 in CONFIG-DB") create_entry_tbl( dvs.cdb, "FDB", "Vlan2|"+mac.lower(), [ ("port", "Port0"), ] ) time.sleep(2) # check that the FDB entry was added in Config DB print("CHECK: Static FDB Vlan2:"+mac.lower()+":Port0 is created in Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan2\|"+mac.lower(), [("port", "Port0")] ) assert mac1_found, str(extra) print("CONFIRM: Static FDB Vlan2:"+mac.lower()+":Port0 is created in Config-DB") # check that the FDB entry was added in APP DB print("CHECK: Static FDB Vlan2:"+mac.lower()+":Port0 is created in APP-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.pdb, "FDB_TABLE", "Vlan2:"+mac.lower(), [("port", "Port0"), ("type", "static"), ] ) assert mac1_found, str(extra) print("CONFIRM: Static FDB Vlan2:"+mac.lower()+"Port0 is created in APP-DB") # check that the FDB entry is not inserted into ASIC DB print("CHECK: Static FDB Vlan2:"+mac.lower()+":Port0 is not created in ASIC-DB") ok, extra = dvs.is_fdb_entry_exists(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_FDB_ENTRY", [("mac", mac.lower())], [("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_STATIC")] ) assert ok == False, str(extra) print("CONFIRM: Static FDB Vlan2:"+mac.lower()+":Port0 is not created in ASIC-DB") print("ACTION: Removing static FDB Vlan2:"+mac.lower()+":Port0 from CONFIG-DB") remove_entry_tbl(dvs.cdb, "FDB", "Vlan2|"+mac.lower()) time.sleep(2) #Check the mac is removed from config-db print("CHECK: Static FDB Vlan2:"+mac.lower()+":Port0 is deleted from Config-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.cdb, "FDB", "Vlan2\|"+mac.lower(), [("port", "Port0")] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan2:"+mac.lower()+":Port0 is deleted from Config-DB") # check that the FDB entry is removed from APP DB print("CHECK: Static FDB Vlan2:"+mac.lower()+":Port0 is deleted from APP-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.pdb, "FDB_TABLE", "Vlan2:"+mac.lower(), [("port", "Port0"), ("type", "static"), ] ) assert mac1_found == False, str(extra) print("CONFIRM: Static FDB Vlan2:"+mac.lower()+":Port0 is deleted from APP-DB") print("NEG4 - simulate mac learn event for a port which is not part of vlan") bp_eth8 = iface_2_bridge_port_id["Ethernet8"] dvs.remove_vlan_member("4", "Ethernet8") print("ACTION Creating FDB Vlan4:52-54-00-25-06-E9:Ethernet8 in ASIC-DB") create_entry_tbl( dvs.adb, "ASIC_STATE", "SAI_OBJECT_TYPE_FDB_ENTRY:{\"bvid\":\""+vlan_oid_4+"\",\"mac\":\"52:54:00:25:06:E9\",\"switch_id\":\""+switch_id+"\"}", [ ("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_DYNAMIC"), ("SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID", bp_eth8), ] ) ntf = swsscommon.NotificationProducer(dvs.adb, "FDB_NOTIFICATIONS") fvp = swsscommon.FieldValuePairs() ntf_data = "[{\"fdb_entry\":\"{\\\"bvid\\\":\\\""+vlan_oid_4+"\\\",\\\"mac\\\":\\\"52:54:00:25:06:E9\\\",\\\"switch_id\\\":\\\""+switch_id+"\\\"}\",\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\",\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\""+bp_eth8+"\"}]}]" ntf.send("fdb_event", ntf_data, fvp) time.sleep(2) # check that the FDB entry was added in ASIC DB print("CHECK: FDB Vlan4:52-54-00-25-06-E9:Ethernet8 is created in ASIC-DB") ok, extra = dvs.is_fdb_entry_exists(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_FDB_ENTRY", [("mac", "52:54:00:25:06:E9"), ("bvid", vlan_oid_4)], [("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_DYNAMIC"), ("SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID", bp_eth8)] ) assert ok, str(extra) print("CONFIRM: FDB Vlan4:52-54-00-25-06-E9:Ethernet8 is created in ASIC-DB") # check that the FDB entry was not added in STATE DB print("CHECK: FDB Vlan4:52-54-00-25-06-E9:Ethernet8 is not created in STATE-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.sdb, "FDB_TABLE", "Vlan4:52:54:00:25:06:e9", [("port", "Ethernet8"), ("type", "dynamic"), ] ) assert mac1_found == False, str(extra) print("CONFIRM: FDB Vlan4:52-54-00-25-06-E9:Ethernet8 is not created in STATE-DB") print("NEG5 - simulate mac learn event for a vlan which does not exist") bp_eth12 = iface_2_bridge_port_id["Ethernet12"] dvs.remove_vlan_member("10", "Ethernet12") dvs.remove_vlan("10") print("ACTION: Creating FDB Vlan10:52-54-00-25-06-E9:Ethernet12 in ASIC-DB") create_entry_tbl( dvs.adb, "ASIC_STATE", "SAI_OBJECT_TYPE_FDB_ENTRY:{\"bvid\":\""+vlan_oid_10+"\",\"mac\":\"52:54:00:25:06:E9\",\"switch_id\":\""+switch_id+"\"}", [ ("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_DYNAMIC"), ("SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID", bp_eth12), ] ) ntf = swsscommon.NotificationProducer(dvs.adb, "FDB_NOTIFICATIONS") fvp = swsscommon.FieldValuePairs() ntf_data = "[{\"fdb_entry\":\"{\\\"bvid\\\":\\\""+vlan_oid_10+"\\\",\\\"mac\\\":\\\"52:54:00:25:06:E9\\\",\\\"switch_id\\\":\\\""+switch_id+"\\\"}\",\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\",\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\""+bp_eth12+"\"}]}]" ntf.send("fdb_event", ntf_data, fvp) time.sleep(2) # check that the FDB entry was added in ASIC DB print("CHECK: FDB Vlan10:52-54-00-25-06-E9:Ethernet12 is created in ASIC-DB") ok, extra = dvs.is_fdb_entry_exists(dvs.adb, "ASIC_STATE:SAI_OBJECT_TYPE_FDB_ENTRY", [("mac", "52:54:00:25:06:E9"), ("bvid", vlan_oid_10)], [("SAI_FDB_ENTRY_ATTR_TYPE", "SAI_FDB_ENTRY_TYPE_DYNAMIC"), ("SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID", bp_eth12)] ) assert ok, str(extra) print("CONFIRM: FDB Vlan10:52-54-00-25-06-E9:Ethernet12 is created in ASIC-DB") # check that the FDB entry was not added in STATE DB print("CHECK: FDB Vlan10:52-54-00-25-06-E9:Ethernet12 is not created in STATE-DB") mac1_found, extra = dvs.is_table_entry_exists(dvs.sdb, "FDB_TABLE", "Vlan10:52:54:00:25:06:e9", [("port", "Ethernet12"), ("type", "dynamic"), ] ) assert mac1_found == False, str(extra) print("CONFIRM: FDB Vlan10:52-54-00-25-06-E9:Ethernet12 is not created in STATE-DB") print("NEG6 - simulate mac age event for a vlan which does not exist") print("ACTION: Deleting FDB Vlan10:52-54-00-25-06-E9:Ethernet12 from ASIC-DB") remove_entry_tbl(dvs.adb, "ASIC_STATE", "SAI_OBJECT_TYPE_FDB_ENTRY:{\"bvid\":\""+vlan_oid_10+"\",\"mac\":\"52:54:00:25:06:E9\",\"switch_id\":\""+switch_id+"\"}") ntf = swsscommon.NotificationProducer(dvs.adb, "FDB_NOTIFICATIONS") fvp = swsscommon.FieldValuePairs() ntf_data = "[{\"fdb_entry\":\"{\\\"bvid\\\":\\\""+vlan_oid_10+"\\\",\\\"mac\\\":\\\"52:54:00:25:06:E9\\\",\\\"switch_id\\\":\\\""+switch_id+"\\\"}\",\"fdb_event\":\"SAI_FDB_EVENT_AGED\",\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\""+bp_eth12+"\"}]}]" ntf.send("fdb_event", ntf_data, fvp) time.sleep(2)
* level + '{\n' text += '\t' * (level + 1) text += '"caption": "%s",\n' % index_letter text += '\t' * (level + 1) text += '"id": "stino_example_cat_%s_%s",\n' % (level, index_letter) text += '\t' * (level + 1) text += '"children":\n' text += '\t' * (level + 1) text += '[\n' text += '\t' * (level + 2) text += '{"caption": "-"}' text += get_example_paths_text(level + 2, paths) text += '\t' * (level + 1) text += ']\n' text += '\t' * level text += '}' return text def update_example_menu(arduino_info): """.""" ext_app_path = arduino_info.get('ext_app_path') sketchbook_path = arduino_info.get('sketchbook_path') paths = [] if os.path.isdir(ext_app_path): paths.append(ext_app_path) paths.append(sketchbook_path) all_paths = [] for path in paths: examples_path = os.path.join(path, 'examples') example_paths = glob.glob(examples_path + '/*') example_paths = [p for p in example_paths if os.path.isdir(p)] libraries_path = os.path.join(path, 'libraries') library_paths = glob.glob(libraries_path + '/*') library_paths = [p for p in library_paths if os.path.isdir(p)] all_paths.append(example_paths) all_paths.append(library_paths) text = '\t' * 0 + '[\n' text += '\t' * 1 + '{\n' text += '\t' * 2 + '"caption": "Arduino",\n' text += '\t' * 2 + '"mnemonic": "A",\n' text += '\t' * 2 + '"id": "arduino",\n' text += '\t' * 2 + '"children":\n' text += '\t' * 2 + '[\n' text += '\t' * 3 + '{\n' text += '\t' * 4 + '"caption": "Open Example",\n' text += '\t' * 4 + '"id": "stino_examples",\n' text += '\t' * 4 + '"children":\n' text += '\t' * 4 + '[\n' text += '\t' * 5 + '{\n' text += '\t' * 6 + '"caption": "Refresh",\n' text += '\t' * 6 + '"id": "stino_refresh_examples",\n' text += '\t' * 6 + '"command": "stino_refresh_examples"\n' text += '\t' * 5 + '},\n' text += '\t' * 5 + '{"caption": "-"}' sep_text = ',\n' + '\t' * 5 + '{"caption": "-"}' sub_texts = [] for paths in all_paths: sub_texts.append(get_example_menu_text(5, paths)) text += sep_text.join(sub_texts) text += '\n' + '\t' * 4 + ']\n' text += '\t' * 3 + '}\n' text += '\t' * 2 + ']\n' text += '\t' * 1 + '}\n' text += '\t' * 0 + ']\n' write_menu('examples', text) def get_lib_name_in_path(lib_path): """.""" lib_name = os.path.basename(lib_path) properties_file_name = 'library.properties' p_path = os.path.join(lib_path, properties_file_name) if os.path.isfile(p_path): p_file = plain_params_file.PlainParamsFile(p_path) info = p_file.get_info() if 'name' in info: lib_name = info['name'] return lib_name def update_library_menu(arduino_info): """.""" ext_app_path = arduino_info.get('ext_app_path') sketchbook_path = arduino_info.get('sketchbook_path') paths = [] if os.path.isdir(ext_app_path): paths.append(ext_app_path) paths.append(sketchbook_path) all_paths = [] for path in paths: libraries_path = os.path.join(path, 'libraries') library_paths = glob.glob(libraries_path + '/*') library_paths = [p for p in library_paths if os.path.isdir(p)] all_paths.append(library_paths) text = '\t' * 0 + '[\n' text += '\t' * 1 + '{\n' text += '\t' * 2 + '"caption": "Arduino",\n' text += '\t' * 2 + '"mnemonic": "A",\n' text += '\t' * 2 + '"id": "arduino",\n' text += '\t' * 2 + '"children":\n' text += '\t' * 2 + '[\n' text += '\t' * 3 + '{\n' text += '\t' * 4 + '"caption": "Import Library",\n' text += '\t' * 4 + '"id": "stino_import_library",\n' text += '\t' * 4 + '"children":\n' text += '\t' * 4 + '[\n' text += '\t' * 5 + '{\n' text += '\t' * 6 + '"caption": "Refresh",\n' text += '\t' * 6 + '"id": "stino_refresh_libraries",\n' text += '\t' * 6 + '"command": "stino_refresh_libraries"\n' text += '\t' * 5 + '},\n' text += '\t' * 5 + '{"caption": "-"}' sep_text = ',\n' + '\t' * 5 + '{"caption": "-"}' sub_texts = [] for paths in all_paths: sub_text = '' if len(paths) < 21: for library_path in paths: library_path = library_path.replace('\\', '/') library_name = get_lib_name_in_path(library_path) sub_text += ',\n' sub_text += '\t' * 5 + '{\n' sub_text += '\t' * 6 + '"caption": "%s",\n' % library_name sub_text += '\t' * 6 sub_text += '"id": "stino_library_%s",\n' % library_name sub_text += '\t' * 6 + '"command": "stino_import_library",\n' sub_text += '\t' * 6 + '"args": {"library_path": ' sub_text += '"%s"}\n' % library_path sub_text += '\t' * 5 + '}' else: index = 0 index_letters = [] while len(index_letters) < 2: index_letters = [] letter_path_info = {} for path in paths: name = os.path.basename(path) if index < len(name): index_letter = name[index].upper() else: index_letter = '->' if index_letter not in index_letters: index_letters.append(index_letter) letter_path_info[index_letter] = [] letter_path_info[index_letter].append(path) index += 1 for index_letter in index_letters: paths = letter_path_info[index_letter] sub_text += ',\n' sub_text += '\t' * 5 + '{\n' sub_text += '\t' * 6 + '"caption": "%s",\n' % index_letter sub_text += '\t' * 6 sub_text += '"id": "stino_library_cat_%s",\n' % index_letter sub_text += '\t' * 6 + '"children":\n' sub_text += '\t' * 6 + '[\n' sub_text += '\t' * 7 + '{"caption": "-"}' for library_path in paths: library_path = library_path.replace('\\', '/') library_name = get_lib_name_in_path(library_path) sub_text += ',\n' sub_text += '\t' * 7 + '{\n' sub_text += '\t' * 8 + '"caption": "%s",\n' % library_name sub_text += '\t' * 8 sub_text += '"id": "stino_library_%s",\n' % library_name sub_text += '\t' * 8 sub_text += '"command": "stino_import_library",\n' sub_text += '\t' * 8 + '"args": {"library_path": ' sub_text += '"%s"}\n' % library_path sub_text += '\t' * 7 + '}' sub_text += '\t' * 6 + ']\n' sub_text += '\t' * 5 + '}' sub_texts.append(sub_text) text += sep_text.join(sub_texts) text += '\n' + '\t' * 4 + ']\n' text += '\t' * 3 + '}\n' text += '\t' * 2 + ']\n' text += '\t' * 1 + '}\n' text += '\t' * 0 + ']\n' write_menu('libraries', text) def update_install_library_menu(arduino_info): """.""" libraries_info = arduino_info.get('libraries', {}) lib_cats = libraries_info.get('categorys', []) text = '\t' * 0 + '[\n' text += '\t' * 1 + '{\n' text += '\t' * 2 + '"caption": "Arduino",\n' text += '\t' * 2 + '"mnemonic": "A",\n' text += '\t' * 2 + '"id": "arduino",\n' text += '\t' * 2 + '"children":\n' text += '\t' * 2 + '[\n' text += '\t' * 3 + '{\n' text += '\t' * 4 + '"caption": "Install Library",\n' text += '\t' * 4 + '"id": "stino_install_library",\n' text += '\t' * 4 + '"children":\n' text += '\t' * 4 + '[\n' text += '\t' * 5 + '{\n' text += '\t' * 6 + '"caption": "Refresh",\n' text += '\t' * 6 + '"id": "stino_refresh_install_library",\n' text += '\t' * 6 + '"command": "stino_refresh_install_library"\n' text += '\t' * 5 + '},\n' text += '\t' * 5 + '{"caption": "-"}' for lib_cat in lib_cats: text += ',\n' text += '\t' * 5 + '{\n' text += '\t' * 6 + '"caption": "%s",\n' % lib_cat text += '\t' * 6 + '"id": "stino_lib_cat_%s",\n' % lib_cat text += '\t' * 6 + '"children":\n' text += '\t' * 6 + '[\n' text += '\t' * 7 + '{"caption": "-"}' cat_info = libraries_info.get(lib_cat, {}) names = cat_info.get('names', []) if len(names) < 31: for name in names: text += ',\n' text += '\t' * 7 + '{\n' text += '\t' * 8 + '"caption": "%s",\n' % name text += '\t' * 8 + '"id": "stino_lib_cat_name_%s",\n' % name text += '\t' * 8 + '"children":\n' text += '\t' * 8 + '[' text += '\t' * 9 + '{"caption": "-"}' name_info = cat_info.get(name, {}) versions = name_info.get('versions', []) for version in versions: text += ',\n' text += '\t' * 9 + '{' text += '\t' * 10 + '"caption": "%s",\n' % version text += '\t' * 10 + '"id": ' text += '"stino_lib_cat_name_ver_%s",\n' % version text += '\t' * 10 + '"command": "stino_install_lib",\n' arg_text = '"args": {"category": "%s", ' % lib_cat arg_text += '"name": "%s", ' % name arg_text += '"version": "%s"}\n' % version text += '\t' * 10 + arg_text text += '\t' * 9 + '}' text += '\n' + '\t' * 8 + ']' text += '\t' * 7 + '}' else: index = 0 index_letters = [] while len(index_letters) < 2: index_letters = [] letter_name_info = {} for name in names: if index
<filename>ros_model_extractor.py #!/usr/bin/env python # # Copyright 2019 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) # # <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import argparse import subprocess from ros_model_generator.rosmodel_generator import RosModelGenerator import ros_metamodels.ros_metamodel_core as RosModelMetamodel import rospkg #import ament_index_python from haros.extractor import NodeExtractor, RoscppExtractor, RospyExtractor from haros.metamodel import Node, Package, RosName, SourceFile from haros.launch_parser import LaunchParser, LaunchParserError, NodeTag from haros.cmake_parser import RosCMakeParser from bonsai.analysis import CodeQuery, resolve_expression try: from bonsai.cpp.clang_parser import CppAstParser except ImportError: CppAstParser = None from bonsai.py.py_parser import PyAstParser class RosExtractor(): def launch(self): self.parse_arg() ws = self.args.worspace_path #BONSAI PARSER parser = CppAstParser(workspace = ws) parser.set_library_path("/usr/lib/llvm-10/lib") parser.set_standard_includes("/usr/lib/llvm-10/lib/clang/10.0.0/include") db_dir = os.path.join(ws, "build") if os.path.isfile(os.path.join(db_dir, "compile_commands.json")): parser.set_database(db_dir) else: print("The compile_commands.json file can't be found") if (self.args.node): self.extract_node(self.args.name, self.args.name, self.args.package_name, None, ws, None) def extract_node(self, name, node_name, pkg_name, ns, ws, rossystem): self.pkg = Package(pkg_name) if os.environ.get("ROS_VERSION") == "1": rospack = rospkg.RosPack() self.pkg.path = rospack.get_path(pkg_name) self.pkg_type="CatkinPackage" elif os.environ.get("ROS_VERSION") == "2": self.pkg.path= self.args.path_to_src self.pkg_type="AmentPackage" roscomponent = None #HAROS NODE EXTRACTOR srcdir = self.pkg.path[len(ws):] srcdir = os.path.join(ws, srcdir.split(os.sep, 1)[0]) bindir = os.path.join(ws, "build") #HAROS CMAKE PARSER parser = RosCMakeParser(srcdir, bindir, pkgs = [self.pkg]) model_str = "" if os.path.isfile(os.path.join(self.pkg.path, "CMakeLists.txt")): parser.parse(os.path.join(self.pkg.path, "CMakeLists.txt")) for target in parser.executables.values(): print("INFO: Found artifact: "+target.output_name) if (self.args.a): node_name = target.output_name node = Node(node_name, self.pkg, rosname=RosName(node_name)) for file_in in target.files: full_path = file_in relative_path = full_path.replace(self.pkg.path+"/","").rpartition("/")[0] file_name = full_path.rsplit('/', 1)[-1] source_file = SourceFile(file_name, relative_path , self.pkg) node.source_files.append(source_file) else: if target.output_name == node_name: node = Node(node_name, self.pkg, rosname=RosName(node_name)) for file_in in target.files: full_path = file_in relative_path = full_path.replace(self.pkg.path+"/","").rpartition("/")[0] file_name = full_path.rsplit('/', 1)[-1] source_file = SourceFile(file_name, relative_path , self.pkg) node.source_files.append(source_file) else: continue if node.language == "cpp": parser = CppAstParser(workspace = ws) analysis = RoscppExtractor(self.pkg, ws) if node.language == "python": parser = PyAstParser(workspace = ws) analysis = RospyExtractor(self.pkg, ws) #node.source_tree = parser.global_scope for sf in node.source_files: try: if parser.parse(sf.path) is not None: # ROS MODEL EXTRACT PRIMITIVES if node.language == "python": node_name=node_name.replace(".py","") RosModel_node=RosModelMetamodel.Node(node_name) try: self.extract_primitives(node, parser, analysis, RosModel_node, roscomponent, pkg_name, node_name, node_name) # SAVE ROS MODEL ros_model = RosModelGenerator() ros_model.create_model_from_node(self.pkg.name,node_name, RosModel_node, self.args.repo, self.pkg_type) print("Save model in:") print(self.args.model_path+"/"+node_name+".ros") model_str = ros_model.generate_ros_model(self.args.model_path+"/"+node_name+".ros") except error: print("The interfaces can't be extracted "+error) else: print("The model couldn't be extracted") except: pass if rossystem is not None and roscomponent is not None: rossystem.add_component(roscomponent) if self.args.output: print(model_str) def transform_type(self, param_type): if os.environ.get("ROS_VERSION") == "2": param_type=str(param_type) param_type=param_type[param_type.find("[")+1:param_type.find("]")] if param_type == 'double': return 'Double' elif param_type == 'bool': return 'Boolean' elif param_type == 'int' or param_type == 'long': return 'Integer' elif (param_type == 'str' or 'basic_string<char>' in param_type or param_type == 'std::string'): return 'String' #elif param_type == 'yaml': #return 'Struct' #elif 'std::vector' in param_type: #return 'List' else: return None def extract_primitives(self, node, parser, analysis, RosModel_node, roscomponent, pkg_name, node_name, art_name): gs = parser.global_scope node.source_tree = parser.global_scope if os.environ.get("ROS_VERSION") == "1": if node.language == "cpp": #print(CodeQuery(gs).all_calls.get()) for call in (CodeQuery(gs).all_calls.where_name("SimpleActionServer").get()): if len(call.arguments) > 0: name = analysis._extract_action(call) action_type = analysis._extract_action_type(call).split("_<",1)[0] RosModel_node.add_action_server(name,action_type.replace("/",".")) #roscomponent.add_interface(name,"actsrvs", pkg_name+"."+art_name+"."+node_name+"."+name) for call in (CodeQuery(gs).all_calls.where_name("SimpleActionClient").get()): if len(call.arguments) > 0: name = analysis._extract_action(call) action_type = analysis._extract_action_type(call).split("_<",1)[0] RosModel_node.add_action_client.append(name,action_type.replace("/",".")) #roscomponent.add_interface(name,"actcls", str(pkg_name)+"."+str(art_name)+"."+str(node_name)+"."+str(name)) for call in (CodeQuery(gs).all_calls.where_name("advertise").where_result("ros::Publisher").get()): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) RosModel_node.add_publisher(name, msg_type.replace("/",".")) #roscomponent.add_interface(name,"pubs", pkg_name+"."+art_name+"."+node_name+"."+name) for call in (CodeQuery(gs).all_calls.where_name("subscribe").where_result("ros::Subscriber").get()): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) RosModel_node.add_subscriber(name, msg_type.replace("/",".")) #roscomponent.add_interface(name,"subs", pkg_name+"."+art_name+"."+node_name+"."+name) for call in (CodeQuery(gs).all_calls.where_name("advertiseService").where_result("ros::ServiceServer").get()): if len(call.arguments) > 1: name = analysis._extract_topic(call) srv_type = analysis._extract_message_type(call) RosModel_node.add_service_server(name, srv_type.replace("/",".").replace("Request","")) #roscomponent.add_interface(name,"srvsrvs", pkg_name+"."+art_name+"."+node_name+"."+name) for call in (CodeQuery(gs).all_calls.where_name("serviceClient").where_result("ros::ServiceClient").get()): if len(call.arguments) > 1: name = analysis._extract_topic(call) srv_type = analysis._extract_message_type(call) RosModel_node.add_service_client(name, srv_type.replace("/",".").replace("Response","")) #roscomponent.add_interface(name,"srvcls", pkg_name+"."+art_name+"."+node_name+"."+name) #PARAMETERS nhg:this needs review nh_prefix = "c:@N@ros@S@NodeHandle@" gets = ("getParam", "getParamCached", "param") reads = gets + ("hasParam", "searchParam") sets = ("setParam",) writes = sets + ("deleteParam",) for call in CodeQuery(gs).all_calls.where_name(reads).get(): if (call.full_name.startswith("ros::NodeHandle") or (isinstance(call.reference, str) and call.reference.startswith(nh_prefix))): param_type = default_value = None param_name = analysis._extract_topic(call) if call.name in gets: param_type = self.transform_type(analysis._extract_param_type(call.arguments[1])) if call.name == "param": if len(call.arguments) > 2: default_value = analysis._extract_param_value( call, arg_pos=2) elif len(call.arguments) == 2: default_value = analysis._extract_param_value( call, arg_pos=1) if not ((default_value is None or default_value == "") and param_type is None): RosModel_node.add_parameter(param_name, default_value, param_type, None) for call in CodeQuery(gs).all_calls.where_name(writes).get(): if (call.full_name.startswith("ros::NodeHandle") or (isinstance(call.reference, str) and call.reference.startswith(nh_prefix))): param_type = value = None param_name = analysis._extract_topic(call) if len(call.arguments) >= 2 and call.name in sets: param_type = self.transform_type(analysis._extract_param_type(call.arguments[1])) value = analysis._extract_param_value(call, arg_pos=1) if not ((default_value is None or default_value == "") and param_type is None): RosModel_node.add_parameter(param_name, default_value, param_type, None) ros_prefix = "c:@N@ros@N@param@" gets = ("get", "getCached", "param") reads = gets + ("has",) sets = ("set",) writes = sets + ("del",) for call in CodeQuery(gs).all_calls.where_name(reads).get(): if (call.full_name.startswith("ros::param") or (isinstance(call.reference, str) and call.reference.startswith(ros_prefix))): param_type = default_value = None param_name = analysis._extract_topic(call) if call.name == "param": if call.name in gets: param_type = self.transform_type(analysis._extract_param_type(call.arguments[1])) if len(call.arguments) > 2: default_value = analysis._extract_param_value(call, arg_pos=2) elif len(call.arguments) == 2: default_value = analysis._extract_param_value(call, arg_pos=1) if not ((default_value is None or default_value == "") and param_type is None): RosModel_node.add_parameter(param_name, default_value, param_type, None) for call in CodeQuery(gs).all_calls.where_name(writes).get(): if (call.full_name.startswith("ros::param") or (isinstance(call.reference, str) and call.reference.startswith(ros_prefix))): param_type = value = None if len(call.arguments) >= 2 and call.name in sets: param_type = self.transform_type(analysis._extract_param_type(call.arguments[1])) value = analysis._extract_param_value(call, arg_pos=1) param_name = analysis._extract_topic(call) if not ((default_value is None or default_value == "") and param_type is None): RosModel_node.add_parameter(param_name, default_value, param_type, None) #PYTHON nhg:this needs review if node.language == "python": msgs_list = [] pkgs_list = [] for imp_name in parser.imported_names_list: s = str(imp_name) if "msg" in s or "srv" in s: ss = s.split(".") if len(ss) < 2: continue if ss[-1] == "msg" or ss[-1] == "srv": pkgs_list.append(ss[0]) elif ss[1] == "msg" or ss[1] == "srv": msgs_list.append((ss[0], ss[2])) else: log.debug(("Python import with 'msg' or 'srv', " "but unable to process it: ") + s) for call in CodeQuery(gs).all_calls.get(): if "rospy.Publisher" in str(call): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call, '', msgs_list, pkgs_list) #queue_size = analysis._extract_queue_size(call ) RosModel_node.add_publisher(name, msg_type.replace("/",".")) #roscomponent.add_interface(name,"pubs", pkg_name+"."+art_name+"."+node_name+"."+name) if "rospy.Subscriber" in str(call): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call, '', msgs_list, pkgs_list) #queue_size = analysis._extract_queue_size(call ) RosModel_node.add_subscriber(name, msg_type.replace("/",".")) #roscomponent.add_interface(name,"subs", pkg_name+"."+art_name+"."+node_name+"."+name) if "rospy.Service" in str(call): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) srv_type = analysis._extract_message_type(call, '', msgs_list) RosModel_node.add_service_server(name, srv_type.replace("/",".").replace("Request","")) #roscomponent.add_interface(name,"srvsrvs", pkg_name+"."+art_name+"."+node_name+"."+name) if "rospy.ServiceProxy" in str(call): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) srv_type = analysis._extract_message_type(call, '', msgs_list) RosModel_node.add_service_client(name, srv_type.replace("/",".").replace("Response","")) #roscomponent.add_interface(name,"srvcls", pkg_name+"."+art_name+"."+node_name+"."+name) #if "rospy.get_param" in str(call): # print("PARAM GET:") # print(call) if "rospy.set_param" in str(call): param_name = analysis._extract_topic(call, topic_pos=0) param_type = default_value = None default_value = resolve_expression(call.arguments[1]) RosModel_node.add_parameter(param_name.replace(".","/"), default_value , param_type, None) if os.environ.get("ROS_VERSION") == "2": #ROS2 if node.language == "cpp": for call in (CodeQuery(gs).all_calls.get()): if "Publisher" in str(call): #print(call) if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) if name!="?" or msg_type!="?": RosModel_node.add_publisher(name, msg_type.replace("/",".").replace(".msg","")) for call in (CodeQuery(gs).all_calls.get()): if "Subscription" in str(call): #print(call) if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) msg_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) if name!="?" or msg_type!="?": RosModel_node.add_subscriber(name, msg_type.replace("/",".").replace(".msg","")) for call in (CodeQuery(gs).all_calls.get()): if "Service" in str(call) and "::srv::" in str(call): #print(call) if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) srv_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) print(name + " " + srv_type) if name!="?" or srv_type!="?": RosModel_node.add_service_server(name, srv_type.replace("/",".").replace(".srv","")) for call in (CodeQuery(gs).all_calls.get()): if "Client" in str(call) and "::srv::" in str(call): #print(call) if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) srv_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) print(name + " " + srv_type) if name!="?" or srv_type!="?": RosModel_node.add_service_client(name, srv_type.replace("/",".").replace(".srv","")) if "Client" in str(call) and "::action::" in str(call): if len(call.arguments) > 1: name = analysis._extract_topic(call, topic_pos=0) act_type = analysis._extract_message_type(call) queue_size = analysis._extract_queue_size(call, queue_pos=1) if name!="?" or act_type!="?": RosModel_node.add_action_client(name, act_type.replace("/",".").replace(".action","")) if
the default subnetpool for ``ip_version`` to obtain a CIDR. It is required to pass ``None`` to the ``cidr`` argument when enabling this option. :param kwargs: Key value pairs to be passed to the Neutron API. :returns: The new subnet object. :raises: OpenStackCloudException on operation error. """ if tenant_id is not None: filters = {'tenant_id': tenant_id} else: filters = None network = self.get_network(network_name_or_id, filters) if not network: raise exc.OpenStackCloudException( "Network %s not found." % network_name_or_id) if disable_gateway_ip and gateway_ip: raise exc.OpenStackCloudException( 'arg:disable_gateway_ip is not allowed with arg:gateway_ip') if not cidr and not use_default_subnetpool: raise exc.OpenStackCloudException( 'arg:cidr is required when a subnetpool is not used') if cidr and use_default_subnetpool: raise exc.OpenStackCloudException( 'arg:cidr must be set to None when use_default_subnetpool == ' 'True') # Be friendly on ip_version and allow strings if isinstance(ip_version, str): try: ip_version = int(ip_version) except ValueError: raise exc.OpenStackCloudException( 'ip_version must be an integer') # The body of the neutron message for the subnet we wish to create. # This includes attributes that are required or have defaults. subnet = dict({ 'network_id': network['id'], 'ip_version': ip_version, 'enable_dhcp': enable_dhcp, }, **kwargs) # Add optional attributes to the message. if cidr: subnet['cidr'] = cidr if subnet_name: subnet['name'] = subnet_name if tenant_id: subnet['tenant_id'] = tenant_id if allocation_pools: subnet['allocation_pools'] = allocation_pools if gateway_ip: subnet['gateway_ip'] = gateway_ip if disable_gateway_ip: subnet['gateway_ip'] = None if dns_nameservers: subnet['dns_nameservers'] = dns_nameservers if host_routes: subnet['host_routes'] = host_routes if ipv6_ra_mode: subnet['ipv6_ra_mode'] = ipv6_ra_mode if ipv6_address_mode: subnet['ipv6_address_mode'] = ipv6_address_mode if prefixlen: subnet['prefixlen'] = prefixlen if use_default_subnetpool: subnet['use_default_subnetpool'] = True response = self.network.post("/subnets", json={"subnet": subnet}) return self._get_and_munchify('subnet', response) def delete_subnet(self, name_or_id): """Delete a subnet. If a name, instead of a unique UUID, is supplied, it is possible that we could find more than one matching subnet since names are not required to be unique. An error will be raised in this case. :param name_or_id: Name or ID of the subnet being deleted. :returns: True if delete succeeded, False otherwise. :raises: OpenStackCloudException on operation error. """ subnet = self.get_subnet(name_or_id) if not subnet: self.log.debug("Subnet %s not found for deleting", name_or_id) return False exceptions.raise_from_response(self.network.delete( "/subnets/{subnet_id}".format(subnet_id=subnet['id']))) return True def update_subnet(self, name_or_id, subnet_name=None, enable_dhcp=None, gateway_ip=None, disable_gateway_ip=None, allocation_pools=None, dns_nameservers=None, host_routes=None): """Update an existing subnet. :param string name_or_id: Name or ID of the subnet to update. :param string subnet_name: The new name of the subnet. :param bool enable_dhcp: Set to ``True`` if DHCP is enabled and ``False`` if disabled. :param string gateway_ip: The gateway IP address. When you specify both allocation_pools and gateway_ip, you must ensure that the gateway IP does not overlap with the specified allocation pools. :param bool disable_gateway_ip: Set to ``True`` if gateway IP address is disabled and ``False`` if enabled. It is not allowed with gateway_ip. Default is ``False``. :param allocation_pools: A list of dictionaries of the start and end addresses for the allocation pools. For example:: [ { "start": "192.168.199.2", "end": "192.168.199.254" } ] :param dns_nameservers: A list of DNS name servers for the subnet. For example:: [ "172.16.31.10", "8.8.8.8" ] :param host_routes: A list of host route dictionaries for the subnet. For example:: [ { "destination": "0.0.0.0/0", "nexthop": "123.456.78.9" }, { "destination": "192.168.0.0/24", "nexthop": "192.168.0.1" } ] :returns: The updated subnet object. :raises: OpenStackCloudException on operation error. """ subnet = {} if subnet_name: subnet['name'] = subnet_name if enable_dhcp is not None: subnet['enable_dhcp'] = enable_dhcp if gateway_ip: subnet['gateway_ip'] = gateway_ip if disable_gateway_ip: subnet['gateway_ip'] = None if allocation_pools: subnet['allocation_pools'] = allocation_pools if dns_nameservers: subnet['dns_nameservers'] = dns_nameservers if host_routes: subnet['host_routes'] = host_routes if not subnet: self.log.debug("No subnet data to update") return if disable_gateway_ip and gateway_ip: raise exc.OpenStackCloudException( 'arg:disable_gateway_ip is not allowed with arg:gateway_ip') curr_subnet = self.get_subnet(name_or_id) if not curr_subnet: raise exc.OpenStackCloudException( "Subnet %s not found." % name_or_id) response = self.network.put( "/subnets/{subnet_id}".format(subnet_id=curr_subnet['id']), json={"subnet": subnet}) return self._get_and_munchify('subnet', response) @_utils.valid_kwargs('name', 'admin_state_up', 'mac_address', 'fixed_ips', 'subnet_id', 'ip_address', 'security_groups', 'allowed_address_pairs', 'extra_dhcp_opts', 'device_owner', 'device_id', 'binding:vnic_type', 'binding:profile', 'port_security_enabled', 'qos_policy_id', 'binding:host_id') def create_port(self, network_id, **kwargs): """Create a port :param network_id: The ID of the network. (Required) :param name: A symbolic name for the port. (Optional) :param admin_state_up: The administrative status of the port, which is up (true, default) or down (false). (Optional) :param mac_address: The MAC address. (Optional) :param fixed_ips: List of ip_addresses and subnet_ids. See subnet_id and ip_address. (Optional) For example:: [ { "ip_address": "10.29.29.13", "subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd" }, ... ] :param subnet_id: If you specify only a subnet ID, OpenStack Networking allocates an available IP from that subnet to the port. (Optional) If you specify both a subnet ID and an IP address, OpenStack Networking tries to allocate the specified address to the port. :param ip_address: If you specify both a subnet ID and an IP address, OpenStack Networking tries to allocate the specified address to the port. :param security_groups: List of security group UUIDs. (Optional) :param allowed_address_pairs: Allowed address pairs list (Optional) For example:: [ { "ip_address": "2172.16.58.3", "mac_address": "fa:16:3e:c4:cd:3f" }, ... ] :param extra_dhcp_opts: Extra DHCP options. (Optional). For example:: [ { "opt_name": "opt name1", "opt_value": "value1" }, ... ] :param device_owner: The ID of the entity that uses this port. For example, a DHCP agent. (Optional) :param device_id: The ID of the device that uses this port. For example, a virtual server. (Optional) :param binding vnic_type: The type of the created port. (Optional) :param port_security_enabled: The security port state created on the network. (Optional) :param qos_policy_id: The ID of the QoS policy to apply for port. :returns: a ``munch.Munch`` describing the created port. :raises: ``OpenStackCloudException`` on operation error. """ kwargs['network_id'] = network_id data = proxy._json_response( self.network.post("/ports", json={'port': kwargs}), error_message="Error creating port for network {0}".format( network_id)) return self._get_and_munchify('port', data) @_utils.valid_kwargs('name', 'admin_state_up', 'fixed_ips', 'security_groups', 'allowed_address_pairs', 'extra_dhcp_opts', 'device_owner', 'device_id', 'binding:vnic_type', 'binding:profile', 'port_security_enabled', 'qos_policy_id', 'binding:host_id') def update_port(self, name_or_id, **kwargs): """Update a port Note: to unset an attribute use None value. To leave an attribute untouched just omit it. :param name_or_id: name or ID of the port to update. (Required) :param name: A symbolic name for the port. (Optional) :param admin_state_up: The administrative status of the port, which is up (true) or down (false). (Optional) :param fixed_ips: List of ip_addresses and subnet_ids. (Optional) If you specify only a subnet ID, OpenStack Networking allocates an available IP from that subnet to the port. If you specify both a subnet ID and an IP address, OpenStack Networking tries to allocate the specified address to the port. For example:: [ { "ip_address": "10.29.29.13", "subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd" }, ... ] :param security_groups: List of security group UUIDs. (Optional) :param allowed_address_pairs: Allowed address pairs list (Optional) For example:: [ { "ip_address": "192.168.3.11", "mac_address": "fa:16:3e:c4:cd:3f" }, ... ] :param extra_dhcp_opts: Extra DHCP options. (Optional). For example:: [ { "opt_name": "opt name1", "opt_value": "value1" }, ... ] :param device_owner: The ID of the entity that uses this port. For example, a DHCP agent. (Optional) :param device_id: The ID of the resource this port is attached to. :param binding vnic_type: The type of the created port. (Optional) :param port_security_enabled: The security port state created on the network. (Optional) :param qos_policy_id: The ID of the QoS policy to apply for port. :returns: a ``munch.Munch`` describing the updated port. :raises: OpenStackCloudException on operation error. """ port = self.get_port(name_or_id=name_or_id) if port is None: raise exc.OpenStackCloudException( "failed to find port '{port}'".format(port=name_or_id)) data = proxy._json_response( self.network.put( "/ports/{port_id}".format(port_id=port['id']), json={"port": kwargs}), error_message="Error updating port {0}".format(name_or_id)) return self._get_and_munchify('port', data) def delete_port(self, name_or_id): """Delete a port :param name_or_id: ID or name of the port to delete. :returns: True if delete succeeded, False otherwise. :raises: OpenStackCloudException on operation error. """ port = self.get_port(name_or_id=name_or_id) if port is None: self.log.debug("Port %s not found for deleting", name_or_id) return False exceptions.raise_from_response( self.network.delete( "/ports/{port_id}".format(port_id=port['id'])), error_message="Error deleting port {0}".format(name_or_id)) return True def _get_port_ids(self, name_or_id_list, filters=None): """ Takes a list of port names or ids, retrieves ports and returns a list with port ids only. :param list[str] name_or_id_list: list of port names or ids :param dict filters: optional filters :raises: SDKException on multiple matches
tensor's elements across a specified axis or a list of specified axes. Args: x (Tensor): input tensor. axis (int,list): axis along which the reduction will be performed keepdims (bool): Keep the reduced dimension or not, default True mean keep reduced dimension **kwargs (): Returns: The sum of the input tensor's elements across a specified axis or a list of specified axes. Examples: >>> data = to_tensor(np.array([[[5,1], [20,2]],[[30,1], [40,2]],[[55,1], [60,2]]], dtype=np.float32)) >>> print(reduce_sum(data).cpu()) tensor(219.) >>> print(reduce_sum(data, 0).cpu()) tensor([[ 90., 3.], [120., 6.]]) >>> print(reduce_sum(data, axis=0).cpu()) tensor([[ 90., 3.], [120., 6.]]) >>> print(reduce_sum(data, axis=[0,2]).cpu()) tensor([ 93., 126.]) """ axis = kwargs.get('dim', axis) keepdims = kwargs.get('keepdim', keepdims) if x.element_size() == 0: return x if x.dtype==Dtype.bool: x.to(_float_dtype) if axis is None or isinstance(axis, (int, list, tuple)): if axis is None and keepdims == False: return torch.sum(x) else: return torch.sum(x, axis, keepdim=keepdims) else: return torch.sum(x) @numpy_compatible def reduce_max(x: Tensor, axis=None, keepdims=False, **kwargs): """Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned. See the numpy docs for `np.amax` and `np.nanmax` behavior. Args: x (Tensor): input tensor. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor),rank(input_tensor)]`. keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced tensor. Examples: >>> x = to_tensor([5, 1, 2, 4]) >>> print(reduce_max(x)) tensor(5, shape=(), dtype=int32) >>> x = to_tensor([-5, -1, -2, -4]) >>> print(reduce_max(x)) tensor(-1, shape=(), dtype=int32) >>> x = to_tensor([4, float('nan')]) >>> print(reduce_max(x)) tensor(4.0, shape=(), dtype=float32) >>> x = to_tensor([float('nan'), float('nan')]) >>> print(reduce_max(x)) tensor(-inf, shape=(), dtype=float32) >>> x =to_tensor([float('-inf'), float('inf')]) >>> print(reduce_max(x)) tensor(inf, shape=(), dtype=float32) """ axis = kwargs.get('dim', axis) keepdims = kwargs.get('keepdim', keepdims) if x.element_size() == 0: return x if x.dtype==Dtype.bool: x.to(_float_dtype) if axis is None or isinstance(axis, (int, list, tuple)): if axis is None and keepdims ==False: result = x.max() elif keepdims == False: result = x.max(axis) else: result = x.max(axis, keepdims) if is_tensor(result): return result elif isinstance(result, tuple) : # (values, indices) # RuntimeError: Please look up dimensions by name, got: name = None. return result[0] else: return torch.max(x) @numpy_compatible def reduce_min(x: Tensor, axis=None, keepdims=False, **kwargs): """Computes the minimum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned. See the numpy docs for `np.amin` and `np.nanmin` behavior. Args: x (Tensor): input tensor. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced tensor. Examples: >>> x = to_tensor([5, 1, 2, 4]) >>> print(reduce_min(x)) tensor(5, shape=(), dtype=int32) >>> x = to_tensor([-5, -1, -2, -4]) >>> print(reduce_min(x)) tensor(-1, shape=(), dtype=int32) >>> x = to_tensor([4, float('nan')]) >>> print(reduce_min(x)) tensor(4.0, shape=(), dtype=float32) >>> x = to_tensor([float('nan'), float('nan')]) >>> print(reduce_min(x)) tensor(-inf, shape=(), dtype=float32) >>> x =to_tensor([float('-inf'), float('inf')]) >>> print(reduce_min(x)) tensor(inf, shape=(), dtype=float32) """ axis = kwargs.get('dim', axis) keepdims = kwargs.get('keepdim', keepdims) if x.element_size() == 0: return x if x.dtype==Dtype.bool: x.to(_float_dtype) if axis is None or isinstance(axis, (int, list,tuple)): if axis is None and keepdims ==False: result = x.min() elif keepdims ==False: result = x.min(axis) else: result = x.min(axis, keepdims) if is_tensor(result): return result elif isinstance(result, tuple): # (values, indices) #RuntimeError: Please look up dimensions by name, got: name = None. return result[0] else: return torch.min(x) @numpy_compatible def reduce_logsumexp(x: Tensor, axis=None, keepdims=False, **kwargs): """Computes log(sum(exp(elements across dimensions of a tensor))). Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, all dimensions are reduced, and a tensor with a single element is returned. This function is more numerically stable than log(sum(exp(input))). It avoids overflows caused by taking the exp of large inputs and underflows caused by taking the log of small inputs. Examples: >>> x =to_tensor([[0., 0., 0.], [0., 0., 0.]]) >>> reduce_logsumexp(x) # log(6) >>> reduce_logsumexp(x, 0) # [log(2), log(2), log(2)] >>> reduce_logsumexp(x, 1) # [log(3), log(3)] >>> reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]] >>> reduce_logsumexp(x, [0, 1]) # log(6) Args: x (Tensor): input tensor. axis (int, list, tuple): The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keepdims (bool): If true, retains reduced dimensions with length 1. Returns: The reduced tensor. """ if x.element_size() == 0: return x if x.dtype==Dtype.bool: x.to(_float_dtype) if axis is None or isinstance(axis, (int, list,tuple)): return torch.logsumexp(x, dim=axis, keepdim=keepdims) else: return log(reduce_sum(exp(x), axis=axis, keepdims=keepdims)) @numpy_compatible def reduce_prod(x: Tensor, axis=None, keepdims=False, **kwargs): """Computes the product of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned. Args: x (Tensor): input tensor. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced tensor. @compatibility(numpy) Equivalent to np.prod @end_compatibility """ axis = kwargs.get('dim', axis) keepdims = kwargs.get('keepdim', keepdims) if x.element_size() == 0: return x if axis is None: if ndim(x) == 1: axis = 0 elif ndim(x) > 1: axis =tuple(list(range(ndim(x)))) return torch.prod(x, dim=axis, keepdim=keepdims) elif isinstance(axis, list): axis = sorted(axis) axis.reverse() for a in axis: arr, idx = x.prod(dim=a, keepdim=keepdims) x = arr return x @numpy_compatible def reduce_any(x: Tensor, axis=None, keepdims=False, **kwargs): axis = kwargs.get('dim', axis) keepdims = kwargs.get('keepdim', keepdims) if x.element_size() == 0: return x x=x.gt(0) if isinstance(axis, int): return x.any(dim=axis, keepdim=keepdims) elif isinstance(axis, list): axis = sorted(axis) axis.reverse() for a in axis: arr, idx = x.any(dim=a, keepdim=keepdims) x = arr return x # reduce_log_sum_exp # reduce_prod # reduce_l1 # reduce_l2 # reduce_sum_square mean = reduce_mean sum = reduce_sum @numpy_compatible def max(*args, **kwargs): """General function for max operation Examples: >>> max(to_tensor([0.1, 0.9, 0.8, 0.4, 0.5])).cpu() tensor(0.9000) >>> max(to_tensor([0.1, 0.9, 0.8, 0.4, 0.5]),0.5).cpu() tensor([0.5000, 0.9000, 0.8000, 0.5000, 0.5000]) >>> max(3,7) 7 >>> max(to_numpy([0.1, 0.9, 0.8, 0.4, 0.5]),0.5) array([5.0000e-01, 9.0000e-01, 8.0000e-01, 5.0000e-01, 5.0000e-01]) >>> print(int_shape(to_tensor([[0.1, 0.9, 0.8],[0.3, 0.4, 0.5]]))) (2, 3) >>> max(to_tensor([[0.1, 0.9, 0.8],[0.3, 0.4, 0.5]]),axis=0).cpu() tensor([0.3000, 0.9000, 0.8000]) >>> max(to_tensor([[0.1, 0.9, 0.8],[0.3, 0.4, 0.5]]),dim=0).cpu() tensor([0.3000, 0.9000, 0.8000]) >>> max(to_tensor([[0.1, 0.9, 0.8],[0.3, 0.4, 0.5]]),axis=0,keepdims=True).cpu() tensor([[0.3000, 0.9000, 0.8000]]) >>> max(to_tensor([[0.1, 0.9, 0.8],[0.3, 0.4, 0.5]]),dim=0,keepdim=True).cpu() tensor([[0.3000, 0.9000, 0.8000]]) """ allargs=args+tuple(list(kwargs.values())) if len(allargs) == 1 and is_tensor(allargs[0]) and allargs[0].element_size() == 0: return allargs[0] elif len(allargs) == 1 and is_tensor(allargs[0]) and allargs[0].element_size() >0: value, idx = allargs[0].max() return value elif len(allargs) > 1 and is_tensor(allargs[0]) and not is_tensor(allargs[1]) and ('axis' in kwargs or 'dim' in kwargs or 'keepdims' in kwargs or 'keepdim' in kwargs): axis = kwargs.get('axis', kwargs.get('dim', None)) keepdims = kwargs.get('keepdims', kwargs.get('keepdim', False)) return reduce_max(allargs[0], axis=axis, keepdims=keepdims) elif len(args) > 1 and is_tensor(args[0]) and all([is_tensor(arg) or isinstance(arg,(np.ndarray,float,int))for arg in args]): new_args = [to_tensor(a) for a in args] return torch.max(*new_args) else: raise NotImplementedError('Max({0},{1}) is not implemented yet '.format(*args,**kwargs)) @numpy_compatible def min(*args, **kwargs): """ Args: *args (): Returns: """ allargs = args + tuple(list(kwargs.values())) if len(allargs) == 1 and is_tensor(allargs[0]) and allargs[0].element_size() == 0: return allargs[0] elif len(allargs) == 1 and is_tensor(allargs[0]) and allargs[0].element_size() > 0: return torch.min(allargs[0]) elif len(allargs) >
# Certainly prime or not prime. return (method.__name__, flag) assert flag == 2 # Unsure. return (method.__name__, flag) def is_probable_prime(self, n): """xxx """ return self._check_primality(n)[1] def __call__(self, n): """Instrumented version of the ``is_probable_prime`` method.""" name, flag = self._check_primality(n) instrument = self.instrument if instrument is not None: instrument.update(name, n, flag) return flag is_probable_prime = IsProbablePrime().is_probable_prime # === Specific primality tests === # http://en.wikipedia.org/wiki/Fermat_primality_test def is_fermat_probable_prime(n, base=2): """is_fermat_probable_prime(n [, base]) -> 0|1|2 Return a three-state flag (either 0, 1 or 2) that integer ``n `` is either a prime or Fermat pseudoprime, as witnessed by one or more integer bases. Arguments --------- n Integer to be tested for primality. base Optional integer base, or tuple of bases. (Defaults to 2.) Return result ------------- 0 Number is definitely non-prime. 1 Number is definitely prime. 2 Number is a weak probable prime or pseudoprime. ``is_fermat_probable_prime`` performs the Fermat primality test, which is a weak probabilistic test. If a number fails this test, it is definitely composite (there are no false negative tests): >>> is_fermat_probable_prime(99, 7) 0 However, if the number passes the test, it is provisional evidence that it may be a prime: >>> is_fermat_probable_prime(29, 7) # 29 actually is prime. 2 In this case we can state that "7 is a witness that 29 may be prime". As the Fermat test is probabilistic, composite numbers will sometimes pass a test, or even repeated tests. We call them pseudoprimes to some base: >>> is_fermat_probable_prime(3*11, 10) # 33 is a pseudoprime to base 10. 2 and we call 10 a "Fermat liar" for 33. A single passed test is not very convincing, but with more tests, we can gain more confidence. ``base`` must be a positive int between 1 and n-1 inclusive, or a tuple of such bases. 1 is permitted, but not very useful: it is a witness for all numbers. By default, base=2. >>> is_fermat_probable_prime(33, (10, 7)) 0 It may take an arbitrary number of Fermat tests to definitively prove a number is composite: >>> is_fermat_probable_prime(7*11*13*41, (17, 23, 356, 359)) 2 >>> is_fermat_probable_prime(7*11*13*41, (17, 23, 356, 359, 363)) 0 Unfortunately, there are some numbers which are composite but still pass *all* Fermat tests. These pseudoprime numbers are called the Carmichael numbers, and ``is_fermat_probable_prime`` cannot distinguish them from actual primes no matter how many tests you perform. For large enough ``n``, if a number passes ``k`` randomly chosen and independent Fermat tests, we can conclude that the probability that it is either prime or a Carmichael number is (on average) at least ``1 - (1/2**k)``. """ if not isinstance(base, tuple): base = (base,) # Deal with the simple deterministic cases first. if n < 2: return 0 # Certainly composite (or unity, or zero). elif n == 2: return 1 # Certainly prime. elif n % 2 == 0: return 0 # Now the Fermat test proper. for a in base: if pow(a, n-1, n) != 1: return 0 # n is certainly composite. return 2 # All of the bases are witnesses for n being prime. # http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test def is_miller_rabin_probable_prime(n, base=2): """is_miller_rabin_probable_prime(n [, base]) -> 0|1|2 Return a three-state flag (either 0, 1 or 2) that integer ``n `` is either a prime or strong pseudoprime, as witnessed by one or more integer bases. Arguments --------- n Integer to be tested for primality. base Optional integer base, or tuple of bases. (Defaults to 2.) Return result ------------- 0 Number is definitely non-prime. 1 Number is definitely prime. 2 Number is a probable prime or pseudoprime. ``is_miller_rabin_probable_prime`` performs the Miller-Rabin primality test, which is a strong probabilistic test. If a number fails this test, it is definitely composite (there are no false negative tests): >>> is_miller_rabin_probable_prime(99, 7) 0 However, if the number passes the test, it is provisional evidence that it may be a prime: >>> is_miller_rabin_probable_prime(29, 7) # 29 actually is prime. 2 In this case we can state that "7 is a witness that 29 may be prime". As the Miller-Rabin test is probabilistic, composite numbers will sometimes pass a test, or even repeated tests. Such numbers are known as pseudoprimes to some base: >>> assert 561 == 3*11*17 # Actually composite. >>> is_miller_rabin_probable_prime(561, 103) 2 A single passed test is not very convincing, but with more tests, we can gain more confidence. ``base`` must be a positive int between 1 and n-1 inclusive, or a tuple of such bases. 1 is permitted, but not very useful: it is a witness for all numbers. By default, base=2. >>> is_miller_rabin_probable_prime(561, (103, 7)) 0 It may take an arbitrary number of Miller-Rabin tests to definitively prove a number is composite: >>> assert 41041 == 7*11*13*41 # Actually composite. >>> is_miller_rabin_probable_prime(41041, (16, 92, 100, 256)) 2 >>> is_miller_rabin_probable_prime(41041, (16, 92, 100, 256, 288)) 0 For large enough ``n``, if a number passes ``k`` randomly chosen and independent Miller-Rabin tests, we can conclude that the probability that it is either prime or a strong pseudoprime is (on average) at least ``1 - (1/4**k)``. """ if not isinstance(base, tuple): base = (base,) # Deal with the trivial cases. if n < 2: return 0 # Certainly composite (or unity, or zero). if n == 2: return 1 # Certainly prime. elif n % 2 == 0: return 0 # Now perform the Miller-Rabin test proper. # Start by writing n-1 as 2**s * d. d, s = _factor2(n-1) for a in base: if _is_composite(a, d, s, n): return 0 # n is definitely composite. # If we get here, all of the bases are witnesses for n being prime. return 2 # Maybe prime. def _factor2(n): """Factorise positive integer n as d*2**i, and return (d, i). >>> _factor2(768) (3, 8) >>> _factor2(18432) (9, 11) Private function used internally by the Miller-Rabin primality test. """ assert n > 0 i = 0 d = n while 1: q, r = divmod(d, 2) if r == 1: break i += 1 d = q assert d%2 == 1 assert d*2**i == n return (d, i) def _is_composite(b, d, s, n): """_is_composite(b, d, s, n) -> True|False Tests base b to see if it is a witness for n being composite. Returns True if n is definitely composite, otherwise False if it *may* be prime. >>> _is_composite(4, 3, 7, 385) True >>> _is_composite(221, 3, 7, 385) False Private function used internally by the Miller-Rabin primality test. """ assert d*2**s == n-1 if pow(b, d, n) == 1: return False for i in range(s): if pow(b, 2**i * d, n) == n-1: return False return True def is_miller_rabin_definite_prime(n): """Deterministic but limited primality test using Miller-Rabin. Returns True for definite primes, False for definite non-primes, and raises ValueError for numbers which are unsure. """ if n <= 1: return False elif n == 2: return True elif n % 2 == 0: return False witnesses = _get_miller_rabin_witnesses(n) if witnesses is None: msg = 'no definite Miller-Rabin test is available for %d' % n raise ValueError(msg) return is_miller_rabin_probable_prime(n, witnesses) != 0 def _get_miller_rabin_witnesses(n): """Return a tuple of definitive Miller-Rabin witnesses for n.""" # We can always get a guaranteed (determistic, non-probabilistic) # result from Miller-Rabin by exhaustively testing with every # potential witness in the inclusive range 1...sqrt(n). If the # extended Riemann hypothesis is correct, that upper bound can be # further reduced to min(n-1, floor(2*(ln n)**2)). # # However, for sufficiently small n, it is possible to get a # deterministic answer from a mere handful of witnesses. # # Pomerance, Selfridge and Wagstaff (1980), and Jaeschke (1993) # have found small sets of bases which conclusively determine # primality for all values of n up to some upper limit, currently # around 3.8 million trillion (3.8e18). # # References: # [1] http://oeis.org/A014233 # [2] http://mathworld.wolfram.com/Rabin-MillerStrongPseudoprimeTest.html # [3] http://primes.utm.edu/prove/prove2_3.html # [4]
<reponame>oraclecode-moonsun/bmcs-cli<filename>tests/test_object_storage.py<gh_stars>0 # coding: utf-8 # Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. import click from datetime import datetime, timedelta import json import math import os import pytest import re import oraclebmc_cli from . import util CONTENT_INPUT_FILE = 'tests/resources/content_input.txt' GENERATED_CONTENT_INPUT_FILE = 'tests/temp/generated_content_input.txt' CONTENT_OUTPUT_FILE = 'tests/resources/content_output.txt' LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 5 DEFAULT_TEST_PART_SIZE = 2 @pytest.fixture def content_input_file(): return GENERATED_CONTENT_INPUT_FILE @pytest.fixture(params=[True, False]) def multipart(request): return request.param @pytest.fixture(params=[True, False]) def debug(request): return request.param @pytest.fixture(scope='module', autouse=True) def test_data(object_storage_client): # Setup test data util.ensure_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, 'Cli') def setup_function(): if os.path.exists(CONTENT_OUTPUT_FILE): os.remove(CONTENT_OUTPUT_FILE) def setup_module(): # generate large file for multipart testing util.create_large_file(GENERATED_CONTENT_INPUT_FILE, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) def teardown_module(): if os.path.exists(CONTENT_OUTPUT_FILE): os.remove(CONTENT_OUTPUT_FILE) if os.path.exists(GENERATED_CONTENT_INPUT_FILE): os.remove(GENERATED_CONTENT_INPUT_FILE) def test_run_all_operations(runner, config_file, debug, test_id): """Successfully calls every operation with required arguments only.""" bucket_name = 'cli_temp_bucket_' + test_id + ('_debug' if debug else '_no_debug') object_name = 'a' # ns get result = invoke(runner, config_file, ['ns', 'get'], debug=debug) validate_response(result, includes_debug_data=debug) assert util.NAMESPACE in result.output # bucket create result = invoke(runner, config_file, ['bucket', 'create', '-ns', util.NAMESPACE, '--compartment-id', util.COMPARTMENT_ID, '--name', bucket_name], debug=debug) validate_response(result, includes_debug_data=debug) # bucket get result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket_name], debug=debug) validate_response(result, includes_debug_data=debug) # bucket update result = invoke(runner, config_file, ['bucket', 'update', '-ns', util.NAMESPACE, '--name', bucket_name, '--metadata', '{"foo1":"bar1","key_with_underscore":"value_with_underscore"}', '--public-access-type', 'ObjectRead'], debug=debug) validate_response(result, includes_debug_data=debug) assert 'foo1' in result.output assert 'key_with_underscore' in result.output assert 'value_with_underscore' in result.output if not debug: response = json.loads(result.output) assert response['data']['public-access-type'] == 'ObjectRead' # remove foo1, keep key_with_underscore result = invoke(runner, config_file, ['bucket', 'update', '-ns', util.NAMESPACE, '--name', bucket_name, '--metadata', '{"foo1":null}'], debug=debug) validate_response(result, includes_debug_data=debug) assert 'bar1' not in result.output assert 'key_with_underscore' in result.output if not debug: assert 'foo1' not in result.output # bucket list (with both short and long version of compartment-id) result = invoke(runner, config_file, ['bucket', 'list', '-ns', util.NAMESPACE, '--compartment-id', util.COMPARTMENT_ID, '--limit', '10'], debug=debug) validate_response(result, includes_debug_data=debug) result = invoke(runner, config_file, ['bucket', 'list', '-ns', util.NAMESPACE, '-c', util.COMPARTMENT_ID, '--limit', '10'], debug=debug) validate_response(result, includes_debug_data=debug) # object put result = invoke(runner, config_file, ['object', 'put', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', CONTENT_INPUT_FILE], debug=debug) validate_response(result, includes_debug_data=debug) # object get result = invoke(runner, config_file, ['object', 'get', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', CONTENT_OUTPUT_FILE], debug=debug) validate_response(result, json_response_expected=False, includes_debug_data=debug) assertEqual(get_file_content(CONTENT_INPUT_FILE), get_file_content(CONTENT_OUTPUT_FILE)) # object head result = invoke(runner, config_file, ['object', 'head', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name], debug=debug) validate_response(result, includes_debug_data=debug) # object list result = invoke(runner, config_file, ['object', 'list', '-ns', util.NAMESPACE, '-bn', bucket_name], debug=debug) validate_response(result, includes_debug_data=debug) # object delete result = invoke(runner, config_file, ['object', 'delete', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name], input='n', debug=debug) assert result.exit_code != 0 result = invoke(runner, config_file, ['object', 'delete', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name], input='y', debug=debug) validate_response(result, json_response_expected=False, includes_debug_data=debug) # bucket delete result = invoke(runner, config_file, ['bucket', 'delete', '-ns', util.NAMESPACE, '--name', bucket_name, '--force'], debug=debug) validate_response(result, includes_debug_data=debug) def test_set_client_request_id(runner, config_file): input_id = 'examplerequestid' result = invoke(runner, config_file, ['ns', 'get'], root_params=['--request-id', input_id], debug=True) validate_response(result, includes_debug_data=True) assert input_id in result.output def test_bucket_options(runner, config_file, test_id): bucket = 'cli_test_bucket_options_' + test_id # bucket create result = invoke(runner, config_file, ['bucket', 'create', '-ns', util.NAMESPACE, '--compartment-id', util.COMPARTMENT_ID, '--name', bucket, '--public-access-type', 'ObjectRead']) validate_response(result) # bucket get result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket]) response = json.loads(result.output) etag = response['etag'] # validate public bucket setting assert response['data']['public-access-type'] == 'ObjectRead' result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket, '--if-match', etag]) validate_response(result) result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket, '--if-match', 'blah']) util.validate_service_error(result, 'The If-Match header') result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket, '--if-none-match', 'blah']) validate_response(result) result = invoke(runner, config_file, ['bucket', 'get', '-ns', util.NAMESPACE, '--name', bucket, '--if-none-match', etag]) util.validate_service_error(result) # bucket delete result = invoke(runner, config_file, ['bucket', 'delete', '-ns', util.NAMESPACE, '--name', bucket, '--if-match', 'blah', '--force']) util.validate_service_error(result) result = invoke(runner, config_file, ['bucket', 'delete', '-ns', util.NAMESPACE, '--name', bucket, '--if-match', etag, '--force']) validate_response(result) def test_object_put_confirmation_prompt(runner, config_file, content_input_file, test_id, multipart): bucket_name = 'CliReadOnlyTestBucket7' object_name = 'cli_test_object_put_confirmation_prompt_' + test_id put_required_args = ['object', 'put', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', content_input_file] if multipart: put_required_args = put_required_args + ['--part-size', str(DEFAULT_TEST_PART_SIZE)] head_required_args = ['object', 'head', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name] content_input_file_size = os.path.getsize(content_input_file) # Putting the object for the first time should not require a prompt. result = invoke(runner, config_file, put_required_args) validate_response(result) json_head = json.loads(invoke(runner, config_file, head_required_args).output) assertEquals(content_input_file_size, int(json_head['content-length'])) etag = json_head['etag'] # Test confirmation prompt accept. result = invoke(runner, config_file, put_required_args, input='y') validate_response(result, json_response_expected=False) json_head = json.loads(invoke(runner, config_file, head_required_args).output) assertEquals(content_input_file_size, int(json_head['content-length'])) new_etag = json_head['etag'] assertNotEquals(etag, new_etag) etag = new_etag # Test confirmation prompt reject. result = invoke(runner, config_file, put_required_args, input='n') assert result.exit_code != 0 json_head = json.loads(invoke(runner, config_file, head_required_args).output) # Make sure that etag and content length haven't changed. assertEquals(content_input_file_size, int(json_head['content-length'])) assertEquals(etag, json_head['etag']) # Test force result = invoke(runner, config_file, put_required_args + ['--force']) validate_response(result) new_etag = json.loads(result.output)['etag'] assertNotEquals(etag, new_etag) etag = new_etag json_head = json.loads(invoke(runner, config_file, head_required_args).output) assertEquals(content_input_file_size, int(json_head['content-length'])) # Test if-match with force result = invoke(runner, config_file, put_required_args + ['--if-match', etag, '--force']) validate_response(result) new_etag = json.loads(result.output)['etag'] assertNotEquals(etag, new_etag) etag = new_etag json_head = json.loads(invoke(runner, config_file, head_required_args).output) assertEquals(content_input_file_size, int(json_head['content-length'])) # Test if-match with force incorrect etag result = invoke(runner, config_file, put_required_args + ['--if-match', 'incorrect_etag', '--force']) assert result.exit_code != 0 json_head = json.loads(invoke(runner, config_file, head_required_args).output) # Make sure that etag and content length haven't changed. assertEquals(content_input_file_size, int(json_head['content-length'])) assertEquals(etag, json_head['etag']) # Test if-match with incorrect etag result = invoke(runner, config_file, put_required_args + ['--if-match', 'incorrect_etag']) assert result.exit_code != 0 json_head = json.loads(invoke(runner, config_file, head_required_args).output) # Make sure that etag and content length haven't changed. assertEquals(content_input_file_size, int(json_head['content-length'])) assertEquals(etag, json_head['etag']) # Test if-match with confirmation prompt reject. result = invoke(runner, config_file, put_required_args + ['--if-match', etag], input='n') assert result.exit_code != 0 json_head = json.loads(invoke(runner, config_file, head_required_args).output) # Make sure that etag and content length haven't changed. assertEquals(content_input_file_size, int(json_head['content-length'])) assertEquals(etag, json_head['etag']) # Test if-match with prompt accept. result = invoke(runner, config_file, put_required_args + ['--if-match', etag], input='y') validate_response(result, json_response_expected=False) json_head = json.loads(invoke(runner, config_file, head_required_args).output) new_etag = json_head['etag'] assert etag != new_etag assert content_input_file_size == int(json_head['content-length']) etag = new_etag # Clean up result = invoke(runner, config_file, ['object', 'delete', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--force', '--if-match', etag]) validate_response(result) def test_object_options(runner, config_file, test_id, content_input_file, multipart): bucket_name = 'CliReadOnlyTestBucket7' object_name = 'cli_test_object_put_options_' + test_id required_args = ['object', 'put', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', content_input_file, '--force'] if multipart: required_args = required_args + ['--part-size', str(DEFAULT_TEST_PART_SIZE)] head_required_args = ['object', 'head', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name] # Test object put ifm and md5 result = invoke(runner, config_file, required_args + ['--if-match', 'foo']) util.validate_service_error(result, 'IfMatchFailed') result = invoke(runner, config_file, required_args) assertEqual(0, result.exit_code) json_output = json.loads(result.output) etag = json_output['etag'] result = invoke(runner, config_file, required_args + ['--if-match', etag]) validate_response(result) if multipart: assert json_output['opc-multipart-md5'] else: md5 = json_output['opc-content-md5'] # multi part uploads do not take into account --content-md5 param result = invoke(runner, config_file, required_args + ['--content-md5', 'foo']) util.validate_service_error(result, error_message='The value of the Content-MD5 header') result = invoke(runner, config_file, required_args + ['--content-md5', md5]) validate_response(result) # Test object metadata result = invoke(runner, config_file, required_args + ['--metadata', '{"foo1":"bar1","foo2":"bar2"}']) validate_response(result) result = invoke(runner, config_file, head_required_args) validate_response(result) assert 'foo1' in result.output assert 'bar2' in result.output result = invoke(runner, config_file, required_args + ['--metadata', '{"foo2":"bar2"}']) validate_response(result) result = invoke(runner, config_file, head_required_args) validate_response(result) assert 'foo1' not in result.output assert 'foo2' in result.output # Test object head ifm and ifnm required_args = head_required_args etag = json.loads(invoke(runner, config_file, required_args).output)['etag'] result = invoke(runner, config_file, required_args + ['--if-match', etag]) validate_response(result) result = invoke(runner, config_file, required_args + ['--if-match', 'foo']) util.validate_service_error(result) # Test object get required_args = ['object', 'get', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', '-'] result = invoke(runner, config_file, required_args) validate_response(result, json_response_expected=False) # Check that "-f -" writes file content to SDTOUT. assert (get_file_content(content_input_file) in result.output) result = invoke(runner, config_file, required_args + ['--if-match', etag]) validate_response(result, json_response_expected=False) result = invoke(runner, config_file, required_args + ['--if-match', 'foo']) util.validate_service_error(result) result = invoke(runner, config_file, required_args + ['--if-none-match', etag]) util.validate_service_error(result) result = invoke(runner, config_file, required_args + ['--if-none-match', 'foo']) validate_response(result, json_response_expected=False) required_args = ['object', 'get', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--file', '-'] result = invoke(runner, config_file, required_args + ['--range', 'bytes=2-4']) # the two different content input files have different data expected_response_data = 'amp' if content_input_file == CONTENT_INPUT_FILE else 'aaa' assertEqual(expected_response_data, result.output) # Test object delete required_args = ['object', 'delete', '-ns', util.NAMESPACE, '-bn', bucket_name, '--name', object_name, '--force'] result = invoke(runner, config_file, required_args + ['--if-match', 'foo'])
<gh_stars>1-10 import click import pandas as pd import numpy as np import os import cv2 import skvideo.io import sys import time import tempfile import tensorflow as tf import xlsxwriter import json from PIL import Image from luminoth.tools.checkpoint import get_checkpoint_config from luminoth.utils.config import get_config, override_config_params from luminoth.utils.predicting import PredictorNetwork from luminoth.utils.vis import vis_objects IMAGE_FORMATS = ["jpg", "jpeg", "png", "tif"] VIDEO_FORMATS = ["mov", "mp4", "avi"] # TODO: check if more formats work LUMI_CSV_COLUMNS = ["image_id", "xmin", "xmax", "ymin", "ymax", "label", "prob"] def get_file_type(filename): extension = filename.split(".")[-1].lower() if extension in IMAGE_FORMATS: return "image" elif extension in VIDEO_FORMATS: return "video" def resolve_files(path_or_dir): """Returns the file paths for `path_or_dir`. Args: path_or_dir: String or list of strings for the paths or directories to run predictions in. For directories, will return all the files within. Returns: List of strings with the full path for each file. """ if not isinstance(path_or_dir, tuple): path_or_dir = (path_or_dir,) paths = [] for entry in path_or_dir: if tf.gfile.IsDirectory(entry): paths.extend( [ os.path.join(entry, f) for f in tf.gfile.ListDirectory(entry) if get_file_type(f) in ("image", "video") ] ) elif get_file_type(entry) in ("image", "video"): if not tf.gfile.Exists(entry): click.echo("Input {} not found, skipping.".format(entry)) continue paths.append(entry) return paths def filter_classes(objects, only_classes=None, ignore_classes=None): if ignore_classes: objects = [o for o in objects if o["label"] not in ignore_classes] if only_classes: objects = [o for o in objects if o["label"] in only_classes] return objects def filter_probabilities(objects, min_prob=None, max_prob=None): if min_prob: objects = [o for o in objects if o["prob"] > min_prob] if max_prob: objects = [o for o in objects if o["prob"] <= max_prob] return objects def bbs_pixel_apart(obj, objects, pixel_distance): repeated_indices = [] for index, each_obj in enumerate(objects): set_index_flags = 0 unique_differences = np.unique(np.fabs(np.subtract(each_obj, obj))).tolist() for i in unique_differences: if i <= pixel_distance: set_index_flags += 1 if set_index_flags == len(unique_differences): repeated_indices.append(index) return repeated_indices def filter_close_bbs(predictions, pixel_distance): # Save a prediction by suppressing the class with # lowest probability for the same bounding box objects = [prediction["bbox"] for prediction in predictions] labels = [prediction["label"] for prediction in predictions] probs = [prediction["prob"] for prediction in predictions] predictions = [None] * len(objects) assert len(objects) == len(labels) == len(probs) count = 0 for obj, label, prob in zip(objects, labels, probs): repeated_indices = bbs_pixel_apart(obj, objects, pixel_distance) if len(repeated_indices) > 0: repeated_probs = [probs[i] for i in repeated_indices] repeated_probs.append(prob) repeated_indices.append(count) max_prob = max(repeated_probs) assert len(repeated_probs) == len(repeated_indices) prob_index = [ index for index, prob in zip(repeated_indices, repeated_probs) if prob == max_prob ][0] d = { "bbox": objects[prob_index], "label": labels[prob_index], "prob": round(max_prob, 4), } predictions[prob_index] = d else: if objects.count(obj) == 1: d = {"bbox": obj, "label": label, "prob": round(prob, 4)} predictions[count] = d elif objects.count(obj) > 1: prob_repeated_objs = [ [i, probs[i]] for i, value in enumerate(objects) if value == obj ] repeated_indices = [i for (i, _) in prob_repeated_objs] repeated_probs = [j for (_, j) in prob_repeated_objs] max_prob = max(repeated_probs) prob_index = [ index for index, prob in zip(repeated_indices, repeated_probs) if prob == max_prob ][0] d = { "bbox": obj, "label": labels[prob_index], "prob": round(max_prob, 4), } predictions[prob_index] = d count += 1 predictions = list(filter(None, predictions)) predictions = sorted(predictions, key=lambda x: x["prob"], reverse=True) return predictions def rename_labels(predictions, new_labels): objects = [prediction["bbox"] for prediction in predictions] labels = [prediction["label"] for prediction in predictions] new_labels = [new_labels[label] for label in labels] probs = [prediction["prob"] for prediction in predictions] predictions = [None] * len(objects) predictions = sorted( [ { "bbox": obj, "label": label, "prob": round(prob, 4), } for obj, label, prob in zip(objects, new_labels, probs) ], key=lambda x: x["prob"], reverse=True, ) return predictions def run_image_through_network( network, image, only_classes=None, ignore_classes=None, save_path=None, min_prob=None, max_prob=None, pixel_distance=0, new_labels=None, ): objects = network.predict_image(image) # Filter the results according to the user input. objects = filter_classes( objects, only_classes=only_classes, ignore_classes=ignore_classes ) # Filter the results according to the user input. objects = filter_probabilities(objects, min_prob=min_prob, max_prob=max_prob) objects = filter_close_bbs(objects, pixel_distance) if new_labels is not None: objects = rename_labels(objects, new_labels) # Save predicted image. if save_path: image = cv2.cvtColor(vis_objects(np.array(image), objects), cv2.COLOR_BGR2RGB) cv2.imwrite(save_path, image) click.echo(" done.") return objects def predict_image( network, path, only_classes=None, ignore_classes=None, save_path=None, min_prob=None, max_prob=None, pixel_distance=0, new_labels=None, ): click.echo("Predicting {}...".format(path), nl=False) extension = path.split(".")[-1] basename = os.path.basename(path) # Convert tif to a png acceptable by tensorflow in next steps below # Tried jpg creates all zeros on uint16 data -also jpg is lossy compression if extension == "tif": image = Image.open(path) image = cv2.cvtColor(np.array(image), cv2.COLOR_GRAY2BGR) tempname = basename.replace("." + extension, "." + "png") path = os.path.join(tempfile.mkdtemp(prefix="lumi"), tempname) cv2.imwrite(path, image) # Open and read the image to predict. with tf.gfile.Open(path, "rb") as f: try: image = Image.open(f).convert("RGB") except (tf.errors.OutOfRangeError, OSError) as e: click.echo() click.echo("Error while processing {}: {}".format(path, e)) return # Run image through the network. return run_image_through_network( network, image, only_classes, ignore_classes, save_path, min_prob, max_prob, pixel_distance, new_labels, ) def predict_video( network, path, only_classes=None, ignore_classes=None, save_path=None, min_prob=None, max_prob=None, pixel_distance=0, new_labels=None, ): if save_path: # We hardcode the video output to mp4 for the time being. save_path = os.path.splitext(save_path)[0] + ".mp4" try: writer = skvideo.io.FFmpegWriter(save_path) except AssertionError as e: tf.logging.error(e) tf.logging.error("Please install ffmpeg before making video predictions.") exit() else: click.echo( "Video not being saved. Note that for the time being, no JSON " "output is being generated. Did you mean to specify `--save-path`?" ) num_of_frames = int(skvideo.io.ffprobe(path)["video"]["@nb_frames"]) video_progress_bar = click.progressbar( skvideo.io.vreader(path), length=num_of_frames, label="Predicting {}".format(path), ) objects_per_frame = [] with video_progress_bar as bar: try: start_time = time.time() for idx, frame in enumerate(bar): # Run image through network. objects = network.predict_image(frame) # Filter the results according to the user input. objects = filter_classes( objects, only_classes=only_classes, ignore_classes=ignore_classes ) objects = filter_probabilities( objects, min_prob=min_prob, max_prob=max_prob ) objects = filter_close_bbs(objects, pixel_distance) if new_labels is not None: objects = rename_labels(objects, new_labels) objects_per_frame.append({"frame": idx, "objects": objects}) # Draw the image and write it to the video file. if save_path: image = vis_objects(frame, objects) writer.writeFrame(image) stop_time = time.time() click.echo("fps: {0:.1f}".format(num_of_frames / (stop_time - start_time))) except RuntimeError as e: click.echo() # Error prints next to progress bar otherwise. click.echo("Error while processing {}: {}".format(path, e)) if save_path: click.echo( "Partially processed video file saved in {}".format(save_path) ) if save_path: writer.close() return objects_per_frame def write_xlsx(csv_path, spacing, class_labels_percentage): folder_path = os.path.dirname(csv_path) workbook = xlsxwriter.Workbook(csv_path.replace(".csv", ".xlsx")) worksheet = workbook.add_worksheet("sheet1") worksheet.set_column("A:A", 15) worksheet.set_column("B:B", 10) temp_folder = os.path.join(folder_path, "predict_temp_bbs") if not os.path.exists(temp_folder): os.makedirs(temp_folder) else: print("Path {} already exists, might be overwriting data".format(temp_folder)) df = pd.read_csv(csv_path) rowy = 0 for label, frac in class_labels_percentage.items(): subset_df = df[df["label"] == label].sample(frac=frac) for index, row in subset_df.iterrows(): for i in range(len(row)): worksheet.write(rowy * spacing, i, row[i]) image = cv2.imread( row["image_id"], cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR ) if len(image.shape) == 3: image = image[row.ymin : row.ymax, row.xmin : row.xmax, :] else: image = image[row.ymin : row.ymax, row.xmin : row.xmax] temp_image = os.path.join(temp_folder, "temp_{}.png".format(rowy)) cv2.imwrite(temp_image, image) worksheet.insert_image( rowy * spacing, i + 1, temp_image, {"x_scale": 0.3, "y_scale": 0.3} ) rowy += 1 workbook.close() def get_key(new_labels, val): for key, value in new_labels.items(): if val == value: return key def predict_function( path_or_dir, config_files, checkpoint, override_params, output_path, save_media_to, min_prob, max_prob, max_detections, only_class, ignore_class, debug, xlsx_spacing, classes_json, pixel_distance, new_labels, ): class_labels_percentage = {} if classes_json is not None: with open(classes_json, "r") as f: class_labels_percentage = json.load(f) if new_labels is not None: with open(new_labels, "r") as f: new_labels = json.load(f) if debug: tf.logging.set_verbosity(tf.logging.DEBUG) else: tf.logging.set_verbosity(tf.logging.ERROR) if only_class and ignore_class: click.echo("Only one of `only-class` or `ignore-class` may be specified.") return # Process the input and get the actual files to predict. files = resolve_files(path_or_dir) if not files: error = "No files to predict found. Accepted formats are: {}.".format( ", ".join(IMAGE_FORMATS + VIDEO_FORMATS) ) click.echo(error) return else: click.echo("Found {} files to predict.".format(len(files))) # Create `save_media_to` if specified and it doesn't exist. if save_media_to: tf.gfile.MakeDirs(save_media_to) # Resolve the config to use and initialize the model. if checkpoint: config = get_checkpoint_config(checkpoint) elif config_files: config = get_config(config_files) else: click.echo("Neither checkpoint not config specified, assuming `accurate`.") config = get_checkpoint_config("accurate") if override_params: config = override_config_params(config, override_params) # Filter bounding boxes according to `min_prob` and `max_detections`. if config.model.type == "fasterrcnn": if config.model.network.with_rcnn: config.model.rcnn.proposals.total_max_detections = max_detections else: config.model.rpn.proposals.post_nms_top_n = max_detections config.model.rcnn.proposals.min_prob_threshold = min_prob elif config.model.type == "ssd": config.model.proposals.total_max_detections = max_detections config.model.proposals.min_prob_threshold = min_prob else: raise ValueError("Model type '{}' not supported".format(config.model.type)) # Instantiate the model indicated by the
intervals of the ordering. INPUT FORMAT (file bcount.in): The first line of input contains N and Q (1≤N≤100,000, 1≤Q≤100,000). The next N lines contain an integer that is either 1, 2, or 3, giving the breed ID of a single cow in the ordering. The next Q lines describe a query in the form of two integers a,b (a≤b). OUTPUT FORMAT (file bcount.out): For each of the Q queries (a,b), print a line containing three numbers: the number of cows numbered a…b that are Holsteins (breed 1), Guernseys (breed 2), and Jerseys (breed 3). SAMPLE INPUT: 6 3 2 1 1 3 2 1 1 6 3 3 2 4 SAMPLE OUTPUT: 3 2 1 1 0 0 2 0 1 Problem credits: <NAME> ''' class BreedCounting: def __init__( self, breedIdList, queryList ): self.breedIdList = breedIdList self.queryList = queryList self.idHolstein, self.idGuernsey, self.idJersey = 1, 2, 3 def process( self ): cumulativeSumList = [ [ 0 ], [ 0 ], [ 0 ] ] for breedId in self.breedIdList: for index in range( len( cumulativeSumList ) ): # index 0..2 is mapped to the breedId from 1..3 count = 1 if index + 1 == breedId else 0 cumulativeSumList[ index ].append( count + cumulativeSumList[ index ][ -1 ] ) resultList = list() for low, high in self.queryList: countList = list() for index in range( len( cumulativeSumList ) ): count = cumulativeSumList[ index ][ high ] - cumulativeSumList[ index ][ low - 1 ] countList.append( count ) resultList.append( tuple( countList ) ) return resultList class BreedCountingTest( unittest.TestCase ): def test_BreedCounting( self ): for testfile in getTestFileList( tag='breedcounting' ): self._verify( testfile ) def _verify( self, testfile ): with open( 'tests/usaco/breedcounting/{}.in'.format( testfile ) ) as inputFile, \ open( 'tests/usaco/breedcounting/{}.out'.format( testfile ) ) as solutionFile: N, Q = readIntegers( inputFile ) breedIdList = [ readInteger( inputFile ) for _ in range( N ) ] queryList = [ tuple( readIntegers( inputFile ) ) for _ in range( Q ) ] resultList = [ tuple( readIntegers( solutionFile ) ) for _ in range( Q ) ] print( 'Testcase {} N = {} Q = {}'.format( testfile, N, Q ) ) self.assertEqual( BreedCounting( breedIdList, queryList ).process(), resultList ) def test_BreedCounting_Sample( self ): breedIdList = [ 2, 1, 1, 3, 2, 1 ] queryList = [ (1, 6), (3, 3), (2, 4) ] self.assertEqual( BreedCounting( breedIdList, queryList ).process(), [ (3, 2, 1), (1, 0, 0), (2, 0, 1 ) ] ) ''' USACO 2015 December Contest, Silver Problem 2. High Card Wins Bessie the cow is a huge fan of card games, which is quite surprising, given her lack of opposable thumbs. Unfortunately, none of the other cows in the herd are good opponents. They are so bad, in fact, that they always play in a completely predictable fashion! Nonetheless, it can still be a challenge for Bessie to figure out how to win. Bessie and her friend Elsie are currently playing a simple card game where they take a deck of 2N cards, conveniently numbered 1…2N, and divide them into N cards for Bessie and N cards for Elsie. The two then play N rounds, where in each round Bessie and Elsie both play a single card, and the player with the highest card earns a point. Given that Bessie can predict the order in which Elsie will play her cards, please determine the maximum number of points Bessie can win. INPUT FORMAT (file highcard.in): The first line of input contains the value of N (1≤N≤50,000). The next N lines contain the cards that Elsie will play in each of the successive rounds of the game. Note that it is easy to determine Bessie's cards from this information. OUTPUT FORMAT (file highcard.out): Output a single line giving the maximum number of points Bessie can score. SAMPLE INPUT: 3 1 6 4 SAMPLE OUTPUT: 2 Here, Bessie must have cards 2, 3, and 5 in her hand, and she can use these to win at most 2 points by saving the 5 until the end to beat Elsie's 4. Problem credits: <NAME> and <NAME> ''' class HighCardWins: def __init__( self, elsieCards ): self.elsieCards = elsieCards def maximumPoints( self ): N = len( self.elsieCards ) cardsAvailable = [ True for _ in range( 2 * N + 1 ) ] for card in self.elsieCards: cardsAvailable[ card ] = False elsieCardsSorted = list() bessieCardsSorted = list() for cardNumber in range( 1, len( cardsAvailable ) ): if cardsAvailable[ cardNumber ]: bessieCardsSorted.append( cardNumber ) else: elsieCardsSorted.append( cardNumber ) points = 0 i = j = 0 while j < len( bessieCardsSorted ): if bessieCardsSorted[ j ] > elsieCardsSorted[ i ]: points += 1 i += 1 j += 1 return points class HighCardWinsTest( unittest.TestCase ): def test_HighCardWins( self ): for testfile in getTestFileList( tag='highcardwins' ): self._verify( testfile ) def _verify( self, testfile ): with open( 'tests/usaco/highcardwins/{}.in'.format( testfile ) ) as inputFile, \ open( 'tests/usaco/highcardwins/{}.out'.format( testfile ) ) as solutionFile: N = readInteger( inputFile ) elsieCards = [ readInteger( inputFile ) for _ in range( N ) ] maximumPoints = readInteger( solutionFile ) print( 'Testcase {} N = {} maximumPoints = {}'.format( testfile, N, maximumPoints ) ) self.assertEqual( HighCardWins( elsieCards ).maximumPoints(), maximumPoints ) def test_HighCardWins_Sample( self ): self.assertEqual( HighCardWins( [ 1, 6, 4 ] ).maximumPoints(), 2 ) ''' USACO 2015 December Contest, Gold Problem 2. Fruit Feast Bessie has broken into <NAME>'s house again! She has discovered a pile of lemons and a pile of oranges in the kitchen (effectively an unlimited number of each), and she is determined to eat as much as possible. Bessie has a maximum fullness of T (1≤T≤5,000,000). Eating an orange increases her fullness by A, and eating a lemon increases her fullness by B (1≤A,B≤T). Additionally, if she wants, Bessie can drink water at most one time, which will instantly decrease her fullness by half (and will round down). Help Bessie determine the maximum fullness she can achieve! INPUT FORMAT (file feast.in): The first (and only) line has three integers T, A, and B. OUTPUT FORMAT (file feast.out): A single integer, representing the maximum fullness Bessie can achieve. SAMPLE INPUT: 8 5 6 SAMPLE OUTPUT: 8 Problem credits: <NAME> ''' class FruitFeast: def __init__( self, T, A, B ): self.T, self.A, self.B = T, A, B def full( self ): waterUsageIndexDict = { True : 0, False : 1 } visited = [ [ False for _ in range( self.T + 1 ) ] for _ in range( 2 ) ] stack = list() stack.append( (0, True) ) bestFullness = 0 while len( stack ) > 0: N, waterUsageRemaining = stack.pop() bestFullness = max( bestFullness, N ) visited[ waterUsageIndexDict[ waterUsageRemaining ] ][ N ] = True possibleFullness = [ (N + self.A, waterUsageRemaining), (N + self.B, waterUsageRemaining) ] if waterUsageRemaining: possibleFullness.append( (N // 2, False) ) for fullness, waterUsageRemaining in possibleFullness: if fullness > self.T: continue if not visited[ waterUsageIndexDict[ waterUsageRemaining ] ][ fullness ]: stack.append( (fullness, waterUsageRemaining) ) return bestFullness class FruitFeastTest( unittest.TestCase ): def test_FruitFeast( self ): for testfile in getTestFileList( tag='fruitfeast' ): self._verify( testfile ) def _verify( self, testfile ): with open( 'tests/usaco/fruitfeast/{}.in'.format( testfile ) ) as inputFile, \ open( 'tests/usaco/fruitfeast/{}.out'.format( testfile ) ) as solutionFile: T, A, B = readIntegers( inputFile ) bestFullness = readInteger( solutionFile ) print( 'Testcase {} T = {} A = {} B = {} bestFullness = {}'.format( testfile, T, A, B, bestFullness ) ) self.assertEqual( FruitFeast( T, A, B ).full(), bestFullness ) def test_FruitFeast_Sample( self ): self.assertEqual( FruitFeast( 8, 5, 6 ).full(), 8 ) ''' USACO 2021 January Contest, Bronze Problem 1. Uddered but not Herd A little known fact about cows is that they have their own version of the alphabet, the "cowphabet". It consists of the 26 letters 'a' through 'z', but when a cow speaks the cowphabet, she lists these letters in a specific ordering that might be different from the order 'abcdefghijklmnopqrstuvwxyz' we are used to hearing. To pass the time, Bessie the cow has been humming the cowphabet over and over again, and <NAME> is curious how many times she's hummed it. Given a lowercase string of letters that <NAME> has heard Bessie say, compute the minimum number of times Bessie must have hummed the entire cowphabet in order for <NAME> to have heard the given string. <NAME> isn't always paying attention to what Bessie hums, and so he might have missed some of the letters that Bessie has hummed. The string you are told consists of just the letters that he remembers hearing. INPUT FORMAT (input arrives from the terminal / stdin): The first line of input contains the 26 lowercase letters 'a' through 'z' in the order they appear in the cowphabet. The next line contains the string of lowercase letters that <NAME> heard Bessie say. This string has
40, 40], dtype=np.float64), avg_color + np.array([20, 30, 50], dtype=np.float64)) for i in range(maskHSV.shape[0]): t = maskHSV[i].nonzero()[0].flatten() if t.size > 1: maskHSV[i, t[0]:t[-1]] = 255 masked_HSV = cv2.bitwise_and(img_HSV, img_HSV, mask=maskHSV) # set img new_img = masked_HSV.copy().astype(np.float32) left_edge = np.zeros(masked_HSV.shape[0], dtype=np.uint32) right_edge = np.full(masked_HSV.shape[0], img_HSV.shape[1], dtype=np.uint32) for _y in range(masked_HSV.shape[0]): t = np.argwhere(masked_HSV[_y].sum(-1) > 0).flatten() if t.size > 0: k = 4 left_edge[_y] = np.min(t) + k right_edge[_y] = np.max(t) - k new_img[_y, :left_edge[_y]] = new_img[_y, left_edge[_y]] new_img[_y, right_edge[_y]:] = new_img[_y, right_edge[_y]] up_edge = np.zeros(img_HSV.shape[1], dtype=np.uint32) down_edge = np.full(img_HSV.shape[1], img_HSV.shape[0], dtype=np.uint32) for _x in range(img_HSV.shape[1]): t = np.argwhere(new_img[:, _x, :].sum(-1) > 0).flatten() if t.size > 0: k = 4 up_edge[_x] = np.min(t) + k down_edge[_x] = np.max(t) - k new_img[:up_edge[_x], _x, :] = new_img[up_edge[_x], _x, :] new_img[down_edge[_x]:, _x, :] = new_img[down_edge[_x], _x, :] out_img = new_img.round().clip(0, 255).astype(np.uint8) out_img_BGR = hsv2bgr(out_img) display(np.concatenate((img_BGR, out_img_BGR), axis=1)) return def m4(): img_BGR = cv2.imread(r'Data/mask/0_texture_2.png') img_HSV = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2HSV).astype(np.float64) avg_color = img_HSV[np.logical_and(img_HSV.sum(-1) > 10, img_HSV.sum(-1) < 700)].mean(0) maskHSV = cv2.inRange(img_HSV, avg_color - np.array([10, 40, 40], dtype=np.float64), avg_color + np.array([20, 30, 50], dtype=np.float64)) for i in range(maskHSV.shape[0]): t = maskHSV[i].nonzero()[0].flatten() if t.size > 1: maskHSV[i, t[0]:t[-1]] = 255 masked_HSV = cv2.bitwise_and(img_HSV, img_HSV, mask=maskHSV) # set img new_img = masked_HSV.copy().astype(np.float32) left_edge = np.zeros(masked_HSV.shape[0], dtype=np.uint32) right_edge = np.full(masked_HSV.shape[0], img_HSV.shape[1], dtype=np.uint32) for _y in range(masked_HSV.shape[0]): t = np.argwhere(masked_HSV[_y].sum(-1) > 0).flatten() if t.size > 0: k = 4 left_edge[_y] = np.min(t) + k right_edge[_y] = np.max(t) - k kind = "slinear" x_fit = np.concatenate(([0], np.arange(left_edge[_y], left_edge[_y] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, left_edge[_y]:left_edge[_y] + k, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate(([new_img.shape[1]], np.arange(right_edge[_y] - k, right_edge[_y])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, right_edge[_y] - k: right_edge[_y], :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[_y, :left_edge[_y]] = fl(np.arange(left_edge[_y])).clip(0, 255) new_img[_y, right_edge[_y]:] = fr(np.arange(right_edge[_y], new_img.shape[1])).clip(0, 255) up_edge = np.zeros(img_HSV.shape[1], dtype=np.uint32) down_edge = np.full(img_HSV.shape[1], img_HSV.shape[0], dtype=np.uint32) for _x in range(img_HSV.shape[1]): t = np.argwhere(new_img[:, _x, :].sum(-1) > 0).flatten() if t.size > 0: k = 4 up_edge[_x] = np.min(t) + k down_edge[_x] = np.max(t) - k k = 1 kind = "slinear" x_fit = np.concatenate(([0], np.arange(up_edge[_x], up_edge[_x] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[up_edge[_x]:up_edge[_x] + k, _x, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate(([new_img.shape[1]], np.arange(down_edge[_x] - k, down_edge[_x])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[down_edge[_x] - k: down_edge[_x], _x, :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[:up_edge[_x], _x, :] = fl(np.arange(up_edge[_x])).clip(0, 255) new_img[down_edge[_x]:, _x, :] = fr(np.arange(down_edge[_x], new_img.shape[0])).clip(0, 255) out_img = new_img.round().clip(0, 255).astype(np.uint8) out_img_BGR = hsv2bgr(out_img) display(np.concatenate((img_BGR, out_img_BGR), axis=1)) return def m5(): img_BGR = cv2.imread(r'Data/mask/0_texture_2.png') img_HSV = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2HSV).astype(np.float64) avg_color = img_HSV[np.logical_and(img_HSV.sum(-1) > 10, img_HSV.sum(-1) < 700)].mean(0) maskHSV = cv2.inRange(img_HSV, avg_color - np.array([10, 40, 40], dtype=np.float64), avg_color + np.array([20, 30, 50], dtype=np.float64)) for i in range(maskHSV.shape[0]): t = maskHSV[i].nonzero()[0].flatten() if t.size > 1: maskHSV[i, t[0]:t[-1]] = 255 masked_HSV = cv2.bitwise_and(img_HSV, img_HSV, mask=maskHSV) # set img new_img = masked_HSV.copy().astype(np.float32) left_edge = np.zeros(masked_HSV.shape[0], dtype=np.uint32) right_edge = np.full(masked_HSV.shape[0], img_HSV.shape[1], dtype=np.uint32) for _y in range(masked_HSV.shape[0]): t = np.argwhere(masked_HSV[_y].sum(-1) > 0).flatten() if t.size > 0: k = 4 left_edge[_y] = np.min(t) + k right_edge[_y] = np.max(t) - k kind = "slinear" x_fit = np.concatenate(([left_edge[_y] // 2], np.arange(left_edge[_y], left_edge[_y] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, left_edge[_y]:left_edge[_y] + k, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate( ([(new_img.shape[1] + right_edge[_y]) // 2], np.arange(right_edge[_y] - k, right_edge[_y])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, right_edge[_y] - k: right_edge[_y], :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[_y, :left_edge[_y]] = fl(np.arange(left_edge[_y])).clip(0, 255) new_img[_y, right_edge[_y]:] = fr(np.arange(right_edge[_y], new_img.shape[1])).clip(0, 255) for _y in range(new_img.shape[0] - 1): for _x in reversed(range(0, left_edge[_y])): new_img[_y, _x] = 0.33 * new_img[_y - 1, _x] + 0.34 * new_img[_y, _x + 1] + 0.33 * new_img[ _y + 1, _x] for _x in range(right_edge[_y], new_img.shape[1]): new_img[_y, _x] = 0.33 * new_img[_y - 1, _x] + 0.34 * new_img[_y, _x - 1] + 0.33 * new_img[ _y + 1, _x] up_edge = np.zeros(img_HSV.shape[1], dtype=np.uint32) down_edge = np.full(img_HSV.shape[1], img_HSV.shape[0], dtype=np.uint32) for _x in range(img_HSV.shape[1]): t = np.argwhere(new_img[:, _x, :].sum(-1) > 0).flatten() if t.size > 0: k = 4 up_edge[_x] = np.min(t) + k down_edge[_x] = np.max(t) - k k = 1 kind = "slinear" x_fit = np.concatenate(([up_edge[_x] // 2], np.arange(up_edge[_x], up_edge[_x] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[up_edge[_x]:up_edge[_x] + k, _x, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate( ([(new_img.shape[1] + down_edge[_x]) // 2], np.arange(down_edge[_x] - k, down_edge[_x])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[down_edge[_x] - k: down_edge[_x], _x, :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[:up_edge[_x], _x, :] = fl(np.arange(up_edge[_x])).clip(0, 255) new_img[down_edge[_x]:, _x, :] = fr(np.arange(down_edge[_x], new_img.shape[0])).clip(0, 255) for _x in range(new_img.shape[1] - 1): for _y in reversed(range(0, up_edge[_x])): new_img[_y, _x] = 0.33 * new_img[_y, _x - 1] + 0.34 * new_img[_y + 1, _x] + 0.33 * new_img[ _y, _x + 1] for _y in range(down_edge[_x], new_img.shape[0]): new_img[_y, _x] = 0.33 * new_img[_y, _x - 1] + 0.34 * new_img[_y - 1, _x] + 0.33 * new_img[ _y, _x + 1] out_img = new_img.round().clip(0, 255).astype(np.uint8) out_img_BGR = hsv2bgr(out_img) display(np.concatenate((img_BGR, out_img_BGR), axis=1)) return def m6(): img_BGR = cv2.imread(r'Data/mask/0_texture_2.png') img_HSV = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2HSV).astype(np.float64) avg_color = img_HSV[np.logical_and(img_HSV.sum(-1) > 10, img_HSV.sum(-1) < 700)].mean(0) maskHSV = cv2.inRange(img_HSV, avg_color - np.array([10, 40, 40], dtype=np.float64), avg_color + np.array([20, 30, 50], dtype=np.float64)) for i in range(maskHSV.shape[0]): t = maskHSV[i].nonzero()[0].flatten() if t.size > 1: maskHSV[i, t[0]:t[-1]] = 255 masked_HSV = cv2.bitwise_and(img_HSV, img_HSV, mask=maskHSV) # set img new_img = masked_HSV.copy().astype(np.float32) left_edge = np.zeros(masked_HSV.shape[0], dtype=np.uint32) right_edge = np.full(masked_HSV.shape[0], img_HSV.shape[1], dtype=np.uint32) for _y in range(masked_HSV.shape[0]): t = np.argwhere(masked_HSV[_y].sum(-1) > 0).flatten() if t.size > 0: k = 4 left_edge[_y] = np.min(t) + k right_edge[_y] = np.max(t) - k kind = "slinear" x_fit = np.concatenate(([left_edge[_y] // 2], np.arange(left_edge[_y], left_edge[_y] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, left_edge[_y]:left_edge[_y] + k, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate( ([(new_img.shape[1] + right_edge[_y]) // 2], np.arange(right_edge[_y] - k, right_edge[_y])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[_y, right_edge[_y] - k: right_edge[_y], :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[_y, left_edge[_y] // 2:left_edge[_y], :] = fl(np.arange(left_edge[_y] // 2, left_edge[_y])).clip(0, 255) new_img[_y, right_edge[_y]:(new_img.shape[1] + right_edge[_y]) // 2, :] = fr( np.arange(right_edge[_y], (new_img.shape[1] + right_edge[_y]) // 2)).clip(0, 255) new_img[_y, :left_edge[_y] // 2, :] = avg_color new_img[_y, (new_img.shape[1] + right_edge[_y]) // 2:, :] = avg_color for _y in range(new_img.shape[0] - 1): for _x in reversed(range(0, left_edge[_y])): new_img[_y, _x] = 0.33 * new_img[_y - 1, _x] + 0.34 * new_img[_y, _x + 1] + 0.33 * new_img[ _y + 1, _x] for _x in range(right_edge[_y], new_img.shape[1]): new_img[_y, _x] = 0.33 * new_img[_y - 1, _x] + 0.34 * new_img[_y, _x - 1] + 0.33 * new_img[ _y + 1, _x] up_edge = np.zeros(img_HSV.shape[1], dtype=np.uint32) down_edge = np.full(img_HSV.shape[1], img_HSV.shape[0], dtype=np.uint32) for _x in range(img_HSV.shape[1]): t = np.argwhere(new_img[:, _x, :].sum(-1) > 0).flatten() if t.size > 0: k = 4 up_edge[_x] = np.min(t) + k down_edge[_x] = np.max(t) - k k = 1 kind = "slinear" x_fit = np.concatenate(([up_edge[_x] // 2], np.arange(up_edge[_x], up_edge[_x] + k)), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[up_edge[_x]:up_edge[_x] + k, _x, :]), 0) fl = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") x_fit = np.concatenate( ([(new_img.shape[1] + down_edge[_x]) // 2], np.arange(down_edge[_x] - k, down_edge[_x])), 0) y_fit = np.concatenate((avg_color.reshape(1, 3), new_img[down_edge[_x] - k: down_edge[_x], _x, :]), 0) fr = interpolate.interp1d(x_fit, y_fit, kind=kind, axis=0, fill_value="extrapolate") new_img[up_edge[_x] // 2:up_edge[_x], _x, :] = fl(np.arange(up_edge[_x] // 2, up_edge[_x])).clip(0, 255) new_img[down_edge[_x]:(new_img.shape[0] + down_edge[_y]) // 2, _x, :] = fr( np.arange(down_edge[_x], (new_img.shape[0] + down_edge[_y]) // 2)).clip(0, 255) new_img[:up_edge[_x] // 2, _x, :] = avg_color new_img[(new_img.shape[0] + down_edge[_x]) // 2:, _x, :] = avg_color for _x in range(new_img.shape[1] - 1): for _y in reversed(range(0, up_edge[_x])): new_img[_y, _x] = 0.33 * new_img[_y, _x - 1] + 0.34 * new_img[_y + 1, _x] + 0.33 * new_img[ _y, _x + 1] for _y in range(down_edge[_x], new_img.shape[0]): new_img[_y, _x]
1 final_argument_whitespace = True option_spec = { 'scale' : rst.directives.unchanged, 'label' : rst.directives.unchanged, 'position' : rst.directives.unchanged, 'offset' : rst.directives.unchanged, } has_content = True def run(self): node_list = [] # Unlike a normal image, our reference will come from the content... content = '\n'.join(self.content)#.replace('\\\\','\\') # Have to have some serious protection here.... if '\nimport' in content: assert False # Define image name and location image_hash = hashlib.md5(content.encode('utf-8')).hexdigest() image_name = '%s.png' % image_hash image_path = os.path.join(SYSGEN_PATH, 'matplotlib', image_name) image_url = posixpath.normpath(os.path.join(SYSGEN_URL, 'matplotlib', image_name)) self.options['uri'] = image_url # Maybe we already made it? If not, make it now... if not os.path.isfile(image_path): print 'Making image %s' % image_name # Set up our folders and filename variables curdir = os.getcwd() # Write the matplotlib file to the temp folder os.chdir(MATPLOTLIB_WORK_PATH) f = codecs.open('temp.py', 'w', 'utf-8') f.write(MATPLOTLIB_TEMPLATE % content) f.close() # Run matplotlib ... cmd = [PYTHON_CMD, 'temp.py'] p = Popen(cmd,stdout=PIPE,stderr=PIPE) out, err = p.communicate() # Move the image file and clean up image_dir = os.path.dirname(image_path) if not os.path.exists(image_dir): os.makedirs(image_dir) shutil.copyfile('temp.png', image_path) # os.remove('rm temp.*') os.chdir(curdir) try: scale = float(self.options['scale']) except: scale = 1.00 if 'position' in self.options.keys(): position = self.options['position'] else: position = 'default' check_path = image_path # LaTeX writer specifics start (offset is ignored for HTML writer) if 'offset' in self.options.keys(): offset = self.options['offset'] else: offset = '0pt' if self.arguments: caption = rst2latex(self.arguments[0]) caption = r'\captionof{figure}{%s}' % caption else: caption = '' if 'label' in self.options.keys(): label = nodes.make_id(self.options['label']) label = r'\label{plt:%s}' % label else: label = '' if os.path.exists(check_path): latex_path = get_latex_path(check_path) figtext = r'\includegraphics[scale=%s]{%s}' figtext = figtext % (scale*0.5, latex_path) if not label: label = nodes.make_id(image_name) label = r'\label{plt:%s}' % label else: print 'Could not locate "%s"' % check_path figtext = '\n'.join(self.content) text = FIG_TEMPLATE[position] % { 'offset' : offset, 'caption' : caption, 'label' : label, 'figtext' : figtext, } node = nodes.raw(text=text, format='latex', **self.options) node_list += [node] # # HTML writer specifics start... if os.path.exists(check_path): img_width, img_height = Image.open(check_path).size fig_width = int(img_width*scale*0.75) if 'label' in self.options.keys(): label = nodes.make_id(self.options['label']) else: label = nodes.make_id(image_name) figtext = '\n' if 'side' in position: # figtext += '<div id="plt:{0}" class="my-docutils plt {1}" style="width:{2}px;">\n' figtext += '<div id="plt:{0}" class="my-docutils plt {1}">\n' else: figtext += '<div id="plt:{0}" class="my-docutils plt {1}">\n' # figtext += '<div id="plt:{0}" class="my-docutils plt {1}" style="width:{2}px;">\n' figtext = figtext.format(label, position, fig_width) figtext += '<a href="{0}"><img width="{1}px" src="{0}"></a>\n'.format(image_url, fig_width) # figtext += '<a href="{0}"><img src="{0}"></a>\n'.format(image_url, fig_width) if self.arguments: figtext += rst2html(self.arguments[0]) figtext += '</div>\n' else: print 'Could not locate "%s"' % check_path figtext = '\n<div class="my-docutils-error">\n<p>File generation error:</p>\n<pre>\n' + '\n'.join(self.content) + '</pre>\n</div>\n' text = figtext node = nodes.raw(text=text, format='html', **self.options) node_list += [node] return node_list rst.directives.register_directive('plt', plt_directive) class ani_directive(rst.Directive): """ --------------------------- Docutils directive: ``ani`` --------------------------- Inserts a matplotlib animation. Example ------- :: .. ani:: Wave motion :label: test-anim ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) # initialization function: plot the background of each frame def init(): line.set_data([], []) return line, # animation function. This is called sequentially def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, Options ------- :scale: Used to scale the image. :label: Used for hyperlinks references. See ``ani`` role. :position: Used to position figure within document. There are three possible values: :inline: Placement within flow of text [default]. :side: Placement in side margin. :full: Used for large figures---will not respect margins but will center across the full page. Notes ----- * Must have content. Will be wrapped by begin and end statements. * Argument used for figure caption (optional). * If the image option is used, the label defaults to image name. """ required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = { 'scale' : rst.directives.unchanged, 'label' : rst.directives.unchanged, 'position' : rst.directives.unchanged, 'offset' : rst.directives.unchanged, } has_content = True def run(self): node_list = [] # Unlike a normal image, our reference will come from the content... content = '\n'.join(self.content)#.replace('\\\\','\\') # Have to have some serious protection here.... if '\nimport' in content: assert False # Define image name and location image_hash = hashlib.md5(content.encode('utf-8')).hexdigest() image_name = '%s.mp4' % image_hash image_path = os.path.join(SYSGEN_PATH, 'matplotlib', image_name) image_url = posixpath.normpath(os.path.join(SYSGEN_URL, 'matplotlib', image_name)) self.options['uri'] = image_url # Maybe we already made it? If not, make it now... if not os.path.isfile(image_path): print 'Making image %s' % image_name print image_path print image_url # Set up our folders and filename variables curdir = os.getcwd() # Write the matplotlib file to the temp folder os.chdir(MATPLOTLIB_WORK_PATH) if os.path.isfile('temp.mp4'): os.remove('temp.mp4') f = codecs.open('temp.py', 'w', 'utf-8') f.write(MATPLOTLIB_ANI_TEMPLATE % content) f.close() # Run matplotlib ... cmd = [PYTHON_CMD, 'temp.py'] p = Popen(cmd,stdout=PIPE,stderr=PIPE) out, err = p.communicate() # Move the image file and clean up if os.path.isfile('temp.mp4'): image_dir = os.path.dirname(image_path) if not os.path.exists(image_dir): os.makedirs(image_dir) shutil.copyfile('temp.mp4', image_path) os.chdir(curdir) try: scale = float(self.options['scale']) except: scale = 1.00 if 'position' in self.options.keys(): position = self.options['position'] else: position = 'default' check_path = image_path # LaTeX writer specifics start (offset is ignored for HTML writer) ### WILL THIS EVEN WORK FOR AN MP4 FILE ??? if 'offset' in self.options.keys(): offset = self.options['offset'] else: offset = '0pt' if self.arguments: caption = rst2latex(self.arguments[0]) caption = r'\captionof{figure}{%s}' % caption else: caption = '' if 'label' in self.options.keys(): label = nodes.make_id(self.options['label']) label = r'\label{ani:%s}' % label else: label = '' if os.path.exists(check_path): latex_path = get_latex_path(check_path) figtext = r'\includegraphics[scale=%s]{%s}' figtext = figtext % (scale*0.5, latex_path) if not label: label = nodes.make_id(image_name) label = r'\label{ani:%s}' % label else: print 'Could not locate "%s"' % check_path figtext = '\n'.join(self.content) text = FIG_TEMPLATE[position] % { 'offset' : offset, 'caption' : caption, 'label' : label, 'figtext' : figtext, } node = nodes.raw(text=text, format='latex', **self.options) node_list += [node] # # HTML writer specifics start... if os.path.exists(check_path): # img_width, img_height = Image.open(check_path).size # fig_width = int(img_width*scale*0.75) # fig_height = int(img_height*scale*0.75) # # From: http://stackoverflow.com/questions/7362130/getting-video-dimension-from-ffmpeg-i # # import subprocess, re # # pattern = re.compile(r'Stream.*Video.*([0-9]{3,})x([0-9]{3,})') # # def get_size(pathtovideo): # # p = subprocess.Popen(['ffmpeg', '-i', pathtovideo], # # stdout=subprocess.PIPE, # # stderr=subprocess.PIPE) # # stdout, stderr = p.communicate() # # match = pattern.search(stderr) # # if match: # # x, y = map(int, match.groups()[0:2]) # # else: # # x = y = 0 # # return x, y fig_width = 800 fig_height = 600 if 'label' in self.options.keys(): label = nodes.make_id(self.options['label']) else: label = nodes.make_id(image_name) figtext = '\n' if 'side' in position: # figtext += '<div id="ani:{0}" class="my-docutils ani {1}" style="width:{2}px;">\n' figtext += '<div id="ani:{0}" class="my-docutils ani {1}">\n' else: figtext += '<div id="ani:{0}" class="my-docutils ani {1}">\n' # figtext += '<div id="ani:{0}" class="my-docutils ani {1}" style="width:{2}px;">\n' figtext = figtext.format(label, position, fig_width) figtext += '<a href="{0}"><video width="{1}px" height="{2}px" controls><source src="{0}" type="video/mp4"></video></a>\n'.format(image_url, fig_width, fig_height) if self.arguments: figtext += rst2html(self.arguments[0]) figtext += '</div>\n' else: print 'Could not locate "%s"' % check_path figtext = '\n<div class="my-docutils-error">\n<p>File generation error:</p>\n<pre>\n' + '\n'.join(self.content) + '</pre>\n</div>\n' text = figtext node = nodes.raw(text=text, format='html', **self.options) node_list += [node] return node_list rst.directives.register_directive('ani', ani_directive) class tbl_directive(rst.Directive): required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True option_spec = { 'label' : rst.directives.unchanged, 'cols' : rst.directives.unchanged, 'left-headers' : rst.directives.unchanged, } has_content = True def run(self): node_list = [] self.assert_has_content() try: parser = rst.tableparser.GridTableParser() tbl = parser.parse(self.content) except: try: parser = rst.tableparser.SimpleTableParser() tbl = parser.parse(self.content) except: tbl = None if tbl: # parser.parse() returns a list of three items # # 1. A list of column widths # 2. A list of head rows # 3. A list of body rows colspecs = tbl[0] headrows = tbl[1] # tbl[1][i] is the ith column head bodyrows = tbl[2] # Each row contains a list of cells # # Each cell is either # # - None (for a cell unused because of another cell's span), or # - A tuple with four items: # # 1. The number of extra rows used by the cell in a vertical span # 2. The number of extra columns used by
files','Please load images to process') return file=self.file path=self.exportpath suggsize=8 smallfont=ImageFont.truetype('cmb10.ttf',size=suggsize) # kernersizes={} # for file in batch_filenames: labeldict=self.batch_results[file][0] itervalue='iter0' labels=labeldict[itervalue]['labels'] counts=labeldict[itervalue]['counts'] colortable=labeldict[itervalue]['colortable'] head_tail=os.path.split(file) originfile,extension=os.path.splitext(head_tail[1]) if len(path)>0: tup=(labels,counts,colortable,[],file) _band,segimg,small_segimg=self.showcounting(tup,False,True,True,whext,blkext) imageband=segimg draw=ImageDraw.Draw(imageband) uniquelabels=list(colortable.keys()) tempdict={} pixelmmratio=1.0 print('pixelmmratio',pixelmmratio) if file not in self.kernersizes: for uni in uniquelabels: if uni !=0: pixelloc = np.where(labels == float(uni)) try: ulx = min(pixelloc[1]) except: continue uly = min(pixelloc[0]) rlx = max(pixelloc[1]) rly = max(pixelloc[0]) print(ulx, uly, rlx, rly) midx = ulx + int((rlx - ulx) / 2) midy = uly + int((rly - uly) / 2) length={} currborder=tkintercore.get_boundaryloc(labels,uni) # print('currborder',currborder) print('currborder length',len(currborder[0])*len(currborder[1])) pixperc=float(len(pixelloc[0])/(labels.shape[0]*labels.shape[1])) print('pix length percentage',pixperc) if pixperc>0.06: x0=ulx y0=uly x1=rlx y1=rly kernellength=float(((x0-x1)**2+(y0-y1)**2)**0.5) else: for i in range(len(currborder[0])): for j in range(i+1,len(currborder[0])): templength=float(((currborder[0][i]-currborder[0][j])**2+(currborder[1][i]-currborder[1][j])**2)**0.5) length.update({(i,j):templength}) sortedlength=sorted(length,key=length.get,reverse=True) try: topcouple=sortedlength[0] except: continue kernellength=length[topcouple] i=topcouple[0] j=topcouple[1] x0=currborder[1][i] y0=currborder[0][i] x1=currborder[1][j] y1=currborder[0][j] #slope=float((y0-y1)/(x0-x1)) linepoints=[(currborder[1][i],currborder[0][i]),(currborder[1][j],currborder[0][j])] #draw.line(linepoints,fill='yellow') #points=linepixels(currborder[1][i],currborder[0][i],currborder[1][j],currborder[0][j]) lengthpoints=cal_kernelsize.bresenhamline(x0,y0,x1,y1) #x0,y0,x1,y1 for point in lengthpoints: # if imgtypevar.get()=='0': draw.point([int(point[0]),int(point[1])],fill='yellow') tengentaddpoints=cal_kernelsize.tengentadd(x0,y0,x1,y1,rlx,rly,labels,uni) #find tangent line above #for point in tengentaddpoints: #if int(point[0])>=ulx and int(point[0])<=rlx and int(point[1])>=uly and int(point[1])<=rly: # draw.point([int(point[0]),int(point[1])],fill='green') tengentsubpoints=cal_kernelsize.tengentsub(x0,y0,x1,y1,ulx,uly,labels,uni) #find tangent line below #for point in tengentsubpoints: # draw.point([int(point[0]),int(point[1])],fill='green') pointmatchdict={} for i in range(len(tengentaddpoints)): #find the pixel pair with shortest distance width=kernellength pointmatch=[] point=tengentaddpoints[i] try: templabel=labels[int(point[1]),int(point[0])] except: continue if templabel==uni: for j in range(len(tengentsubpoints)): subpoint=tengentsubpoints[j] tempwidth=float(((point[0]-subpoint[0])**2+(point[1]-subpoint[1])**2)**0.5) if tempwidth<width: pointmatch[:]=[] pointmatch.append(point) pointmatch.append(subpoint) #print('tempwidth',width) width=tempwidth if len(pointmatch)>0: #print('pointmatch',pointmatch) pointmatchdict.update({(pointmatch[0],pointmatch[1]):width}) widthsort=sorted(pointmatchdict,key=pointmatchdict.get,reverse=True) try: pointmatch=widthsort[0] print('final pointmatch',pointmatch) except: continue if len(pointmatch)>0: x0=int(pointmatch[0][0]) y0=int(pointmatch[0][1]) x1=int(pointmatch[1][0]) y1=int(pointmatch[1][1]) # if imgtypevar.get()=='0': draw.line([(x0,y0),(x1,y1)],fill='yellow') width=float(((x0-x1)**2+(y0-y1)**2)**0.5) print('width',width,'length',kernellength) print('kernelwidth='+str(width*pixelmmratio)) print('kernellength='+str(kernellength*pixelmmratio)) #print('kernelwidth='+str(kernelwidth*pixelmmratio)) tempdict.update({uni:[kernellength,width,pixelmmratio**2*len(pixelloc[0]),kernellength*pixelmmratio,width*pixelmmratio]}) if uni in colortable: canvastext = str(colortable[uni]) else: canvastext = 'No label' # if imgtypevar.get()=='0': draw.text((midx-1, midy+1), text=canvastext, font=smallfont, fill='white') draw.text((midx+1, midy+1), text=canvastext, font=smallfont, fill='white') draw.text((midx-1, midy-1), text=canvastext, font=smallfont, fill='white') draw.text((midx+1, midy-1), text=canvastext, font=smallfont, fill='white') #draw.text((midx,midy),text=canvastext,font=font,fill=(141,2,31,0)) draw.text((midx,midy),text=canvastext,font=smallfont,fill='black') #print(event.x, event.y, labels[event.x, event.y], ulx, uly, rlx, rly) #recborder = canvas.create_rectangle(ulx, uly, rlx, rly, outline='red') #drawcontents.append(recborder) self.kernersizes.update({file:tempdict}) originheight,originwidth=self.batch_Multigraybands[file].size image=imageband.resize([originwidth,originheight],resample=Image.BILINEAR) extcolor="" if whext==True: extcolor= "-extwht" if blkext==True: extcolor="-extblk" image.save(path+'/'+originfile+extcolor+'-sizeresult'+'.png',"PNG") tup=(labels,counts,colortable,[],file) _band,segimg,small_segimg=self.showcounting(tup,False,True,True,whext,blkext) segimage=segimg.resize([originwidth,originheight],resample=Image.BILINEAR) segimage.save(path+'/'+originfile+extcolor+'-segmentresult'+'.png',"PNG") _band,segimg,small_segimg=self.showcounting(tup,True,True,True,whext,blkext) segimage=segimg.resize([originwidth,originheight],resample=Image.BILINEAR) segimage.save(path+'/'+originfile+extcolor+'-labelresult'+'.png',"PNG") def export_result(self): file=self.file if len(batch_filenames)==0: messagebox.showerror('No files','Please load images to process') return suggsize=8 smallfont=ImageFont.truetype('cmb10.ttf',size=suggsize) self.kernersizes={} # path=filedialog.askdirectory() self.export_ext(True,False) self.export_ext(False,True) # for file in batch_filenames: labeldict=self.batch_results[self.file][0] itervalue='iter0' labels=labeldict[itervalue]['labels'] counts=labeldict[itervalue]['counts'] colortable=labeldict[itervalue]['colortable'] head_tail=os.path.split(self.file) originfile,extension=os.path.splitext(head_tail[1]) if len(self.exportpath)>0: tup=(labels,counts,colortable,[],self.file) _band,segimg,small_segimg=self.showcounting(tup,False) #imageband=outputimgbands[file][itervalue] imageband=segimg # draw=ImageDraw.Draw(imageband) uniquelabels=list(colortable.keys()) # tempdict={} pixelmmratio=1.0 #print('coinsize',coinsize.get(),'pixelmmratio',pixelmmratio) print('pixelmmratio',pixelmmratio) originheight,originwidth=self.batch_Multigraybands[file].size image=imageband.resize([originwidth,originheight],resample=Image.BILINEAR) image.save(self.exportpath+'/'+originfile+'-sizeresult'+'.png',"PNG") tup=(labels,counts,colortable,[],file) _band,segimg,small_segimg=self.showcounting(tup,False) segimage=segimg.resize([originwidth,originheight],resample=Image.BILINEAR) segimage.save(self.exportpath+'/'+originfile+'-segmentresult'+'.png',"PNG") _band,segimg,small_segimg=self.showcounting(tup,True) segimage=segimg.resize([originwidth,originheight],resample=Image.BILINEAR) segimage.save(self.exportpath+'/'+originfile+'-labelresult'+'.png',"PNG") originrestoredband=np.copy(labels) restoredband=originrestoredband.astype('uint8') colordicesband=self.batch_colordicesband[file] colordiv=np.zeros((colordicesband.shape[0],colordicesband.shape[1],3)) self.savePCAimg(originfile) # kvar=int(kmeans.get()) # print('kvar',kvar) # for i in range(kvar): # locs=np.where(colordicesband==i) # colordiv[locs]=colorbandtable[i] # colordivimg=Image.fromarray(colordiv.astype('uint8')) # colordivimg.save(path+'/'+originfile+'-colordevice'+'.jpeg',"JPEG") colordivimg=Image.open(file+'-allcolorindex.png') copycolordiv=colordivimg.resize([originwidth,originheight],resample=Image.BILINEAR) copycolordiv.save(self.exportpath+'/'+originfile+'-colordevice'+'.png',"PNG") #pyplt.imsave(path+'/'+originfile+'-colordevice'+'.png',colordiv.astype('uint8')) # copybinary=np.zeros((originbinaryimg.shape[0],originbinaryimg.shape[1],3),dtype='float') # nonzeros=np.where(originbinaryimg==1) # copybinary[nonzeros]=[255,255,0] # binaryimg=Image.fromarray(copybinary.astype('uint8')) binaryimg=Image.open(file+'-binaryimg.png') copybinaryimg=binaryimg.resize([originwidth,originheight],resample=Image.BILINEAR) copybinaryimg.save(self.exportpath+'/'+originfile+'-binaryimg'+'.png',"PNG") # pyplt.imsave(path+'/'+originfile+'-binaryimg'+'.png',originbinaryimg.astype('uint8')) #restoredband=cv2.resize(src=restoredband,dsize=(originwidth,originheight),interpolation=cv2.INTER_LINEAR) print(restoredband.shape) currentsizes=self.kernersizes[self.file] indicekeys=list(self.batch_originbandarray[self.file].keys()) indeclist=[ 0 for i in range(len(indicekeys)*3)] pcalist=[0 for i in range(3)] # temppcabands=np.zeros((self.batch_originpcabands[self.file].shape[0],len(pcs))) # for i in range(len(pcs)): # temppcabands[:,i]=temppcabands[:,i]+self.batch_originpcabands[self.file][:,pcs[i]-1] # pcabands=np.mean(temppcabands,axis=1) # # pcabands=pcabands.reshape((originheight,originwidth)) # pcabands=pcabands.reshape((self.displayfea_l,self.displayfea_w)) pcabands=np.copy(self.displaypclagels) datatable={} origindata={} for key in indicekeys: data=self.batch_originbandarray[self.file][key] data=data.tolist() tempdict={key:data} origindata.update(tempdict) print(key) # for uni in colortable: print(uniquelabels) print('len uniquelabels',len(uniquelabels)) for uni in uniquelabels: print(uni,colortable[uni]) uniloc=np.where(labels==float(uni)) if len(uniloc)==0 or len(uniloc[1])==0: print('no uniloc\n') print(uniloc[0],uniloc[1]) continue smalluniloc=np.where(originrestoredband==uni) ulx,uly=min(smalluniloc[1]),min(smalluniloc[0]) rlx,rly=max(smalluniloc[1]),max(smalluniloc[0]) width=rlx-ulx length=rly-uly print(width,length) subarea=restoredband[uly:rly+1,ulx:rlx+1] subarea=subarea.tolist() amount=len(uniloc[0]) print(amount) try: sizes=currentsizes[uni] except: print('no sizes\n') continue #templist=[amount,length,width] templist=[amount,sizes[0],sizes[1],sizes[2],sizes[3],sizes[4]] tempdict={colortable[uni]:templist+indeclist+pcalist} #NIR,Redeyes,R,G,B,NDVI,area print(tempdict) for ki in range(len(indicekeys)): originNDVI=origindata[indicekeys[ki]] print(len(originNDVI),len(originNDVI[0])) pixellist=[] for k in range(len(uniloc[0])): #print(uniloc[0][k],uniloc[1][k]) try: tempdict[colortable[uni]][6+ki*3]+=originNDVI[uniloc[0][k]][uniloc[1][k]] except IndexError: print(uniloc[0][k],uniloc[1][k]) tempdict[colortable[uni]][7+ki*3]+=originNDVI[uniloc[0][k]][uniloc[1][k]] pixellist.append(originNDVI[uniloc[0][k]][uniloc[1][k]]) tempdict[colortable[uni]][ki*3+6]=tempdict[colortable[uni]][ki*3+6]/amount tempdict[colortable[uni]][ki*3+8]=np.std(pixellist) pixellist=[] for k in range(len(uniloc[0])): try: tempdict[colortable[uni]][-2]+=pcabands[uniloc[0][k]][uniloc[1][k]] except IndexError: print(uniloc[0][k],uniloc[1][k]) tempdict[colortable[uni]][-3]+=pcabands[uniloc[0][k]][uniloc[1][k]] pixellist.append(pcabands[uniloc[0][k]][uniloc[1][k]]) tempdict[colortable[uni]][-3]=tempdict[colortable[uni]][-3]/amount tempdict[colortable[uni]][-1]=np.std(pixellist) datatable.update(tempdict) filename=self.exportpath+'/'+originfile+'-outputdata.csv' with open(filename,mode='w') as f: csvwriter=csv.writer(f) rowcontent=['Index','Plot','Area(#pixel)','Length(#pixel)','Width(#pixel)','Area(mm2)','Length(mm)','Width(mm)'] for key in indicekeys: rowcontent.append('avg-'+str(key)) rowcontent.append('sum-'+str(key)) rowcontent.append('std-'+str(key)) rowcontent.append('avg-PCA') rowcontent.append('sum-PCA') rowcontent.append('std-PCA') #csvwriter.writerow(['ID','NIR','Red Edge','Red','Green','Blue','NIRv.s.Green','LabOstu','area(#of pixel)']) #csvwriter.writerow(['Index','Plot','Area(#pixels)','avg-NDVI','sum-NDVI','std-NDVI','Length(#pixel)','Width(#pixel)'])#,'#holes']) csvwriter.writerow(rowcontent) i=1 for uni in datatable: row=[i,uni] for j in range(len(datatable[uni])): row.append(datatable[uni][j]) #row=[i,uni,datatable[uni][0],datatable[uni][1],datatable[uni][2],datatable[uni][5],datatable[uni][3],datatable[uni][4]]#, #datatable[uni][5]] i+=1 print(row) csvwriter.writerow(row) print('total data length=',len(datatable)) def process(self): if self.Open_batchimage()==False: return self.singleband() colordicesband=self.kmeansclassify() if type(colordicesband)==type(None): return self.batch_colordicesband.update({self.file:colordicesband}) currentlabels,originbinaryimg=self.generateimgplant(colordicesband) if self.extraction(currentlabels)==False: return if self.resegment()==False: return self.export_result() batch_filenames=[] batch_Multiimage={} batch_Multigray={} batch_Multitype={} batch_Multiimagebands={} batch_Multigraybands={} batch_displaybandarray={} batch_originbandarray={} batch_originpcabands={} batch_colordicesband={} batch_results={} pcweight=0 pcs=0 kmeans=0 kmeans_sel=[] maxthres=0 minthres=0 maxlw=0 minlw=0 std_nonzeroratio=0 FOLDER='' exportpath='' def batch_findratio(originsize,objectsize): oria=originsize[0] orib=originsize[1] obja=objectsize[0] objb=objectsize[1] if oria>obja or orib>objb: ratio=round(max((oria/obja),(orib/objb))) else: ratio=round(min((obja/oria),(objb/orib))) if oria*orib>850 * 850: if ratio<2: ratio=2 return ratio def Open_batchimage(dir,filename): global batch_Multiimage,batch_Multigray,batch_Multitype,batch_Multiimagebands,batch_Multigraybands try: Filersc=cv2.imread(dir+'/'+filename,flags=cv2.IMREAD_ANYCOLOR) height,width,channel=np.shape(Filersc) Filesize=(height,width) print('filesize:',height,width) RGBfile=cv2.cvtColor(Filersc,cv2.COLOR_BGR2RGB) Grayfile=cv2.cvtColor(Filersc,cv2.COLOR_BGR2Lab) Grayfile=cv2.cvtColor(Grayfile,cv2.COLOR_BGR2GRAY) Grayimg=batch_img(Filesize,Grayfile) RGBbands=np.zeros((channel,height,width)) for j in range(channel): band=RGBfile[:,:,j] band=np.where(band==0,1e-6,band) RGBbands[j,:,:]=band RGBimg=batch_img(Filesize,RGBbands) tempdict={filename:RGBimg} batch_Multiimagebands.update(tempdict) tempdict={filename:Grayfile} batch_Multigray.update(tempdict) tempdict={filename:0} batch_Multitype.update(tempdict) tempdict={filename:Grayimg} batch_Multigraybands.update(tempdict) # batch_filenames.append(filename) except: # messagebox.showerror('Invalid Image Format','Cannot open '+filename) return False return True def Open_batchfile(): global pcs,pcweight,kmeans,kmeans_sel,maxthres,minthres,maxlw,minlw,std_nonzeroratio btfile=filedialog.askopenfilename() if len(btfile)>0: if '.txt' in btfile: with open(btfile,mode='r') as f: setting=f.readlines() # print(setting) pcweight=float(setting[0].split(',')[1]) pcs=int(setting[1].split(',')[1])+1 # print(pcs) # for i in range(len(pcs)): # pcs[i]=int(pcs[i]) kmeans=setting[2].split(',')[1] kmeans=int(kmeans) kmeans_sel=setting[3].split(',')[1:-1] maxthres=setting[4].split(',')[1] try: maxthres=float(maxthres) except: messagebox.showerror('Load Max area error','No Max area threshold value.') return minthres=setting[5].split(',')[1] minthres=float(minthres) maxlw=setting[6].split(',')[1] maxlw=float(maxlw) minlw=setting[7].split(',')[1] minlw=float(minlw) std_nonzeroratio=float(setting[8].split(',')[1]) for i in range(len(kmeans_sel)): kmeans_sel[i]=int(kmeans_sel[i]) print('PCweight',pcweight,'PCsel',pcs,'KMeans',kmeans,'KMeans-Selection',kmeans_sel) print('maxthres',maxthres,'minthres',minthres,'maxlw',maxlw,'minlw',minlw) messagebox.showinfo('Batch settings','PCweight='+str(pcweight)+'\nPCsel='+str(pcs)+'\nKMeans='+str(kmeans)+ '\nCluster selection'+str(kmeans_sel)+'\nMax area='+str(maxthres)+ '\nMin area='+str(minthres)+'\nMax diagonal='+str(maxlw)+'\nMin diagonal='+ str(minlw)) def Open_batchfolder(): # global batch_filenames,batch_Multiimage,batch_Multigray,batch_Multitype,batch_Multiimagebands,batch_Multigraybands # global batch_displaybandarray,batch_originbandarray,batch_originpcabands # global pcs,kmeans,kmeans_sel # global batch_results global batch_filenames global FOLDER batch_filenames=[] # batch_Multiimage={} # batch_Multigray={} # batch_Multitype={} # batch_Multiimagebands={} # batch_Multigraybands={} # # batch_displaybandarray={} # batch_originbandarray={} # batch_originpcabands={} # # batch_results={} # pcs=0 # kmeans=0 # kmeans_sel=0 FOLDER=filedialog.askdirectory() if len(FOLDER)>0: print(FOLDER) # for root, dirs,files in os.walk(FOLDER): files=os.listdir(FOLDER) for filename in files: # print('root',root) # print('dirs',dirs) # print("filename",filename) batch_filenames.append(filename) # batch_filenames.append(filename) # Open_batchimage(FOLDER,filename) # batch_singleband(filename) # messagebox.showinfo('Finish loading','Loading Image finished') # if len(batch_filenames)==0: # messagebox.showerror('No file','No file under current folder') # return batch_filenames.sort() print('filenames',batch_filenames) def batch_kmeansclassify(file): if kmeans==0: messagebox.showerror('Kmeans error','Kmeans should greater than 0') return originpcabands=batch_displaybandarray[file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape print(file,'originpcabands',pcah,pcaw,pcac) pcakeys=pcs tempband=np.zeros((pcah,pcaw,len(pcakeys))) for i in range(len(pcakeys)): channel=int(pcakeys[i])-1 tempband[:,:,i]=tempband[:,:,i]+originpcabands[:,:,channel] if kmeans==1: print('kmeans=1') displaylabels=np.mean(tempband,axis=2) pyplt.imsave(file+'_k=1.png',displaylabels) else: #tempband=displaybandarray[currentfilename]['LabOstu'] if kmeans>1: h,w,c=tempband.shape print('shape',tempband.shape) reshapedtif=tempband.reshape(tempband.shape[0]*tempband.shape[1],c) print('reshape',reshapedtif.shape) clf=KMeans(n_clusters=kmeans,init='k-means++',n_init=10,random_state=0) tempdisplayimg=clf.fit(reshapedtif) # print('label=0',np.any(tempdisplayimg==0)) displaylabels=tempdisplayimg.labels_.reshape((batch_displaybandarray[file]['LabOstu'].shape[0], batch_displaybandarray[file]['LabOstu'].shape[1])) return displaylabels def batch_generateimgplant(displaylabels,file): colordicesband=np.copy(displaylabels) tempdisplayimg=np.zeros((batch_displaybandarray[file]['LabOstu'].shape[0], batch_displaybandarray[file]['LabOstu'].shape[1])) colordivimg=np.zeros((batch_displaybandarray[file]['LabOstu'].shape[0], batch_displaybandarray[file]['LabOstu'].shape[1])) for i in range(len(kmeans_sel)): sk=kmeans_sel[i]-1 tempdisplayimg=np.where(displaylabels==sk,1,tempdisplayimg) currentlabels=np.copy(tempdisplayimg) originbinaryimg=np.copy(tempdisplayimg) tempcolorimg=np.copy(displaylabels).astype('float32') ratio=batch_findratio([tempdisplayimg.shape[0],tempdisplayimg.shape[1]],[850,850]) if tempdisplayimg.shape[0]*tempdisplayimg.shape[1]<850*850: tempdisplayimg=cv2.resize(tempdisplayimg,(int(tempdisplayimg.shape[1]*ratio),int(tempdisplayimg.shape[0]*ratio))) colordivimg=cv2.resize(tempcolorimg,(int(colordivimg.shape[1]*ratio),int(colordivimg.shape[0]*ratio))) else: tempdisplayimg=cv2.resize(tempdisplayimg,(int(tempdisplayimg.shape[1]/ratio),int(tempdisplayimg.shape[0]/ratio))) colordivimg=cv2.resize(tempcolorimg,(int(colordivimg.shape[1]/ratio),int(colordivimg.shape[0]/ratio))) binaryimg=np.zeros((tempdisplayimg.shape[0],tempdisplayimg.shape[1],3)) colordeimg=np.zeros((colordivimg.shape[0],colordivimg.shape[1],3)) locs=np.where(tempdisplayimg==1) binaryimg[locs]=[240,228,66] for i in range(kmeans): locs=np.where(colordivimg==i) colordeimg[locs]=batch_colorbandtable[i] Image.fromarray(colordeimg.astype('uint8')).save(file+'-allcolorindex.png',"PNG") Image.fromarray((binaryimg.astype('uint8'))).save(file+'-binaryimg.png',"PNG") return currentlabels,originbinaryimg def batch_extraction(currentlabels,file): global batch_results if kmeans==1: messagebox.showerror('Invalid Class #',message='#Class = 1, try change it to 2 or more, and refresh Color-Index.') return nonzeros=np.count_nonzero(currentlabels) print('nonzero counts',nonzeros) nonzeroloc=np.where(currentlabels!=0) try: ulx,uly=min(nonzeroloc[1]),min(nonzeroloc[0]) except: messagebox.showerror('Invalid Colorindices',message='Need to process colorindicies') return rlx,rly=max(nonzeroloc[1]),max(nonzeroloc[0]) nonzeroratio=float(nonzeros)/((rlx-ulx)*(rly-uly)) print(nonzeroratio) dealpixel=nonzeroratio*currentlabels.shape[0]*currentlabels.shape[1] ratio=1 if nonzeroratio<=0.2:# and nonzeroratio>=0.1: ratio=batch_findratio([currentlabels.shape[0],currentlabels.shape[1]],[1600,1600]) if currentlabels.shape[0]*currentlabels.shape[1]>1600*1600: workingimg=cv2.resize(currentlabels,(int(currentlabels.shape[1]/ratio),int(currentlabels.shape[0]/ratio)),interpolation=cv2.INTER_LINEAR) else: #ratio=1 #print('nonzeroratio',ratio) workingimg=np.copy(currentlabels) segmentratio=0 else: print('deal pixel',dealpixel) if dealpixel>512000: if currentlabels.shape[0]*currentlabels.shape[1]>850*850: segmentratio=batch_findratio([currentlabels.shape[0],currentlabels.shape[1]],[850,850]) if segmentratio<2: segmentratio=2 workingimg=cv2.resize(currentlabels,(int(currentlabels.shape[1]/segmentratio),int(currentlabels.shape[0]/segmentratio)),interpolation=cv2.INTER_LINEAR) else: segmentratio=1 #print('ratio',ratio) workingimg=np.copy(currentlabels) pixelmmratio=1.0 coin=False print('nonzeroratio:',ratio,'segmentation ratio',segmentratio) print('workingimgsize:',workingimg.shape) pyplt.imsave('workingimg.png',workingimg) originlabels=None if originlabels is None: originlabels,border,colortable,originlabeldict=tkintercorestat.init(workingimg,workingimg,'',workingimg,10,coin) batch_results.update({file:(originlabeldict,{})}) def batch_proc_func(file): if len(FOLDER)==0: messagebox.showerror('No image folder','Need to assign image folder') return if len(exportpath)==0: messagebox.showerror('No output folder','Need to assign output folder') return if len(pcs)==0: messagebox.showerror('No batch file','Need to load batch file') return procobj=batch_ser_func(file) procobj.process() del procobj def batch_process(): global batch_colordicesband global batch_Multiimage,batch_Multigray,batch_Multitype,batch_Multiimagebands,batch_Multigraybands global batch_displaybandarray,batch_originbandarray,batch_originpcabands global batch_results if len(batch_filenames)==0: messagebox.showerror('No files','Please load images to process') return cpunum=multiprocessing.cpu_count() print('# of CPUs',cpunum) starttime=time.time() print('start time',starttime) for file in batch_filenames: # batch_Multiimage={} # batch_Multigray={} # batch_Multitype={} # batch_Multiimagebands={} # batch_Multigraybands={} # # batch_displaybandarray={} # batch_originbandarray={} # batch_originpcabands={} # batch_colordicesband={} # # batch_results={} # if Open_batchimage(FOLDER,file)==False: # continue # batch_singleband(file) # colordicesband=batch_kmeansclassify(file) # batch_colordicesband.update({file:colordicesband}) # currentlabels,originbinaryimg=batch_generateimgplant(colordicesband,file) # batch_extraction(currentlabels,file) # batch_export_result(exportpath,file) procobj=batch_ser_func(file) procobj.process() del procobj # multi_pool=multiprocessing.Pool(int(cpunum/4)) # multi_pool.map(batch_proc_func,batch_filenames) print('used time',time.time()-starttime) messagebox.showinfo('Done','Batch process ends!') def batch_showcounting(tup,number=True,frame=True,header=True,whext=False,blkext=False): labels=tup[0] colortable=tup[2] coinparts=tup[3] filename=tup[4] uniquelabels=list(colortable.keys()) imgrsc=cv2.imread(FOLDER+'/'+filename,flags=cv2.IMREAD_ANYCOLOR) imgrsc=cv2.cvtColor(imgrsc,cv2.COLOR_BGR2RGB) imgrsc=cv2.resize(imgrsc,(labels.shape[1],labels.shape[0]),interpolation=cv2.INTER_LINEAR) image=Image.fromarray(imgrsc) if whext==True: # blkbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') whbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') whbkg[:,:,:]=[255,255,255] itemlocs=np.where(labels!=0) # blkbkg[itemlocs]=imgrsc[itemlocs] whbkg[itemlocs]=imgrsc[itemlocs] image=Image.fromarray(whbkg.astype('uint8')) if blkext==True: blkbkg=np.zeros((labels.shape[0],labels.shape[1],3),dtype='float') itemlocs=np.where(labels!=0) blkbkg[itemlocs]=imgrsc[itemlocs] blkbkg[itemlocs]=imgrsc[itemlocs] image=Image.fromarray(blkbkg.astype('uint8')) print('showcounting_resize',image.size) image.save('beforlabel.gif',append_images=[image]) draw=ImageDraw.Draw(image) sizeuniq,sizecounts=np.unique(labels,return_counts=True) minsize=min(sizecounts) suggsize=int(minsize**0.5) if suggsize>22: suggsize=22 if suggsize<14: suggsize=14 font=ImageFont.truetype('cmb10.ttf',size=suggsize) for uni in uniquelabels: if uni!=0: pixelloc = np.where(labels == uni) try: ulx = min(pixelloc[1]) except: continue uly = min(pixelloc[0]) rlx = max(pixelloc[1]) rly = max(pixelloc[0]) midx = ulx + int((rlx - ulx) / 2) midy = uly + int((rly - uly) / 2) print(ulx, uly, rlx, rly) if frame==True: draw.polygon([(ulx,uly),(rlx,uly),(rlx,rly),(ulx,rly)],outline='red') if number==True: if uni in colortable: canvastext = str(colortable[uni]) else: canvastext = 'No label' # if imgtypevar.get()=='0': draw.text((midx-1, midy+1), text=canvastext, font=font, fill='white') draw.text((midx+1, midy+1), text=canvastext, font=font, fill='white') draw.text((midx-1, midy-1), text=canvastext, font=font, fill='white') draw.text((midx+1, midy-1), text=canvastext, font=font, fill='white') #draw.text((midx,midy),text=canvastext,font=font,fill=(141,2,31,0)) draw.text((midx,midy),text=canvastext,font=font,fill='black') if header==True: content='item count:'+str(len(uniquelabels))+'\n File: '+filename contentlength=len(content)+50 #rectext=canvas.create_text(10,10,fill='black',font='Times 16',text=content,anchor=NW) draw.text((10-1, 10+1), text=content, font=font, fill='white') draw.text((10+1, 10+1), text=content, font=font, fill='white') draw.text((10-1, 10-1), text=content, font=font, fill='white') draw.text((10+1, 10-1), text=content, font=font, fill='white') #draw.text((10,10),text=content,font=font,fill=(141,2,31,0)) draw.text((10,10),text=content,font=font,fill='black') #image.save(originfile+'-countresult'+extension,"JPEG") #firstimg=Multigraybands[currentfilename] #height,width=firstimg.size height,width,channel=batch_displaybandarray[filename]['LabOstu'].shape ratio=batch_findratio([height,width],[850,850]) #if labels.shape[0]*labels.shape[1]<850*850: # disimage=image.resize([int(labels.shape[1]*ratio),int(labels.shape[0]*ratio)],resample=Image.BILINEAR) #else: # disimage=image.resize([int(labels.shape[1]/ratio),int(labels.shape[0]/ratio)],resample=Image.BILINEAR) print('show counting ratio',ratio) if height*width<850*850: print('showcounting small') disimage=image.resize([int(width*ratio),int(height*ratio)],resample=Image.BILINEAR) else: print('showcounting big') disimage=image.resize([int(width/ratio),int(height/ratio)],resample=Image.BILINEAR) print('showcounting shape',disimage.size) displayoutput=ImageTk.PhotoImage(disimage) disimage.save('output.gif',append_images=[disimage]) #image.save('originoutput.gif',append_images=[image]) return displayoutput,image,disimage def batch_savePCAimg(path,originfile,file): originpcabands=batch_displaybandarray[file]['LabOstu'] pcah,pcaw,pcac=originpcabands.shape pcakeys=pcs tempband=np.zeros((pcah,pcaw,len(pcakeys))) for i in
from __future__ import print_function from romspline.__init__ import state if state._MATPLOTLIB: import matplotlib.pyplot as plt if state._PARALLEL: from concurrent.futures import ProcessPoolExecutor, wait, as_completed from multiprocessing import cpu_count import numpy as np import romspline.greedy as greedy ###################################### # Random seeds for greedy algorithm # ###################################### def _randomSeeds(x, y, seeds, tol=1e-6, rel=False, deg=5): """Build reduced-order splines from an arbitrary seed for the greedy algorithm. See RandomSeeds for further details. Input ----- x -- samples y -- data to be downsampled seeds -- list of integers specifying the array indexes of the samples used to seed the greedy algorithm tol -- L-infinity error tolerance for reduced-order spline (default 1e-6) rel -- L-infinity error tolerance is relative to max abs of data? (default False) deg -- degree of interpolating polynomials (default 5) """ # Sort the seeds as a precaution seeds = np.sort(seeds) # Build spline spline = greedy.ReducedOrderSpline(x, y, tol=tol, rel=rel, deg=deg, seeds=seeds) # Return last greedy error, size, seeds, and reduced data samples return spline.errors[-1], spline.size, seeds, spline.X class RandomSeeds(object): """A class for studying how the initial distribution of seed points effects the size of the reduced data set. The default distribution of seed points depends on the degree (deg) of the spline polynomial used for interpolation. In general, one needs deg+1 points to fit a polynomial of degree deg. The default seed points include the first and last points of the data and then deg-1 points that are as equally spaced as possible. In this class, a set of deg+1 seed points are randomly selected and a reduced-order spline is generated for each such seed selection. The resulting sizes of the reduced data are recorded. """ def __init__(self, tol=1e-6, rel=False, deg=5): """Create a RandomSeeds object. Input ----- tol -- L-infinity error tolerance for reduced-order spline (default 1e-6) rel -- L-infinity error tolerance is relative to max abs of data? (default False) deg -- degree of interpolating polynomials (default 5) """ self._tol = tol self._rel = rel self._deg = deg self._made = False # Assume that random seeds study is not made yet def __call__(self, x, y, Nseeds, parallel=True): """Make reduced-order splines for Nseeds number of random sets of seed points. Input ----- x -- samples y -- data to be downsampled Nseeds -- number of random sets of seed points parallel -- parallelize the computation for each random seed set? (default True) Attributes ---------- errors -- greedy errors associated with each random set of seed points sizes -- reduced data sizes from each random set of seed points seeds -- the full set of random seed points Xs -- reduced data from each random set of seed points Comments -------- The `parallel` option also accepts positive integers indicating the number of processors that the user wants to use. Parallelization uses some features from the concurrent.futures module. """ return self.make(x, y, Nseeds, parallel=parallel) def make(self, x, y, Nseeds, parallel=True): """Make reduced-order splines for Nseeds number of random sets of seed points. Input ----- x -- samples y -- data to be downsampled Nseeds -- number of random sets of seed points parallel -- parallelize the computation for each random seed set? (default True) Attributes ---------- errors -- greedy errors associated with each random set of seed points sizes -- reduced data sizes from each random set of seed points seeds -- the full set of random seed points Xs -- reduced data from each random set of seed points Comments -------- The `parallel` option also accepts positive integers indicating the number of processors that the user wants to use. Parallelization uses some features from the concurrent.futures module. """ # Allocate some memory self.errors = np.zeros(Nseeds, dtype='double') # Greedy errors self.sizes = np.zeros(Nseeds, dtype='double') # Sizes of each reduced data self.seeds = np.zeros((Nseeds, self._deg+1), dtype='double') # All seeds self.Xs = [] # Reduced data for each seed if (parallel is False) or (state._PARALLEL is False): for nn in range(Nseeds): seeds = np.sort( np.random.choice(range(len(x)), self._deg+1, replace=False) ) self.errors[nn], self.sizes[nn], self.seeds[nn], Xs = _randomSeeds(x, y, seeds, tol=self._tol, rel=self._rel, deg=self._deg) self.Xs.append(Xs) elif state._PARALLEL is True: # Determine the number of processes to run on if parallel is True: try: numprocs = cpu_count() except NotImplementedError: numprocs = 1 else: numprocs = parallel # Create a parallel process executor executor = ProcessPoolExecutor(max_workers=numprocs) # Build reduced-order splines for many random sets of seed points output = [] for nn in range(Nseeds): seeds = np.sort( np.random.choice(range(len(x)), self._deg+1, replace=False) ) output.append(executor.submit(_randomSeeds, x, y, seeds, tol=self._tol, rel=self._rel, deg=self._deg)) # Gather the results as they complete #for ii, oo in enumerate(as_completed(output)): for ii, oo in enumerate(output): self.errors[ii], self.sizes[ii], self.seeds[ii], Xs = oo.result() self.Xs.append(Xs) self._made = True def plot_sizes(self, n=20, ax=None, show=True, xlabel='Size of reduced data', ylabel='Occurrence'): """Plot a histogram of the reduced data sizes produced by building reduced-order splines from random sets of seed points. Input ----- n -- number of histogram bins (default 20) ax -- matplotlib plot/axis object (default None) show -- display the plot? (default True) xlabel -- x-axis label (default 'Size of reduced data') ylabel -- y-axis label (default 'Occurrence') Output ------ If show=True then the plot is displayed. Otherwise, the matplotlib plot/axis object is output. """ if self._made: if ax is None: fig, ax = plt.subplots(nrows=1, ncols=1) ax.hist(self.sizes, n, color='k', alpha=0.33); mean = np.mean(self.sizes) std = np.std(self.sizes) ax.axvline(x=mean, color='k', linewidth=2) ax.axvline(x=mean+std, color='k', linestyle='--', linewidth=1) ax.axvline(x=mean-std, color='k', linestyle='--', linewidth=1) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if show: # Display the plot plt.show() else: # Otherwise, return plot objects for editing the plot in the future if ax is None: return fig, ax else: return ax else: print("No data to plot. Run make method or set _made attribute to True.") def plot_samples(self, x, y, ax=None, show=True, xlabel='$x$', ylabel='Size of reduced data, $n$'): if self._made: if ax is None: fig, ax = plt.subplots(nrows=1, ncols=1) # Assemble all reduced samples into a 2d array longest = max(map(len, self.Xs)) Xs = max(x)*np.ones((len(self.Xs),longest), dtype='double') for ii, kk in enumerate(self.Xs): Xs[ii][:len(kk)] = kk # Plot ranges of selected samples for each iteration mins, maxes = [], [] for cc in Xs.T: mins.append(np.min(cc)) maxes.append(np.max(cc)) ax.plot(mins, np.arange(len(mins)), 'k-', maxes, np.arange(len(maxes)), 'k-') # Shade between the min and max number of reduced samples spline_mins = greedy.UnivariateSpline(np.sort(mins), np.arange(len(mins)), s=0) ax.fill_between(np.sort(maxes), spline_mins(np.sort(maxes)), np.arange(len(maxes)), facecolor='k', alpha=0.33) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if show: plt.show() else: if ax is None: return fig, ax else: return ax else: print("No data to plot. Run `make` method or set _made attribute to True.") def small_spline(x, y, num, tol=1e-6, deg=None, rel=False, parallel=True, verbose=False): """Build reduced-order splines for a number of randomly selected input seed points for the purpose of finding the spline with the smallest such reduced data over the sampled seeds. The degree of the spline polynomial can also be varied. Input ----- x -- samples y -- data to be downsampled num -- number of sets of random initial seed points tol -- L-infinity error tolerance for reduced-order spline (default 1e-6) deg -- degree of interpolating polynomials (default None) rel -- L-infinity error tolerance is relative to max abs of data? (default False) parallel -- parallelize the computation of each random seed set? (default True) verbose -- print progress to screen? (default False) Output ------ Reduced-order spline object with the smallest reduced data size for the seeds (and spline degrees) sampled. Comments -------- If deg is None then polynomials of degrees 1-5 are also sampled, in addition to the random sets of initial seeds. """ if deg is None: # Use all integers in [1,5] degs = range(1, 6) else: if len(np.shape(deg)) == 1:
mil habitantes" ): # Ver metodologia do SimulaCovid: a capacidade hospitalar é projetada com os dados mais recentes da doença no município, regional ou estado. st.write( """<div class="base-wrapper">Desde final de 2020 notamos que o modelo passou a calcular valores muito abaixo do que observamos na realidade - dizemos que o modelo estava "sobrehospitalizando" a projeção de casos de Covid-19. Isso foi observado primeiramente nas estimativas dos estados que sempre indicavam + de 30 dias (novo normal) para atingir da capacidade máxima de leitos UTI. Além dessa observação, vimos em outros modelos e pesquisas que muitos deixaram de performar bem devido a alterações de tratamento (positivamente uma melhoria) e na própria disseminação do vírus que mudaram o comportamento da evolução dos quadros hospitalares. <br><br> Dito isso, alteramos nosso indicador para leitos UTI por 100mil hab. com os dados atualizados mensalmente no DataSUS/CNES como valor alternativo para classificação de capacidade hospitalar até resolvermos o simulador. </div>""", unsafe_allow_html=True, ) # def main(session_state): # user_analytics = amplitude.gen_user(utils.get_server_session()) # opening_response = user_analytics.safe_log_event( # "opened risk_level", session_state, is_new_page=True # ) # st.header("""Níveis de Risco: como saber se estou no controle da Covid-19?""") # st.write( # """ # <br> # Até que uma vacina ou tratamento sejam encontrados para a Covid-19, será # necessário <strong>controlar a quantidade de pessoas infectadas, para # ter certeza de que o sistema de saúde terá capacidade de atender a todas # e todos, e não venha a colapsar.</strong><br><br> Depois de um primeiro # momento de mitigação da Covid-19 nos estados e municípios brasileiros, # passamos a uma nova fase da resposta à pandemia, quando será necessário # avaliar, a cada momento, qual a abordagem mais adequada para seu # município ou estado, de acordo com informações sobre a dinâmica de # transmissão da doença e sua capacidade de resposta.<br><br> Enquanto # muitas cidades já convivem com um número alto de casos diagnosticados, # outros municípios ainda não registram internações ou óbitos por # Covid-19. Tampouco o "pico" do número de casos e óbitos será atingido ao # mesmo tempo em todo o território.<br><br> Ainda que haja medidas # indicadas para todas as situações, como os protocolos de higienização e # a adoção de um espaço de segurança entre as pessoas em espaços # compartilhados, em um país de dimensões continentais como o Brasil, a # resposta à pandemia do coronavírus precisa considerar a capacidade # hospitalar de cada região e o momento onde cada um se encontra na # evolução da doença.<br><br> # """, # unsafe_allow_html=True, # ) # st.subheader("Indicadores-chave") # st.write( # """ # Para desenvolver # os níveis de risco do FarolCovid, avaliamos três # indicadores-chave:<br><br> # <li><strong>Ritmo de contágio (Rt),</strong> que # traduz para quantas pessoas cada pessoa doente transmitirá a doença. Ele # é calculado por meio de uma atualização do estimador do número efetivo # de reprodução da Covid-19, a partir do número de novos casos registrados # por dia. O Ritmo de contágio indica qual é o cenário futuro esperado # para a doença. Para mais informações de como esse número é calculado, # acesse nossa metodologia do estimador de Rt na aba à # esquerda. # </li><li><strong>Taxa de subnotificação,</strong> que estima a # quantidade de pessoas doentes que não são diagnosticadas. Ela é # calculada considerando uma taxa de mortalidade padrão de 2% e estimando # quantos casos teriam que estar ativos para produzir o número de mortos # registrados naquele estado ou município. É um indicador da necessidade # de realizar mais testes na população. Para mais informações sobre como # esse número é calculado, acesse nossa metodologia na aba à # esquerda. # </li><li><strong>Capacidade hospitalar,</strong> que reporta a # estimativa do número de dias até que todos os leitos da rede de saúde # disponíveis para Covid-19 estarão ocupados. Ela é feita utilizando o # modelo do SimulaCovid calibrado com o ritmo de contágio atual. É um # indicador do tempo que o gestor pode ter para reagir, caso venha a # registrar um aumento inesperado no número de casos. Para mais # informações sobre como esse número é calculado, acesse nossa metodologia # do modelo na aba à esquerda.<br><br> # </li>Ainda não há estudos científicos # que indiquem a relação exata entre a Taxa de Isolamento e o seu impacto # no Ritmo de Contágio para municípios brasileiros; portanto, essa versão # do FarolCovid informa ao gestor público qual é o nível de isolamento # social, mas não o inclui no cálculo para classificação de níveis de # risco.<br><br> # """, # unsafe_allow_html=True, # ) # st.write( # """ # Avaliamos se os três indicadores-chave estão bons, insatisfatórios ou # ruins, avaliamos suas tendências (se estão crescendo, estáveis ou # diminuindo) e então classificamos o município ou estado no nível de # risco equivalente: baixo, médio ou alto risco de colapso do sistema de # saúde.<br><br> Os indicadores são avaliados da seguinte forma:<br><br> # <ul> # <li><strong>Ritmo de Contágio</strong><br><br> # <ul> # <li><strong style="color:green">Bom</strong>: < 1, indicando que cada pessoa doente infecta menos de uma nova pessoa;</li> # <li><strong style="color: orange">Insatisfatório</strong>: entre 1 e 1.2, indicando o início de um comportamento exponencial de crescimento do número de pessoas doentes;</li> # <li><strong style="color:red">Ruim</strong>: > 1.2, indicando que há um crescimento exponencial do número de pessoas sendo infectadas.</li> # </ul> # </li> # <li><strong>Tendência do ritmo de contágio</strong><br><br> # <ul> # <li><strong style="color:green">Descendo</strong>: A taxa reportada há 10 dias é menor do que aquela reportada 17 dias atrás, indicando que o ritmo de contágio pode ter continuado a cair nos últimos 10 dias;</li> # <li><strong style="color:orange">Estável</strong>: A taxa reportada há 10 dias é 0.9 a 1.1 vezes aquela reportada 17 dias atrás, indicando que o ritmo de contágio pode ter se mantido semelhante nos últimos 10 dias;</li> # <li><strong style="color:red">Subindo</strong>: A taxa reportada há 10 dias é maior do que aquela reportada 17 dias atrás, indicando que o ritmo de contágio tenha continuado a subir nos últimos 10 dias.</li> # </ul> </li> # <li><strong>Taxa de subnotificação</strong><br><br> # <ul> # <li><strong style="color:green">Bom</strong>: < 50%, indicando que o número de casos registrados não está tão distante do esperado quando comparado com o número de mortos. Aceitamos esse limite de 50% pois pode ser o caso da mortalidade ser mais alta naquele município ou estado por um padrão de vulnerabilidade da população;</li> # <li><strong style="color:orange">Insatisfatório</strong>: entre 50 e 70%, indicando que o número de casos registrados está distante do esperado quando comparado com o número de mortos;</li> # <li><strong style="color:red">Ruim</strong>: > 70%. Indica que o número de casos registrados está muito pequeno quando comparado com o número de mortos confirmados com Covid-19. Indica que há falta de testagem.</li> # </ul> </li> # <li><strong>Capacidade Hospitalar</strong><br><br> # <ul> # <li><strong style="color:green">Bom</strong>: > 60 dias até que todos os leitos estejam ocupados com pacientes com Covid-19, indicando que o poder público terá tempo para organizar uma resposta caso o número de casos venha a crescer de modo inesperado;</li> # <li><strong style="color:orange">Insatisfatório</strong>: entre 30 e 60 dias até que todos os leitos estejam ocupados com pacientes com Covid-19;</li> # <li><strong style="color:red">Ruim</strong>: < 30 até que todos os leitos estejam ocupados com pacientes com Covid-19, indicando que o gestor terá pouco tempo de reação antes do colapso do sistema de saúde, caso haja um crescimento inesperado no número de casos.</li> # </ul> </li> # </ul> # <br> # """, # unsafe_allow_html=True, # ) # st.subheader("Regras de classificação para os níveis de risco") # st.write( # """ # Inspirados pelo modelo do Rio Grande # do Sul [1], desenvolvemos um sistema de níveis de risco de colapso do # sistema de saúde, seja por um ritmo de contágio mais elevado ou por uma # baixa capacidade do sistema em si.<br><br> A classificação em níveis de # risco é <strong>dinâmica</strong>, indicando que ela muda conforme os # indicadores das cidades e municípios são atualizados, diariamente. # Portanto, aconselhamos que seja feito um acompanhamento frequente do # FarolCovid por parte de gestores.<br><br> Esses números podem, ainda, # ser uma importante ferramenta para comunicação com os cidadãos, servindo # de embasamento e justificativa para a tomada de decisão adequada a cada # realidade local. O público, em geral, também pode utilizar esses números # para engajar o poder público em um debate informado sobre quais são as # melhores políticas para sua cidade ou Estado.<br><br> # """, # unsafe_allow_html=True, # ) # st.image( # Image.open("imgs/semaforo0.png"), # use_column_width=True, # caption="Imagem meramente ilustrativa", # ) # st.write( # """ # <span> # Dizemos que município
[c_uint32, c_uint16] api.ScpChTrSetLevelMode.restype = c_uint32 api.ScpChTrSetLevelMode.argtypes = [c_uint32, c_uint16, c_uint32] api.ScpChTrGetLevelCount.restype = c_uint32 api.ScpChTrGetLevelCount.argtypes = [c_uint32, c_uint16] api.ScpChTrGetLevel.restype = c_double api.ScpChTrGetLevel.argtypes = [c_uint32, c_uint16, c_uint32] api.ScpChTrSetLevel.restype = c_double api.ScpChTrSetLevel.argtypes = [c_uint32, c_uint16, c_uint32, c_double] api.ScpChTrGetHysteresisCount.restype = c_uint32 api.ScpChTrGetHysteresisCount.argtypes = [c_uint32, c_uint16] api.ScpChTrGetHysteresis.restype = c_double api.ScpChTrGetHysteresis.argtypes = [c_uint32, c_uint16, c_uint32] api.ScpChTrSetHysteresis.restype = c_double api.ScpChTrSetHysteresis.argtypes = [c_uint32, c_uint16, c_uint32, c_double] api.ScpChTrGetConditions.restype = c_uint32 api.ScpChTrGetConditions.argtypes = [c_uint32, c_uint16] api.ScpChTrGetConditionsEx.restype = c_uint32 api.ScpChTrGetConditionsEx.argtypes = [c_uint32, c_uint16, c_uint32, c_uint64] api.ScpChTrGetCondition.restype = c_uint32 api.ScpChTrGetCondition.argtypes = [c_uint32, c_uint16] api.ScpChTrSetCondition.restype = c_uint32 api.ScpChTrSetCondition.argtypes = [c_uint32, c_uint16, c_uint32] api.ScpChTrGetTimeCount.restype = c_uint32 api.ScpChTrGetTimeCount.argtypes = [c_uint32, c_uint16] api.ScpChTrGetTime.restype = c_double api.ScpChTrGetTime.argtypes = [c_uint32, c_uint16, c_uint32] api.ScpChTrSetTime.restype = c_double api.ScpChTrSetTime.argtypes = [c_uint32, c_uint16, c_uint32, c_double] api.ScpChTrVerifyTime.restype = c_double api.ScpChTrVerifyTime.argtypes = [c_uint32, c_uint16, c_uint32, c_double] api.ScpChTrVerifyTimeEx2.restype = c_double api.ScpChTrVerifyTimeEx2.argtypes = [c_uint32, c_uint16, c_uint32, c_double, c_uint32, c_double, c_uint64, c_uint32] api.ScpGetData.restype = c_uint64 api.ScpGetData.argtypes = [c_uint32, c_void_p, c_uint16, c_uint64, c_uint64] api.ScpGetData1Ch.restype = c_uint64 api.ScpGetData1Ch.argtypes = [c_uint32, c_void_p, c_uint64, c_uint64] api.ScpGetData2Ch.restype = c_uint64 api.ScpGetData2Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData3Ch.restype = c_uint64 api.ScpGetData3Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData4Ch.restype = c_uint64 api.ScpGetData4Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData5Ch.restype = c_uint64 api.ScpGetData5Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData6Ch.restype = c_uint64 api.ScpGetData6Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData7Ch.restype = c_uint64 api.ScpGetData7Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetData8Ch.restype = c_uint64 api.ScpGetData8Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetValidPreSampleCount.restype = c_uint64 api.ScpGetValidPreSampleCount.argtypes = [c_uint32] api.ScpChGetDataValueRange.restype = None api.ScpChGetDataValueRange.argtypes = [c_uint32, c_uint16, c_void_p, c_void_p] api.ScpChGetDataValueMin.restype = c_double api.ScpChGetDataValueMin.argtypes = [c_uint32, c_uint16] api.ScpChGetDataValueMax.restype = c_double api.ScpChGetDataValueMax.argtypes = [c_uint32, c_uint16] api.ScpGetDataRaw.restype = c_uint64 api.ScpGetDataRaw.argtypes = [c_uint32, c_void_p, c_uint16, c_uint64, c_uint64] api.ScpGetDataRaw1Ch.restype = c_uint64 api.ScpGetDataRaw1Ch.argtypes = [c_uint32, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw2Ch.restype = c_uint64 api.ScpGetDataRaw2Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw3Ch.restype = c_uint64 api.ScpGetDataRaw3Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw4Ch.restype = c_uint64 api.ScpGetDataRaw4Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw5Ch.restype = c_uint64 api.ScpGetDataRaw5Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw6Ch.restype = c_uint64 api.ScpGetDataRaw6Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw7Ch.restype = c_uint64 api.ScpGetDataRaw7Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpGetDataRaw8Ch.restype = c_uint64 api.ScpGetDataRaw8Ch.argtypes = [c_uint32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_uint64, c_uint64] api.ScpChGetDataRawType.restype = c_uint32 api.ScpChGetDataRawType.argtypes = [c_uint32, c_uint16] api.ScpChGetDataRawValueRange.restype = None api.ScpChGetDataRawValueRange.argtypes = [c_uint32, c_uint16, c_void_p, c_void_p, c_void_p] api.ScpChGetDataRawValueMin.restype = c_int64 api.ScpChGetDataRawValueMin.argtypes = [c_uint32, c_uint16] api.ScpChGetDataRawValueZero.restype = c_int64 api.ScpChGetDataRawValueZero.argtypes = [c_uint32, c_uint16] api.ScpChGetDataRawValueMax.restype = c_int64 api.ScpChGetDataRawValueMax.argtypes = [c_uint32, c_uint16] api.ScpChIsRangeMaxReachable.restype = c_uint8 api.ScpChIsRangeMaxReachable.argtypes = [c_uint32, c_uint16] api.ScpIsGetDataAsyncCompleted.restype = c_uint8 api.ScpIsGetDataAsyncCompleted.argtypes = [c_uint32] api.ScpStartGetDataAsync.restype = c_uint8 api.ScpStartGetDataAsync.argtypes = [c_uint32, c_void_p, c_uint16, c_uint64, c_uint64] api.ScpStartGetDataAsyncRaw.restype = c_uint8 api.ScpStartGetDataAsyncRaw.argtypes = [c_uint32, c_void_p, c_uint16, c_uint64, c_uint64] api.ScpCancelGetDataAsync.restype = c_uint8 api.ScpCancelGetDataAsync.argtypes = [c_uint32] api.ScpSetCallbackDataReady.restype = None api.ScpSetCallbackDataReady.argtypes = [c_uint32, Callback, c_void_p] api.ScpSetCallbackDataOverflow.restype = None api.ScpSetCallbackDataOverflow.argtypes = [c_uint32, Callback, c_void_p] api.ScpSetCallbackConnectionTestCompleted.restype = None api.ScpSetCallbackConnectionTestCompleted.argtypes = [c_uint32, Callback, c_void_p] api.ScpSetCallbackTriggered.restype = None api.ScpSetCallbackTriggered.argtypes = [c_uint32, Callback, c_void_p] if platform.system() == 'Linux': api.ScpSetEventDataReady.restype = None api.ScpSetEventDataReady.argtypes = [c_uint32, c_int] api.ScpSetEventDataOverflow.restype = None api.ScpSetEventDataOverflow.argtypes = [c_uint32, c_int] api.ScpSetEventConnectionTestCompleted.restype = None api.ScpSetEventConnectionTestCompleted.argtypes = [c_uint32, c_int] api.ScpSetEventTriggered.restype = None api.ScpSetEventTriggered.argtypes = [c_uint32, c_int] if platform.system() == 'Windows': api.ScpSetEventDataReady.restype = None api.ScpSetEventDataReady.argtypes = [c_uint32, HANDLE] api.ScpSetEventDataOverflow.restype = None api.ScpSetEventDataOverflow.argtypes = [c_uint32, HANDLE] api.ScpSetEventConnectionTestCompleted.restype = None api.ScpSetEventConnectionTestCompleted.argtypes = [c_uint32, HANDLE] api.ScpSetEventTriggered.restype = None api.ScpSetEventTriggered.argtypes = [c_uint32, HANDLE] api.ScpSetMessageDataReady.restype = None api.ScpSetMessageDataReady.argtypes = [c_uint32, HWND, WPARAM, LPARAM] api.ScpSetMessageDataOverflow.restype = None api.ScpSetMessageDataOverflow.argtypes = [c_uint32, HWND, WPARAM, LPARAM] api.ScpSetMessageConnectionTestCompleted.restype = None api.ScpSetMessageConnectionTestCompleted.argtypes = [c_uint32, HWND, WPARAM, LPARAM] api.ScpSetMessageTriggered.restype = None api.ScpSetMessageTriggered.argtypes = [c_uint32, HWND, WPARAM, LPARAM] api.ScpStart.restype = c_uint8 api.ScpStart.argtypes = [c_uint32] api.ScpStop.restype = c_uint8 api.ScpStop.argtypes = [c_uint32] api.ScpForceTrigger.restype = c_uint8 api.ScpForceTrigger.argtypes = [c_uint32] api.ScpGetMeasureModes.restype = c_uint32 api.ScpGetMeasureModes.argtypes = [c_uint32] api.ScpGetMeasureMode.restype = c_uint32 api.ScpGetMeasureMode.argtypes = [c_uint32] api.ScpSetMeasureMode.restype = c_uint32 api.ScpSetMeasureMode.argtypes = [c_uint32, c_uint32] api.ScpIsRunning.restype = c_uint8 api.ScpIsRunning.argtypes = [c_uint32] api.ScpIsTriggered.restype = c_uint8 api.ScpIsTriggered.argtypes = [c_uint32] api.ScpIsTimeOutTriggered.restype = c_uint8 api.ScpIsTimeOutTriggered.argtypes = [c_uint32] api.ScpIsForceTriggered.restype = c_uint8 api.ScpIsForceTriggered.argtypes = [c_uint32] api.ScpIsDataReady.restype = c_uint8 api.ScpIsDataReady.argtypes = [c_uint32] api.ScpIsDataOverflow.restype = c_uint8 api.ScpIsDataOverflow.argtypes = [c_uint32] api.ScpGetAutoResolutionModes.restype = c_uint32 api.ScpGetAutoResolutionModes.argtypes = [c_uint32] api.ScpGetAutoResolutionMode.restype = c_uint32 api.ScpGetAutoResolutionMode.argtypes = [c_uint32] api.ScpSetAutoResolutionMode.restype = c_uint32 api.ScpSetAutoResolutionMode.argtypes = [c_uint32, c_uint32] api.ScpGetResolutions.restype = c_uint32 api.ScpGetResolutions.argtypes = [c_uint32, c_void_p, c_uint32] api.ScpGetResolution.restype = c_uint8 api.ScpGetResolution.argtypes = [c_uint32] api.ScpSetResolution.restype = c_uint8 api.ScpSetResolution.argtypes = [c_uint32, c_uint8] api.ScpIsResolutionEnhanced.restype = c_uint8 api.ScpIsResolutionEnhanced.argtypes = [c_uint32] api.ScpIsResolutionEnhancedEx.restype = c_uint8 api.ScpIsResolutionEnhancedEx.argtypes = [c_uint32, c_uint8] api.ScpGetClockSources.restype = c_uint32 api.ScpGetClockSources.argtypes = [c_uint32] api.ScpGetClockSource.restype = c_uint32 api.ScpGetClockSource.argtypes = [c_uint32] api.ScpSetClockSource.restype = c_uint32 api.ScpSetClockSource.argtypes = [c_uint32, c_uint32] api.ScpGetClockSourceFrequencies.restype = c_uint32 api.ScpGetClockSourceFrequencies.argtypes = [c_uint32, c_void_p, c_uint32] api.ScpGetClockSourceFrequenciesEx.restype = c_uint32 api.ScpGetClockSourceFrequenciesEx.argtypes = [c_uint32, c_uint32, c_void_p, c_uint32] api.ScpGetClockSourceFrequency.restype = c_double api.ScpGetClockSourceFrequency.argtypes = [c_uint32] api.ScpSetClockSourceFrequency.restype = c_double api.ScpSetClockSourceFrequency.argtypes = [c_uint32, c_double] api.ScpGetClockOutputs.restype = c_uint32 api.ScpGetClockOutputs.argtypes = [c_uint32] api.ScpGetClockOutput.restype = c_uint32 api.ScpGetClockOutput.argtypes = [c_uint32] api.ScpSetClockOutput.restype = c_uint32 api.ScpSetClockOutput.argtypes = [c_uint32, c_uint32] api.ScpGetClockOutputFrequencies.restype = c_uint32 api.ScpGetClockOutputFrequencies.argtypes = [c_uint32, c_void_p, c_uint32] api.ScpGetClockOutputFrequenciesEx.restype = c_uint32 api.ScpGetClockOutputFrequenciesEx.argtypes = [c_uint32, c_uint32, c_void_p, c_uint32] api.ScpGetClockOutputFrequency.restype = c_double api.ScpGetClockOutputFrequency.argtypes = [c_uint32] api.ScpSetClockOutputFrequency.restype = c_double api.ScpSetClockOutputFrequency.argtypes = [c_uint32, c_double] api.ScpGetSampleFrequencyMax.restype = c_double api.ScpGetSampleFrequencyMax.argtypes = [c_uint32] api.ScpGetSampleFrequency.restype = c_double api.ScpGetSampleFrequency.argtypes = [c_uint32] api.ScpSetSampleFrequency.restype = c_double api.ScpSetSampleFrequency.argtypes = [c_uint32, c_double] api.ScpVerifySampleFrequency.restype = c_double api.ScpVerifySampleFrequency.argtypes = [c_uint32, c_double] api.ScpVerifySampleFrequencyEx.restype = c_double api.ScpVerifySampleFrequencyEx.argtypes = [c_uint32, c_double, c_uint32, c_uint8, c_void_p, c_uint16] api.ScpVerifySampleFrequenciesEx.restype = None api.ScpVerifySampleFrequenciesEx.argtypes = [c_uint32, c_void_p, c_uint32, c_uint32, c_uint32, c_uint8, c_void_p, c_uint16] api.ScpGetRecordLengthMax.restype = c_uint64 api.ScpGetRecordLengthMax.argtypes = [c_uint32] api.ScpGetRecordLengthMaxEx.restype = c_uint64 api.ScpGetRecordLengthMaxEx.argtypes = [c_uint32, c_uint32, c_uint8] api.ScpGetRecordLength.restype = c_uint64 api.ScpGetRecordLength.argtypes = [c_uint32] api.ScpSetRecordLength.restype = c_uint64 api.ScpSetRecordLength.argtypes = [c_uint32, c_uint64] api.ScpVerifyRecordLength.restype = c_uint64 api.ScpVerifyRecordLength.argtypes = [c_uint32, c_uint64] api.ScpVerifyRecordLengthEx.restype = c_uint64 api.ScpVerifyRecordLengthEx.argtypes = [c_uint32, c_uint64, c_uint32, c_uint8, c_void_p, c_uint16] api.ScpGetPreSampleRatio.restype = c_double api.ScpGetPreSampleRatio.argtypes = [c_uint32] api.ScpSetPreSampleRatio.restype = c_double api.ScpSetPreSampleRatio.argtypes = [c_uint32, c_double] api.ScpGetSegmentCountMax.restype = c_uint32 api.ScpGetSegmentCountMax.argtypes = [c_uint32] api.ScpGetSegmentCountMaxEx.restype = c_uint32 api.ScpGetSegmentCountMaxEx.argtypes = [c_uint32, c_uint32] api.ScpGetSegmentCount.restype = c_uint32 api.ScpGetSegmentCount.argtypes = [c_uint32] api.ScpSetSegmentCount.restype = c_uint32 api.ScpSetSegmentCount.argtypes = [c_uint32, c_uint32] api.ScpVerifySegmentCount.restype = c_uint32 api.ScpVerifySegmentCount.argtypes = [c_uint32, c_uint32] api.ScpVerifySegmentCountEx2.restype = c_uint32 api.ScpVerifySegmentCountEx2.argtypes = [c_uint32, c_uint32, c_uint32, c_uint64, c_void_p, c_uint16] api.ScpHasTrigger.restype = c_uint8 api.ScpHasTrigger.argtypes = [c_uint32] api.ScpHasTriggerEx.restype = c_uint8 api.ScpHasTriggerEx.argtypes = [c_uint32, c_uint32] api.ScpGetTriggerTimeOut.restype = c_double api.ScpGetTriggerTimeOut.argtypes = [c_uint32] api.ScpSetTriggerTimeOut.restype = c_double api.ScpSetTriggerTimeOut.argtypes = [c_uint32, c_double] api.ScpVerifyTriggerTimeOut.restype = c_double api.ScpVerifyTriggerTimeOut.argtypes = [c_uint32, c_double] api.ScpVerifyTriggerTimeOutEx.restype = c_double api.ScpVerifyTriggerTimeOutEx.argtypes = [c_uint32, c_double, c_uint32, c_double] api.ScpHasTriggerDelay.restype = c_uint8 api.ScpHasTriggerDelay.argtypes = [c_uint32] api.ScpHasTriggerDelayEx.restype = c_uint8 api.ScpHasTriggerDelayEx.argtypes = [c_uint32, c_uint32] api.ScpGetTriggerDelayMax.restype = c_double api.ScpGetTriggerDelayMax.argtypes = [c_uint32] api.ScpGetTriggerDelayMaxEx.restype = c_double api.ScpGetTriggerDelayMaxEx.argtypes = [c_uint32, c_uint32, c_double] api.ScpGetTriggerDelay.restype = c_double api.ScpGetTriggerDelay.argtypes = [c_uint32] api.ScpSetTriggerDelay.restype = c_double api.ScpSetTriggerDelay.argtypes = [c_uint32, c_double] api.ScpVerifyTriggerDelay.restype = c_double api.ScpVerifyTriggerDelay.argtypes = [c_uint32, c_double] api.ScpVerifyTriggerDelayEx.restype = c_double api.ScpVerifyTriggerDelayEx.argtypes = [c_uint32, c_double, c_uint32, c_double] api.ScpHasTriggerHoldOff.restype = c_uint8 api.ScpHasTriggerHoldOff.argtypes = [c_uint32] api.ScpHasTriggerHoldOffEx.restype = c_uint8 api.ScpHasTriggerHoldOffEx.argtypes = [c_uint32, c_uint32] api.ScpGetTriggerHoldOffCountMax.restype = c_uint64 api.ScpGetTriggerHoldOffCountMax.argtypes = [c_uint32] api.ScpGetTriggerHoldOffCountMaxEx.restype = c_uint64 api.ScpGetTriggerHoldOffCountMaxEx.argtypes = [c_uint32, c_uint32] api.ScpGetTriggerHoldOffCount.restype = c_uint64 api.ScpGetTriggerHoldOffCount.argtypes = [c_uint32] api.ScpSetTriggerHoldOffCount.restype = c_uint64 api.ScpSetTriggerHoldOffCount.argtypes = [c_uint32, c_uint64] api.ScpHasConnectionTest.restype = c_uint8 api.ScpHasConnectionTest.argtypes = [c_uint32] api.ScpChHasConnectionTest.restype = c_uint8 api.ScpChHasConnectionTest.argtypes = [c_uint32, c_uint16] api.ScpStartConnectionTest.restype = c_uint8 api.ScpStartConnectionTest.argtypes = [c_uint32] api.ScpStartConnectionTestEx.restype = c_uint8 api.ScpStartConnectionTestEx.argtypes = [c_uint32, c_void_p, c_uint16] api.ScpIsConnectionTestCompleted.restype = c_uint8 api.ScpIsConnectionTestCompleted.argtypes = [c_uint32] api.ScpGetConnectionTestData.restype = c_uint16 api.ScpGetConnectionTestData.argtypes = [c_uint32, c_void_p, c_uint16] api.GenGetConnectorType.restype = c_uint32 api.GenGetConnectorType.argtypes = [c_uint32] api.GenIsDifferential.restype = c_uint8 api.GenIsDifferential.argtypes = [c_uint32] api.GenGetImpedance.restype = c_double api.GenGetImpedance.argtypes = [c_uint32] api.GenGetResolution.restype = c_uint8 api.GenGetResolution.argtypes = [c_uint32] api.GenGetOutputValueMin.restype = c_double api.GenGetOutputValueMin.argtypes = [c_uint32] api.GenGetOutputValueMax.restype = c_double api.GenGetOutputValueMax.argtypes = [c_uint32] api.GenGetOutputValueMinMax.restype = None api.GenGetOutputValueMinMax.argtypes = [c_uint32, c_void_p, c_void_p] api.GenIsControllable.restype = c_uint8 api.GenIsControllable.argtypes = [c_uint32] api.GenIsRunning.restype = c_uint8 api.GenIsRunning.argtypes = [c_uint32] api.GenGetStatus.restype = c_uint32 api.GenGetStatus.argtypes = [c_uint32] api.GenGetOutputOn.restype = c_uint8 api.GenGetOutputOn.argtypes = [c_uint32] api.GenSetOutputOn.restype = c_uint8 api.GenSetOutputOn.argtypes = [c_uint32, c_uint8] api.GenHasOutputInvert.restype = c_uint8 api.GenHasOutputInvert.argtypes = [c_uint32] api.GenGetOutputInvert.restype = c_uint8 api.GenGetOutputInvert.argtypes = [c_uint32] api.GenSetOutputInvert.restype = c_uint8 api.GenSetOutputInvert.argtypes = [c_uint32, c_uint8] api.GenStart.restype = c_uint8 api.GenStart.argtypes = [c_uint32] api.GenStop.restype = c_uint8 api.GenStop.argtypes = [c_uint32] api.GenGetSignalTypes.restype = c_uint32 api.GenGetSignalTypes.argtypes = [c_uint32] api.GenGetSignalType.restype = c_uint32 api.GenGetSignalType.argtypes = [c_uint32] api.GenSetSignalType.restype = c_uint32 api.GenSetSignalType.argtypes = [c_uint32, c_uint32] api.GenHasAmplitude.restype = c_uint8 api.GenHasAmplitude.argtypes = [c_uint32] api.GenHasAmplitudeEx.restype =
import json import logging import math import os import pathlib import subprocess import numpy as np import shapely.geometry import shapely.affinity import venn7.bezier ROOT = pathlib.Path(os.path.realpath(__file__)).parent class VennDiagram: """A simple symmetric monotone Venn diagram. The diagram is encoded discretely using a set of "row swaps." Creation of path data is performed on the fly. See README for more info. Parameters ---------- n : int The order of the Venn diagram. Must be prime. matrix_encoding_string : str A string containing whitespace-separated rows of the "matrix encoding." See README for example. """ def __init__(self, n, matrix_encoding_string, name=None, renderer_args=None): self.name = name self.n = n self.row_swaps = self.parse_matrix_encoding_string( matrix_encoding_string ) self.flattened_row_swaps = [y for x in self.row_swaps for y in x] self.renderer_args = renderer_args if self.renderer_args is None: self.renderer_args = {} self.validate_basic() self.validate_venn() def parse_matrix_encoding_string(self, matrix_encoding_string): rows = matrix_encoding_string.strip().splitlines() matrix = [[int(c) for c in line.strip()] for line in rows] row_swaps = [] for column in range(len(matrix[0])): entry = [] for row in range(len(matrix)): if matrix[row][column] == 1: entry.append(row + 1) row_swaps.append(entry) return row_swaps def validate_basic(self): """Check for basic errors in the matrix flattened_row_swaps.""" n = self.n expected_length = (2 ** n - 2) // n if len(self.flattened_row_swaps) != expected_length: raise ValueError( f"Wrong length: flattened_row_swaps should be of length {expected_length}" ) last_x = self.flattened_row_swaps[-1] for x in self.flattened_row_swaps: if last_x == x: raise ValueError( "Immediate repetitions are not allowed in flattened_row_swaps" ) last_x = x for k in range(1, n - 1): expected = math.comb(n, k) // n count = 0 for x in self.flattened_row_swaps: if x == k: count += 1 if count != expected: raise ValueError(f"Expected {expected} instances of {k}") def validate_venn(self): """Check that this is in fact a Venn diagram.""" n = self.n # I am not sure if this validation code is correct, sorry ranks = [False] * (2 ** n) ranks[0] = ranks[-1] = True p = list(range(n)) for swap_row in self.full_flattened_row_swaps(): a = swap_row b = swap_row - 1 p[a], p[b] = p[b], p[a] rank = sum([2 ** x for x in p[swap_row:]]) if ranks[rank]: raise ValueError(f"Duplicate rank {rank}") ranks[rank] = True if not all(ranks): raise ValueError(f"Not all ranks represented") def full_flattened_row_swaps(self): """Return the flattened_row_swaps duplicated n times.""" full_flattened_row_swaps = [] for i in range(self.n): full_flattened_row_swaps += self.flattened_row_swaps return full_flattened_row_swaps def get_spline(self, index=0): renderer = VennDiagramRenderer(self, **self.renderer_args) return renderer.get_spline() def get_polygon(self, index=0): """Get the shape of a single curve as a polygon.""" spline = self.get_spline(index) resolution = 10 points = [] for bezier in spline.beziers: for i in range(resolution): points.append(bezier(i / resolution)) return points def check_regions(self): """Approximate this Venn diagram with polygons and use Shapely to check that the diagram is valid.""" original_curve = shapely.geometry.Polygon(self.get_polygon()) curves = [] for i in range(self.n): angle = 2 * math.pi * i / self.n curve = shapely.affinity.rotate( original_curve, angle, origin=(0, 0), use_radians=True ) curves.append(curve) # Region at index 0 is an empty set. regions = [[]] for rank in range(1, 2 ** self.n): curves_included = [] curves_excluded = [] tmp_rank = rank for i in range(self.n): if tmp_rank % 2 == 0: curves_excluded.append(curves[i]) else: curves_included.append(curves[i]) tmp_rank //= 2 region = curves_included[0] for curve in curves_included[1:]: region = region.intersection(curve) for curve in curves_excluded: region = region.difference(curve) assert not region.is_empty def export_json(self): result = { "name": self.name, "n": self.n, "curve": self.get_spline().as_svg_path(), } process = subprocess.run( ["node", str(ROOT / "venn_boolean.js")], check=True, capture_output=True, input=json.dumps(result), encoding="utf-8", ) regions = json.loads(process.stdout) processed_regions = [""] for region in regions[1:]: path = venn7.bezier.BezierPath.from_svg_path(region) path = path.remove_tiny_segments(threshold=1) processed_regions.append(path.as_svg_path()) result["regions"] = processed_regions return result def plot(self): import matplotlib.pyplot as plt import matplotlib.patches import matplotlib.collections fig, ax = plt.subplots() polygons = [ matplotlib.patches.Polygon(self.get_polygon(i)) for i in range(diagram.n) ] patches = matplotlib.collections.PatchCollection(polygons, alpha=0.2) ax.add_collection(patches) plt.xlim(-100, 100) plt.ylim(-100, 100) plt.show() class VennDiagramRenderer: """A class that renders discrete Venn diagrams to splines.""" def __init__( self, venn_diagram, inner_radius=30, spacing=5, tension_diagonal=1.0, tension_default=1.0, extra_outer_spacing=0, ): self.n = venn_diagram.n self.row_swaps = venn_diagram.row_swaps self.inner_radius = inner_radius self.spacing = spacing self.tension_diagonal = tension_diagonal self.tension_default = tension_default self.extra_outer_spacing = extra_outer_spacing # Avoid perfectly coincident endpoints, which causes # issues for Boolean ops. self.fudge_factor = 1e-4 def _get_radius_of_row(self, row, use_extra_outer_spacing=True): adjusted_row = row if use_extra_outer_spacing: if row <= 1: adjusted_row -= self.extra_outer_spacing if row >= self.n - 1: adjusted_row += self.extra_outer_spacing result = self.inner_radius + self.spacing * adjusted_row return result def _get_curve_points_on_cylinder(self, index): """Get the set of control points (not Bezier but Metafont control points) if the Venn diagram were unraveled on a cylinder. All these points lie on a grid. Each point is of the form (x, y, type). x is the circular coordinate which wraps around from 0 to len(self.row_swaps). y is the other, non-circular component which ranges from 0 to self.n - 1 inclusive. type is a string used to tag points with information about the point. This method generates two: - intersection_+ means that the curve is going up at this point. - intersection_- means that the curve is going down at this point. """ points = [] row, column = 0, index * len(self.row_swaps) for i in range(self.n): for swap_rows in self.row_swaps: if row + 1 in swap_rows: points.append((row + 1, column, "intersection_+")) row += 1 elif row in swap_rows: points.append((row, column, "intersection_-")) row -= 1 column += 1 return points def _add_arc_points(self, points): """Given a set of control points on the cylinder, find pairs of points that are horizontal and insert new arc points to help round out the curve in that region. It is assumed that all points are intersection type. """ squash_factor = len(self.row_swaps) result = [] for i in range(len(points)): r1, c1, type_1 = point = points[i] r2, c2, type_2 = points[(i + 1) % len(points)] result.append(point) if r1 == r2: radius = (c2 - c1) % len(self.n * self.row_swaps) * 0.5 column = c1 + radius if type_1 == "intersection_+" and type_2 == "intersection_-": arc_direction = 1 type_ = "arc_+" elif type_1 == "intersection_-" and type_2 == "intersection_+": arc_direction = -1 type_ = "arc_-" else: raise RuntimeError vertical_radius = arc_direction * radius * 0.5 ratio = 0.6 #result.append((r1 + vertical_radius, column, type_)) return result def _get_tensions(self, points): """Given a set of control points on the cylinder, determine whether each pair of points is diagonal or horizontal. If they are diagonal and both are of "intersection" type, their tension is set to ``tension_diagonal``. Otherwise, their tension is ``tension_default``. Collect a list of all tensions and return it. """ tensions = [] for i in range(len(points)): r1, c1, type_1 = points[i] r2, c2, type_2 = points[(i + 1) % len(points)] if ( type_1.startswith("intersection_") and type_2.startswith("intersection_") and type_1 == type_2 ): tensions.append(self.tension_diagonal) else: tensions.append(self.tension_default) return tensions def _convert_cylinder_points_to_polar(self, cylinder_points): polar_points = [] for row, column, __ in cylinder_points: radius = self._get_radius_of_row(row) theta = column * 2 * math.pi / (self.n * len(self.row_swaps)) x = radius * math.cos(theta) y = radius * math.sin(theta) polar_points.append((x, y)) return polar_points def _normalize_rotation_and_scaling(self, spline): """Given a spline, rotate and uniformly scale it so that its furthest point from the origin is transformed to (0, -50).""" x, y = spline.get_furthest_point_from((0, 0)) angle = np.arctan2(y, x) scale = np.hypot(x, y) return spline.transform( venn7.bezier.get_rotation_matrix(-np.pi * 0.5 - angle) * 50 / scale ) def _get_angles(self, cylinder_points): result = [] for row, column, type_ in cylinder_points: tangent_angle = 2 * np.pi * column / (self.n * len(self.row_swaps)) + np.pi / 2 angle = tangent_angle dy = self.spacing dx = self._get_radius_of_row(row) * 2 * np.pi / (self.n * len(self.row_swaps)) tilt_angle = np.arctan2(dy, dx) if type_ == "intersection_+": angle -= tilt_angle elif type_ == "intersection_-": angle += tilt_angle angle = angle % (2 * np.pi) result.append(angle) return result def get_spline(self, index=0): """Render a single curve of the Venn diagram to a BezierSpline and return the result. Parameters ---------- index : int Which curve to return. For a symmetric Venn diagram, indices other than 0 are rotations of each other. """ cylinder_points = self._get_curve_points_on_cylinder(index) cylinder_points = self._add_arc_points(cylinder_points) angles = self._get_angles(cylinder_points)
MagicWordConfig.EXEC_LOC_SERVER accessLevel = 'MODERATOR' def handleWord(self, invoker, avId, toon, *args): boss = None from toontown.suit.DistributedLawbotBossAI import DistributedLawbotBossAI for do in simbase.air.doId2do.values(): if isinstance(do, DistributedLawbotBossAI): if invoker.doId in do.involvedToons: boss = do break if not boss: return "You aren't in a CJ!" else: if not boss.state == 'BattleTwo': return "You aren't in the cannon round." for i in xrange(len(boss.chairs)): boss.chairs[i].b_setToonJurorIndex(0) boss.chairs[i].requestToonJuror() return 'Filled chairs.' class SkipVP(MagicWord): desc = 'Skips to the indicated round of the VP.' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('round', str, False, 'next')] accessLevel = 'MODERATOR' def handleWord(self, invoker, avId, toon, *args): battle = args[0] from toontown.suit.DistributedSellbotBossAI import DistributedSellbotBossAI boss = None for do in simbase.air.doId2do.values(): if isinstance(do, DistributedSellbotBossAI): if invoker.doId in do.involvedToons: boss = do break if not boss: return "You aren't in a VP!" else: battle = battle.lower() if battle == 'three': if boss.state in ('PrepareBattleThree', 'BattleThree'): return 'You can not return to previous rounds!' else: boss.exitIntroduction() boss.b_setState('PrepareBattleThree') return 'Skipping to final round...' if battle == 'next': if boss.state in ('PrepareBattleOne', 'BattleOne'): boss.exitIntroduction() boss.b_setState('PrepareBattleThree') return 'Skipping current round...' if boss.state in ('PrepareBattleThree', 'BattleThree'): boss.exitIntroduction() boss.b_setState('Victory') return 'Skipping final round...' return class StunVP(MagicWord): desc = 'Stuns the VP in the final round of his battle.' execLocation = MagicWordConfig.EXEC_LOC_SERVER accessLevel = 'MODERATOR' def handleWord(self, invoker, avId, toon, *args): from toontown.suit.DistributedSellbotBossAI import DistributedSellbotBossAI boss = None for do in simbase.air.doId2do.values(): if isinstance(do, DistributedSellbotBossAI): if invoker.doId in do.involvedToons: boss = do break if not boss: return "You aren't in a VP!" else: currState = boss.getCurrentOrNextState() if currState != 'BattleThree': return "You aren't in the final round of a VP!" boss.b_setAttackCode(ToontownGlobals.BossCogDizzyNow) boss.b_setBossDamage(boss.getBossDamage(), 0, 0) return class SkipCEO(MagicWord): desc = 'Skips to the indicated round of the CEO.' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('round', str, False, 'next')] accessLevel = 'MODERATOR' def handleWord(self, invoker, avId, toon, *args): battle = args[0] from toontown.suit.DistributedBossbotBossAI import DistributedBossbotBossAI boss = None for do in simbase.air.doId2do.values(): if isinstance(do, DistributedBossbotBossAI): if invoker.doId in do.involvedToons: boss = do break if not boss: return "You aren't in a CEO!" else: battle = battle.lower() if battle == 'two': if boss.state in ('PrepareBattleFour', 'BattleFour', 'PrepareBattleThree', 'BattleThree', 'PrepareBattleTwo', 'BattleTwo'): return 'You can not return to previous rounds!' else: boss.exitIntroduction() boss.b_setState('PrepareBattleTwo') return 'Skipping to second round...' if battle == 'three': if boss.state in ('PrepareBattleFour', 'BattleFour', 'PrepareBattleThree', 'BattleThree'): return 'You can not return to previous rounds!' else: boss.exitIntroduction() boss.b_setState('PrepareBattleThree') return 'Skipping to third round...' if battle == 'four': if boss.state in ('PrepareBattleFour', 'BattleFour'): return 'You can not return to previous rounds!' else: boss.exitIntroduction() boss.b_setState('PrepareBattleFour') return 'Skipping to last round...' if battle == 'next': if boss.state in ('PrepareBattleOne', 'BattleOne'): boss.exitIntroduction() boss.b_setState('PrepareBattleTwo') return 'Skipping current round...' if boss.state in ('PrepareBattleTwo', 'BattleTwo'): boss.exitIntroduction() boss.b_setState('PrepareBattleThree') return 'Skipping current round...' if boss.state in ('PrepareBattleThree', 'BattleThree'): boss.exitIntroduction() boss.b_setState('PrepareBattleFour') return 'Skipping current round...' if boss.state in ('PrepareBattleFour', 'BattleFour'): boss.exitIntroduction() boss.b_setState('Victory') return 'Skipping final round...' return class FeedDiners(MagicWord): desc = 'Feed the diners in the CEO battle.' execLocation = MagicWordConfig.EXEC_LOC_SERVER def handleWord(self, invoker, avId, toon, *args): boss = None from toontown.suit.DistributedBossbotBossAI import DistributedBossbotBossAI for do in simbase.air.doId2do.values(): if isinstance(do, DistributedBossbotBossAI): if invoker.doId in do.involvedToons: boss = do break if not boss: return "You aren't in a CEO!" else: if boss.state != 'BattleTwo': return "You aren't in the waiter round!" for table in boss.tables: for chairIndex in table.dinerInfo.keys(): dinerStatus = table.getDinerStatus(chairIndex) if dinerStatus in (table.HUNGRY, table.ANGRY): table.foodServed(chairIndex) return 'All diners have been fed!' class AbortGame(MagicWord): aliases = [ 'abortminigame', 'leaveminigame'] desc = 'Abort any minigame you are currently in.' execLocation = MagicWordConfig.EXEC_LOC_CLIENT def handleWord(self, invoker, avId, toon, *args): messenger.send('minigameAbort') class RequestGame(MagicWord): aliases = [ 'reqgame', 'requestminigame', 'reqminigame'] desc = 'Request a minigame' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('name', str, False, 'remove'), ('keep', bool, False, False), ('diff', int, False, 0), ('zoneId', int, False, ToontownGlobals.ToontownCentral)] def handleWord(self, invoker, avId, toon, *args): minigameName = args[0] minigameKeep = args[1] minigameDiff = args[2] minigameZone = args[3] from toontown.minigame import MinigameCreatorAI if minigameName == 'remove': if invoker.doId in MinigameCreatorAI.RequestMinigame: del MinigameCreatorAI.RequestMinigame[invoker.doId] return 'Deleted minigame request.' else: return 'You had no minigame requests!' else: if minigameName not in ToontownGlobals.MinigameNames: return 'Invalid minigame name!' else: if minigameZone not in ToontownGlobals.HoodsWithMinigames: return 'Invalid playground!' MinigameCreatorAI.RequestMinigame[invoker.doId] = (ToontownGlobals.MinigameNames[minigameName], minigameKeep, minigameDiff, minigameZone) return 'Your request for the ' + minigameName + ' minigame was added.' class SpawnCog(MagicWord): aliases = [ 'cog'] desc = 'Spawns a cog with the defined level' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('suit', str, True), ('level', int, False, 1), ('specialSuit', int, False, 0)] def handleWord(self, invoker, avId, toon, *args): name = args[0] level = args[1] specialSuit = args[2] zoneId = invoker.getLocation()[1] if name not in SuitDNA.suitHeadTypes: return 'Suit %s is not a valid suit!' % name if level not in ToontownGlobals.SuitLevels: return 'Invalid Cog Level.' level = ToontownGlobals.SuitLevels.index(level) + 1 sp = simbase.air.suitPlanners.get(zoneId - zoneId % 100) if not sp: return 'Unable to spawn %s in current zone.' % name pointmap = sp.streetPointList sp.createNewSuit([], pointmap, suitName=name, suitLevel=level, specialSuit=specialSuit) return 'Spawned %s in current zone.' % name class SpawnInvasion(MagicWord): aliases = [ 'invasion'] desc = "Spawn an invasion on the current AI if one doesn't exist." execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('command', str, True), ('suit', str, False, 'f'), ('amount', int, False, 1000), ('skelecog', bool, False, False)] def handleWord(self, invoker, avId, toon, *args): cmd = args[0] name = args[1] num = args[2] skeleton = args[3] if not 10 <= num <= 25000: return ("Can't the invasion amount to {}! Specify a value between 10 and 25,000.").format(num) invMgr = simbase.air.suitInvasionManager if cmd == 'start': if invMgr.getInvading(): return 'There is already an invasion on the current AI!' if name not in SuitDNA.suitHeadTypes: return 'This cog does not exist!' invMgr.startInvasion(name, num, skeleton) elif cmd == 'stop': if not invMgr.getInvading(): return 'There is no invasion on the current AI!' invMgr.stopInvasion() else: return "You didn't enter a valid command! Commands are ~invasion start or stop." class SetTrophyScore(MagicWord): aliases = [ 'trophyscore'] desc = 'Set the trophy score of target.' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('val', int, True)] def handleWord(self, invoker, avId, toon, *args): amt = args[0] if not 0 <= amt <= 255: return 'The amount must be between 0 and 255!' simbase.air.trophyMgr.addTrophy(toon.doId, toon.name, amt, True) class GivePies(MagicWord): aliases = [ 'pies'] desc = 'Gives the target pies to throw.' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('type', int, True), ('amount', int, False, -1)] def handleWord(self, invoker, avId, toon, *args): pieType = args[0] numPies = args[1] if pieType == -1: toon.b_setNumPies(0) return "Removed %s's pies." % toon.getName() if not 0 <= pieType <= 7: return 'You can only specify between pie types 0 and 7.' if numPies == -1: toon.b_setPieType(pieType) toon.b_setNumPies(ToontownGlobals.FullPies) return 'Gave %s an infinite amount of pies' % toon.getName() if not 0 <= numPies <= 99: return 'You can only specify between 0 and 99 pies.' toon.b_setPieType(pieType) toon.b_setNumPies(numPies) class SetQP(MagicWord): aliases = [ 'qp', 'questprogress'] desc = 'Get and set the targets quest progress.' execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('id', int, False, 0), ('progress', int, False, 0)] def handleWord(self, invoker, avId, toon, *args): questId = args[0] progress = args[1] questIds = '' for index in range(len(toon.quests)): questIds += ('{0} ').format(toon.quests[index][0]) if toon.quests[index][0] == questId: toon.quests[index][4] = progress toon.b_setQuests(toon.quests) return questIds class SetUnites(MagicWord): aliases = [ 'unites', 'restockunites'] desc = "Restocks the target's unites. The default amount is 999." execLocation = MagicWordConfig.EXEC_LOC_SERVER arguments = [('amount', int, False, 999)] def handleWord(self, invoker, avId, toon, *args): amt = args[0] if not 1 <= amt <= 999: return 'Unite amount must be between 0 and 999!' toon.restockAllResistanceMessages(amt) return 'Restocked ' + str(amt) + ' unites successfully!' class UnlockTricks(MagicWord): aliases = [ 'tricks'] desc = "Unlock all the target's pet trick phrases." execLocation = MagicWordConfig.EXEC_LOC_SERVER def handleWord(self, invoker, avId, toon, *args): invoker.b_setPetTrickPhrases(range(7)) return 'Unlocked pet tricks!' class RestockSummons(MagicWord): desc = "Restock all of the target's CJ summons." aliases = ['summons'] execLocation = MagicWordConfig.EXEC_LOC_SERVER def handleWord(self, invoker, avId, toon, *args): cogCount = [] for deptIndex in xrange(5): for cogIndex in xrange(9): cogCount.append(CogPageGlobals.COG_QUOTAS[1][cogIndex] if cogIndex != 8 else 0) invoker.b_setCogCount(cogCount) invoker.b_setCogStatus(([CogPageGlobals.COG_COMPLETE2] *
if the table already exists, returns it.""" where_node = self._hdf5file.get_node(where) if not tablename in where_node: if not expectedrows is None: table = self._hdf5file.create_table(where=where_node, name=tablename, description=description, title=tablename, expectedrows=expectedrows, filters=self._all_get_filters()) else: table = self._hdf5file.create_table(where=where_node, name=tablename, description=description, title=tablename, filters=self._all_get_filters()) else: table = where_node._f_get_child(tablename) return table def _all_get_node_by_name(self, name): """Returns an HDF5 node by the path specified in `name`""" path_name = name.replace('.', '/') where = '/%s/%s' % (self._trajectory_name, path_name) return self._hdf5file.get_node(where=where) @staticmethod def _all_get_from_attrs(ptitem, name): """Gets an attribute `name` from `ptitem`, returns None if attribute does not exist.""" try: return getattr(ptitem._v_attrs, name) except AttributeError: return None @staticmethod def _all_set_attr(ptitem, name, value): """Sets an attribute `name` from `ptitem`""" return setattr(ptitem._v_attrs, name, value) @staticmethod def _all_set_attributes_to_recall_natives(data, ptitem, prefix): """Stores original data type to hdf5 node attributes for preserving the data type. :param data: Data to be stored :param ptitem: HDF5 node to store data types as attributes. Can also be just a PTItemMock. :param prefix: String prefix to label and name data in HDF5 attributes """ # If `data` is a container, remember the container type if type(data) is tuple: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_TUPLE) elif type(data) is list: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_LIST) elif type(data) is np.ndarray: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_NDARRAY) elif type(data) is np.matrix: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_MATRIX) elif type(data) in pypetconstants.PARAMETER_SUPPORTED_DATA: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_SCALAR) strtype = type(data).__name__ if not strtype in pypetconstants.PARAMETERTYPEDICT: raise TypeError('I do not know how to handle `%s` its type is `%s`.' % (str(data), repr(type(data)))) HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.SCALAR_TYPE, strtype) elif type(data) is dict: if len(data) > 0: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_DICT) else: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_EMPTY_DICT) else: raise TypeError('I do not know how to handle `%s` its type is `%s`.' % (str(data), repr(type(data)))) if type(data) in (list, tuple): # If data is a list or tuple we need to remember the data type of the elements # in the list or tuple. # We do NOT need to remember the elements of `dict` explicitly, though. # `dict` is stored # as an `ObjectTable` and thus types are already conserved. if len(data) > 0: strtype = type(data[0]).__name__ if not strtype in pypetconstants.PARAMETERTYPEDICT: raise TypeError('I do not know how to handle `%s` its type is ' '`%s`.' % (str(data), strtype)) HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.SCALAR_TYPE, strtype) elif (type(data) in (np.ndarray, np.matrix) and np.issubdtype(data.dtype, str)): HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.SCALAR_TYPE, str.__name__) def _all_recall_native_type(self, data, ptitem, prefix): """Checks if loaded data has the type it was stored in. If not converts it. :param data: Data item to be checked and converted :param ptitem: HDf5 Node or Leaf from where data was loaded :param prefix: Prefix for recalling the data type from the hdf5 node attributes :return: Tuple, first item is the (converted) `data` item, second boolean whether item was converted or not. """ typestr = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.SCALAR_TYPE) colltype = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.COLL_TYPE) type_changed = False # Check what the original data type was from the hdf5 node attributes if colltype == HDF5StorageService.COLL_SCALAR: # Here data item was a scalar if isinstance(data, np.ndarray): # If we recall a numpy scalar, pytables loads a 1d array :-/ # So we have to change it to a real scalar value data = np.array([data])[0] type_changed = True if not typestr is None: # Check if current type and stored type match # if not convert the data if typestr != type(data).__name__: if typestr == str.__name__: data = data.decode(self._encoding) else: try: data = pypetconstants.PARAMETERTYPEDICT[typestr](data) except KeyError: # For compatibility with files from older pypet versions data = pypetconstants.COMPATPARAMETERTYPEDICT[typestr](data) type_changed = True elif (colltype == HDF5StorageService.COLL_TUPLE or colltype == HDF5StorageService.COLL_LIST): # Here data item was originally a tuple or a list if type(data) is not list and type is not tuple: # If the original type cannot be recalled, first convert it to a list type_changed = True data = list(data) if len(data) > 0: first_item = data[0] # Check if the type of the first item was conserved if not typestr == type(first_item).__name__: if not isinstance(data, list): data = list(data) # If type was not conserved we need to convert all items # in the list or tuple for idx, item in enumerate(data): if typestr == str.__name__: data[idx] = data[idx].decode(self._encoding) else: try: data[idx] = pypetconstants.PARAMETERTYPEDICT[typestr](item) except KeyError: # For compatibility with files from older pypet versions: data[idx] = pypetconstants.COMPATPARAMETERTYPEDICT[typestr](item) type_changed = True if colltype == HDF5StorageService.COLL_TUPLE: # If it was originally a tuple we need to convert it back to tuple if type(data) is not tuple: data = tuple(data) type_changed = True elif colltype == HDF5StorageService.COLL_EMPTY_DICT: data = {} type_changed = True elif isinstance(data, np.ndarray): if typestr == str.__name__: data = np.core.defchararray.decode(data, self._encoding) type_changed = True if colltype == HDF5StorageService.COLL_MATRIX: # Here data item was originally a matrix data = np.matrix(data) type_changed = True return data, type_changed @staticmethod def _all_kill_iterator(iterator): if iterator is not None: try: while True: next(iterator) except StopIteration: pass def _all_add_or_modify_row(self, item_name, insert_dict, table, index=None, condition=None, condvars=None, flags=(ADD_ROW, MODIFY_ROW,)): """Adds or changes a row in a pytable. :param item_name: Name of item, the row is about, only important for throwing errors. :param insert_dict: Dictionary of data that is about to be inserted into the pytables row. :param table: The table to insert or modify a row in :param index: Index of row to be modified. Instead of an index a search condition can be used as well, see below. :param condition: Condition to search for in the table :param condvars: Variables for the search condition :param flags: Flags whether to add, modify, or remove a row in the table """ if len(flags) == 0: # No flags means no-op return # You can only specify either an index or a condition not both if index is not None and condition is not None: raise ValueError('Please give either a condition or an index or none!') elif condition is not None: row_iterator = table.where(condition, condvars=condvars) elif index is not None: row_iterator = table.iterrows(index, index + 1) else: row_iterator = None try: row = next(row_iterator) except TypeError: row = None except StopIteration: row = None # multiple_entries = [] if ((HDF5StorageService.MODIFY_ROW in flags or HDF5StorageService.ADD_ROW in flags) and HDF5StorageService.REMOVE_ROW in flags): # You cannot remove and modify or add at the same time raise ValueError('You cannot add or modify and remove a row at the same time.') if row is None and HDF5StorageService.ADD_ROW in flags: # Here we add a new row row = table.row self._all_insert_into_row(row, insert_dict) row.append() elif row is not None and HDF5StorageService.MODIFY_ROW in flags: # Here we modify an existing row self._all_insert_into_row(row, insert_dict) row.update() elif HDF5StorageService.REMOVE_ROW in flags: # Here we delete an existing row if row is not None: # Only delete if the row does exist otherwise we do not have to do anything row_number = row.nrow try: table.remove_rows(start=row_number, stop=row_number+1) except NotImplementedError: pass # We get here if we try to remove the last row of a table # there is nothing we can do but keep it :-( else: raise ValueError('Something is wrong, you might not have found ' 'a row, or your flags are not set appropriately') self._all_kill_iterator(row_iterator) table.flush() if HDF5StorageService.REMOVE_ROW not in flags and row is None: raise RuntimeError('Could not add or modify entries of `%s` in ' 'table %s' % (item_name, table._v_name)) def _all_insert_into_row(self, row, insert_dict): """Copies data from `insert_dict` into a pytables `row`.""" for key, val in insert_dict.items(): try: row[key] = val except KeyError as ke: self._logger.warning('Could not write `%s` into a table, ' % key + repr(ke)) def _all_extract_insert_dict(self, item, colnames, additional_info=None): """Extracts information from a given item to be stored into a pytable row. Items can be a variety of things here, trajectories, single runs, group node, parameters, results. :param item: Item from which data should be extracted :param colnames: Names of the columns in the pytable :param additional_info:
""" The MIT License (MIT) Copyright © 2018 <NAME> & HC² (www.hc2.fr) """ from ustruct import pack, unpack from ubinascii import hexlify class BLEAdvReader : # ============================================================================ # ===( Constants )============================================================ # ============================================================================ DATA_TYPE_FLAGS = 0x01 DATA_TYPE_INCOMP_16BITS_UUIDS = 0x02 DATA_TYPE_COMP_16BITS_UUIDS = 0x03 DATA_TYPE_INCOMP_32BITS_UUIDS = 0x04 DATA_TYPE_COMP_32BITS_UUIDS = 0x05 DATA_TYPE_INCOMP_128BITS_UUIDS = 0x06 DATA_TYPE_COMP_128BITS_UUIDS = 0x07 DATA_TYPE_SHORT_NAME = 0x08 DATA_TYPE_COMPLETE_NAME = 0x09 DATA_TYPE_TX_POWER_LEVEL = 0x0A DATA_TYPE_DEVICE_CLASS = 0x0B DATA_TYPE_SMP_PAIR_HASH_C = 0x0C DATA_TYPE_SMP_PAIR_HASH_C192 = 0x0D DATA_TYPE_SMP_PAIR_RAND_R = 0x0E DATA_TYPE_SMP_PAIR_RAND_R192 = 0x0F DATA_TYPE_DEVICE_ID = 0x10 DATA_TYPE_SECU_MNGR_TK_VAL = 0x11 DATA_TYPE_SECU_MNGR_OOB_FLAGS = 0x12 DATA_TYPE_SLAVE_CONN_INT_RNG = 0x13 DATA_TYPE_16BITS_SVC_SOL_UUIDS = 0x14 DATA_TYPE_128BITS_SVC_SOL_UUIDS = 0x15 DATA_TYPE_SVC_DATA = 0x16 DATA_TYPE_SVC_DATA_16BITS_UUID = 0x17 DATA_TYPE_PUB_TARGET_ADDR = 0x18 DATA_TYPE_RAND_TARGET_ADDR = 0x19 DATA_TYPE_APPEARANCE = 0x1A DATA_TYPE_ADV_INT = 0x1B DATA_TYPE_LE_BLT_DEVICE_ADDR = 0x1C DATA_TYPE_LE_ROLE = 0x1D DATA_TYPE_SMP_PAIR_HASH_C256 = 0x1E DATA_TYPE_SMP_PAIR_RAND_R256 = 0x1F DATA_TYPE_32BITS_SVC_SOL_UUIDS = 0x20 DATA_TYPE_SVC_DATA_32BITS_UUID = 0x21 DATA_TYPE_SVC_DATA_128BITS_UUID = 0x22 DATA_TYPE_LE_SECU_CONN_RAND_VAL = 0x23 DATA_TYPE_URI = 0x24 DATA_TYPE_INDOOR_POS = 0x25 DATA_TYPE_TRANS_DISCOV_DATA = 0x26 DATA_TYPE_LE_SUPPORT_FEAT = 0x27 DATA_TYPE_CHAN_MAP_UPD_INDIC = 0x28 DATA_TYPE_PB_ADV = 0x29 DATA_TYPE_MESH_MSG = 0x2A DATA_TYPE_MESH_BEACON = 0x2B DATA_TYPE_3D_INFO_DATA = 0x3D DATA_TYPE_MANUFACTURER_DATA = 0xFF MEMBER_UUID_GOOGLE_EDDYSTONE = 0xFEAA COMPANY_ID_APPLE = 0x004C APPLE_TYPE_IBEACON = 0x02 APPLE_TYPE_AIRDROP = 0x05 APPLE_TYPE_AIRPODS = 0x07 APPLE_TYPE_AIRPLAY_DEST = 0x09 APPLE_TYPE_AIRPLAY_SRC = 0x0A APPLE_TYPE_HANDOFF = 0x0C APPLE_TYPE_NEARBY = 0x10 # ============================================================================ # ===( Class InvalidAdvData )================================================= # ============================================================================ class InvalidAdvData(Exception) : pass # ============================================================================ # ===( Constructor )========================================================== # ============================================================================ def __init__(self, advertisingData) : self._advData = dict() self._advObj = [ ] self._advDataProcess(advertisingData) self._advDataElementsProcess() self._advKnownElementsProcess() # ============================================================================ # ===( Functions )============================================================ # ============================================================================ @staticmethod def _hex(data) : if data : return hexlify(data).decode().upper() return '' # ---------------------------------------------------------------------------- @staticmethod def _twosComp(val, bits) : if val < 2**bits : return val - int((val << 1) & 2**bits) raise ValueError('Value %s out of range of %s-bit value.' % (val, bits)) # ---------------------------------------------------------------------------- @staticmethod def _accum88(data16b) : if isinstance(data16b, bytes) and len(data16b) == 2 : return BLEAdvReader._twosComp(data16b[0], 8) + \ BLEAdvReader._twosComp(data16b[1], 16) / 256 raise ValueError('%s is not a 16 bits data value.' % data16b) # ---------------------------------------------------------------------------- @staticmethod def _128bitsUUID(uuidBytes) : if uuidBytes and len(uuidBytes) == 16 : s = hexlify(uuidBytes).decode() return s[:8] + '-' + s[8:12] + '-' + s[12:16] + '-' + s[16:20] + '-' + s[20:] return '' # ---------------------------------------------------------------------------- @staticmethod def _decodeURIBeacon(data) : schemes = { 0x00 : 'http://www.', 0x01 : 'https://www.', 0x02 : 'http://', 0x03 : 'https://' } expansions = { 0x00 : '.com/', 0x01 : '.org/', 0x02 : '.edu/', 0x03 : '.net/', 0x04 : '.info/', 0x05 : '.biz/', 0x06 : '.gov/', 0x07 : '.com', 0x08 : '.org', 0x09 : '.edu', 0x0A : '.net', 0x0B : '.info', 0x0C : '.biz', 0x0D : '.gov' } try : url = schemes[data[0]] for b in data[1:] : url += expansions[b] if b in expansions else chr(b) return url except : return '' # ---------------------------------------------------------------------------- def _advDataProcess(self, advData) : if advData : advDataLen = len(advData) idx = 0 while idx < advDataLen : dataLen = advData[idx] idx += 1 if dataLen > 0 : idxEnd = idx + dataLen if idxEnd < advDataLen : dataType = advData[idx] data = advData[idx+1:idxEnd] self._advData[dataType] = data else : raise self.InvalidAdvData('Data element invalid size') idx = idxEnd # ---------------------------------------------------------------------------- def _advDataElementsProcess(self) : if not self._advData : raise self.InvalidAdvData('No advertising data element') for dataType in self._advData : data = self._advData[dataType] advObj = None if dataType == self.DATA_TYPE_FLAGS : try : advObj = self.Flags(ord(data)) except : raise self.InvalidAdvData('Invalid flags data element') elif dataType == self.DATA_TYPE_COMP_16BITS_UUIDS : try : advObj = self.AdoptedService16bits(unpack('<H', data)[0]) except : raise self.InvalidAdvData('Invalid adopted service 16bits data element') elif dataType == self.DATA_TYPE_COMP_32BITS_UUIDS : try : advObj = self.AdoptedService32bits(unpack('<I', data)[0]) except : raise self.InvalidAdvData('Invalid adopted service 32bits data element') elif dataType == self.DATA_TYPE_COMP_128BITS_UUIDS : try : advObj = self.AdoptedService128bits(data) except : raise self.InvalidAdvData('Invalid adopted service 128bits data element') elif dataType == self.DATA_TYPE_SHORT_NAME : try : advObj = self.ShortName(data.decode()) except : raise self.InvalidAdvData('Invalid short name data element') elif dataType == self.DATA_TYPE_COMPLETE_NAME : try : advObj = self.CompleteName(data.decode()) except : raise self.InvalidAdvData('Invalid complete name data element') elif dataType == self.DATA_TYPE_TX_POWER_LEVEL : try : advObj = self.TXPowerLevel(unpack('<b', data)[0]) except : raise self.InvalidAdvData('Invalid TX power level data element') elif dataType == self.DATA_TYPE_SVC_DATA : try : advObj = self.ServiceData(unpack('<H', data[0:2])[0], data[2:]) except : raise self.InvalidAdvData('Invalid service data element') elif dataType == self.DATA_TYPE_MANUFACTURER_DATA : try : advObj = self.ManufacturerData(unpack('<H', data[0:2])[0], data[2:]) except : raise self.InvalidAdvData('Invalid manufacturer data element') if advObj : self._advObj.append(advObj) # ---------------------------------------------------------------------------- def _advKnownElementsProcess(self) : for advObj in self._advObj : if isinstance(advObj, self.AdoptedService16bits) : if advObj.UUID == self.MEMBER_UUID_GOOGLE_EDDYSTONE : try : advObjToAdd = None for ao in self._advObj : if isinstance(ao, self.ServiceData) and \ ao.UUID == self.MEMBER_UUID_GOOGLE_EDDYSTONE : advObjToAdd = self._getAdvObjForGoogleEddyStoneData(ao.Data) break if advObjToAdd : self._advObj.append(advObjToAdd) else : raise Exception() except : raise self.InvalidAdvData('Invalid Google EddyStone data') elif isinstance(advObj, self.ManufacturerData) : if advObj.CompanyID == self.COMPANY_ID_APPLE : try : advObjToAdd = self._getAdvObjForAppleCompanyData(advObj.Data) if advObjToAdd : self._advObj.append(advObjToAdd) else : raise Exception() except : raise self.InvalidAdvData('Invalid Apple manufacturer data') # ---------------------------------------------------------------------------- def _getAdvObjForAppleCompanyData(self, data) : appleType = data[0] dataLen = data[1] data = data[2:] if appleType == self.APPLE_TYPE_IBEACON : return self.AppleIBeacon( data[:16], unpack('>H', data[16:18])[0], unpack('>H', data[18:20])[0], data[20] - 256 ) elif appleType == self.APPLE_TYPE_AIRDROP : return self.AppleService('AirDrop', data) elif appleType == self.APPLE_TYPE_AIRPODS : return self.AppleService('AirPods', data) elif appleType == self.APPLE_TYPE_AIRPLAY_DEST : return self.AppleService('AirPlay Destination', data) elif appleType == self.APPLE_TYPE_AIRPLAY_SRC : return self.AppleService('AirPlay Source', data) elif appleType == self.APPLE_TYPE_HANDOFF : return self.AppleService('HandOff', data) elif appleType == self.APPLE_TYPE_NEARBY : return self.AppleService('Nearby', data) return self.AppleService() # ---------------------------------------------------------------------------- def _getAdvObjForGoogleEddyStoneData(self, data) : frameType = data[0] if frameType == 0x00 : txPower = unpack('<b', bytes([data[1]]))[0] namespace = data[2:12] instance = data[12:18] return self.EddyStoneUID(txPower, namespace, instance) elif frameType == 0x10 : txPower = unpack('<b', bytes([data[1]]))[0] url = self._decodeURIBeacon(data[2:]) return self.EddyStoneURL(txPower, url) elif frameType == 0x20 : version = data[1] if version == 0x00 : vbatt = unpack('>H', data[2:4])[0] temp = BLEAdvReader._accum88(data[4:6]) advCnt = unpack('>I', data[6:10])[0] secCnt = unpack('>I', data[10:14])[0] return self.EddyStoneTLMUnencrypted(vbatt, temp, advCnt, secCnt) elif version == 0x01 : etlm = data[2:14] salt = unpack('>H', data[14:16])[0] mic = unpack('>H', data[16:18])[0] return self.EddyStoneTLMEncrypted(etlm, salt, mic) elif frameType == 0x30 : txPower = unpack('<b', bytes([data[1]]))[0] encryptedID = data[2:10] return self.EddyStoneEID(txPower, encryptedID) return None # ---------------------------------------------------------------------------- def GetDataByDataType(self, dataType) : return self._advData.get(dataType) # ---------------------------------------------------------------------------- def GetAllElements(self) : return self._advObj # ---------------------------------------------------------------------------- def GetElementByClass(self, elementType) : for advObj in self._advObj : if isinstance(advObj, elementType) : return advObj return None # ============================================================================ # ===( Class Flags )========================================================== # ============================================================================ class Flags : FLAG_LE_LIMITED_DISC_MODE = 0x01 FLAG_LE_GENERAL_DISC_MODE = 0x02 FLAG_BR_EDR_NOT_SUPPORTED = 0x04 FLAG_LE_BR_EDR_CONTROLLER = 0x08 FLAG_LE_BR_EDR_HOST = 0x10 FLAGS_LE_ONLY_LIMITED_DISC_MODE = 0x01 | 0x04 FLAGS_LE_ONLY_GENERAL_DISC_MODE = 0x02 | 0x04 def __init__(self, flags=0x00) : self._flags = flags def __str__(self) : return '{0:08b}'.format(self._flags) @property def LE_LIMITED_DISC_MODE(self) : return bool(self._flags & self.FLAG_LE_LIMITED_DISC_MODE) @property def LE_GENERAL_DISC_MODE(self) : return bool(self._flags & self.FLAG_LE_GENERAL_DISC_MODE) @property def BR_EDR_NOT_SUPPORTED(self) : return bool(self._flags & self.FLAG_BR_EDR_NOT_SUPPORTED) @property def LE_BR_EDR_CONTROLLER(self) : return bool(self._flags & self.FLAG_LE_BR_EDR_CONTROLLER) @property def LE_BR_EDR_HOST(self) : return bool(self._flags & self.FLAG_LE_BR_EDR_HOST) @property def LE_ONLY_LIMITED_DISC_MODE(self) : return bool(self._flags & self.FLAGS_LE_ONLY_LIMITED_DISC_MODE) @property def LE_ONLY_GENERAL_DISC_MODE(self) : return bool(self._flags & self.FLAGS_LE_ONLY_GENERAL_DISC_MODE) # ============================================================================ # ===( Class AdoptedService16bits )=========================================== # ============================================================================ class AdoptedService16bits : def __init__(self, svcUUID=0x0000) : self._svcUUID = svcUUID def __str__(self) : return 'Adopted Service (16bits UUID=%s)' % self.StrUUID @property def UUID(self) : return self._svcUUID @property def StrUUID(self) : return BLEAdvReader._hex(pack('<H', self._svcUUID)) # ============================================================================ # ===( Class AdoptedService32bits )=========================================== # ============================================================================ class AdoptedService32bits : def __init__(self, svcUUID=0x00000000) : self._svcUUID = svcUUID def __str__(self) : return 'Adopted Service (32bits UUID=%s)' % self.StrUUID @property def UUID(self) : return self._svcUUID @property def StrUUID(self) : return BLEAdvReader._hex(pack('<I', self._svcUUID)) # ============================================================================ # ===( Class AdoptedService128bits )========================================== # ============================================================================ class AdoptedService128bits : def __init__(self, svcUUID=b'') : self._svcUUID = svcUUID def __str__(self) : return 'Adopted Service (128bits UUID=%s)' % self.StrUUID @property def UUID(self) : return self._svcUUID @property def StrUUID(self) : return BLEAdvReader._128bitsUUID(self._svcUUID) # ============================================================================ # ===( Class ShortName )====================================================== # ============================================================================ class ShortName : def __init__(self, shortName='') : self._shortName = shortName def __str__(self) : return self._shortName # ============================================================================ # ===( Class CompleteName )=================================================== # ============================================================================ class CompleteName : def
# coding: utf-8 from __future__ import unicode_literals from datetime import datetime import json import hashlib from inspect import getsource import random import re import time from .common import InfoExtractor, SearchInfoExtractor from ..compat import ( compat_chr, compat_kwargs, compat_parse_qs, compat_urllib_parse_unquote, compat_urllib_parse_unquote_plus, compat_urllib_parse_urlencode, compat_urllib_parse_urlparse, compat_urlparse, compat_str, ) from ..utils import ( bool_or_none, clean_html, error_to_compat_str, ExtractorError, float_or_none, get_element_by_id, int_or_none, mimetype2ext, parse_codecs, parse_duration, remove_quotes, remove_start, smuggle_url, str_or_none, str_to_int, try_get, unescapeHTML, unified_strdate, unsmuggle_url, uppercase_escape, url_or_none, urlencode_postdata, GeoRestrictedError, ) try: from ..extractor_artifacts.youtube import _decrypt_signature_protected except ImportError: _decrypt_signature_protected = None class YoutubeBaseInfoExtractor(InfoExtractor): """Provide base functions for Youtube extractors""" _LOGIN_URL = 'https://accounts.google.com/ServiceLogin' _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge' _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup' _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge' _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}' _NETRC_MACHINE = 'youtube' # If True it will raise an error if no login info is provided _LOGIN_REQUIRED = False _PLAYLIST_ID_RE = r'(?:LL|WL|(?:PL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,})' _YOUTUBE_CLIENT_HEADERS = { 'x-youtube-client-name': '1', 'x-youtube-client-version': '2.20201112.04.01', } _YOUTUBE_API_KEY = '<KEY>' def _set_consent(self): self._set_cookie( '.youtube.com', 'CONSENT', 'YES+0x557755', expire_time=time.time() + 2 * 30 * 24 * 3600) def _ids_to_results(self, ids): return [ self.url_result(vid_id, 'Youtube', video_id=vid_id) for vid_id in ids] def _login(self): """ Attempt to log in to YouTube. True is returned if successful or skipped. False is returned if login failed. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised. """ username, password = self._get_login_info() # No authentication to be performed if username is None: if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None: raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True) return True login_page = self._download_webpage( self._LOGIN_URL, None, note='Downloading login page', errnote='unable to fetch login page', fatal=False) if login_page is False: return login_form = self._hidden_inputs(login_page) def req(url, f_req, note, errnote): data = login_form.copy() data.update({ 'pstMsg': 1, 'checkConnection': 'youtube', 'checkedDomains': 'youtube', 'hl': 'en', 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]', 'f.req': json.dumps(f_req), 'flowName': 'GlifWebSignIn', 'flowEntry': 'ServiceLogin', # TODO: reverse actual botguard identifier generation algo 'bgRequest': '["identifier",""]', }) return self._download_json( url, None, note=note, errnote=errnote, transform_source=lambda s: re.sub(r'^[^[]*', '', s), fatal=False, data=urlencode_postdata(data), headers={ 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Google-Accounts-XSRF': 1, }) def warn(message): self._downloader.report_warning(message) lookup_req = [ username, None, [], None, 'US', None, None, 2, False, True, [ None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4], 1, [None, None, []], None, None, None, True ], username, ] lookup_results = req( self._LOOKUP_URL, lookup_req, 'Looking up account info', 'Unable to look up account info') if lookup_results is False: return False user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str) if not user_hash: warn('Unable to extract user hash') return False challenge_req = [ user_hash, None, 1, None, [1, None, None, None, [password, None, True]], [ None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4], 1, [None, None, []], None, None, None, True ]] challenge_results = req( self._CHALLENGE_URL, challenge_req, 'Logging in', 'Unable to log in') if challenge_results is False: return login_res = try_get(challenge_results, lambda x: x[0][5], list) if login_res: login_msg = try_get(login_res, lambda x: x[5], compat_str) warn( 'Unable to login: %s' % 'Invalid password' if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg) return False res = try_get(challenge_results, lambda x: x[0][-1], list) if not res: warn('Unable to extract result entry') return False login_challenge = try_get(res, lambda x: x[0][0], list) if login_challenge: challenge_str = try_get(login_challenge, lambda x: x[2], compat_str) if challenge_str == 'TWO_STEP_VERIFICATION': # SEND_SUCCESS - TFA code has been successfully sent to phone # QUOTA_EXCEEDED - reached the limit of TFA codes status = try_get(login_challenge, lambda x: x[5], compat_str) if status == 'QUOTA_EXCEEDED': warn('Exceeded the limit of TFA codes, try later') return False tl = try_get(challenge_results, lambda x: x[1][2], compat_str) if not tl: warn('Unable to extract TL') return False tfa_code = self._get_tfa_info('2-step verification code') if not tfa_code: warn( 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>' '(Note that only TOTP (Google Authenticator App) codes work at this time.)') return False tfa_code = remove_start(tfa_code, 'G-') tfa_req = [ user_hash, None, 2, None, [ 9, None, None, None, None, None, None, None, [None, tfa_code, True, 2] ]] tfa_results = req( self._TFA_URL.format(tl), tfa_req, 'Submitting TFA code', 'Unable to submit TFA code') if tfa_results is False: return False tfa_res = try_get(tfa_results, lambda x: x[0][5], list) if tfa_res: tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str) warn( 'Unable to finish TFA: %s' % 'Invalid TFA code' if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg) return False check_cookie_url = try_get( tfa_results, lambda x: x[0][-1][2], compat_str) else: CHALLENGES = { 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.", 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.', 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.", } challenge = CHALLENGES.get( challenge_str, '%s returned error %s.' % (self.IE_NAME, challenge_str)) warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge) return False else: check_cookie_url = try_get(res, lambda x: x[2], compat_str) if not check_cookie_url: warn('Unable to extract CheckCookie URL') return False check_cookie_results = self._download_webpage( check_cookie_url, None, 'Checking cookie', fatal=False) if check_cookie_results is False: return False if 'https://myaccount.google.com/' not in check_cookie_results: warn('Unable to log in') return False return True def _download_webpage_handle(self, *args, **kwargs): return super(YoutubeBaseInfoExtractor, self)._download_webpage_handle( *args, **compat_kwargs(kwargs)) def _real_initialize(self): if self._downloader is None: return self._set_consent() if not self._login(): return class YoutubeIE(YoutubeBaseInfoExtractor): IE_DESC = 'YouTube.com' _VALID_URL = r"""(?x)^ ( (?:https?://|//) # http(s):// or protocol-independent URL (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/| (?:www\.)?deturl\.com/www\.youtube\.com/| (?:www\.)?pwnyoutube\.com/| (?:www\.)?hooktube\.com/| (?:www\.)?yourepeat\.com/| tube\.majestyc\.net/| # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances (?:(?:www|dev)\.)?invidio\.us/| (?:(?:www|no)\.)?invidiou\.sh/| (?:(?:www|fi)\.)?invidious\.snopyta\.org/| (?:www\.)?invidious\.kabi\.tk/| (?:www\.)?invidious\.13ad\.de/| (?:www\.)?invidious\.mastodon\.host/| (?:www\.)?invidious\.zapashcanon\.fr/| (?:www\.)?invidious\.kavin\.rocks/| (?:www\.)?invidious\.tube/| (?:www\.)?invidiou\.site/| (?:www\.)?invidious\.site/| (?:www\.)?invidious\.xyz/| (?:www\.)?invidious\.nixnet\.xyz/| (?:www\.)?invidious\.drycat\.fr/| (?:www\.)?tube\.poal\.co/| (?:www\.)?tube\.connect\.cafe/| (?:www\.)?vid\.wxzm\.sx/| (?:www\.)?vid\.mint\.lgbt/| (?:www\.)?yewtu\.be/| (?:www\.)?yt\.elukerio\.org/| (?:www\.)?yt\.lelux\.fi/| (?:www\.)?invidious\.ggc-project\.de/| (?:www\.)?yt\.maisputain\.ovh/| (?:www\.)?invidious\.13ad\.de/| (?:www\.)?invidious\.toot\.koeln/| (?:www\.)?invidious\.fdn\.fr/| (?:www\.)?watch\.nettohikari\.com/| (?:www\.)?kgg2m7yk5aybusll\.onion/| (?:www\.)?qklhadlycap4cnod\.onion/| (?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion/| (?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion/| (?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion/| (?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion/| (?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p/| (?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion/| youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains (?:.*?\#/)? # handle anchor (#/) redirect urls (?: # the various things that can precede the ID: (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/ |(?: # or the v= param in all its forms (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx) (?:\?|\#!?) # the params delimiter ? or # or #! (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY) v= ) )) |(?: youtu\.be| # just youtu.be/xxxx (?:www\.)?youtube\.com/(?: shorts| # or youtube.com/shorts/xxx video # or youtube.com/video/xxx )| vid\.plus| # or vid.plus/xxxx zwearz\.com/watch| # or zwearz.com/watch/xxxx )/ |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId= ) )? # all until now is optional -> you can pass the naked ID ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID (?!.*?\blist= (?: %(playlist_id)s| # combined list/video URLs are handled by the playlist IE WL # WL are handled by the watch later IE ) ) (?(1).+)? # if we found the ID, everything can follow $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE} _NEXT_URL_RE = r'[\?&]next_url=([^&]+)' _PLAYER_INFO_RE = ( r'/(?P<id>[a-zA-Z0-9_-]{8,})/player_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?/base\.(?P<ext>[a-z]+)$', r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.(?P<ext>[a-z]+)$', ) _formats = { # '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}, # '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}, # '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'}, # '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'}, '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'}, # '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}, # '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}, # '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}, # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well # '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'}, # '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}, # '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}, # '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}, # '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}, # '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}, # '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}, # '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}, # '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec':
import re import os import pandas as pd import numpy as np from .extract_tools import default_tokenizer as _default_tokenizer def _getDictionnaryKeys(dictionnary): """ Function that get keys from a dict object and flatten sub dict. """ keys_array = [] for key in dictionnary.keys(): keys_array.append(key) if (type(dictionnary[key]) == type({})): keys_array = keys_array+_getDictionnaryKeys(dictionnary[key]) return(keys_array) class pandasToBrat: """ Class for Pandas brat folder management. For each brat folder, there is an instance of pandasToBrat. It supports importation and exportation of configurations for relations and entities. Documents importation and exportation. Annotations and entities importation and exportation. Inputs : folder, str : path of brat folder """ def __init__(self, folder): self.folder = folder self.conf_file = 'annotation.conf' self.emptyDFCols = { "annotations":["id","type_id", "word", "label", "start", "end"], "relations":["id","type_id","relation","Arg1","Arg2"] } # Adding '/' to folder path if missing if(self.folder[-1] != '/'): self.folder += '/' # Creating folder if do not exist if (os.path.isdir(self.folder)) == False: os.mkdir(self.folder) # Loading conf file if exists | creating empty conf file if not self.read_conf() def _emptyData(self): fileList = self._getFileList() nb_files = fileList.shape[0] confirmation = input("Deleting all data ({} files), press y to confirm :".format(nb_files)) if confirmation == 'y': fileList["filename"].apply(lambda x: os.remove(self.folder+x)) print("{} files deleted.".format(nb_files)) def _generateEntitiesStr (self, conf, data = '', level = 0): if (type(conf) != type({})): return data # Parsing keys for key in conf.keys(): value = conf[key] if value == True: data += '\n'+level*'\t'+key elif value == False: data += '\n'+level*'\t'+'!'+key elif type(value) == type({}): data += '\n'+level*'\t'+key data = self._generateEntitiesStr(value, data, level+1) return data def _writeEntitiesLevel (self, conf, data, last_n = -1): for n in range(last_n,len(conf)): # If empty : pass, if not the last line : pass if (conf[n] != '' and n > last_n): level = len(conf[n].split("\t"))-1 if (n+1 <= len(conf)): # Level of next item next_level = len(conf[n+1].split("\t"))-1 else: next_level = level splitted_str = conf[n].split("\t") str_clean = splitted_str[len(splitted_str)-1] if (level >= next_level): # On écrit les lignes de même niveau if (str_clean[0] == '!'): data[str_clean[1:]] = False else: data[str_clean] = True if (level > next_level): # On casse la boucle break elif (level < next_level): # On écrit les lignes inférieurs par récurence splitted_str = conf[n].split("\t") last_n, data[str_clean] = self._writeEntitiesLevel(conf, {}, n) return(n, data) def _readRelations(self, relations, entities = []): data = {} for relation in relations.split("\n"): if relation != '': relation_data = relation.split("\t")[0] args = list(map(lambda x: x.split(":")[1], relation.split("\t")[1].split(", "))) args_valid = list(filter(lambda x: x in entities, args)) if (len(args_valid) > 0): data[relation_data] = {"args":args_valid} return data def _writeRelations(self, relations, entities = []): data = '' for relation in relations: args_array = list(filter(lambda x: x in entities, relations[relation]["args"])) if (len(args_array) > 0): data += '\n'+relation+'\t' for n in range(0, len(args_array)): data += int(bool(n))*', '+'Arg'+str(n+1)+':'+args_array[n] return data def read_conf (self): """ Get the current Brat configuration. Output : Dict containing "entities" and "relations" configurations. """ if (os.path.isfile(self.folder+self.conf_file)): # Reading file file = open(self.folder+self.conf_file) conf_str = file.read() file.close() # Splitting conf_str conf_data = re.split(re.compile(r"\[[a-zA-Z]+\]", re.DOTALL), conf_str)[1:] data = {} # Reading enteties data["entities"] = self._writeEntitiesLevel(conf_data[0].split("\n"), {})[1] # Reading relations entitiesKeys = _getDictionnaryKeys(data["entities"]) data["relations"] = self._readRelations(conf_data[1], entitiesKeys) return(data) else: self.write_conf() self.read_conf() def write_conf(self, entities = {}, relations = {}, events = {}, attributes = {}): """ Write or overwrite configuration file. It actually doesn't suppport events and attributes configuration data. inputs : entities, dict : dict containing the entities. If an entities do have children, his value is an other dict, otherwise, it is set as True. relations, dict : dict containing the relations between entities, each key is a relation name, the value is a dict with a "args" key containing the list of related entities. """ # TODO : Add events and attributes support. conf_str = '' # Entities conf_str += '\n\n[entities]' conf_str += self._generateEntitiesStr(entities) # relations conf_str += '\n\n[relations]' entitiesKeys = _getDictionnaryKeys(entities) conf_str += self._writeRelations(relations, entitiesKeys) # attributes conf_str += '\n\n[attributes]' # events conf_str += '\n\n[events]' # Write conf file file = open(self.folder+self.conf_file,'w') file.write(conf_str) file.close() def _getFileList(self): # Listing files filesDF = pd.DataFrame({'filename':pd.Series(os.listdir(self.folder))}) filesDFSplitted = filesDF["filename"].str.split(".", expand = True) filesDF["id"] = filesDFSplitted[0] filesDF["filetype"] = filesDFSplitted[1] filesDF = filesDF[filesDF["filetype"].isin(["txt","ann"])] return(filesDF) def _parseData(self): # Listing files filesDF = self._getFileList() # Getting data from txt and ann filesDF_txt = filesDF.rename(columns = {"filename":"text_data"}).loc[filesDF["filetype"] == "txt", ["id","text_data"]] filesDF_ann = filesDF.rename(columns = {"filename":"annotation"}).loc[filesDF["filetype"] == "ann", ["id","annotation"]] dataDF = filesDF_txt.join(filesDF_ann.set_index("id"), on = "id") dataDF["text_data"] = dataDF["text_data"].apply(lambda x: open(self.folder+x).read()) dataDF["annotation"] = dataDF["annotation"].apply(lambda x: open(self.folder+x).read()) return(dataDF) def read_text(self): """ read_text Get a pandas DataFrame containing the brat documents. Input : None Output : Pandas dataframe """ dataDF = self._parseData() return(dataDF[["id","text_data"]]) def read_annotation(self, ids = []): """ read_annotation Get annotations from the brat folder. You can get specific annotation by filtering by id. input : ids, list (optionnal) : list of id for which you want the annotation data, if empty all annotations are returned. output : dict containing an annotations and relations data. """ data = {} data["annotations"] = pd.DataFrame(columns=self.emptyDFCols["annotations"]) data["relations"] = pd.DataFrame(columns=self.emptyDFCols["relations"]) dataDF = self._parseData()[["id","annotation"]] dataDF = dataDF[(dataDF["annotation"].isna() == False) & (dataDF["annotation"] != '')] # Removing empty annotation # Filtering by ids if (len(ids) > 0): dataDF = dataDF[dataDF["id"].isin(pd.Series(ids).astype(str))] if (dataDF.shape[0] > 0): # Ann data to pandas dataDF = dataDF.join(dataDF["annotation"].str.split("\n").apply(pd.Series).stack().reset_index(level = 0).set_index("level_0")).reset_index(drop = True).drop("annotation", axis = 1).rename(columns = {0: "annotation"}) dataDF = dataDF[dataDF["annotation"].str.len() > 0].reset_index(drop = True) dataDF = dataDF.join(dataDF["annotation"].str.split("\t", expand = True).rename(columns = {0: 'type_id', 1: 'data', 2: 'word'})).drop("annotation", axis = 1) dataDF["type"] = dataDF["type_id"].str.slice(0,1) ## Annotations data["annotations"] = dataDF[dataDF["type"] == 'T'] if (data["annotations"].shape[0] > 0): data["annotations"] = data["annotations"].join(data["annotations"]["data"].str.split(" ", expand = True).rename(columns = {0: "label", 1: "start", 2: "end"})).drop(columns = ["data","type"]) ## Relations data["relations"] = dataDF[dataDF["type"] == 'R'] if (data["relations"].shape[0] > 0): tmp_splitted = data["relations"]["data"].str.split(" ", expand = True).rename(columns = {0: "relation"}) ### Col names rename_dict = dict(zip(list(tmp_splitted.columns.values[1:]), list("Arg"+tmp_splitted.columns.values[1:].astype(str).astype(object)))) tmp_splitted = tmp_splitted.rename(columns = rename_dict) ### Merging data tmp_splitted = tmp_splitted[["relation"]].join(tmp_splitted.loc[:,tmp_splitted.columns[tmp_splitted.columns != 'relation']].applymap(lambda x: x.split(":")[1])) data["relations"] = data["relations"].join(tmp_splitted).drop(columns = ["data","type","word"]) return(data) def _write_function(self, x, filetype = "txt", overwrite = False): filenames = [] if (filetype == 'txt' or filetype == 'both'): filenames.append(self.folder+str(x["filename"])+'.txt') if (filetype == 'ann' or filetype == 'both'): filenames.append(self.folder+str(x["filename"])+'.ann') for filename in filenames: try: open(str(filename), "r") is_file = True except FileNotFoundError: is_file = False if ((is_file == False) or (overwrite == True)): file = open(str(filename), "w") file.write(x["content"]) file.close() def write_text(self, text_id, text, empty = False, overWriteAnnotations = False): """ write_text Send text data from the brat folder. input : text_id, pd.Series : pandas series containing documents ids text, pd.Series : pandas series containing documents text in the same order as text_id empty, boolean : if True the brat folder is emptyied of all but configuration data (text and ann files) before writting overwriteAnnotations, boolean : if True, the current annotation files are replaced by blank one """ if overWriteAnnotations == True: # On controle la façon dont la variable est écrite overwriteAnn = True else: overwriteAnn = False if (type(text) == type(pd.Series()) and type(text_id) == type(pd.Series()) and text.shape[0] == text_id.shape[0]): # ID check : check should be smaller than text : check if not inverted if (text_id.astype(str).str.len().max() < text.astype(str).str.len().max()): # empty : option to erase existing data if (empty): self._emptyData() # Writting data print("Writting data") df_text = pd.DataFrame({"filename":text_id, "content":text}) df_ann = pd.DataFrame({"filename":text_id, "content":""}) df_text.apply(lambda x: self._write_function(x, filetype = "txt", overwrite = True), axis = 1) df_ann.apply(lambda x: self._write_function(x, filetype = "ann", overwrite = overwriteAnn), axis = 1) print("data written.") else: raise ValueError('ID is larger than text, maybe you inverted them.') else: raise ValueError('Incorrect variable type, expected two Pandas Series of same shape.') def write_annotations(self, df, text_id, word, label, start, end, overwrite
<reponame>foo-dogsquared/texture-notes<filename>scripts/manager.py # native packages from datetime import date from functools import reduce import logging from multiprocessing import cpu_count from os import chdir, getcwd from os.path import relpath from shutil import copy, copytree, rmtree from pathlib import Path from platform import system import sqlite3 from string import Template from subprocess import run # custom packages import scripts.constants as constants import scripts.exceptions as exceptions from .helper import kebab_case, initialized_db, use_db, regex_match, deduplicate_list """ All of the note functions accepts a metalist of notes with the subject as the first item in each individual list. [[SUBJECT_1, TITLE_1.1, TITLE_1.2, ..., TITLE_1.x], [SUBJECT_2, TITLE_2.1, TITLE_2.2, ..., TITLE_2.y], ...] Example: - add_note([["Calculus", "Precalculus Review", "Introduction to Limits"], ["Physics", "Introduction to Electronics"]]) - remove_note([["Calculus", "Note that I don't need to"]]) - compile_note([["Calculus", ":all:"], ["Physics", "A note that I need to compile right now", "Physics 2: Electric Boogaloo"]]) """ def create_symbolic_link(_link, _target, filename): """Simply creates a relative symbolic link through the shell. Cross-platform support is down to a minimum so expect some bugs to pop up often. :param _link: The path to be linked. :type _link: Path :param _target: The target or the destination of the symbolic link to be created. :type _target: Path :return: The results from a `subprocess.run` invocation. For more information, visit the following page (https://docs.python.org/3/library/subprocess.html#subprocess.run). """ os_platform = system() symbolic_link_creation_process = None link = relpath(_link, _target) target = _target if os_platform == "Windows": symbolic_link_creation_process = run(["ln", "--symbolic", link, target / filename]) elif os_platform == "Linux": symbolic_link_creation_process = run(["ln", "--symbolic", link, target / filename]) else: symbolic_link_creation_process = run(["ln", "--symbolic", link, filename]) return symbolic_link_creation_process def convert_subject_query_to_dictionary(subject_query, metadata=None): subject_query = dict(subject_query) subject_query["slug"] = kebab_case(subject_query["name"]) subject_query["path"] = metadata["notes"] / subject_query["slug"] return subject_query def get_profile(location=constants.CURRENT_DIRECTORY): """ Gets a profile and return the appropriate data. :param location: :return: """ location_path = Path(location) profile = location_path / constants.PROFILE_DIRECTORY_NAME if profile.exists() is False: raise exceptions.ProfileDoesNotExistsError(location) notes = profile / constants.NOTES_DIRECTORY_NAME db = initialized_db(notes / constants.NOTES_DB_FILENAME) return { "profile": profile, "notes": notes, "styles": profile / constants.STYLE_DIRECTORY_NAME, "db": db, } def create_profile(location=constants.CURRENT_DIRECTORY): """ Create a TexTure Notes profile. :param location: The location where the profile will be created. :type location: str :return: dict """ location_path = Path(location) profile = location_path / constants.PROFILE_DIRECTORY_NAME if profile.exists() is True or profile.is_symlink() is True: raise exceptions.ProfileAlreadyExistsError(location) profile.mkdir() latexmkrc_file = profile / "latexmkrc" latexmkrc_file.touch() with open(latexmkrc_file, "w") as latexmkrc: latexmkrc.write(constants.config["DEFAULT_LATEXMKRC_TEMPLATE"]) styles = profile / constants.STYLE_DIRECTORY_NAME styles.mkdir() notes = profile / constants.NOTES_DIRECTORY_NAME notes.mkdir() notes_db = initialized_db(notes / constants.NOTES_DB_FILENAME) return { "profile": profile, "notes": notes, "styles": styles, "db": notes_db, } def get_subject(subject, delete_in_db=True, metadata=None): """Get a subject if it exists in the database and automatically handles the case if the directory is deleted while the subject is found in the database. :param subject: The subject to be searched. :type subject: str :param delete_in_db: Simply deletes the subject entry in database if it's found to be a dangling subject. It is enabled by default. :type delete_in_db: bool :param db: The database connection to be used. :type db: sqlite3.Connection :return: A dictionary of the subject query from the SQLite database along with an instance of Path of their filepath. :rtype: dict :raises NoSubjectFoundError: Raised if the subject is not found in the database. :raises DanglingSubjectError: Raised if the subject is found in the database but not found in the filesystem. """ with use_db(metadata["db"]) as (notes_cursor, notes_db): subject_slug = kebab_case(subject) notes_cursor.execute("SELECT id, name, datetime_modified FROM subjects WHERE name == :name;", {"name": subject}) subject_query = notes_cursor.fetchone() if subject_query is None: raise exceptions.NoSubjectFoundError(subject) subject_value = convert_subject_query_to_dictionary(subject_query, metadata=metadata) if subject_value["path"].is_dir() is False: if delete_in_db is True: notes_cursor.execute("DELETE FROM subjects WHERE id == :subject_id;", {"subject_id": subject_query["id"]}) notes_db.commit() raise exceptions.DanglingSubjectError(subject_value) return subject_value def get_subject_by_id(id, delete_in_db=True, metadata=None): with use_db(metadata["db"]) as (notes_cursor, notes_db): notes_cursor.execute("SELECT id, name, datetime_modified FROM subjects WHERE " "id == :id;", {"id": id}) subject_query = notes_cursor.fetchone() if subject_query is None: raise exceptions.NoSubjectFoundError(id) subject_query = convert_subject_query_to_dictionary(subject_query, metadata=metadata) if subject_query["path"].is_dir() is False: if delete_in_db is True: notes_cursor.execute("DELETE FROM subjects WHERE id == :subject_id;", {"subject_id": subject_query["id"]}) notes_db.commit() raise exceptions.DanglingSubjectError(subject_query["name"]) return subject_query def convert_note_query_to_dictionary(note_query, subject_query): note = dict(note_query) note["subject"] = subject_query["name"] note["slug"] = kebab_case(note["title"]) note["path"] = subject_query["path"] / (note["slug"] + ".tex") note["subject_path"] = subject_query["path"] return note def get_subjects(*subjects, **kwargs): """ Retrieves a list of subjects. Query data results are similar to the `get_subject` function. :param subjects: A list of subjects to be searched. :type subjects: list[str] :keyword strict: Indicates that the function will raise an exception if there are missing and dangling subjects. It is disabled by default. :keyword delete_in_db: Deletes the subject entry in the database if it's found to be a dangling subject. It is enabled by default. :return: A tuple that is made up of three items: a list of dictionaries similar to the data returned from `get_subject` function, a list of subjects that are not found, and a list of dangling subjects with their data similar to the first list. :rtype: tuple[list] :raises MultipleSubjectError: Raises an exception if the function is in strict mode and there's invalid and dangling subjects. """ db = kwargs.pop("db", None) profile_metadata = kwargs.pop("metadata") with use_db(profile_metadata["db"]) as (notes_cursor, notes_db): # this will eventually be the list for subjects that are not found subjects_set = deduplicate_list(subjects) subject_set_valid_sql_string = "(" + ", ".join(str(f"'{subject}'") for subject in subjects_set) + ")" notes_cursor.execute(f"SELECT id, name, datetime_modified FROM subjects WHERE name " f"IN {subject_set_valid_sql_string};") subjects_query = notes_cursor.fetchall() # getting the valid keyword arguments handling for this function strict = kwargs.pop("strict", False) delete_in_db = kwargs.pop("delete_in_db", True) # this list will first receive the index of the dangling notes before the note dictionaries dangling_subjects = [] for (index, subject) in enumerate(subjects_query): subject = convert_subject_query_to_dictionary(subject, metadata=profile_metadata) subjects_query[index] = subject # remove the subjects that are found in the set # the remaining subject names are the one that is not found in the database try: subject_index = subjects_set.index(subject["name"]) subjects_set.pop(subject_index) except ValueError: continue if subject["path"].is_dir() is False: dangling_subjects.append(index) if delete_in_db is True: notes_cursor.execute("DELETE FROM subjects WHERE id == :subject_id;", {"subject_id": subject["id"]}) notes_db.commit() continue dangling_subjects[:] = [subjects_query.pop(index) for index in dangling_subjects] if (len(subjects_set) > 0 or len(dangling_subjects) > 0) or len(subjects_query) > 0: if strict is True: raise exceptions.MultipleSubjectError(subjects_set, dangling_subjects) return subjects_query, subjects_set, dangling_subjects def get_all_subjects(sort_by=None, strict=False, delete_in_db=True, metadata=None): """Retrieve all of the subjects from the notes database. :param sort_by: Lists note in a particular order. Only accepts a limited range of keywords. Such keywords include "id", "name", and "date". Any invalid choices are not sorted in any way. :type sort_by: str :param strict: Indicates that the function will raise an exception if there are missing and/or dangling subjects. It is disabled by default. :type strict: bool :param delete_in_db: If enabled, let the function handle dangling subjects simply by deleting their entry in the database. It is enabled by default. :type delete_in_db: bool :param db: The database connection to be used. If none was provided, it'll use the default connection. :type db: sqlite3.Connection :return: A tuple made up of the following: a list of dictionaries similar of structure from "get_subject" function and a list of dangling subjects. :rtype: tuple[list] :raises DanglingSubjectError: When the function is in strict mode and there are dangling subjects found in the database. """ with use_db(metadata["db"]) as (notes_cursor, notes_db): select_all_notes_sql_statement = "SELECT id, name, datetime_modified FROM subjects " if sort_by == "id": select_all_notes_sql_statement += "ORDER BY id;" elif sort_by == "name": select_all_notes_sql_statement += "ORDER BY name;" elif sort_by == "date": select_all_notes_sql_statement += "ORDER BY datetime_modified;" notes_cursor.execute(select_all_notes_sql_statement) # take note that this list will receive list indices before the metadata dangled_subjects = [] subjects_query = notes_cursor.fetchall() for (index, _subject) in enumerate(subjects_query): subject = convert_subject_query_to_dictionary(_subject, metadata=metadata) subjects_query[index] = subject if subject["path"].is_dir() is False: dangled_subjects.append(index) if delete_in_db is True: notes_cursor.execute("DELETE FROM subjects WHERE id == :subject_id;", {"subject_id": subject["id"]}) notes_db.commit() continue # putting all of the dangling subjects in the array dangled_subjects[:] = [subjects_query.pop(index) for index in dangled_subjects] if len(dangled_subjects) > 0 and strict is True: raise exceptions.DanglingSubjectError(dangled_subjects) return subjects_query, dangled_subjects def get_subject_note(subject, note, delete_in_db=True, metadata=None): """ Simply finds the note from the given subject. :param subject: The subject from where
<gh_stars>0 from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt import base64,time,random,hashlib,json,re,django,platform from . import server_helper,match,view,web_socket,search_process,GlobalVar,anticheatz from www.index import player as index_player def hash_md5(str): return hashlib.md5(str).hexdigest() def get_json(result): return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8") def process_getdata_by_key(key): return GlobalVar.runSQL('SELECT * FROM userdata WHERE `Key` = %s LIMIT 1', key) def process_playerlist_decode(playerlist): return json.loads(base64.b64decode(playerlist).decode(encoding='GBK')) def process_playerlist_encode(playerlist): return base64.b64encode(json.dumps(playerlist).encode(encoding='GBK')) def process_playerlist_remove(playerlist, name): #del playerlist[name] playerlist.pop(name) return playerlist def get_by_steamid(steamid): return GlobalVar.runSQL( 'SELECT * FROM userdata WHERE `SteamID` = %s LIMIT 1', (steamid)) def get_by_name(player_name): return GlobalVar.runSQL( 'SELECT * FROM userdata WHERE `username` = %s LIMIT 1', (player_name)) def process_exit_room(sec_key): Check = process_getdata_by_key(sec_key) if not Check: return False room_id = Check[0][GlobalVar.sql_userdata_roomid] myName = Check[0][GlobalVar.sql_userdata_username] if room_id == '0': return False Check = GlobalVar.runSQL( 'SELECT * FROM roomlist WHERE `RoomID` = %s LIMIT 1', (room_id)) if not Check: GlobalVar.runSQL( "UPDATE userdata SET `roomid` = '0' WHERE `Key` = %s LIMIT 1", sec_key) return True player_list = Check[0][GlobalVar.sql_roomlist_PlayerList] player_number = Check[0][GlobalVar.sql_roomlist_PlayerNumber] ready_number = Check[0][GlobalVar.sql_roomlist_ReadyNumber] player_list_decode = process_playerlist_decode(player_list) found = False for name in player_list_decode: if name == myName: found = True if not found: GlobalVar.runSQL( "UPDATE userdata SET `roomid` = '0' WHERE `Key` = %s LIMIT 1", sec_key) return True if Check[0][GlobalVar.sql_roomlist_ingame]: return True # if search_process.check_in_search(Check): # search_process.stop_search(room_id) if player_number == 1: if search_process.check_in_search(Check): search_process.stop_search(room_id) GlobalVar.runSQL( "UPDATE userdata SET `roomid` = '0' WHERE `Key` = %s LIMIT 1", sec_key) GlobalVar.runSQL( "DELETE FROM roomlist WHERE `RoomID` = %s LIMIT 1", room_id) return True player_list_decode = process_playerlist_remove(player_list_decode, myName) web_socket.send_player_leave_room(room_id, myName) new_player_num = player_number - 1 new_ready_num = ready_number - 1 new_max_rank = 100 #{'ready': False, 'Rank': 100, 'ico': 'null'} for name in player_list_decode: #print('name:' + name + "rank:" + str(player_list_decode[name]['Rank'])) if player_list_decode[name]['Rank'] > new_max_rank: new_max_rank = player_list_decode[name]['Rank'] player_list_encode = process_playerlist_encode( player_list_decode).decode(encoding='GBK') GlobalVar.runSQL( "UPDATE userdata SET `roomid` = '0' WHERE `Key` = %s LIMIT 1", sec_key) GlobalVar.runSQL( "UPDATE roomlist SET `Rank`=%s,`PlayerNumber` = %s ,`ReadyNumber`= %s,`PlayerList`= %s WHERE `RoomID` = %s LIMIT 1", (new_max_rank, new_player_num, new_ready_num, player_list_encode, room_id)) return True def get_invietcode(name,code): check = GlobalVar.runSQL("SELECT * FROM invitecode WHERE `code` = %s and `used` = 0 limit 1", code) if not check: return False GlobalVar.runSQL("UPDATE invitecode SET `used` = 1,`name` = %s WHERE `code` = %s limit 1", (name, code)) return True @csrf_exempt def do_register(request): result = { 'msgType': 'register', 'uFuck': 1, 'success': 0 } room_config = { 'ico': 'default.jpg', 'title': '菜鸡房间', 'text': '这个人是菜鸡,因为他的房间还是默认的标题和内容!', 'maps': ['de_dust2', 'de_nuke', 'de_mirage', 'de_overpass', 'de_cache', 'de_inferno', 'de_train', 'de_cbble'], 'public': 1 } data = { 'kill': 0, 'dead': 0, 'first': 0, 'headshot': 0, 'help': 0, 'music': 39227624, 'autoplay': 1, 'matched': [], 'rank': {}, 'ico': 'null' } if request.method == 'POST': if True: if 'Regname' in request.POST and 'Regpass' in request.POST and 'Regemail' in request.POST and 'auth' in request.POST and 'InviteCode' in request.POST: if not view.auth_send_post(request.POST['auth']): result['uFuck'] = 6 return get_json(result) if not re.findall(r'^[0-9a-zA-Z\_\-]+(\.[0-9a-zA-Z\_\-]+)*@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+){1,}$', request.POST['Regemail']): result['uFuck'] = 2 return get_json(result) name_proccesed = web_socket.htmlescape(request.POST['Regname']) if name_proccesed == '你是个好人' or name_proccesed == 'huoji': result['uFuck'] = 5 return get_json(result) if len(name_proccesed) > 15: result['uFuck'] = 7 return get_json(result) email_proccesed = web_socket.htmlescape( request.POST['Regemail']) if not re.search(u'^[_a-zA-Z0-9\u4e00-\u9fa5]+$', name_proccesed): result['uFuck'] = 5 return get_json(result) Check = GlobalVar.runSQL( 'SELECT * FROM userdata WHERE username = %s LIMIT 1', (name_proccesed)) if Check: result['uFuck'] = 3 return get_json(result) Check = GlobalVar.runSQL( 'SELECT * FROM userdata WHERE email = %s LIMIT 1', (email_proccesed)) if Check: result['uFuck'] = 4 return get_json(result) if not get_invietcode(name_proccesed, request.POST['InviteCode']): result['uFuck'] = 8 return get_json(result) password = <PASSWORD>_md5( hash_md5(request.POST['Regpass'].encode(encoding='GBK')).encode(encoding='GBK')) TheKey = hash_md5(base64.b64encode( str( name_proccesed + email_proccesed ).encode(encoding='GBK') + password.encode(encoding='GBK') )) data_encode = process_playerlist_encode( data).decode(encoding='GBK') GlobalVar.runSQL( 'INSERT INTO userdata (`username`,`password`,`email`,`Key`,`roomconfig`,`data`) VALUES (%s,%s,%s,%s,%s,%s)', (name_proccesed, password, email_proccesed, TheKey, process_playerlist_encode(room_config).decode(encoding='GBK'), data_encode)) result['uFuck'] = 0 result['success'] = 1 return get_json(result) #except: # return HttpResponse('you mother fuck up') return get_json(result) @csrf_exempt def do_login(request): result = { 'msgType': 'Login', 'uFuck': 1, 'secKey': 'NULL', 'success': 0 } if 'logname' in request.POST and 'logpass' in request.POST: Check = GlobalVar.runSQL( 'SELECT * FROM userdata WHERE username = %s LIMIT 1', (request.POST['logname'])) if not Check: result['uFuck'] = 2 return get_json(result) hashed_key = hash_md5(hash_md5(request.POST['logpass'].encode( encoding='GBK')).encode(encoding='GBK')) if Check[0][GlobalVar.sql_userdata_password] != hashed_key: result['uFuck'] = 3 return get_json(result) if Check[0][GlobalVar.sql_userdata_banned]: result['uFuck'] = 4 return get_json(result) result['secKey'] = Check[0][GlobalVar.sql_userdata_Key] result['uFuck'] = 0 result['success'] = 1 return get_json(result) return get_json(result) def process_check_room(key): Check = process_getdata_by_key(key) if not Check: return 0 sec_key = Check[0][GlobalVar.sql_userdata_Key] player_name = Check[0][GlobalVar.sql_userdata_username] room_id = Check[0][GlobalVar.sql_userdata_roomid] banned = Check[0][GlobalVar.sql_userdata_banned] if room_id == '0': return 0 if banned == 1: return 110 Check = GlobalVar.runSQL( 'SELECT * FROM roomlist WHERE `RoomID` = %s LIMIT 1', room_id) if not Check: GlobalVar.runSQL( "UPDATE userdata SET `roomid` = '0' WHERE `Key` = %s LIMIT 1", key) return 0 return room_id def do_check_steamid(request): result = { 'msgType': 'CheckSteamid', 'success': 0 } if request.GET and 'key' in request.GET: data = GlobalVar.runSQL('select * from userdata where `SteamID` is null and `Key` = %s limit 1',request.GET['key']) if not data: return get_json(result) result['success'] = 1 return get_json(result) return get_json(result) def do_check(request): result = { 'msgType': 'CheckRoom', 'uFuck': 1, 'RoomID': 'NULL', 'ingame': 0, 'success': 0 } if request.method != 'GET': return get_json(result) try: if 'key' in request.GET: result['uFuck'] = 0 result['success'] = 1 result['RoomID'] = 0 room_id = process_check_room(request.GET['key']) if room_id == 0: return get_json(result) elif room_id == 110: result['uFuck'] = 3 result['RoomID'] = room_id return get_json(result) else: Check = GlobalVar.runSQL( 'SELECT * FROM roomlist WHERE `RoomID` = %s AND `ingame` = 0 LIMIT 1', room_id) if not Check: result['ingame'] = 1 result['uFuck'] = 2 result['RoomID'] = room_id return get_json(result) except: result['success'] = 0 return get_json(result) return get_json(result) def do_exit(request): result = { 'msgType': 'ExitRoom', 'uFuck': 1, 'success': 0 } # 要加try if True: if 'key' in request.GET: result['success'] = process_exit_room(request.GET['key']) return get_json(result) # except: return get_json(result) def do_join(request): result = { 'msgType': 'JoinRoom', 'uFuck': 1, 'RoomID': 'NULL', 'success': 0 } if request.method != 'GET': return get_json(result) # 要加try try: if 'key' in request.GET and 'create' in request.GET and 'roomid' in request.GET: if request.GET['create'] != 'true' and request.GET['create'] != 'false': return get_json(result) sec_key = request.GET['key'] Check = process_getdata_by_key(sec_key) if not Check: return get_json(result) room_id = process_check_room(sec_key) if room_id != 0: result['uFuck'] = 2 result['RoomID'] = room_id return get_json(result) player_name = Check[0][GlobalVar.sql_userdata_username] player_rank = Check[0][GlobalVar.sql_userdata_rank] player_room_config = Check[0][GlobalVar.sql_userdata_roomconfig] player_ico = Check[0][GlobalVar.sql_userdata_PlayerInfo] if Check[0][GlobalVar.sql_userdata_banned]: result['RoomID'] = '好聪明哦' return get_json(result) if request.GET['create'] == 'true': player_room_config_decode = process_playerlist_decode( player_room_config) time_tick = str(time.time()).replace('.', '') room_id = hash_md5( str(time_tick + str(player_name)).encode(encoding='GBK'))[0:6] player_list = process_playerlist_encode({ player_name: { 'ready': False, 'Rank': player_rank, 'ico': player_ico } }).decode(encoding='GBK') GlobalVar.runSQL( "UPDATE userdata SET `roomid` = %s WHERE `Key` = %s LIMIT 1", (room_id, sec_key)) GlobalVar.runSQL( 'INSERT INTO roomlist (`RoomID`,`ingame`,`PlayerNumber`,`PlayerList`,`Rank`,`config`,`public`) VALUES (%s,%s,%s,%s,%s,%s,%s)', (room_id, 0, 1, player_list, player_rank, player_room_config, player_room_config_decode['public'])) result['uFuck'] = 0 result['success'] = 1 result['RoomID'] = room_id # print(result['success']) return get_json(result) elif request.GET['create'] == 'false': room_id = request.GET['roomid'] result['RoomID'] = room_id Check = GlobalVar.runSQL( 'SELECT * FROM roomlist WHERE `RoomID` = %s LIMIT 1', (room_id)) if not Check: result['uFuck'] = 3 return get_json(result) if Check[0][GlobalVar.sql_roomlist_PlayerNumber] >= 5: result['uFuck'] = 4 return get_json(result) if Check[0][GlobalVar.sql_roomlist_ingame] == 1: result['uFuck'] = 6 return get_json(result) if search_process.check_in_search(Check): search_process.stop_search(room_id) result['success'] = 1 GlobalVar.runSQL( "UPDATE userdata SET `roomid` = %s WHERE `Key` = %s LIMIT 1", (room_id, sec_key)) plyaer_list_decode = process_playerlist_decode( Check[0][GlobalVar.sql_roomlist_PlayerList]) plyaer_list_decode[player_name] = { 'ready': False, 'Rank': player_rank, 'ico': player_ico } new_player_num = Check[0][GlobalVar.sql_roomlist_PlayerNumber] + 1 new_ready_num = Check[0][GlobalVar.sql_roomlist_ReadyNumber] + 1 new_max_rank = 100 for name in plyaer_list_decode: if plyaer_list_decode[name]['Rank'] > new_max_rank: new_max_rank = plyaer_list_decode[name]['Rank'] player_list_encode = process_playerlist_encode( plyaer_list_decode).decode(encoding='GBK') #print(str((new_max_rank, player_list_encode, # new_player_num, new_ready_num, room_id))) GlobalVar.runSQL( "UPDATE roomlist SET `Rank` = %s ,`PlayerList` = %s,`PlayerNumber`=%s,`ReadyNumber`=%s WHERE `RoomID` = %s LIMIT 1", (new_max_rank, player_list_encode, new_player_num, new_ready_num, room_id)) result['uFuck'] = 0 result['success'] = 1 result['RoomID'] = room_id web_socket.send_player_join_room(room_id, player_name) return get_json(result) except: return get_json(result) @csrf_exempt def process(request, moudle): result = HttpResponse() if moudle in 'register': result = do_register(request) if moudle in 'login': result = do_login(request) if moudle in 'check_in_room': result = do_check(request) if moudle in 'exit_room': result = do_exit(request) if moudle in 'join_room': result = do_join(request) if moudle in 'check_steamid': result = do_check_steamid(request) if moudle in 'resolve_server': result = server_helper.resolve_server(request) if moudle in 'get_all_casual_server': result = server_helper.get_all_casual_server(request) if moudle in
an element to the mesh :param element: :return: """ self.elements.append( element ) lg.info( 'add_element: %s element added, node ids are %s', element.element_type( ), element.node_ids ) def add_elements( self, element_list ): """ Add a list of elements to the mesh :param element_list: :return: """ for ele in element_list: self.add_element( ele ) def add_bc_node( self, axis, node_id ): """ Set a node to be a boundary condition :param axis: x, y or z :param node_id: :return: """ self.bcs[ axis ].append( node_id ) def add_pressure_facet( self, gc_index, facet ): """ Add a pressure facet (a facet on the inside of a guard cell) :param gc_index: 0 or 1 :param facet: list of node ids :return: """ self.pressure_facets[ gc_index ].append( facet ) def add_external_facet( self, facet ): """ Add a facet on the outside of the guard cell to the dorsal/ventral facet list :param facet: :return: """ # TODO use the node map # Is it dorsal or ventral? mid_ellipse = self.mesh_config.stoma_cfg.mid_ellipse semi_maj = mid_ellipse.semi_x_axis semi_min = mid_ellipse.semi_y_axis # get the points for the facet points = [ self.nodes_map[ nid ] for nid in facet ] centroid = sum( points ) / len( points ) # use the axial ellipse to determine if the facet is dorsal or ventral is_ventral_facet = (centroid.x / semi_maj) ** 2 + (centroid.y / semi_min) ** 2 < 1.0 # GC #0 has y>0 and GC #1 has y<0 gc_index = 0 if centroid.y > 0 else 1 if is_ventral_facet: self._ventral_facets[ gc_index ].append( facet ) else: self._dorsal_facets[ gc_index ].append( facet ) return def add_epidermis_facet( self, facet ): """ Add a facet to the epidermal wall :param facet: :return: """ self._epidermis_facets.append( facet ) def get_elements_by_type( self ): """ Get elements in the mesh :return: dict with keys equal to the element types, e.g. hex8 """ result = { } for ele in self.elements: if ele.element_type( ) not in result: result[ ele.element_type( ) ] = [ ] result[ ele.element_type( ) ].append( ele ) return result def set_bcs( self ): """ Add the boundary conditions (for symmetry) """ # floating point tolerance fp_tolerance = 1e-5 for node in self.nodes_map.values(): for coord_label_pair in ((node.x, 'x'), (node.y, 'y'), (node.z, 'z')): if abs( coord_label_pair[ 0 ] ) < fp_tolerance: self.add_bc_node( coord_label_pair[ 1 ], node.id ) return def calculate_all_surface_facets( self ): """ Calculate information on facets that lie on the surfaces When there is 1 guard cell the external tip wall is ignored and when there are 2 GCs it is still ignored.""" def is_polar_wall_facet( _facet ): """ Facet is on the (external) polar wall if all of its points have x, y or z equal to 0. Only happens when mesh has not been reflected, i.e. facet should be part of a wall """ _sum = [ 0.0, 0.0, 0.0 ] for _node_id in _facet: _sum = [ _sum[ i ] + abs( self.nodes_map[ _node_id ].xyz[ i ] ) for i in range( 3 ) ] return abs( min( _sum ) ) < 1e-5 # map of facets with sorted node ids to facet with the node ids in their original order # e.g if facet is (1,3,2) then key-value pair is (1,2,3) -> (1,3,2) dict_sortedfacet_facet = dict( ) # list of facets - each facet has sorted node ids # there are duplicates but this is desired! # all_sortedfacets = [ ] for ele in self.elements: facets = ele.facets( ) for facet in facets: sortedfacet = tuple( sorted( facet ) ) # the value will be overwritten when a facet is shared but this occurs when # it is in the wall and we are not interested in these ones dict_sortedfacet_facet[ sortedfacet ] = facet all_sortedfacets.append( sortedfacet ) # count occurrences of each facet sortedfacet_count = collections.Counter( all_sortedfacets ) # a list of surface facets - the node ids are sorted surface_sortedfacets = [ ] for candidate_sortedfacet, count in sortedfacet_count.items( ): # surface facets have a count of 1 - internal facets are shared so count > 1 if count == 1 and not is_polar_wall_facet( candidate_sortedfacet ): surface_sortedfacets.append( candidate_sortedfacet ) # remove entries that aren't required dict_sortedfacet_facet = { k: dict_sortedfacet_facet[ k ] for k in surface_sortedfacets } # create a dictionary of node ids to a list of associated facets # e.g. 1 -> [ (1,2,3), (1,4,10) ] node_sfacet_dict = dict( ) for s_sfacet in surface_sortedfacets: for node_id in s_sfacet: if node_id not in node_sfacet_dict: node_sfacet_dict[ node_id ] = [ ] node_sfacet_dict[ node_id ].append( s_sfacet ) return surface_sortedfacets, dict_sortedfacet_facet, node_sfacet_dict @staticmethod def calculate_attached_facets( start_node_id, node_sfacet_dict ): """ Calculate the facets attached to a node """ # the set of candidate nodes - will spread from start point like a 'front' candidate_nodes = { start_node_id } visited_nodes = set( ) attached_facets = set( ) while candidate_nodes: candidate_node_id = candidate_nodes.pop( ) if candidate_node_id in visited_nodes: continue if candidate_node_id in node_sfacet_dict: for facet in node_sfacet_dict[ candidate_node_id ]: attached_facets.add( facet ) for node_id in facet: if node_id != candidate_node_id and node_id not in visited_nodes: candidate_nodes.add( node_id ) visited_nodes.add( candidate_node_id ) return attached_facets def set_surface_facets( self ): """ Get the surface facets (sorted node ids) and the map of sorted facets -> original facets Use 's' to denote sorted """ surface_facets = self.calculate_all_surface_facets( ) sfacets_facet_dict, node_sfacet_dict = surface_facets[1], surface_facets[2] # find pressure facets (inside each guard cell) for idx, node_id in enumerate( self._special[ 'pressure_node_ids' ] ): pressure_facets = self.calculate_attached_facets( node_id, node_sfacet_dict ) # add the pressure facets for s_sfacet in pressure_facets: facet = sfacets_facet_dict[ s_sfacet ] self.add_pressure_facet( idx, facet ) # find external wall facets by starting at the first dorsal node id -- will then get all external facets init_dorsal_nid = self._special[ 'dorsal_node_ids' ][ 0 ] external_facets = self.calculate_attached_facets( init_dorsal_nid, node_sfacet_dict ) # add the facets for s_sfacet in external_facets: facet = sfacets_facet_dict[ s_sfacet ] self.add_external_facet( facet ) # find ventral wall facets # DOES the above find all the facets on the external walls? if len( self._special[ 'epidermis' ] ) > 0: init_epidermis_nid = self._special[ 'epidermis' ][ 0 ] epidermis_facets = self.calculate_attached_facets( init_epidermis_nid, node_sfacet_dict ) # add the facets for s_sfacet in epidermis_facets: facet = sfacets_facet_dict[ s_sfacet ] self.add_epidermis_facet( facet ) return def __repr__( self ): return 'Mesh: {} nodes, {} elements'.format( len( self.nodes_map ), len( self.elements ) ) def perform_simple_check(self): """ Check the mesh using the Jacobian ratio :return: """ j_ratios = [ ele.jacobian_ratio( self.nodes_map ) for ele in self.elements ] max_jratio = max( j_ratios ) num_gt_5 = sum( (1 for _ in j_ratios if _ > 5) ) num_lt_0 = sum( (1 for _ in j_ratios if _ < 0) ) print( '--> Mesh statistics:' ) print( '--> {} elements'.format( len( j_ratios ) ) ) print( '--> max Jacobian ratio : {}'.format( max_jratio ) ) print( '--> number > 5 : {}'.format( num_gt_5 ) ) print( '--> number < 0 : {}'.format( num_lt_0 ) ) def create_vtk_checker( self ): """ Converts the mesh created by the internal mesh creator to a mesh checker :param a_mesh: Instance of a Mesh object (from simple_mesh.py) :type a_mesh: simple_mesh.SimpleMesh :return: """ points = self.nodes_map.values( ) elements = [ ele.node_ids for ele in self.elements ] return mesh_check.VTKMeshChecker.create_from_points_and_elements( points=points, elements=elements ) def build_test_mesh( ): """ Build a tests mesh """ mesh = Mesh( ) # create the nodes pts = list( ) pts.append( p.Point( 0, 0, 0 ) ) pts.append( p.Point( 2, 0, 0 ) ) pts.append( p.Point( 2, 3, 0 ) ) pts.append( p.Point( 0, 3, 0 ) ) pts.append( p.Point( 0, 0, 1 ) ) pts.append( p.Point( 2, 0, 1 ) ) pts.append( p.Point( 2, 3, 1 ) ) pts.append( p.Point( 0, 3, 1 ) ) pts.append( p.Point( 3, 0, 0 ) ) pts.append( p.Point( 3, 3, 0 ) ) pts.append( p.Point( 3, 0, 1 ) ) pts.append( p.Point( 3, 3, 1 ) ) p.Point.point_id = 1 for pt
self.common_headers is not None: result['commonHeaders'] = self.common_headers if self.x_acs_dingtalk_access_token is not None: result['x-acs-dingtalk-access-token'] = self.x_acs_dingtalk_access_token return result def from_map(self, m: dict = None): m = m or dict() if m.get('commonHeaders') is not None: self.common_headers = m.get('commonHeaders') if m.get('x-acs-dingtalk-access-token') is not None: self.x_acs_dingtalk_access_token = m.get('x-acs-dingtalk-access-token') return self class SearchResidentRequest(TeaModel): def __init__( self, resident_crop_id: str = None, search_word: str = None, ): self.resident_crop_id = resident_crop_id self.search_word = search_word def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.resident_crop_id is not None: result['residentCropId'] = self.resident_crop_id if self.search_word is not None: result['searchWord'] = self.search_word return result def from_map(self, m: dict = None): m = m or dict() if m.get('residentCropId') is not None: self.resident_crop_id = m.get('residentCropId') if m.get('searchWord') is not None: self.search_word = m.get('searchWord') return self class SearchResidentResponseBodyResidenceList(TeaModel): def __init__( self, name: str = None, relate_type: str = None, is_property_owner: bool = None, active: bool = None, ext_field: str = None, ): self.name = name # 业主/租客/亲友等 self.relate_type = relate_type # 是否是产权人 self.is_property_owner = is_property_owner # 是否激活 self.active = active # 扩展字段,如果是租客存起止时间 self.ext_field = ext_field def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.name is not None: result['name'] = self.name if self.relate_type is not None: result['relateType'] = self.relate_type if self.is_property_owner is not None: result['isPropertyOwner'] = self.is_property_owner if self.active is not None: result['active'] = self.active if self.ext_field is not None: result['extField'] = self.ext_field return result def from_map(self, m: dict = None): m = m or dict() if m.get('name') is not None: self.name = m.get('name') if m.get('relateType') is not None: self.relate_type = m.get('relateType') if m.get('isPropertyOwner') is not None: self.is_property_owner = m.get('isPropertyOwner') if m.get('active') is not None: self.active = m.get('active') if m.get('extField') is not None: self.ext_field = m.get('extField') return self class SearchResidentResponseBody(TeaModel): def __init__( self, residence_list: List[SearchResidentResponseBodyResidenceList] = None, ): # result self.residence_list = residence_list def validate(self): if self.residence_list: for k in self.residence_list: if k: k.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() result['residenceList'] = [] if self.residence_list is not None: for k in self.residence_list: result['residenceList'].append(k.to_map() if k else None) return result def from_map(self, m: dict = None): m = m or dict() self.residence_list = [] if m.get('residenceList') is not None: for k in m.get('residenceList'): temp_model = SearchResidentResponseBodyResidenceList() self.residence_list.append(temp_model.from_map(k)) return self class SearchResidentResponse(TeaModel): def __init__( self, headers: Dict[str, str] = None, body: SearchResidentResponseBody = None, ): self.headers = headers self.body = body def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = SearchResidentResponseBody() self.body = temp_model.from_map(m['body']) return self class AddResidentDepartmentHeaders(TeaModel): def __init__( self, common_headers: Dict[str, str] = None, x_acs_dingtalk_access_token: str = None, ): self.common_headers = common_headers self.x_acs_dingtalk_access_token = x_acs_dingtalk_access_token def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.common_headers is not None: result['commonHeaders'] = self.common_headers if self.x_acs_dingtalk_access_token is not None: result['x-acs-dingtalk-access-token'] = self.x_acs_dingtalk_access_token return result def from_map(self, m: dict = None): m = m or dict() if m.get('commonHeaders') is not None: self.common_headers = m.get('commonHeaders') if m.get('x-acs-dingtalk-access-token') is not None: self.x_acs_dingtalk_access_token = m.get('x-acs-dingtalk-access-token') return self class AddResidentDepartmentRequest(TeaModel): def __init__( self, is_residence_group: bool = None, department_name: str = None, parent_department_id: int = None, ): # 是否为组 self.is_residence_group = is_residence_group # 部门名字 self.department_name = department_name # 父部门id self.parent_department_id = parent_department_id def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.is_residence_group is not None: result['isResidenceGroup'] = self.is_residence_group if self.department_name is not None: result['departmentName'] = self.department_name if self.parent_department_id is not None: result['parentDepartmentId'] = self.parent_department_id return result def from_map(self, m: dict = None): m = m or dict() if m.get('isResidenceGroup') is not None: self.is_residence_group = m.get('isResidenceGroup') if m.get('departmentName') is not None: self.department_name = m.get('departmentName') if m.get('parentDepartmentId') is not None: self.parent_department_id = m.get('parentDepartmentId') return self class AddResidentDepartmentResponseBody(TeaModel): def __init__( self, result: int = None, ): # 创建成功的deptId self.result = result def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.result is not None: result['result'] = self.result return result def from_map(self, m: dict = None): m = m or dict() if m.get('result') is not None: self.result = m.get('result') return self class AddResidentDepartmentResponse(TeaModel): def __init__( self, headers: Dict[str, str] = None, body: AddResidentDepartmentResponseBody = None, ): self.headers = headers self.body = body def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = AddResidentDepartmentResponseBody() self.body = temp_model.from_map(m['body']) return self class PagePointHistoryHeaders(TeaModel): def __init__( self, common_headers: Dict[str, str] = None, x_acs_dingtalk_access_token: str = None, ): self.common_headers = common_headers self.x_acs_dingtalk_access_token = x_acs_dingtalk_access_token def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.common_headers is not None: result['commonHeaders'] = self.common_headers if self.x_acs_dingtalk_access_token is not None: result['x-acs-dingtalk-access-token'] = self.x_acs_dingtalk_access_token return result def from_map(self, m: dict = None): m = m or dict() if m.get('commonHeaders') is not None: self.common_headers = m.get('commonHeaders') if m.get('x-acs-dingtalk-access-token') is not None: self.x_acs_dingtalk_access_token = m.get('x-acs-dingtalk-access-token') return self class PagePointHistoryRequest(TeaModel): def __init__( self, is_circle: bool = None, user_id: str = None, next_token: int = None, max_results: int = None, start_time: int = None, end_time: int = None, ): # 是否查询全员圈积分 self.is_circle = is_circle # 用户userid,可空,不传表示查询组织内所有用户的流水数据 self.user_id = user_id # 用来标记当前开始读取的位置 self.next_token = next_token # 本次读取的最大数据记录数量,最大20 self.max_results = max_results # 起始时间Unix时间戳,可空 self.start_time = start_time # 结束时间Unix时间戳(不包含),可空 self.end_time = end_time def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.is_circle is not None: result['isCircle'] = self.is_circle if self.user_id is not None: result['userId'] = self.user_id if self.next_token is not None: result['nextToken'] = self.next_token if self.max_results is not None: result['maxResults'] = self.max_results if self.start_time is not None: result['startTime'] = self.start_time if self.end_time is not None: result['endTime'] = self.end_time return result def from_map(self, m: dict = None): m = m or dict() if m.get('isCircle') is not None: self.is_circle = m.get('isCircle') if m.get('userId') is not None: self.user_id = m.get('userId') if m.get('nextToken') is not None: self.next_token = m.get('nextToken') if m.get('maxResults') is not None: self.max_results = m.get('maxResults') if m.get('startTime') is not None: self.start_time = m.get('startTime') if m.get('endTime') is not None: self.end_time = m.get('endTime') return self class PagePointHistoryResponseBodyPointRecordList(TeaModel): def __init__( self, corp_id: str = None, user_id: str = None, score: int = None, create_at: int = None, uuid: str = None, rule_code: str = None, rule_name: str = None, ): # 组织id self.corp_id = corp_id # 成员id self.user_id = user_id # 增加或减少的分数(增加为正数,减少为负数) self.score = score # 创建时间(精确到毫秒数) self.create_at = create_at # 幂等键 self.uuid = uuid # 对应的行为代码(可空) self.rule_code = rule_code # 对应的行为名字 self.rule_name = rule_name def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.corp_id is not None: result['corpId'] = self.corp_id if self.user_id is not None: result['userId'] = self.user_id if self.score is not None: result['score'] = self.score if self.create_at is not None: result['createAt'] = self.create_at if self.uuid is not None: result['uuid'] = self.uuid if self.rule_code is not None: result['ruleCode'] = self.rule_code if self.rule_name is not None: result['ruleName'] = self.rule_name return result def from_map(self, m: dict = None): m = m or dict() if m.get('corpId') is not None: self.corp_id = m.get('corpId') if m.get('userId') is not None: self.user_id = m.get('userId') if m.get('score') is not None: self.score = m.get('score')
# Copyright 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """ Common infrastructure for managing Python flavors and versions in third-party2. """ load("@fbcode_macros//build_defs/lib:target_utils.bzl", "target_utils") load("@fbcode_macros//build_defs/lib:third_party.bzl", "third_party") load("@fbcode_macros//build_defs:platform_utils.bzl", "platform_utils") _TP2_PYTHON_PROJECT = third_party.get_tp2_project_target("python") def _get_tp2_project_versions(project, platform): """ Return a list of configured versions for given `project` on `platform`. Multiple versions of a TP2 project is only allowed for a small subset of projects (see `WHITELISTED_VERSIONED_PROJECTS` in `buckify_tp2.py`). """ tp2_conf = third_party.get_third_party_config_for_platform(platform) vers = tp2_conf["build"]["projects"][project] if type(vers) == type(""): return [vers] res = [] for ver in vers: # Each element is either a string, or a pair of the form # (ORIGINAL_TP2_VERSION, ACTUAL_VERSION): if type(ver) == type(""): res.append(ver) else: res.append(ver[1]) return res def _get_all_versions_for_platform(platform): """ Return a list of all configured Python versions for `platform`. """ return _get_tp2_project_versions("python", platform) def _add_flavored_versions(versioned_resources): """ For each resource entry in `versioned_resources` that declares a Python version, add a corresponding entry for every configured TP2 Python version that subsumes the declared Python version. Args: versioned_resources: A list of versioned resource entries accepted by Buck. Each entry in the list should be a pair of the form ( { LABEL1 : VERSION1, ... LABELn : VERSIONn }, { SRC_FILE1 : DST_FILE1, ... SRC_FILEm : DST_FILEm } ) where LABELs are strings that identify dependency targets, and VERSIONs are strings that specify the required version of LABEL. Can be None. Returns: If `versioned_resources` is a list, then a copy of `versioned_resources` extended with entries for Python flavors. Otherwise, `versioned_resources` itself. """ if type(versioned_resources) != type([]): return versioned_resources platforms = platform_utils.get_platforms_for_host_architecture() res = list(versioned_resources) for p in platforms: label = target_utils.target_to_label(_TP2_PYTHON_PROJECT, fbcode_platform = p) for version_spec, resource_spec in versioned_resources: if label in version_spec: pyver = version_spec[label] for cver in _get_all_versions_for_platform(p): # Simple flavor subsumption rule -- version A subsumes # version B if B is a proper suffix of A: if cver != pyver and cver.endswith(pyver): new_spec = dict(version_spec) new_spec[label] = cver res.append([new_spec, resource_spec]) return res # TODO(T38084046): We would rather this to be a provider, but the structs returned from # `provider()` are not hashable. This is likely just a bug in how buck # implements `provider()` in skylark #_PythonVersion = provider(fields = [ # "version_string", # "flavor", # "major", # "minor", # "patchlevel", #]) def _PythonVersion(version_string, flavor, major, minor, patchlevel): return struct( version_string = version_string, flavor = flavor, major = major, minor = minor, patchlevel = patchlevel, ) def _parse_python_version(version_string): if not version_string: fail("Empty version string provided") version_pieces = version_string.split(".") start_idx = 0 flavor = "" if not version_pieces[0].isdigit(): flavor = version_pieces[0] start_idx = 1 if len(version_pieces) == 1: fail("Invalid version string {} provided".format(version_string)) major = int(version_pieces[start_idx]) minor = int(version_pieces[start_idx + 1]) if start_idx + 1 < len(version_pieces) else 0 patchlevel = int(version_pieces[start_idx + 2]) if start_idx + 2 < len(version_pieces) else 0 return _PythonVersion( version_string = version_string, flavor = flavor, major = major, minor = minor, patchlevel = patchlevel, ) # Versions selected based on most commonly specified version strings _INTERNED_PYTHON_VERSIONS = { "2": _parse_python_version("2"), "2.6": _parse_python_version("2.6"), "2.7": _parse_python_version("2.7"), "3": _parse_python_version("3"), "3.0": _parse_python_version("3.0"), "3.2": _parse_python_version("3.2"), "3.3": _parse_python_version("3.3"), "3.4": _parse_python_version("3.4"), "3.5": _parse_python_version("3.5"), "3.6": _parse_python_version("3.6"), "3.7": _parse_python_version("3.7"), } _DEFAULT_PYTHON_MAJOR_VERSION = "3" def _python_version(version_string): """ An abstraction of tp2/python version strings that supports flavor prefixes. See `get_python_platforms_config()` in `tools/build/buck/gen_modes.py` for the format of flavored version strings. Because these are immutable objects, they may also be cached instances Args: version_string: The aforementioned version string Returns: A struct with the 'version_string' (the raw string), 'flavor', 'major', 'minor', and 'patchlevel'. Minor and patchlevel are 0 if they were not provided, though the 0 will not appear in the version string """ version_string = version_string or _DEFAULT_PYTHON_MAJOR_VERSION interned = _INTERNED_PYTHON_VERSIONS.get(version_string) if interned: return interned return _parse_python_version(version_string) def _version_supports_flavor(python_version, flavor): """ Whether a `python_version` is compatible with a flavor """ return python_version.flavor.endswith(flavor) _PythonVersionConstraint = provider(fields = ["op", "version"]) def _constraint_lt(left, right, _check_minor): return (left.major, left.minor, left.patchlevel) < (right.major, right.minor, right.patchlevel) def _constraint_lte(left, right, _check_minor): return (left.major, left.minor, left.patchlevel) <= (right.major, right.minor, right.patchlevel) def _constraint_gt(left, right, _check_minor): return (left.major, left.minor, left.patchlevel) > (right.major, right.minor, right.patchlevel) def _constraint_gte(left, right, _check_minor): return (left.major, left.minor, left.patchlevel) >= (right.major, right.minor, right.patchlevel) def _constraint_eq(left, right, check_minor): return ( (left.major, left.minor, 0 if check_minor else left.patchlevel) == (right.major, right.minor, 0 if check_minor else right.patchlevel) ) def _constraint_partial_match(left, right, check_minor): return (left.major == right.major and (not check_minor or left.minor == right.minor)) def _parse_python_version_constraint(constraint_string): if constraint_string.startswith("<="): version_string = constraint_string[2:].lstrip() op = _constraint_lte elif constraint_string.startswith(">="): version_string = constraint_string[2:].lstrip() op = _constraint_gte elif constraint_string.startswith("<"): version_string = constraint_string[1:].lstrip() op = _constraint_lt elif constraint_string.startswith("="): version_string = constraint_string[1:].lstrip() op = _constraint_eq elif constraint_string.startswith(">"): version_string = constraint_string[1:].lstrip() op = _constraint_gt else: version_string = constraint_string op = _constraint_eq version = _python_version(version_string) return _PythonVersionConstraint(version = version, op = op) def _intern_constraints(): """ Create a map of our most common constraints so that we can pull from the cache more often """ result = { operator + version: _parse_python_version_constraint(operator + version) for version in ["2", "2.7", "3", "3.6"] for operator in ["", "<", "<=", "=", ">=", ">"] } result.update({ 2: _PythonVersionConstraint( version = _python_version("2"), op = _constraint_partial_match, ), 3: _PythonVersionConstraint( version = _python_version("3"), op = _constraint_partial_match, ), "2": _PythonVersionConstraint( version = _python_version("2"), op = _constraint_partial_match, ), "3": _PythonVersionConstraint( version = _python_version("3"), op = _constraint_partial_match, ), }) return result _INTERNED_VERSION_CONSTRAINTS = _intern_constraints() def _python_version_constraint(constraint_string): """ Parses and creates a struct that represents a 'version constraint' This implements the semantics of the `py_version` and `versioned_srcs` parameters of the 'python_xxx' rule types. Note that this method may make use of internal caches of immutable objects Args: constraint_string: A string like '<3', '=2.7', or '3' Returns: A `PythonVersionConstraint` with a comparison `op` and a `version` set """ if not constraint_string: constraint_string = _DEFAULT_PYTHON_MAJOR_VERSION else: # There are some versions that use integers, make sure we pick those up constraint_string = str(constraint_string) if constraint_string in _INTERNED_VERSION_CONSTRAINTS: return _INTERNED_VERSION_CONSTRAINTS[constraint_string] return _parse_python_version_constraint(constraint_string) def _constraint_matches(constraint, version, check_minor = False): """ Whether or not a constraint matches a version Args: constraint: The result of a `python_version_constraint()` call version: The result of a `python_version()` call check_minor: If true, partial checks look at the minor in addition to the major version. For raw constraints (e.g. '2.7'), only the first major and minor versions will be checked. That is, '2.7.1' will match the '2.7' constraint if check_minor is True Returns: Whether the version matches the constraint. Note that the matching effectively checks against triples in most cases, and does not behave identically to python distutils' LooseVersion """ if not _version_supports_flavor(version, constraint.version.flavor): return False return constraint.op(version, constraint.version, check_minor) def _normalize_constraint(constraint): """ Normalizes `constraint` to be a `PythonVersionConstraint` object Returns: Either `constraint` if it is a `PythonVersionConstraint` struct, or parses the string/int into a constraint """ if hasattr(constraint, "version") and hasattr(constraint, "op"): return constraint else: return _python_version_constraint(constraint) _ALL_PYTHON_VERSIONS = { platform: [ _python_version(version_string) for version_string in _get_all_versions_for_platform(platform) ] for platform in platform_utils.get_all_platforms() } def _get_all_versions(fbcode_platform = None): """ Returns a list of `PythonVersion` instances corresponding to the active Python versions for the given `platform`. If `platform` is not specified, then return versions for all platforms. """ versions = {} for p in platform_utils.get_platforms_for_host_architecture(): if fbcode_platform != None and fbcode_platform != p: continue for version in _ALL_PYTHON_VERSIONS[p]: versions[version] = None return versions.keys() def _get_default_version(platform, constraint, flavor = ""): """ Returns a `PythonVersion` instance corresponding to the first Python version that satisfies `constraint` and `flavor` for the given `platform`. """ constraint = _normalize_constraint(constraint) for version in _ALL_PYTHON_VERSIONS[platform]: if _constraint_matches(constraint, version) and _version_supports_flavor(version, flavor): return version return None def _constraint_matches_major(constraint, version): """ True if `constraint` can be satisfied by a Python version that is of major `version` on some active platform. Args: constraint: A constraint that should be satified (`PythonVersionConstraint` or str) version: An integer major version that must be met in addition to the constraint """ constraint = python_versioning.normalize_constraint(constraint) for platform_version in _get_all_versions(): if platform_version.major == version and _constraint_matches(constraint, platform_version): return True return False def _platform_has_version(platform,
# 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 pytest import mock import logging from airflow.models import (TaskInstance, DagRun) from airflow.operators.dummy_operator import DummyOperator from airflow.utils.decorators import apply_defaults from airflow.utils.db import provide_session from airflow.utils.dates import days_ago from airflow.utils import timezone from airflow.utils.state import State from marquez_client.models import JobType, DatasetType from marquez_airflow.dag import _EXTRACTORS as _DAG_EXTRACTORS from marquez_airflow import DAG from marquez_airflow.extractors import ( BaseExtractor, StepMetadata, Source, Dataset ) from marquez_airflow.models import ( DbTableName, DbTableSchema, DbColumn ) from marquez_airflow.utils import get_location, get_job_name from uuid import UUID log = logging.getLogger(__name__) NO_INPUTS = [] NO_OUTPUTS = [] DEFAULT_DATE = timezone.datetime(2016, 1, 1) DAG_ID = 'test_dag' DAG_RUN_ID = 'test_run_id_for_task_completed_and_failed' DAG_RUN_ARGS = {'external_trigger': False} # TODO: check with a different namespace and owner DAG_NAMESPACE = 'default' DAG_OWNER = 'anonymous' DAG_DESCRIPTION = \ 'A simple DAG to test the marquez.DAG metadata extraction flow.' DAG_DEFAULT_ARGS = { 'owner': DAG_OWNER, 'depends_on_past': False, 'start_date': days_ago(1), 'email_on_failure': False, 'email_on_retry': False, 'email': ['<EMAIL>'] } TASK_ID_COMPLETED = 'test_task_completed' TASK_ID_FAILED = 'test_task_failed' @pytest.fixture @provide_session def clear_db_airflow_dags(session=None): session.query(DagRun).delete() session.query(TaskInstance).delete() @provide_session def test_new_run_id(clear_db_airflow_dags, session=None): dag = DAG( DAG_ID, schedule_interval='@daily', default_args=DAG_DEFAULT_ARGS, description=DAG_DESCRIPTION ) run_id = dag.new_run_id() assert UUID(run_id).version == 4 # tests a simple workflow with default extraction mechanism @mock.patch('marquez_airflow.DAG.new_run_id') @mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client') @provide_session def test_marquez_dag(mock_get_or_create_marquez_client, mock_uuid, clear_db_airflow_dags, session=None): dag = DAG( DAG_ID, schedule_interval='@daily', default_args=DAG_DEFAULT_ARGS, description=DAG_DESCRIPTION ) # (1) Mock the marquez client method calls mock_marquez_client = mock.Mock() mock_get_or_create_marquez_client.return_value = mock_marquez_client run_id_completed = "my-test_marquez_dag-uuid-completed" run_id_failed = "my-test_marquez_dag-uuid-failed" mock_uuid.side_effect = [run_id_completed, run_id_failed] # (2) Add task that will be marked as completed task_will_complete = DummyOperator( task_id=TASK_ID_COMPLETED, dag=dag ) completed_task_location = get_location(task_will_complete.dag.fileloc) # (3) Add task that will be marked as failed task_will_fail = DummyOperator( task_id=TASK_ID_FAILED, dag=dag ) failed_task_location = get_location(task_will_complete.dag.fileloc) # (4) Create DAG run and mark as running dagrun = dag.create_dagrun( run_id=DAG_RUN_ID, execution_date=DEFAULT_DATE, state=State.RUNNING) # Assert namespace meta call mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE, DAG_OWNER) # Assert source and dataset meta calls mock_marquez_client.create_source.assert_not_called() mock_marquez_client.create_dataset.assert_not_called() # Assert job meta calls create_job_calls = [ mock.call( job_name=f"{DAG_ID}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=None, output_dataset=None, context=mock.ANY, description=DAG_DESCRIPTION, namespace_name=DAG_NAMESPACE, run_id=None ), mock.call( job_name=f"{DAG_ID}.{TASK_ID_FAILED}", job_type=JobType.BATCH, location=failed_task_location, input_dataset=None, output_dataset=None, context=mock.ANY, description=DAG_DESCRIPTION, namespace_name=DAG_NAMESPACE, run_id=None ) ] log.info( f"{ [name for name, args, kwargs in mock_marquez_client.mock_calls]}") mock_marquez_client.create_job.assert_has_calls(create_job_calls) # Assert job run meta calls create_job_run_calls = [ mock.call( job_name=f"{DAG_ID}.{TASK_ID_COMPLETED}", run_id=mock.ANY, run_args=DAG_RUN_ARGS, nominal_start_time=mock.ANY, nominal_end_time=mock.ANY, namespace_name=DAG_NAMESPACE ), mock.call( job_name=f"{DAG_ID}.{TASK_ID_FAILED}", run_id=mock.ANY, run_args=DAG_RUN_ARGS, nominal_start_time=mock.ANY, nominal_end_time=mock.ANY, namespace_name=DAG_NAMESPACE ) ] mock_marquez_client.create_job_run.assert_has_calls(create_job_run_calls) # (5) Start task that will be marked as completed task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) # (6) Start task that will be marked as failed ti1 = TaskInstance(task=task_will_fail, execution_date=DEFAULT_DATE) ti1.state = State.FAILED session.add(ti1) session.commit() dag.handle_callback(dagrun, success=True, session=session) # Assert start run meta calls start_job_run_calls = [ mock.call(run_id_completed, mock.ANY), mock.call(run_id_failed, mock.ANY) ] mock_marquez_client.mark_job_run_as_started.assert_has_calls( start_job_run_calls ) mock_marquez_client.mark_job_run_as_completed.assert_called_once_with( run_id=run_id_completed, at=mock.ANY ) # When a task run completes, the task outputs are also updated in order # to link a job version (=task version) to a dataset version. # Using a DummyOperator, no outputs exists, so assert that the create # dataset call is not invoked. mock_marquez_client.create_dataset.assert_not_called() dag.handle_callback(dagrun, success=False, session=session) mock_marquez_client.mark_job_run_as_failed.assert_called_once_with( run_id=run_id_failed, at=mock.ANY ) # Assert an attempt to version the outputs of a task is not made when # a task fails mock_marquez_client.create_dataset.assert_not_called() class TestFixtureDummyOperator(DummyOperator): @apply_defaults def __init__(self, *args, **kwargs): super(TestFixtureDummyOperator, self).__init__(*args, **kwargs) class TestFixtureDummyExtractor(BaseExtractor): operator_class = TestFixtureDummyOperator source = Source( type="DummySource", name="dummy_source_name", connection_url="http://dummy/source/url") def __init__(self, operator): super().__init__(operator) def extract(self) -> [StepMetadata]: inputs = [ Dataset.from_table(self.source, "extract_input1") ] outputs = [ Dataset.from_table(self.source, "extract_output1") ] return [StepMetadata( name=get_job_name(task=self.operator), inputs=inputs, outputs=outputs, context={ "extract": "extract" } )] def extract_on_complete(self, task_instance) -> [StepMetadata]: return [] class TestFixtureDummyExtractorOnComplete(BaseExtractor): operator_class = TestFixtureDummyOperator source = Source( type="DummySource", name="dummy_source_name", connection_url="http://dummy/source/url") def __init__(self, operator): super().__init__(operator) def extract(self) -> [StepMetadata]: return [] def extract_on_complete(self, task_instance) -> [StepMetadata]: inputs = [ Dataset.from_table_schema(self.source, DbTableSchema( schema_name='schema', table_name=DbTableName('extract_on_complete_input1'), columns=[DbColumn( name='field1', type='text', description='', ordinal_position=1 ), DbColumn( name='field2', type='text', description='', ordinal_position=2 )] )) ] outputs = [ Dataset.from_table(self.source, "extract_on_complete_output1") ] return [StepMetadata( name=get_job_name(task=self.operator), inputs=inputs, outputs=outputs, context={ "extract_on_complete": "extract_on_complete" } )] # test the lifecycle including with extractors @mock.patch('marquez_airflow.DAG.new_run_id') @mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client') @provide_session def test_marquez_dag_with_extractor(mock_get_or_create_marquez_client, mock_uuid, clear_db_airflow_dags, session=None): # --- test setup dag_id = 'test_marquez_dag_with_extractor' dag = DAG( dag_id, schedule_interval='@daily', default_args=DAG_DEFAULT_ARGS, description=DAG_DESCRIPTION ) run_id = "my-test-uuid" mock_uuid.side_effect = [run_id] # Mock the marquez client method calls mock_marquez_client = mock.Mock() mock_get_or_create_marquez_client.return_value = mock_marquez_client # Add task that will be marked as completed task_will_complete = TestFixtureDummyOperator( task_id=TASK_ID_COMPLETED, dag=dag ) completed_task_location = get_location(task_will_complete.dag.fileloc) # Add the dummy extractor to the list for the task above _DAG_EXTRACTORS[task_will_complete.__class__] = TestFixtureDummyExtractor # --- pretend run the DAG # Create DAG run and mark as running dagrun = dag.create_dagrun( run_id='test_marquez_dag_with_extractor_run_id', execution_date=DEFAULT_DATE, state=State.RUNNING) # --- Asserts that the job starting triggers metadata updates # Namespace created mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE, DAG_OWNER) # Datasets are updated mock_marquez_client.create_source.assert_called_with( 'dummy_source_name', 'DummySource', 'http://dummy/source/url' ) mock_marquez_client.create_dataset.assert_has_calls([ mock.call( dataset_name='extract_input1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_input1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id=None ), mock.call( dataset_name='extract_output1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_output1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id=None ) ]) # job is updated mock_marquez_client.create_job.assert_called_once_with( job_name=f"{dag_id}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=[{'namespace': 'default', 'name': 'extract_input1'}], output_dataset=[{'namespace': 'default', 'name': 'extract_output1'}], context=mock.ANY, description=DAG_DESCRIPTION, namespace_name=DAG_NAMESPACE, run_id=None ) assert mock_marquez_client.create_job.mock_calls[0].\ kwargs['context'].get('extract') == 'extract' # run is created mock_marquez_client.create_job_run.assert_called_once_with( job_name=f"{dag_id}.{TASK_ID_COMPLETED}", run_id=run_id, run_args=DAG_RUN_ARGS, nominal_start_time=mock.ANY, nominal_end_time=mock.ANY, namespace_name=DAG_NAMESPACE ) log.info("Marquez client calls when starting:") for call in mock_marquez_client.mock_calls: log.info(call) assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [ 'create_namespace', 'create_source', 'create_dataset', 'create_source', 'create_dataset', 'create_job', 'create_job_run' ] mock_marquez_client.reset_mock() # --- Pretend complete the task task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) dag.handle_callback(dagrun, success=True, session=session) # run is started mock_marquez_client.mark_job_run_as_started.assert_called_once_with( run_id, mock.ANY ) # --- Assert that the right marquez calls are done # job is updated before completion mock_marquez_client.create_job.assert_has_calls([ mock.call( namespace_name=DAG_NAMESPACE, job_name=f"{dag_id}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=[ {'namespace': 'default', 'name': 'extract_input1'} ], output_dataset=[ {'namespace': 'default', 'name': 'extract_output1'} ], context=mock.ANY, description=DAG_DESCRIPTION, run_id=run_id ) ]) assert mock_marquez_client.create_job.mock_calls[0].\ kwargs['context'].get('extract') == 'extract' mock_marquez_client.mark_job_run_as_completed.assert_called_once_with( run_id=run_id, at=mock.ANY ) # When a task run completes, the task outputs are also updated in order # to link a job version (=task version) to a dataset version. mock_marquez_client.create_dataset.assert_has_calls([ mock.call( dataset_name='extract_input1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_input1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id=None ), mock.call( dataset_name='extract_output1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_output1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id=run_id ) ]) log.info("Marquez client calls when completing:") for call in mock_marquez_client.mock_calls: log.info(call) assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [ 'create_namespace', 'create_source', 'create_dataset', 'create_source', 'create_dataset', 'create_job', 'mark_job_run_as_started', 'mark_job_run_as_completed' ] @mock.patch('marquez_airflow.DAG.new_run_id') @mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client') @provide_session def test_marquez_dag_with_extract_on_complete( mock_get_or_create_marquez_client, mock_uuid, clear_db_airflow_dags, session=None): # --- test setup dag_id = 'test_marquez_dag_with_extractor' dag = DAG( dag_id, schedule_interval='@daily', default_args=DAG_DEFAULT_ARGS, description=DAG_DESCRIPTION ) run_id = "my-test-uuid" mock_uuid.side_effect = [run_id] # Mock the marquez client method calls mock_marquez_client = mock.Mock() mock_get_or_create_marquez_client.return_value = mock_marquez_client # Add task that will be marked as completed task_will_complete = TestFixtureDummyOperator( task_id=TASK_ID_COMPLETED, dag=dag ) completed_task_location = get_location(task_will_complete.dag.fileloc) # Add the dummy extractor to the list for the task above _DAG_EXTRACTORS[task_will_complete.__class__] = \ TestFixtureDummyExtractorOnComplete # Create DAG run and mark as running dagrun = dag.create_dagrun( run_id='test_marquez_dag_with_extractor_run_id', execution_date=DEFAULT_DATE, state=State.RUNNING) # Namespace created mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE, DAG_OWNER) log.info("Marquez client calls when starting:") for call in mock_marquez_client.mock_calls: log.info(call) assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [ 'create_namespace' ] mock_marquez_client.reset_mock() # --- Pretend complete the task task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) dag.handle_callback(dagrun, success=True, session=session) # Datasets are updated mock_marquez_client.create_source.assert_called_with( 'dummy_source_name', 'DummySource', 'http://dummy/source/url' ) # Datasets get called twice, once to reenact the _begin_run_flow # and then again at _end_run_flow w/ the run id appended for # the output dataset mock_marquez_client.create_dataset.assert_has_calls([ mock.call( dataset_name='schema.extract_on_complete_input1', dataset_type=DatasetType.DB_TABLE, physical_name='schema.extract_on_complete_input1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=mock.ANY, run_id=None ), mock.call( dataset_name='extract_on_complete_output1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_on_complete_output1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id=None ), mock.call( dataset_name='schema.extract_on_complete_input1', dataset_type=DatasetType.DB_TABLE, physical_name='schema.extract_on_complete_input1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=mock.ANY, run_id=None ), mock.call( dataset_name='extract_on_complete_output1', dataset_type=DatasetType.DB_TABLE, physical_name='extract_on_complete_output1', source_name='dummy_source_name', namespace_name=DAG_NAMESPACE, fields=[], run_id='my-test-uuid' ) ]) # job is updated mock_marquez_client.create_job.assert_has_calls([ mock.call( job_name=f"{dag_id}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=[{'namespace': 'default', 'name': 'schema.extract_on_complete_input1'}], output_dataset=[{'namespace': 'default', 'name': 'extract_on_complete_output1'}], context=mock.ANY, description=DAG_DESCRIPTION, namespace_name=DAG_NAMESPACE, run_id=None ), mock.call( job_name=f"{dag_id}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=[{'namespace': 'default', 'name': 'schema.extract_on_complete_input1'}], output_dataset=[{'namespace': 'default', 'name': 'extract_on_complete_output1'}], context=mock.ANY, description=DAG_DESCRIPTION, namespace_name=DAG_NAMESPACE, run_id='my-test-uuid' ) ]) assert mock_marquez_client.create_job.mock_calls[0].\ kwargs['context'].get('extract_on_complete') == 'extract_on_complete' # run is created mock_marquez_client.create_job_run.assert_called_once_with( job_name=f"{dag_id}.{TASK_ID_COMPLETED}", run_id=run_id, run_args=DAG_RUN_ARGS, nominal_start_time=mock.ANY, nominal_end_time=mock.ANY, namespace_name=DAG_NAMESPACE ) # run is started mock_marquez_client.mark_job_run_as_started.assert_called_once_with( run_id, mock.ANY ) # --- Assert that the right marquez calls are done # job is updated before completion mock_marquez_client.create_job.assert_has_calls([ mock.call( namespace_name=DAG_NAMESPACE, job_name=f"{dag_id}.{TASK_ID_COMPLETED}", job_type=JobType.BATCH, location=completed_task_location, input_dataset=[ {'namespace': 'default',
noinspection PyPep8Naming class BinaryThresholdEncoder(BaseTransformer): """Implements binary encoding using a threshold function. Parameters ---------- threshold_enc : int or str Threshold for the binary encoder. Default 0. 'auto' will set threshold_enc to feature-wise median of the data passed to the fit function. greater_is_one : bool If True, above threshold is 1 and below 0. Vice versa if False. Attributes ---------- threshold_enc : int or str Threshold for the binary encoder. greater_is_one : bool If True, above threshold is 1 and below 0. Vice versa if False. """ def __init__(self, threshold_enc='auto', greater_is_one=True): if not (isinstance(threshold_enc, float) or isinstance(threshold_enc, int) or threshold_enc == 'auto'): raise ValueError("Argument threshold_enc should be a number or 'auto'.") self.threshold_enc = threshold_enc self.greater_is_one = greater_is_one def fit(self, X, y=None): """ When threshold_enc is 'auto', this method sets it to a vector containing the median of each column of X. Otherwise, it does nothing except print a warning in case threshold_enc is not in the range covered by X. Parameters ---------- X : np.ndarray, the input data to encode. y : np.ndarray, the targets data. Returns ------- self : BinaryThresholdEncoding """ if isinstance(self.threshold_enc, str): # noinspection PyTypeChecker self.threshold_enc = np.median(X, axis=0) # the median is feature-wise else: if self.threshold_enc < X.min() or self.threshold_enc > X.max(): print('WARNING: encoder threshold is outside data range') return self @preserve_type def transform(self, X): """Transforms any numpy array in a uint8 binary array of [0, 1]. Parameters ---------- X : np.ndarray or torch.Tensor the input data to encode. Returns ------- X_enc : np.ndarray or torch.Tensor uint8 containing only zeros and ones the encoded data. """ if isinstance(self.threshold_enc, str): raise RuntimeError("If threshold_enc is 'auto', fit must be called before transform.") if self.greater_is_one: X_enc = (X > self.threshold_enc) else: X_enc = (X < self.threshold_enc) return X_enc.astype(np.uint8) class MultiThresholdEncoder(BaseTransformer): """Implements binary encoding using multiple thresholds. Parameters ---------- thresholds : list, np.ndarray or str thresholds for the binary encoder. If a list or an array is passed, the thresholds will be used unmodified. If thresholds='linspace', the values will be evenly distributed along the data range. If thresholds='quantile', the values will be set to the quantiles corresponding to n_bins. If n_bins=4, the thresholds will be the 1st, 2nd and 3rd quartiles. columnwise: bool, whether to use different thresholds for each column or a common set of thresholds for everything. n_bins: int, if `thresholds` is 'linspace' or 'quantiles', `n_bins - 1` thresholds will be created? Attributes ---------- thresholds : np.ndarray, thresholds for the binary encoder. columnwise: bool, whether to use different thresholds for each column or a common set of thresholds for everything. n_bins: int, number of different values the encoding can take. A value is encoded into n_bins-1 bits. """ def __init__(self, thresholds='linspace', n_bins=8, columnwise=False): if isinstance(thresholds, list) or isinstance(thresholds, np.ndarray): thresholds = np.array(thresholds) if columnwise and thresholds.ndim != 2: raise ValueError(""" You set columnwise to True but thresholds is 1D. Pass a 2D array or set columnwise to False. """) self.n_bins = thresholds.shape[-1] + 1 elif thresholds in ['linspace', 'quantiles']: self.n_bins = n_bins else: raise ValueError("Argument thresholds must be a list, a numpy array or be in ['linspace', 'quantiles'].") self.thresholds = thresholds self.columnwise = columnwise def fit(self, X, y=None): """If thresholds is not None, this method doesn't do anything. If thresholds is `None`, computes `n_bins` thresholds equally spaced on the range of `X`. The range of `X` is determined column-wise but the number of bins is the same for all features. Parameters ---------- X : 2D np.ndarray y: 1D np.ndarray Returns ------- self : MultiThresholdEncoder """ def set_thresholds(array): if self.thresholds == 'linspace': return np.linspace(array.min(), array.max(), self.n_bins + 1)[1:-1] elif self.thresholds == 'quantiles': k = 1 / self.n_bins quantiles = [np.quantile(array, i*k, interpolation='midpoint') for i in range(1, self.n_bins)] return np.array(quantiles) if self.thresholds in ['linspace', 'quantiles']: if self.columnwise: thresholds = np.empty((X.shape[1], self.n_bins - 1), dtype='float32') for col in range(X.shape[1]): column = X[:, col] column_thresholds = set_thresholds(column) thresholds[col] = column_thresholds self.thresholds = thresholds else: self.thresholds = set_thresholds(X) return self @preserve_type def transform(self, X): """Transforms an array to a uint8 binary array of [0, 1]. The bins defined by the thresholds are not mutually exclusive, i.e a value x will activate all the bins corresponding to thresholds lesser than x. Parameters ---------- X : np.ndarray of size n_sample x n_features The input data to encode. Returns ------- X_enc : np.ndarray of uint8, of size n_samples x (n_features x n_bins) The encoded data. """ n_thres = self.thresholds.shape[-1] # we don't modify self.thresholds directly to make sure multiple calls will not cause a problem if self.thresholds.ndim == 1: thresholds = self.thresholds[:, None, None] elif self.thresholds.ndim == 2: thresholds = self.thresholds.T[:, None, :] else: raise RuntimeError("Unexpected threshold.ndim " + self.thresholds.ndim) X = np.repeat(X[None, ...], n_thres, axis=0) X = X > thresholds X_enc = np.concatenate([X[i] for i in range(thresholds.shape[0])], axis=-1).astype('uint8') return X_enc # noinspection PyPep8Naming class SequentialBaseTwoEncoder(BaseTransformer): """Implements a base 2 encoding. E.g. :math:`5` is written :math:`101` in base 2: :math:`1 * 2^2 + 0 * 2^1 + 1 * 2^0` = (1)*4 +(0)*2 +(1)*1, so the encoder will give 1111001. Parameters ---------- n_gray_levels : int, number of values that can be encoded. Must be a power of 2. Attributes ---------- n_gray_levels : int, number of values that can be encoded. Must be a power of 2. n_bits : int, number of bits needed to encode n_gray_levels values. offset : float, value to subtract to get the minimum to 0. scale : float, scaling factor to normalize the data. """ def __init__(self, n_gray_levels=16): assert type(n_gray_levels) == int, 'n_gray_levels must be an integer power of 2' assert ((n_gray_levels & (n_gray_levels - 1)) == 0) and n_gray_levels > 0, \ 'n_gray_levels must be an integer power of 2' self.n_gray_levels = n_gray_levels self.n_bits = np.uint8(np.log2(self.n_gray_levels)) self.n_bits_type = 8 self.indices_axis_2 = np.arange(self.n_bits_type - self.n_bits, self.n_bits_type) self.offset = None self.scale = None def fit(self, X, y=None): """Computes parameters for the normalization. Must be run only on the training set to avoid leaking information to the dev/test set. Parameters ---------- X : np.ndarray of uint [n_samples, n_features], the input data to encode. y : np.ndarray, the targets data. Returns ------- self : SequentialBaseTwoEncoder. """ X, is_tensor = _tensor_to_array(X) self.offset = np.min(X) self.scale = np.max(X - self.offset) return self def normalize(self, X): """Normalize the data in the right range before the integer casting. Parameters ---------- X : np.ndarray of uint [n_samples, n_features], the input data to normalize. Returns ------- X_norm : np.ndarray of uint8 [n_samples, n_features], normalized data. """ assert_msg = 'You have to call fit on the training data before calling transform.' assert self.offset is not None, assert_msg assert self.scale is not None, assert_msg # Data normalization X_norm = ((self.n_gray_levels - 1) * (X - self.offset)) / self.scale X_norm = np.round(X_norm) # Force the data is in the good range X_norm[X_norm < 0] = 0 X_norm[X_norm > (self.n_gray_levels - 1)] = (self.n_gray_levels - 1) # Cast to uint8 X_norm = X_norm.astype(np.uint8) return X_norm @preserve_type def transform(self, X): """Performs the encoding. Parameters ---------- X : 2D np.ndarray of uint [n_samples, n_features], input data to encode. Returns ------- X_enc: 2D np.ndarray of uint8 [n_samples, n_features*(n_gray_levels-1) encoded input data. """ n_samples, n_features = X.shape X = self.normalize(X) # Expand bits along auxiliary axis X_bits = np.unpackbits(np.expand_dims(X, axis=2), axis=2) # Repeat each bit value for the corresponding power of 2 X_enc = np.repeat(X_bits[:, :, self.indices_axis_2], 2 ** np.arange(self.n_bits)[::-1], axis=2) X_enc = X_enc.reshape((n_samples, n_features * (2 ** self.n_bits - 1))) return X_enc class NoEncoding(BaseTransformer): """Implements a No-Op Encoding class for API consistency.""" def transform(self, X): return X class NoDecoding(BaseTransformer): """Implements a No-Op Decoding class for API consistency.""" def transform(self, X): return X class SeparatedBitPlanEncoder(BaseTransformer): """ Implements an encoder for floating point input Parameters ---------- precision: int, optional The number of binary projections that are preformed to reconstruct an unsigned floating point projection. if the input contains both positive and negative values, the total number of projections is
"reversed" if eucl["axis_y"]["o_arrow"]["tip"] == 'none': return_string += '\\tikzset{yaxe style/.style={-}}\n' else: if eucl["axis_y"]["o_arrow"]["direction"]: return_string += '\\tikzset{yaxe style/.style={arrows={-%s[%s]}}}\n' % (o_arrow_name, o_arrow_options) else: return_string += '\\tikzset{yaxe style/.style={arrows={%s[%s]-}}}\n' % (o_arrow_name, o_arrow_options) return_string += "\\tkzDrawY[%s]\n" % options if return_string != '': return_string = '%Y AXIS\n' + return_string return return_string def tikzify_axis_clip(eucl): return_string = "%CLIP TO AXES\n" return_string += "\\tkzClip[space=\\m/\\xstep]\n" return_string += "\\tkzDefPoints{\\mxmin/\\mymin/cornerA,\\mxmax/\\mymin/cornerB,\\mxmax/\\mymax/cornerC,\\mxmin/\\mymax/cornerD}\n" return_string += "\\tkzClipPolygon(cornerA, cornerB, cornerC, cornerD)\n" return return_string def tikzify_grid_without_axis(eucl, grid): return_string = "\\tkzInit[xmin=\\xmin, ymin=\\ymin, xmax=\\xmax, ymax=\\ymax, xstep=\\xstep, ystep=\\ystep]\n" return_string += "\\tkzClip\n" if eucl["grid"]["show"]: return_string += "%GRID\n" if eucl["grid"]["line_opacity"] != DEFAULT_POINT_LINE_OPACITY: return_string += '\\begin{scope}[opacity=%s]\n' % eucl["grid"]["line_opacity"] return_string += grid if eucl["grid"]["line_opacity"] != DEFAULT_POINT_LINE_OPACITY: return_string += '\\end{scope}\n' return return_string def tikzify_all_point_declarations(eucl): return_string = '' mapped_points = ['pt_default'] num_points = len(eucl["points"]) while len(mapped_points) < num_points: for point in eucl["points"]: if point["id"] in mapped_points: continue if point["from"]["type"] == "free": mapped_points.append(point["id"]) return_string += "\\tkzDefPoint(%f, %f){%s}\n" % (eval(point["x"]), eval(point["y"]), point["id"]) elif point["from"]["type"] == "intersection_ll": if point["from"]["A"] in mapped_points and point["from"]["B"] in mapped_points: if point["from"]["C"] in mapped_points and point["from"]["D"] in mapped_points: mapped_points.append(point["id"]) return_string += "\\tkzInterLL(%s,%s)(%s,%s)" % (point["from"]["A"],point["from"]["B"],point["from"]["C"],point["from"]["D"]) return_string += "\\tkzGetPoint{%s}\n" % (point["id"]) elif point["from"]["type"] == "intersection_lc": if point["from"]["A"] in mapped_points and point["from"]["B"] in mapped_points: for pt in eucl["points"]: if pt["from"]["type"] == "intersection_lc" and pt["id"] != point["id"] and pt["from"]["lc_id"] == point["from"]["lc_id"]: circle = get_item_from_id(eucl, point["from"]["circle"], 'c') if circle["type"] == "two_point_circle": if circle["points"]["O"] in mapped_points and circle["points"]["A"] in mapped_points: O = circle["points"]["O"] A = circle["points"]["A"] mapped_points.append(point["id"]) mapped_points.append(pt["id"]) return_string += "\\tkzInterLC(%s,%s)(%s,%s)" % (point["from"]["A"],point["from"]["B"],O,A) if point["reverse_intersections"] == True: return_string += "\\tkzGetPoints{%s}{%s}\n" % (pt["id"], point["id"]) else: return_string += "\\tkzGetPoints{%s}{%s}\n" % (point["id"], pt["id"]) if circle["type"] == "circum_circle" or circle["type"] == "inscribed_circle": if circle["points"]["A"] in mapped_points and circle["points"]["B"] in mapped_points and\ circle["points"]["C"] in mapped_points: circle_type = 'circum' if circle["type"] == "circum_circle" else 'in' mapped_points.append(point["id"]) mapped_points.append(pt["id"]) return_string += "\\tkzDefCircle[%s](%s,%s,%s)\n" % (circle_type, circle["points"]["A"],circle["points"]["B"],circle["points"]["C"]) return_string += "\\tkzInterLC[R](%s,%s)(tkzPointResult, \\tkzLengthResult pt)" % (point["from"]["A"],point["from"]["B"]) return_string += "\\tkzGetPoints{%s}{%s}\n" % (pt["id"], point["id"]) elif point["from"]["type"] == "circle_midpoint": circle_id = point["from"]["circle"] circle = get_item_from_id(eucl, circle_id, 'c') if circle["type"] == "circum_circle": if circle["points"]["A"] in mapped_points and\ circle["points"]["B"] in mapped_points and\ circle["points"]["C"] in mapped_points: mapped_points.append(point["id"]) A = circle["points"]["A"] B = circle["points"]["B"] C = circle["points"]["C"] center_name = f"circum_{A}_{B}_{C}" return_string += "\\tkzDefCircle[circum](%s,%s,%s) \\tkzGetPoint{%s}\\tkzGetLength{%s}\n" % (A, B, C, point["id"], center_name) if circle["type"] == "inscribed_circle": if circle["points"]["A"] in mapped_points and\ circle["points"]["B"] in mapped_points and\ circle["points"]["C"] in mapped_points: mapped_points.append(point["id"]) A = circle["points"]["A"] B = circle["points"]["B"] C = circle["points"]["C"] center_name = f"in_{A}_{B}_{C}" return_string += "\\tkzDefCircle[in](%s,%s,%s) \\tkzGetPoint{%s}\\tkzGetLength{%s}\n" % (A, B, C, point["id"], center_name) elif point["from"]["type"] == "segment_midpoint": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] return_string += "\\tkzDefMidPoint(%s,%s) \\tkzGetPoint{%s}\n" % (A, B, point["id"]) elif point["from"]["type"] == "point_on_line": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] ratio = eval(point["from"]["ratio"]) return_string += "\\tkzDefPointBy[homothety=center %s ratio %s](%s) \\tkzGetPoint{%s}\n" % (A, ratio, B, point["id"]) elif point["from"]["type"] == "point_on_circle": circle_id = point["from"]["circle"] circle = get_item_from_id(eucl, circle_id, 'c') if circle["type"] == "circum_circle": if circle["points"]["A"] in mapped_points and\ circle["points"]["B"] in mapped_points and\ circle["points"]["C"] in mapped_points: mapped_points.append(point["id"]) A = circle["points"]["A"] B = circle["points"]["B"] C = circle["points"]["C"] angle = point["from"]["angle"] name = f"in_{A}_{B}_{C}" return_string += "\\tkzDefCircle[circum](%s,%s,%s)\\tkzDefPointOnCircle[angle=%s, center=tkzPointResult, radius=\\tkzLengthResult pt] \\tkzGetPoint{%s}\\tkzGetLength{%s}\n" % (A, B, C, angle, point["id"], name) if circle["type"] == "inscribed_circle": if circle["points"]["A"] in mapped_points and\ circle["points"]["B"] in mapped_points and\ circle["points"]["C"] in mapped_points: mapped_points.append(point["id"]) A = circle["points"]["A"] B = circle["points"]["B"] C = circle["points"]["C"] angle = point["from"]["angle"] return_string += "\\tkzDefCircle[in](%s,%s,%s)\\tkzDefPointOnCircle[angle=%s, center=tkzPointResult, radius=\\tkzLengthResult pt] \\tkzGetPoint{%s}\n" % (A, B, C, angle, point["id"]) elif point["from"]["type"] == "projection_point": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points and\ point["from"]["P"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] P = point["from"]["P"] return_string += "\\tkzDefPointBy[projection=onto %s--%s](%s)\\tkzGetPoint{%s}\n" % (A, B, P, point["id"]) elif point["from"]["type"] == "bisector_point": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points and\ point["from"]["C"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] C = point["from"]["C"] return_string += "\\tkzDefLine[bisector](%s,%s,%s)\\tkzGetPoint{%s}\n" % (A, B, C, point["id"]) elif point["from"]["type"] == "translation_point": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points and\ point["from"]["P"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] P = point["from"]["P"] return_string += "\\tkzDefPointWith[colinear=at %s](%s,%s)\\tkzGetPoint{%s}\n" % (P, A, B, point["id"]) elif point["from"]["type"] == "orthogonal_point": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] return_string += "\\tkzDefPointWith[orthogonal](%s,%s)\\tkzGetPoint{%s}\n" % (A, B, point["id"]) elif point["from"]["type"] == "rotation": if point["from"]["A"] in mapped_points and\ point["from"]["B"] in mapped_points: mapped_points.append(point["id"]) A = point["from"]["A"] B = point["from"]["B"] angle = eval(point["from"]["angle"]) return_string += "\\tkzDefPointBy[rotation=center %s angle %s](%s)\\tkzGetPoint{%s}\n" % (A, angle, B, point["id"]) if return_string != '': return_string = '%POINT/COORDINATE DEFINITIONS\n' + return_string return return_string def tikzify_polygons_and_linestrings(eucl): return_string = '' for polygon in eucl["polygons"]: if polygon["show"] and polygon["id"] != 'pol_default': common_options = '' if polygon["line_width"] != DEFAULT_SEGMENT_LINE_WIDTH: common_options += "line width=%s" % polygon["line_width"] if polygon["line_stroke"] != DEFAULT_SEGMENT_LINE_STROKE: if common_options != "": common_options += ", " if polygon["line_stroke"] == "custom": common_options += "dash pattern=%s" % line_stroke_custom_to_tkz(polygon["line_stroke_custom"]) else: common_options += str(polygon["line_stroke"]) if polygon["line_colour_name"] != DEFAULT_SEGMENT_LINE_COLOUR_NAME or\ polygon["line_strength"] != DEFAULT_SEGMENT_LINE_STRENGTH: if common_options != "": common_options += ", " common_options += "draw=%s" % polygon["line_colour_name"] if polygon["line_strength"] != DEFAULT_SEGMENT_LINE_STRENGTH: common_options += "!%s" % polygon["line_strength"] if polygon["pattern"]["type"] == 'solid': if common_options != "": common_options += ", " common_options += "fill=%s" % polygon["fill_colour_name"] if polygon["fill_strength"] != DEFAULT_POINT_FILL_STRENGTH: common_options += "!%s" % polygon["fill_strength"] if polygon["decoration"]["type"] != DEFAULT_DECORATOR_TYPE: if common_options != "": common_options += ", " if polygon["decoration"]["type"] == 'text along path': common_options += "decoration={%s, text={%s}}, decorate\n" % (polygon["decoration"]["type"], polygon["decoration"]["text"]) else: common_options += "decoration={%s, amplitude=%s, segment length=%s}, decorate\n" % (polygon["decoration"]["type"], polygon["decoration"]["amplitude"], polygon["decoration"]["wave_length"]) if polygon["fill_opacity"] != DEFAULT_POINT_FILL_OPACITY: if common_options != '': common_options += ', ' common_options += 'fill opacity=%s' % polygon["fill_opacity"] if polygon["line_opacity"] != DEFAULT_POINT_LINE_OPACITY: if common_options != '': common_options += ', ' common_options += 'draw opacity=%s' % polygon["line_opacity"] if not polygon["pattern"]["type"] in ['none', 'solid']: if polygon["fill_colour_name"] != DEFAULT_POINT_FILL_COLOUR_NAME or\ polygon["fill_strength"] != DEFAULT_POINT_FILL_STRENGTH: if common_options != "": common_options += ", " common_options += "pattern color=%s" % polygon["fill_colour_name"] if polygon["fill_strength"] != DEFAULT_POINT_FILL_STRENGTH: common_options += "!%s" % polygon["fill_strength"] if common_options != '': common_options += ', ' if not polygon["pattern"]["type"] in\ ['Lines', 'Hatch', 'Dots', 'Fivepointed stars', 'Sixpointed stars']: common_options += 'pattern=%s' % polygon["pattern"]["type"] else: pattern_options = '' if polygon["pattern"]["rotation"] != DEFAULT_PATTERN_ROTATION: pattern_options += 'angle=%s' % polygon["pattern"]["rotation"] if polygon["pattern"]["distance"] != DEFAULT_PATTERN_DISTANCE: if pattern_options != '': pattern_options += ', ' pattern_options += 'distance=%s' % polygon["pattern"]["distance"] if polygon["pattern"]["type"] in ['Fivepointed stars', 'Sixpointed stars']: pattern_options += ' mm' if polygon["pattern"]["xshift"] != DEFAULT_PATTERN_XSHIFT: if pattern_options != '': pattern_options += ', ' pattern_options += 'xshift=%s' % polygon["pattern"]["xshift"] if polygon["pattern"]["yshift"] != DEFAULT_PATTERN_YSHIFT: if pattern_options != '': pattern_options += ', ' pattern_options += 'yshift=%s' % polygon["pattern"]["yshift"] if polygon["pattern"]["type"] in ['Dots', 'Fivepointed stars', 'Sixpointed stars']: if polygon["pattern"]["size"] != DEFAULT_PATTERN_SIZE: if pattern_options != '': pattern_options += ', ' pattern_options += 'radius=%s mm' % polygon["pattern"]["size"] else: if polygon["pattern"]["size"] != DEFAULT_PATTERN_SIZE: if pattern_options != '': pattern_options += ', ' pattern_options += 'line width=%s' % polygon["pattern"]["size"] if polygon["pattern"]["type"] == 'Fivepointed stars': if pattern_options != '': pattern_options += ', ' pattern_options += 'points=5' if polygon["pattern"]["type"] == 'Sixpointed stars': if pattern_options != '': pattern_options += ', ' pattern_options += 'points=6' if polygon["pattern"]["type"] in ['Sixpointed stars', 'Fivepointed stars']: common_options += 'pattern={Stars[%s]}' % pattern_options else: common_options += 'pattern={%s[%s]}' % (polygon["pattern"]["type"], pattern_options) if polygon["type"] == 'polygon': options = common_options if polygon["curve"]["strategy"] == 'smooth': if options != '': options = 'use Hobby shortcut, ' + options else: options = 'use Hobby shortcut' points = "([closed,]%s)" % ((')..(').join(polygon["points"])) return_string += "\\draw[%s] %s;\n" % (options, points) elif polygon["curve"]["strategy"] == 'nothing': if polygon["curve"]["corner_radius"] != 0: if options != '': options += ', ' options += 'rounded corners=%s' % polygon["curve"]["corner_radius"] points = "%s" % ((')--(').join(polygon["points"])) return_string += "\\draw[%s] (%s)--cycle;\n" % (options, points) elif polygon["curve"]["strategy"] == 'segment_in_out': if polygon["curve"]["corner_radius"] != 0: if options != '': options += ', ' options += 'rounded corners=%s' % polygon["curve"]["corner_radius"] in_out_option = 'out=%s, in=%s' % (polygon["curve"]["out_angle"], polygon["curve"]["in_angle"]) if polygon["curve"]["loop"]: in_out_option += ", loop, min distance=%s" % polygon["curve"]["loop_size"] points = "%s" % ((')--(').join(polygon["points"][1:])) return_string += "\\draw[%s] (%s) to[%s] (%s)--cycle;\n" % (common_options,polygon["points"][0], in_out_option, points) elif polygon["curve"]["strategy"] == 'segment_bend_left': if polygon["curve"]["corner_radius"] != 0: if options != '': options += ',
<reponame>unmonoqueteclea/python # -*- coding: utf-8 -*- # # Copyright 2014-2021 BigML # # 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 KIn545D, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Common auxiliary constants, functions and class for all resources """ import time import os import datetime import json from xml.dom import minidom import bigml.constants as c from bigml.util import get_exponential_wait, get_status, is_status_final, \ save, save_json from bigml.util import DFT_STORAGE from bigml.bigmlconnection import HTTP_OK, HTTP_ACCEPTED, HTTP_CREATED, \ LOGGER, DOWNLOAD_DIR from bigml.constants import WAITING, QUEUED, STARTED, IN_PROGRESS, \ SUMMARIZED, FINISHED, UPLOADING, FAULTY, UNKNOWN, RUNNABLE # Minimum query string to get model fields TINY_RESOURCE = "full=false" # Resource types that are composed by other resources COMPOSED_RESOURCES = ["ensemble", "fusion"] LIST_LAST = "limit=1;full=yes;tags=%s" PMML_QS = "pmml=yes" def get_resource_type(resource): """Returns the associated resource type for a resource """ if isinstance(resource, dict) and 'resource' in resource: resource = resource['resource'] if not isinstance(resource, str): raise ValueError("Failed to parse a resource string or structure.") for resource_type, resource_re in list(c.RESOURCE_RE.items()): if resource_re.match(resource): return resource_type return None def get_resource(resource_type, resource): """Returns a resource/id. """ if isinstance(resource, dict) and 'resource' in resource: resource = resource['resource'] if isinstance(resource, str): if c.RESOURCE_RE[resource_type].match(resource): return resource found_type = get_resource_type(resource) if found_type is not None and \ resource_type != get_resource_type(resource): raise ValueError( "The resource %s has not the expected type:" " %s" % ( resource, resource_type)) raise ValueError("%s is not a valid resource ID." % resource) def resource_is_ready(resource): """Checks a fully fledged resource structure and returns True if finished. """ if not isinstance(resource, dict): raise Exception("No valid resource structure found") # full resources if 'object' in resource: if 'error' not in resource: raise Exception("No valid resource structure found") if resource['error'] is not None: raise Exception(resource['error']['status']['message']) return (resource['code'] in [HTTP_OK, HTTP_ACCEPTED] and get_status(resource)['code'] == c.FINISHED) # only API response contents return get_status(resource)['code'] == c.FINISHED def check_resource_type(resource, expected_resource, message=None): """Checks the resource type. """ if isinstance(expected_resource, str): expected_resources = [expected_resource] else: expected_resources = expected_resource if isinstance(resource, dict) and 'id' in resource: resource = resource['id'] resource_type = get_resource_type(resource) if resource_type not in expected_resources: raise Exception("%s\nFound %s." % (message, resource_type)) def get_source_id(source): """Returns a source/id. """ return get_resource(c.SOURCE_PATH, source) def get_dataset_id(dataset): """Returns a dataset/id. """ return get_resource(c.DATASET_PATH, dataset) def get_model_id(model): """Returns a model/id. """ return get_resource(c.MODEL_PATH, model) def get_prediction_id(prediction): """Returns a prediction/id. """ return get_resource(c.PREDICTION_PATH, prediction) def get_evaluation_id(evaluation): """Returns an evaluation/id. """ return get_resource(c.EVALUATION_PATH, evaluation) def get_ensemble_id(ensemble): """Returns an ensemble/id. """ return get_resource(c.ENSEMBLE_PATH, ensemble) def get_batch_prediction_id(batch_prediction): """Returns a batchprediction/id. """ return get_resource(c.BATCH_PREDICTION_PATH, batch_prediction) def get_cluster_id(cluster): """Returns a cluster/id. """ return get_resource(c.CLUSTER_PATH, cluster) def get_centroid_id(centroid): """Returns a centroid/id. """ return get_resource(c.CENTROID_PATH, centroid) def get_batch_centroid_id(batch_centroid): """Returns a batchcentroid/id. """ return get_resource(c.BATCH_CENTROID_PATH, batch_centroid) def get_anomaly_id(anomaly): """Returns an anomaly/id. """ return get_resource(c.ANOMALY_PATH, anomaly) def get_anomaly_score_id(anomaly_score): """Returns an anomalyscore/id. """ return get_resource(c.ANOMALY_SCORE_PATH, anomaly_score) def get_batch_anomaly_score_id(batch_anomaly_score): """Returns a batchanomalyscore/id. """ return get_resource(c.BATCH_ANOMALY_SCORE_PATH, batch_anomaly_score) def get_project_id(project): """Returns a project/id. """ return get_resource(c.PROJECT_PATH, project) def get_sample_id(sample): """Returns a sample/id. """ return get_resource(c.SAMPLE_PATH, sample) def get_correlation_id(correlation): """Returns a correlation/id. """ return get_resource(c.CORRELATION_PATH, correlation) def get_statistical_test_id(statistical_test): """Returns a statisticaltest/id. """ return get_resource(c.STATISTICAL_TEST_PATH, statistical_test) def get_logistic_regression_id(logistic_regression): """Returns a logisticregression/id. """ return get_resource(c.LOGISTIC_REGRESSION_PATH, logistic_regression) def get_association_id(association): """Returns an association/id. """ return get_resource(c.ASSOCIATION_PATH, association) def get_association_set_id(association_set): """Returns an associationset/id. """ return get_resource(c.ASSOCIATION_SET_PATH, association_set) def get_configuration_id(configuration): """Returns a configuration/id. """ return get_resource(c.CONFIGURATION_PATH, configuration) def get_topic_model_id(topic_model): """Returns a topicmodel/id. """ return get_resource(c.TOPIC_MODEL_PATH, topic_model) def get_topic_distribution_id(topic_distribution): """Returns a topicdistribution/id. """ return get_resource(c.TOPIC_DISTRIBUTION_PATH, topic_distribution) def get_batch_topic_distribution_id(batch_topic_distribution): """Returns a batchtopicdistribution/id. """ return get_resource(c.BATCH_TOPIC_DISTRIBUTION_PATH, batch_topic_distribution) def get_time_series_id(time_series): """Returns a timeseries/id. """ return get_resource(c.TIME_SERIES_PATH, time_series) def get_forecast_id(forecast): """Returns a forecast/id. """ return get_resource(c.FORECAST_PATH, forecast) def get_fusion_id(fusion): """Returns an fusion/id. """ return get_resource(c.FUSION_PATH, fusion) def get_optiml_id(optiml): """Returns an optiml/id. """ return get_resource(c.OPTIML_PATH, optiml) def get_deepnet_id(deepnet): """Returns a deepnet/id. """ return get_resource(c.DEEPNET_PATH, deepnet) def get_pca_id(pca): """Returns a PCA/id. """ return get_resource(c.PCA_PATH, pca) def get_projection_id(projection): """Returns a projection/id. """ return get_resource(c.PROJECTION_PATH, projection) def get_batch_projection_id(batch_projection): """Returns a batchprojection/id. """ return get_resource(c.BATCH_PROJECTION_PATH, batch_projection) def get_linear_regression_id(linear_regression): """Returns a linearregression/id. """ return get_resource(c.LINEAR_REGRESSION_PATH, linear_regression) def get_script_id(script): """Returns a script/id. """ return get_resource(c.SCRIPT_PATH, script) def get_execution_id(execution): """Returns a execution/id. """ return get_resource(c.EXECUTION_PATH, execution) def get_library_id(library): """Returns a library/id. """ return get_resource(c.LIBRARY_PATH, library) def get_external_connector_id(library): """Returns a externalconnector/id. """ return get_resource(c.EXTERNAL_CONNECTOR_PATH, library) def get_resource_id(resource): """Returns the resource id if it falls in one of the registered types """ if isinstance(resource, dict) and 'resource' in resource: return resource['resource'] if isinstance(resource, str) and any( resource_re.match(resource) for _, resource_re in list(c.RESOURCE_RE.items())): return resource return def exception_on_error(resource): """Raises exception if resource has error """ if resource.get('error') is not None: raise Exception(resource.get('error', \ {}).get('status', {}).get('message')) if resource.get('object', resource).get('status', {}).get('error') \ is not None: status = resource.get('object', resource).get( \ 'status', {}) raise Exception(status.get('cause', status).get('message')) def check_resource(resource, get_method=None, query_string='', wait_time=1, retries=None, raise_on_error=False, max_elapsed_estimate=float('inf'), api=None, debug=False): """Waits until a resource is finished. Given a resource and its corresponding get_method (if absent, the generic get_resource is used), it calls the get_method on the resource with the given query_string and waits with sleeping intervals of wait_time until the resource is in a final state (either FINISHED or FAULTY. The number of retries can be limited using the retries parameter. """ resource_id = get_resource_id(resource) # ephemeral predictions if isinstance(resource, dict) and resource.get("resource") is None: return resource if resource_id is None: raise ValueError("Failed to extract a valid resource id to check.") if wait_time <= 0: raise ValueError("The time to wait needs to be positive.") debug = debug or (api is not None and (api.debug or api.short_debug)) if debug: print("Checking resource: %s" % resource_id) kwargs = {'query_string': query_string} if get_method is None and hasattr(api, 'get_resource'): get_method = api.get_resource elif get_method is None: raise ValueError("You must supply either the get_method or the api" " connection info to retrieve the resource") if isinstance(resource, str): if debug: print("Getting resource %s" % resource_id) resource = get_method(resource_id, **kwargs) counter = 0 elapsed = 0 while retries is None or counter < retries: counter += 1 status = get_status(resource) code = status['code'] if debug: print("The resource has status code: %s" % code) if code == c.FINISHED: if counter > 1: if debug: print("Getting resource %s with args %s" % (resource_id, kwargs)) # final get call to retrieve complete resource resource = get_method(resource, **kwargs) if raise_on_error: exception_on_error(resource) return resource if code == c.FAULTY: if raise_on_error: exception_on_error(resource) return resource _wait_time = get_exponential_wait(wait_time, counter) _max_wait = max_elapsed_estimate - _wait_time _wait_time = min(_max_wait, _wait_time) if _wait_time <= 0: # when the max_expected_elapsed time is met, we still wait for # the resource to be finished but we restart all counters and # the exponentially growing time is initialized _wait_time = wait_time counter = 0 elapsed = 0 if debug: print("Sleeping %s" % _wait_time) time.sleep(_wait_time) elapsed += _wait_time # retries for the finished status use a query string that gets the # minimal available resource if kwargs.get('query_string') is not None: tiny_kwargs = {'query_string': c.TINY_RESOURCE} else: tiny_kwargs = {} if debug: print("Getting only status for resource %s" % resource_id) resource = get_method(resource, **tiny_kwargs) if raise_on_error: exception_on_error(resource) return resource def http_ok(resource): """Checking the validity of the http return code """ if 'code' in resource: return resource['code'] in [HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED] class ResourceHandlerMixin(): """This class is used by the BigML class as a mixin that provides the get method for all kind of resources and auxiliar utilities to check their status. It should not be instantiated independently. """ def get_resource(self, resource, **kwargs): """Retrieves a remote resource. The resource parameter should be a string containing the resource id or the dict returned by the corresponding create method. As each resource is an evolving object that is processed until it reaches the FINISHED or FAULTY state, thet function will return a dict that encloses the resource values and state info available at the time it is called. """ resource_type = get_resource_type(resource) if resource_type is None: raise ValueError("A resource id or structure is needed.") resource_id = get_resource_id(resource) if resource_id: return self._get("%s%s" % (self.url, resource_id), **kwargs) def update_resource(self, resource, changes, **kwargs): """Updates a remote resource. The resource parameter
If ``n`` is an integer rather than a multi-index, then the total degree is used in that case as well. EXAMPLES:: sage: A.<a,b,c> = GradedCommutativeAlgebra(QQ, degrees=((1,0), (0, 1), (0,2))) sage: B = A.cdg_algebra(differential={a: c}) sage: B.cohomology_raw((0,2)) Vector space quotient V/W of dimension 0 over Rational Field where V: Vector space of degree 1 and dimension 1 over Rational Field Basis matrix: [1] W: Vector space of degree 1 and dimension 1 over Rational Field Basis matrix: [1] sage: B.cohomology_raw(1) Vector space quotient V/W of dimension 1 over Rational Field where V: Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [1 0] W: Vector space of degree 2 and dimension 0 over Rational Field Basis matrix: [] """ return self._differential.cohomology_raw(n, total) def cohomology(self, n, total=False): """ The ``n``-th cohomology group of the algebra. This is a vector space over the base ring, defined as the quotient cocycles/coboundaries. The elements of the quotient are lifted to the vector space of cocycles, and this is described in terms of those lifts. Compare to :meth:`cohomology_raw`. INPUT: - ``n`` -- degree - ``total`` -- (default: ``False``) if ``True``, return the cohomology in total degree ``n`` If ``n`` is an integer rather than a multi-index, then the total degree is used in that case as well. EXAMPLES:: sage: A.<a,b,c> = GradedCommutativeAlgebra(QQ, degrees=((1,0), (0, 1), (0,2))) sage: B = A.cdg_algebra(differential={a: c}) sage: B.cohomology((0,2)) Free module generated by {} over Rational Field sage: B.cohomology(1) Free module generated by {[b]} over Rational Field """ return self._differential.cohomology(n, total) class Element(GCAlgebra_multigraded.Element, DifferentialGCAlgebra.Element): """ Element class of a commutative differential multi-graded algebra. """ ################################################ # Main entry point def GradedCommutativeAlgebra(ring, names=None, degrees=None, relations=None): r""" A graded commutative algebra. INPUT: There are two ways to call this. The first way defines a free graded commutative algebra: - ``ring`` -- the base field over which to work - ``names`` -- names of the generators. You may also use Sage's ``A.<x,y,...> = ...`` syntax to define the names. If no names are specified, the generators are named ``x0``, ``x1``, ... - ``degrees`` -- degrees of the generators; if this is omitted, the degree of each generator is 1, and if both ``names`` and ``degrees`` are omitted, an error is raised Once such an algebra has been defined, one can use its associated methods to take a quotient, impose a differential, etc. See the examples below. The second way takes a graded commutative algebra and imposes relations: - ``ring`` -- a graded commutative algebra - ``relations`` -- a list or tuple of elements of ``ring`` EXAMPLES: Defining a graded commutative algebra:: sage: GradedCommutativeAlgebra(QQ, 'x, y, z') Graded Commutative Algebra with generators ('x', 'y', 'z') in degrees (1, 1, 1) over Rational Field sage: GradedCommutativeAlgebra(QQ, degrees=(2, 3, 4)) Graded Commutative Algebra with generators ('x0', 'x1', 'x2') in degrees (2, 3, 4) over Rational Field As usual in Sage, the ``A.<...>`` notation defines both the algebra and the generator names:: sage: A.<x,y,z> = GradedCommutativeAlgebra(QQ, degrees=(1, 2, 1)) sage: x^2 0 sage: z*x # Odd classes anticommute. -x*z sage: z*y # y is central since it is in degree 2. y*z sage: (x*y**3*z).degree() 8 sage: A.basis(3) # basis of homogeneous degree 3 elements [y*z, x*y] Defining a quotient:: sage: I = A.ideal(x*y) sage: AQ = A.quotient(I) sage: AQ Graded Commutative Algebra with generators ('x', 'y', 'z') in degrees (1, 2, 1) with relations [x*y] over Rational Field sage: AQ.basis(3) [y*z] Note that ``AQ`` has no specified differential. This is reflected in its print representation: ``AQ`` is described as a "graded commutative algebra" -- the word "differential" is missing. Also, it has no default ``differential``:: sage: AQ.differential() Traceback (most recent call last): ... TypeError: differential() takes exactly 2 arguments (1 given) Now we add a differential to ``AQ``:: sage: B = AQ.cdg_algebra({y:y*z}) sage: B Commutative Differential Graded Algebra with generators ('x', 'y', 'z') in degrees (1, 2, 1) with relations [x*y] over Rational Field with differential: x --> 0 y --> y*z z --> 0 sage: B.differential() Differential of Commutative Differential Graded Algebra with generators ('x', 'y', 'z') in degrees (1, 2, 1) with relations [x*y] over Rational Field Defn: x --> 0 y --> y*z z --> 0 sage: B.cohomology(1) Free module generated by {[z], [x]} over Rational Field sage: B.cohomology(2) Free module generated by {[x*z]} over Rational Field We compute algebra generators for cohomology in a range of degrees. This cohomology algebra appears to be finitely generated:: sage: B.cohomology_generators(15) {1: [z, x]} We can construct multi-graded rings as well. We work in characteristic 2 for a change, so the algebras here are honestly commutative:: sage: C.<a,b,c,d> = GradedCommutativeAlgebra(GF(2), degrees=((1,0), (1,1), (0,2), (0,3))) sage: D = C.cdg_algebra(differential={a:c, b:d}) sage: D Commutative Differential Graded Algebra with generators ('a', 'b', 'c', 'd') in degrees ((1, 0), (1, 1), (0, 2), (0, 3)) over Finite Field of size 2 with differential: a --> c b --> d c --> 0 d --> 0 We can examine ``D`` using both total degrees and multidegrees. Use tuples, lists, vectors, or elements of additive abelian groups to specify degrees:: sage: D.basis(3) # basis in total degree 3 [d, a*c, a*b, a^3] sage: D.basis((1,2)) # basis in degree (1,2) [a*c] sage: D.basis([1,2]) [a*c] sage: D.basis(vector([1,2])) [a*c] sage: G = AdditiveAbelianGroup([0,0]); G Additive abelian group isomorphic to Z + Z sage: D.basis(G(vector([1,2]))) [a*c] At this point, ``a``, for example, is an element of ``C``. We can redefine it so that it is instead an element of ``D`` in several ways, for instance using :meth:`gens` method:: sage: a, b, c, d = D.gens() sage: a.differential() c Or the :meth:`inject_variables` method:: sage: D.inject_variables() Defining a, b, c, d sage: (a*b).differential() b*c + a*d sage: (a*b*c**2).degree() (2, 5) Degrees are returned as elements of additive abelian groups:: sage: (a*b*c**2).degree() in G True sage: (a*b*c**2).degree(total=True) # total degree 7 sage: D.cohomology(4) Free module generated by {[b^2], [a^4]} over Finite Field of size 2 sage: D.cohomology((2,2)) Free module generated by {[b^2]} over Finite Field of size 2 TESTS: We need to specify either name or degrees:: sage: GradedCommutativeAlgebra(QQ) Traceback (most recent call last): ... ValueError: You must specify names or degrees """ multi = False if degrees: try: for d in degrees: _ = list(d) # If the previous line doesn't raise an error, looks multi-graded. multi = True except TypeError: pass if multi: return GCAlgebra_multigraded(ring, names=names, degrees=degrees) else: return GCAlgebra(ring, names=names, degrees=degrees) ################################################ # Miscellaneous utility classes and functions class CohomologyClass(SageObject): """ A class for representing cohomology classes. This just has ``_repr_`` and ``_latex_`` methods which put brackets around the object's name. EXAMPLES:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: CohomologyClass(3) [3] sage: A.<x,y,z,t> = GradedCommutativeAlgebra(QQ, degrees = (2,3,3,1)) sage: CohomologyClass(x^2+2*y*z) [2*y*z + x^2] """ def __init__(self, x): """ EXAMPLES:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: CohomologyClass(x-2) [x - 2] """ self._x = x def __hash__(self): r""" TESTS:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: hash(CohomologyClass(sin)) == hash(sin) True """ return hash(self._x) def _repr_(self): """ EXAMPLES:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: CohomologyClass(sin) [sin] """ return '[{}]'.format(self._x) def _latex_(self): r""" EXAMPLES:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: latex(CohomologyClass(sin)) \left[ \sin \right] sage: latex(CohomologyClass(x^2)) \left[ x^{2} \right] """ from sage.misc.latex import latex return '\\left[ {} \\right]'.format(latex(self._x)) def representative(self): """ Return the representative of ``self``. EXAMPLES:: sage: from sage.algebras.commutative_dga import CohomologyClass sage: x = CohomologyClass(sin) sage: x.representative() == sin True """ return self._x def exterior_algebra_basis(n, degrees): """ Basis of an exterior algebra in degree ``n``, where the generators are in degrees ``degrees``. INPUT: - ``n`` - integer - ``degrees`` - iterable of integers Return list of lists, each list representing exponents for the corresponding generators. (So each list consists of 0's and 1's.) EXAMPLES:: sage: from sage.algebras.commutative_dga import exterior_algebra_basis sage: exterior_algebra_basis(1, (1,3,1)) [[0, 0, 1], [1, 0, 0]] sage: exterior_algebra_basis(4, (1,3,1)) [[0, 1, 1], [1, 1, 0]]
+= "neighbor {} route-map {} in \n".format(kwargs['peer_grp_name'], kwargs['routemap']) command += "exit\n" command += "exit\n" st.config(dut, command, type='vtysh') elif cli_type == 'klish': cmd = "peer-group {} \n".format(kwargs['peer_grp_name']) cmd += "remote-as {} \n".format(kwargs['remote_asn']) if 'keep_alive' in kwargs and 'hold' in kwargs: cmd += "timers {} {} \n".format(kwargs['keep_alive'], kwargs['hold']) if 'password' in kwargs: cmd += 'password {} \n'.format(kwargs['password']) if 'activate' in kwargs: cmd += "address-family {} unicast \n".format(af) cmd += "activate \n" if 'redistribute' in kwargs: redis_li = list(kwargs['redistribute']) if isinstance(kwargs['redistribute'], list) else [kwargs['redistribute']] for each_ in redis_li: cmd += "redistribute {} \n".format(each_) if 'routemap' in kwargs: if 'routemap_dir' in kwargs: cmd += "route-map {} {} \n".format(kwargs['routemap'], kwargs['routemap_dir']) else: cmd += "route-map {} in \n".format(kwargs['routemap']) cmd += "exit \n" for each_neigh in neigh_ip_li: cmd += 'exit \n' cmd += 'neighbor {} \n'.format(each_neigh) cmd += 'peer-group {} \n'.format(kwargs['peer_grp_name']) cmd += 'exit \n' cmd += 'exit \n' st.config(dut, cmd, type='klish') else: st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type)) return False return True def verify_bgp_summary(dut, family='ipv4', shell="sonic", **kwargs): """ :param dut: :param family: :param shell: :param kwargs: :return: """ if shell not in ["vtysh", "klish", "rest-patch", "rest-put"]: if 'vrf' in kwargs and shell=='sonic': vrf = kwargs.pop('vrf') cmd = "show bgp vrf {} {} summary".format(vrf,family.lower()) else: cmd = "show bgp {} summary".format(family.lower()) if not st.is_feature_supported("show-bgp-summary-click-command", dut): output = st.show(dut,cmd, type="vtysh") else: output = st.show(dut,cmd) cli_type = get_show_cli_type(dut, **kwargs) if shell in ["vtysh", "klish", "rest-patch", "rest-put"]: vrf = kwargs.pop('vrf') if 'vrf' in kwargs else "default" if family.lower() == 'ipv4': output = show_bgp_ipv4_summary_vtysh(dut, vrf=vrf, cli_type=cli_type) elif family.lower() == 'ipv6': output = show_bgp_ipv6_summary_vtysh(dut, vrf=vrf, cli_type=cli_type) else: st.log("Invalid family {} or shell {}".format(family, cli_type)) return False st.debug(output) # Specifically checking neighbor state if 'neighbor' in kwargs and 'state' in kwargs: neigh_li = list(kwargs['neighbor']) if isinstance(kwargs['neighbor'], list) else [kwargs['neighbor']] for each_neigh in neigh_li: #For dynamic neighbor, removing *, as it is not displayed in klish if shell == 'klish' or cli_type =='klish': st.log('For dynamic neighbor, removing *, as it is not displayed in klish') each_neigh = each_neigh.lstrip('*') match = {'neighbor': each_neigh} try: entries = filter_and_select(output, None, match)[0] except Exception as e: st.error(e) st.log("Neighbor {} given state {}, matching with {} ".format(each_neigh, kwargs['state'], "Not Found")) return False if entries['state']: if kwargs['state'] == 'Established': if entries['state'].isdigit() or entries['state'] == "ESTABLISHED": st.log("Neighbor {} given state {}, matching with {} ".format(each_neigh, kwargs['state'], entries['state'])) else: st.error( "Neighbor {} given state {}, matching with {} ".format(each_neigh, kwargs['state'], entries['state'])) return False elif kwargs['state'] == 'Active': if entries['state'] == "Active" or entries['state'] == "ACTIVE": st.log("Neighbor {} given state {}, matching with {} ".format(each_neigh, kwargs['state'], entries['state'])) else: st.error( "Neighbor {} given state {}, matching with {} ".format(each_neigh, kwargs['state'], entries['state'])) return False for each in kwargs.keys(): if 'state' not in each and 'neighbor' not in each: match = {each: kwargs[each]} entries = filter_and_select(output, None, match) if not entries: st.log("{} and {} is not match ".format(each, kwargs[each])) return False return True def verify_bgp_neighbor(dut, neighbor_ip, **kwargs): """ :param dut: :param neighbor_ip: :param kwargs: :return: """ #No usage in scripts, so no klish support added output = show_bgp_neighbor(dut, neighbor_ip) st.debug(output) for each in kwargs.keys(): match = {each: kwargs[each]} entries = filter_and_select(output, None, match) if not entries: st.log("{} and {} is not match ".format(each, kwargs[each])) return False return True def verify_bgp_ipv4_neighbor_vtysh(dut, neighbor_ip, **kwargs): """ No usage in scripts. Template needs changes for this to work :param dut: :param neighbor_ip: :param kwargs: :return: """ output = show_bgp_ipv4_neighbor_vtysh(dut, neighbor_ip) st.debug(output) for each in kwargs.keys(): match = {each: kwargs[each]} entries = filter_and_select(output, None, match) if not entries: st.log("{} and {} is not match ".format(each, kwargs[each])) return False return True def verify_bgp_ipv6_neighbor_vtysh(dut, neighbor_ip, **kwargs): """ No usage in scripts. Template needs changes for this to work :param dut: :param neighbor_ip: :param kwargs: :return: """ output = show_bgp_ipv6_neighbor_vtysh(dut, neighbor_ip) st.debug(output) for each in kwargs.keys(): match = {each: kwargs[each]} entries = filter_and_select(output, None, match) if not entries: st.log("{} and {} is not match ".format(each, kwargs[each])) return False return True def config_address_family_redistribute(dut, local_asn, mode_type, mode, value, config='yes',vrf='default',skip_error_check=True, **kwargs): """ :param dut: :param local_asn: :param mode_type: :param mode: :param value: :param config: :param vrf :return: """ cli_type = get_cfg_cli_type(dut, **kwargs) cfgmode = 'no' if config != 'yes' else '' route_map = kwargs.get('route_map') cmd = '' if cli_type == 'vtysh' or cli_type == 'click': if vrf.lower() != 'default': cmd = cmd + "router bgp {} vrf {}\n".format(local_asn, vrf) else: cmd = cmd + "router bgp {}\n".format(local_asn) cmd = cmd + "\n address-family {} {}".format(mode_type, mode) if route_map: cmd = cmd + "\n {} redistribute {} route-map {}".format(cfgmode, value, route_map) else: cmd = cmd + "\n {} redistribute {}".format(cfgmode, value) st.config(dut, cmd, type='vtysh', skip_error_check=skip_error_check) return True elif cli_type == "klish": if vrf != 'default': cmd = cmd + 'router bgp {} vrf {}\n'.format(local_asn, vrf) else: cmd = cmd + 'router bgp {}\n'.format(local_asn) cmd = cmd + 'address-family {} {}\n'.format(mode_type, mode) if route_map: cmd = cmd + "{} redistribute {} route-map {}\n".format(cfgmode, value, route_map) else: cmd = cmd + "{} redistribute {}\n".format(cfgmode, value) cmd = cmd + 'exit\nexit\n' st.config(dut, cmd, type=cli_type, skip_error_check=skip_error_check, conf = True) return True else: st.log("Unsupported CLI TYPE - {}".format(cli_type)) return False def config_bgp(dut, **kwargs): """ config_bgp(dut = DUT1, router_id = '9.9.9.9', local_as='100', neighbor ='192.168.3.2', remote_as='200', config = 'yes', config_type_list =["neighbor"]) config_bgp(dut = DUT1, local_as='100', remote_as='200', neighbor ='2001::2', config = 'yes', config_type_list =["neighbor"] config_bgp(dut = DUT1, local_as='100',config = 'yes',config_type_list =["redist"], redistribute ='connected') config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2',config = 'yes',config_type_list =["bfd"]) config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2',config = 'yes',config_type_list =["bfd","redist"], redistribute ='connected') config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2', config = 'yes', password ='<PASSWORD>' ,config_type_list =["pswd"]) config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2',config = 'no', password ='<PASSWORD>' ,config_type_list =["pswd"]) config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2', config = 'yes', update_src ='2.2.2.1', config_type_list =["update_src"]) config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2', config = 'no', update_src ='2.2.2.1', config_type_list =["update_src"]) config_bgp(dut = DUT1, local_as='100',config = 'yes',config_type_list =["max_path_ibgp"], max_path_ibgp ='8') config_bgp(dut = DUT1, local_as='100',config = 'no',config_type_list =["max_path_ibgp"], max_path_ibgp ='8') config_bgp(dut = DUT1, local_as='100',config = 'yes',addr_family ='ipv6', config_type_list =["max_path_ibgp"], max_path_ibgp ='8') config_bgp(dut = DUT1, local_as='100',config = 'no',addr_family ='ipv6', config_type_list =["max_path_ibgp"], max_path_ibgp ='8') config_bgp(dut = DUT1, local_as='100',config = 'yes',addr_family ='ipv6', config_type_list =["max_path_ebgp"], max_path_ebgp ='20') config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2',config ='yes', config_type_list =["routeMap"], routeMap ='map123', diRection='out') config_bgp(dut = DUT1, local_as='100', neighbor ='192.168.3.2',config ='no', config_type_list =["routeMap"], routeMap ='map123', diRection='out') config_bgp(dut = DUT1, local_as='100', neighbor ='2001::20', addr_family ='ipv6',config = 'yes', config_type_list =["routeMap"], routeMap ='map123', diRection='out') config_bgp(dut = DUT1, local_as='100',config = 'no', removeBGP='yes', config_type_list =["removeBGP"]) config_bgp(dut = dut1,local_as = '100', neighbor = '20.20.20.2', config = 'yes', config_type_list =["nexthop_self"]) config_bgp(dut = dut1,local_as = '100', neighbor = '20.20.20.2', config = 'yes', config_type_list =["ebgp_mhop"],ebgp_mhop ='2') """ cli_type = get_cfg_cli_type(dut, **kwargs) st.log('Configure BGP') config = kwargs.get('config', "yes") vrf_name = kwargs.get('vrf_name', "default") router_id = kwargs.get('router_id','') config_type_list = kwargs.get('config_type_list', None) neighbor = kwargs.get('neighbor', None) local_as = kwargs.get('local_as', None) remote_as = kwargs.get('remote_as', None) peergroup = kwargs.get('peergroup', '') #pswd = kwargs.get('pswd', None) #activate = kwargs.get('activate', None) #nexthop_self = kwargs.get('nexthop_self', None) addr_family = kwargs.get('addr_family', 'ipv4') keepalive = kwargs.get('keepalive', '') holdtime = kwargs.get('holdtime', '') conf_peers = kwargs.get('conf_peers', '') conf_identf = kwargs.get('conf_identf', '') update_src = kwargs.get('update_src', None) update_src_intf = kwargs.get("update_src_intf", "") if "update_src_intf" in config_type_list else "" interface = kwargs.get('interface', None) connect = kwargs.get('connect', None) ebgp_mhop = kwargs.get('ebgp_mhop', None) #failover = kwargs.get('failover', None) shutdown = kwargs.get('shutdown', None) #max_path = kwargs.get('max_path', None) redistribute = kwargs.get('redistribute', None) network = kwargs.get('network', None) password = kwargs.get('password', None) max_path_ibgp = kwargs.get('max_path_ibgp', None) max_path_ebgp = kwargs.get('max_path_ebgp', None) routeMap = kwargs.get('routeMap', None) distribute_list = kwargs.get('distribute_list', None) filter_list = kwargs.get('filter_list', None) prefix_list = kwargs.get('prefix_list', None) #import_vrf = kwargs.get('import_vrf', None) import_vrf_name = kwargs.get('import_vrf_name', None) #fast_external_failover = kwargs.get('fast_external_failover', None) bgp_bestpath_selection = kwargs.get('bgp_bestpath_selection', None) removeBGP = kwargs.get('removeBGP', 'no') diRection = kwargs.get('diRection', 'in') weight = kwargs.get('weight', None) config_cmd = "" if config.lower() == 'yes' else "no" my_cmd ='' if cli_type == "vtysh": if 'local_as' in kwargs and removeBGP != 'yes': if vrf_name != 'default': my_cmd = 'router bgp {} vrf {}\n'.format(local_as, vrf_name) else: my_cmd = 'router bgp {}\n'.format(local_as) if router_id != '': my_cmd += '{} bgp router-id {}\n'.format(config_cmd, router_id) if keepalive != '' and holdtime != '': my_cmd += '{} timers bgp {} {}\n'.format(config_cmd, keepalive, holdtime) if
<gh_stars>1-10 # ##### 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> # Script copyright (C) <NAME> # Contributors: <NAME>, <NAME>?ng, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME> import os import time import struct import bpy import mathutils BOUNDS_3DS = [] ###################################################### # Data Structures ###################################################### #Some of the chunks that we will see #----- Primary Chunk, at the beginning of each file PRIMARY = 0x4D4D #------ Main Chunks OBJECTINFO = 0x3D3D # This gives the version of the mesh and is found right before the material and object information VERSION = 0x0002 # This gives the version of the .3ds file EDITKEYFRAME = 0xB000 # This is the header for all of the key frame info #------ Data Chunks, used for various attributes PERCENTAGE_SHORT = 0x30 PERCENTAGE_FLOAT = 0x31 #------ sub defines of OBJECTINFO MATERIAL = 0xAFFF # This stored the texture info OBJECT = 0x4000 # This stores the faces, vertices, etc... #>------ sub defines of MATERIAL #------ sub defines of MATERIAL_BLOCK MAT_NAME = 0xA000 # This holds the material name MAT_AMBIENT = 0xA010 # Ambient color of the object/material MAT_DIFFUSE = 0xA020 # This holds the color of the object/material MAT_SPECULAR = 0xA030 # SPecular color of the object/material MAT_SHINESS = 0xA040 # ?? MAT_TRANSPARENCY = 0xA050 # Transparency value of material MAT_SELF_ILLUM = 0xA080 # Self Illumination value of material MAT_WIRE = 0xA085 # Only render's wireframe MAT_TEXTURE_MAP = 0xA200 # This is a header for a new texture map MAT_SPECULAR_MAP = 0xA204 # This is a header for a new specular map MAT_OPACITY_MAP = 0xA210 # This is a header for a new opacity map MAT_REFLECTION_MAP = 0xA220 # This is a header for a new reflection map MAT_BUMP_MAP = 0xA230 # This is a header for a new bump map MAT_MAP_FILEPATH = 0xA300 # This holds the file name of the texture MAT_MAP_TILING = 0xa351 # 2nd bit (from LSB) is mirror UV flag MAT_MAP_USCALE = 0xA354 # U axis scaling MAT_MAP_VSCALE = 0xA356 # V axis scaling MAT_MAP_UOFFSET = 0xA358 # U axis offset MAT_MAP_VOFFSET = 0xA35A # V axis offset MAT_MAP_ANG = 0xA35C # UV rotation around the z-axis in rad MAT_FLOAT_COLOR = 0x0010 # color defined as 3 floats MAT_24BIT_COLOR = 0x0011 # color defined as 3 bytes #>------ sub defines of OBJECT OBJECT_MESH = 0x4100 # This lets us know that we are reading a new object OBJECT_LAMP = 0x4600 # This lets un know we are reading a light object OBJECT_LAMP_SPOT = 0x4610 # The light is a spotloght. OBJECT_LAMP_OFF = 0x4620 # The light off. OBJECT_LAMP_ATTENUATE = 0x4625 OBJECT_LAMP_RAYSHADE = 0x4627 OBJECT_LAMP_SHADOWED = 0x4630 OBJECT_LAMP_LOCAL_SHADOW = 0x4640 OBJECT_LAMP_LOCAL_SHADOW2 = 0x4641 OBJECT_LAMP_SEE_CONE = 0x4650 OBJECT_LAMP_SPOT_RECTANGULAR = 0x4651 OBJECT_LAMP_SPOT_OVERSHOOT = 0x4652 OBJECT_LAMP_SPOT_PROJECTOR = 0x4653 OBJECT_LAMP_EXCLUDE = 0x4654 OBJECT_LAMP_RANGE = 0x4655 OBJECT_LAMP_ROLL = 0x4656 OBJECT_LAMP_SPOT_ASPECT = 0x4657 OBJECT_LAMP_RAY_BIAS = 0x4658 OBJECT_LAMP_INNER_RANGE = 0x4659 OBJECT_LAMP_OUTER_RANGE = 0x465A OBJECT_LAMP_MULTIPLIER = 0x465B OBJECT_LAMP_AMBIENT_LIGHT = 0x4680 OBJECT_CAMERA = 0x4700 # This lets un know we are reading a camera object #>------ sub defines of CAMERA OBJECT_CAM_RANGES = 0x4720 # The camera range values #>------ sub defines of OBJECT_MESH OBJECT_VERTICES = 0x4110 # The objects vertices OBJECT_FACES = 0x4120 # The objects faces OBJECT_MATERIAL = 0x4130 # This is found if the object has a material, either texture map or color OBJECT_UV = 0x4140 # The UV texture coordinates OBJECT_TRANS_MATRIX = 0x4160 # The Object Matrix #>------ sub defines of EDITKEYFRAME ED_KEY_AMBIENT_NODE = 0xB001 ED_KEY_OBJECT_NODE = 0xB002 ED_KEY_CAMERA_NODE = 0xB003 ED_KEY_TARGET_NODE = 0xB004 ED_KEY_LIGHT_NODE = 0xB005 ED_KEY_L_TARGET_NODE = 0xB006 ED_KEY_SPOTLIGHT_NODE = 0xB007 #>------ sub defines of ED_KEY_OBJECT_NODE # EK_OB_KEYFRAME_SEG = 0xB008 # EK_OB_KEYFRAME_CURTIME = 0xB009 # EK_OB_KEYFRAME_HEADER = 0xB00A EK_OB_NODE_HEADER = 0xB010 EK_OB_INSTANCE_NAME = 0xB011 # EK_OB_PRESCALE = 0xB012 EK_OB_PIVOT = 0xB013 # EK_OB_BOUNDBOX = 0xB014 # EK_OB_MORPH_SMOOTH = 0xB015 EK_OB_POSITION_TRACK = 0xB020 EK_OB_ROTATION_TRACK = 0xB021 EK_OB_SCALE_TRACK = 0xB022 # EK_OB_CAMERA_FOV_TRACK = 0xB023 # EK_OB_CAMERA_ROLL_TRACK = 0xB024 # EK_OB_COLOR_TRACK = 0xB025 # EK_OB_MORPH_TRACK = 0xB026 # EK_OB_HOTSPOT_TRACK = 0xB027 # EK_OB_FALLOF_TRACK = 0xB028 # EK_OB_HIDE_TRACK = 0xB029 # EK_OB_NODE_ID = 0xB030 ROOT_OBJECT = 0xFFFF global scn scn = None object_dictionary = {} object_matrix = {} class Chunk: __slots__ = ( "ID", "length", "bytes_read", ) # we don't read in the bytes_read, we compute that binary_format = "<HI" def __init__(self): self.ID = 0 self.length = 0 self.bytes_read = 0 def dump(self): print('ID: ', self.ID) print('ID in hex: ', hex(self.ID)) print('length: ', self.length) print('bytes_read: ', self.bytes_read) def read_chunk(file, chunk): temp_data = file.read(struct.calcsize(chunk.binary_format)) data = struct.unpack(chunk.binary_format, temp_data) chunk.ID = data[0] chunk.length = data[1] #update the bytes read function chunk.bytes_read = 6 #if debugging #chunk.dump() def read_string(file): #read in the characters till we get a null character s = [] while True: c = file.read(1) if c == b'\x00': break s.append(c) # print('string: ', s) # Remove the null character from the string # print("read string", s) return str(b''.join(s), "utf-8", "replace"), len(s) + 1 ###################################################### # IMPORT ###################################################### def process_next_object_chunk(file, previous_chunk): new_chunk = Chunk() while (previous_chunk.bytes_read < previous_chunk.length): #read the next chunk read_chunk(file, new_chunk) def skip_to_end(file, skip_chunk): buffer_size = skip_chunk.length - skip_chunk.bytes_read binary_format = "%ic" % buffer_size file.read(struct.calcsize(binary_format)) skip_chunk.bytes_read += buffer_size def add_texture_to_material(image, texture, scale, offset, extension, material, mapto): #print('assigning %s to %s' % (texture, material)) if mapto not in {'COLOR', 'SPECULARITY', 'ALPHA', 'NORMAL'}: print( "\tError: Cannot map to %r\n\tassuming diffuse color. modify material %r later." % (mapto, material.name) ) mapto = "COLOR" if image: texture.image = image mtex = material.texture_slots.add() mtex.texture = texture mtex.texture_coords = 'UV' mtex.use_map_color_diffuse = False mtex.scale = (scale[0], scale[1], 1.0) mtex.offset = (offset[0], offset[1], 0.0) texture.extension = 'REPEAT' if extension == 'mirror': # 3DS mirror flag can be emulated by these settings (at least so it seems) texture.repeat_x = texture.repeat_y = 2 texture.use_mirror_x = texture.use_mirror_y = True elif extension == 'decal': # 3DS' decal mode maps best to Blenders CLIP texture.extension = 'CLIP' if mapto == 'COLOR': mtex.use_map_color_diffuse = True elif mapto == 'SPECULARITY': mtex.use_map_specular = True elif mapto == 'ALPHA': mtex.use_map_alpha = True elif mapto == 'NORMAL': mtex.use_map_normal = True def process_next_chunk(file, previous_chunk, importedObjects, IMAGE_SEARCH): from bpy_extras.image_utils import load_image #print previous_chunk.bytes_read, 'BYTES READ' contextObName = None contextLamp = [None, None] # object, Data contextMaterial = None contextMatrix_rot = None # Blender.mathutils.Matrix(); contextMatrix.identity() #contextMatrix_tx = None # Blender.mathutils.Matrix(); contextMatrix.identity() contextMesh_vertls = None # flat array: (verts * 3) contextMesh_facels = None contextMeshMaterials = [] # (matname, [face_idxs]) contextMeshUV = None # flat array (verts * 2) TEXTURE_DICT = {} MATDICT = {} # TEXMODE = Mesh.FaceModes['TEX'] # Localspace variable names, faster. STRUCT_SIZE_FLOAT = struct.calcsize('f') STRUCT_SIZE_2FLOAT = struct.calcsize('2f') STRUCT_SIZE_3FLOAT = struct.calcsize('3f') STRUCT_SIZE_4FLOAT = struct.calcsize('4f') STRUCT_SIZE_UNSIGNED_SHORT = struct.calcsize('H') STRUCT_SIZE_4UNSIGNED_SHORT = struct.calcsize('4H') STRUCT_SIZE_4x3MAT = struct.calcsize('ffffffffffff') # STRUCT_SIZE_4x3MAT = calcsize('ffffffffffff') # print STRUCT_SIZE_4x3MAT, ' STRUCT_SIZE_4x3MAT' # only init once object_list = [] # for hierarchy object_parent = [] # index of parent in hierarchy, 0xFFFF = no parent pivot_list = [] # pivots with hierarchy handling def putContextMesh(myContextMesh_vertls, myContextMesh_facels, myContextMeshMaterials): bmesh = bpy.data.meshes.new(contextObName) if myContextMesh_facels is None: myContextMesh_facels = [] if myContextMesh_vertls: bmesh.vertices.add(len(myContextMesh_vertls) // 3) bmesh.vertices.foreach_set("co", myContextMesh_vertls) nbr_faces = len(myContextMesh_facels) bmesh.polygons.add(nbr_faces) bmesh.loops.add(nbr_faces * 3) eekadoodle_faces = [] for v1, v2, v3 in myContextMesh_facels: eekadoodle_faces.extend((v3, v1, v2) if v3 == 0 else (v1, v2, v3)) bmesh.polygons.foreach_set("loop_start", range(0, nbr_faces * 3, 3)) bmesh.polygons.foreach_set("loop_total", (3,) * nbr_faces) bmesh.loops.foreach_set("vertex_index", eekadoodle_faces) if bmesh.polygons and contextMeshUV: bmesh.uv_textures.new() uv_faces = bmesh.uv_textures.active.data[:] else: uv_faces = None for mat_idx, (matName, faces) in enumerate(myContextMeshMaterials): if matName is None: bmat = None else: bmat = MATDICT.get(matName) # in rare cases no materials defined. if bmat: img = TEXTURE_DICT.get(bmat.name) else: print(" warning: material %r not defined!" % matName) bmat = MATDICT[matName] = bpy.data.materials.new(matName) img = None bmesh.materials.append(bmat) # can be None if uv_faces and img: for fidx in faces: bmesh.polygons[fidx].material_index = mat_idx uv_faces[fidx].image = img else: for fidx in faces: bmesh.polygons[fidx].material_index = mat_idx if uv_faces: uvl = bmesh.uv_layers.active.data[:] for fidx, pl in enumerate(bmesh.polygons): face = myContextMesh_facels[fidx] v1, v2, v3 = face #
piE_N params['q'] = q params['sep'] = sep params['phi'] = phi params['b_sff'] = b_sff1 params['mag_src'] = mag_src1 out_name = outdir + outroot + '_movie.gif' if animate: ani = plot_models.animate_PSBL(psbl, outfile=out_name) else: ani = None return data, params, psbl, ani def fake_data_multiphot_parallax(raL_in, decL_in, t0_in, u0_amp_in, tE_in, piE_E_in, piE_N_in, b_sff_in1, mag_src_in1, b_sff_in2, mag_src_in2, target='Unknown', outdir=''): pspl_par_in = model.PSPL_Phot_Par_Param1(t0_in, u0_amp_in, tE_in, piE_E_in, piE_N_in, np.array([b_sff_in1, b_sff_in2]), np.array([mag_src_in1, mag_src_in2]), raL=raL_in, decL=decL_in) # Simulate # OGLE-like photometric observations every 1 day and # HST-like photometric observations every 30 days # for the bulge observing window. # Observations missed for 125 days out of 365 days t_phot1 = np.array([], dtype=float) t_phot2 = np.array([], dtype=float) # Start on a Jan 1 jan1_2020 = Time('2020-01-01').mjd end_time = jan1_2020 + 7.0 * 365.25 for year_start in np.arange(jan1_2020, end_time, 365.25): phot1_win = 240.0 phot1_start = (365.25 - phot1_win) / 2.0 t_phot1_new = np.arange(year_start + phot1_start, year_start + phot1_start + phot1_win, 1) t_phot1 = np.concatenate([t_phot1, t_phot1_new]) phot2_win = 180.0 phot2_start = (365.25 - phot2_win) / 2.0 t_phot2_new = np.arange(year_start + phot2_start, year_start + phot2_start + phot2_win, 30) t_phot2 = np.concatenate([t_phot2, t_phot2_new]) # Only keep HST/AO photometry after peak. idx = np.where(t_phot2 > t0_in)[0] t_phot2 = t_phot2[idx] # Make the photometric observations. # Assume 0.05 mag photoemtric errors at I=19. # This means Signal = 400 e- at I=19. iflux0 = 4000.0 imag0 = 19.0 imag_obs1 = pspl_par_in.get_photometry(t_phot1, filt_idx=0) flux_obs1 = iflux0 * 10 ** ((imag_obs1 - imag0) / -2.5) flux_obs1_err = flux_obs1 ** 0.5 flux_obs1 += np.random.randn(len(t_phot1)) * flux_obs1_err imag_obs1 = -2.5 * np.log10(flux_obs1 / iflux0) + imag0 imag_obs1_err = 1.087 / flux_obs1_err kflux0 = 4000.0 kmag0 = 18.0 kmag_obs2 = pspl_par_in.get_photometry(t_phot2, filt_idx=1) flux_obs2 = kflux0 * 10 ** ((kmag_obs2 - kmag0) / -2.5) flux_obs2_err = flux_obs2 ** 0.5 flux_obs2 += np.random.randn(len(t_phot2)) * flux_obs2_err imag_obs2 = -2.5 * np.log10(flux_obs2 / kflux0) + kmag0 imag_obs2_err = 1.087 / flux_obs2_err data = {} data['t_phot1'] = t_phot1 data['mag1'] = imag_obs1 data['mag_err1'] = imag_obs1_err data['t_phot2'] = t_phot2 data['mag2'] = imag_obs2 data['mag_err2'] = imag_obs2_err data['target'] = target data['phot_data'] = 'sim' data['ast_data'] = 'sim' data['raL'] = raL_in data['decL'] = decL_in data['phot_files'] = ['fake_data_phot1', 'fake_data_phot2'] data['ast_files'] = ['fake_data_ast1'] params = {} params['raL'] = raL_in params['decL'] = decL_in params['t0'] = t0_in params['u0_amp'] = u0_amp_in params['tE'] = tE_in params['piE_E'] = piE_E_in params['piE_N'] = piE_N_in params['b_sff1'] = b_sff_in1 params['mag_src1'] = mag_src_in1 params['b_sff2'] = b_sff_in2 params['mag_src2'] = mag_src_in2 model_fitter.plot_photometry(data, pspl_par_in, filt_index=0, dense_time=True) plt.figure(1) plt.title('Input Data and Model') plt.savefig(outdir + 'fake_data_multiphot_par1.png') model_fitter.plot_photometry(data, pspl_par_in, filt_index=1, dense_time=True) plt.figure(2) plt.title('Input Data and Model') plt.savefig(outdir + 'fake_data_multiphot_par2.png') return data, params, pspl_par_in def fake_correlated_data_with_astrom(): """ Only correlations in the photometry, not astrometry """ t0 = 57000 u0_amp = 0.1 tE = 150 thetaE = 1 piS = 0.125 piE_E = 0.05 piE_N = 0.05 xS0_E = 0.0 xS0_N = 0.08E-3 muS_E = -4.18 muS_N = -0.28 b_sff = 0.9 mag_src = 19.0 raL = 17.30 * 15. decL = -29.0 our_model = model.PSPL_PhotAstrom_Par_Param2(t0=t0, u0_amp=u0_amp, tE=tE, thetaE=thetaE, piS=piS, piE_E=piE_E, piE_N=piE_N, xS0_E=xS0_E, xS0_N=xS0_N, muS_E=muS_E, muS_N=muS_N, b_sff=b_sff, mag_src=mag_src, raL=raL, decL=decL) cel_model = model.Celerite_GP_Model(our_model, 0) # Simuate the data # Simulate photometric observations every 1 day and # astrometric observations every 30 days # for the bulge observing window. Observations missed # for 125 days out of 365 days for photometry and missed # for 245 days out of 365 days for astrometry. t_mod = np.linspace(56000, 58000, 2000) t_phot = np.array([], dtype=float) t_ast = np.array([], dtype=float) for year_start in np.arange(56000, 58000, 365.25): phot_win = 240.0 phot_start = (365.25 - phot_win) / 2.0 t_phot_new = np.arange(year_start + phot_start, year_start + phot_start + phot_win, 1) t_phot = np.concatenate([t_phot, t_phot_new]) for year_start in np.arange(56000, 58000, 365.25): ast_win = 120.0 ast_start = (365.25 - ast_win) / 2.0 t_ast_new = np.arange(year_start + ast_start, year_start + ast_start + ast_win, 30) t_ast = np.concatenate([t_ast, t_ast_new]) # Make the photometric observations. # Assume 0.05 mag photoemtric errors at I=19. # This means Signal = 400 e- at I=19. flux0 = 4000.0 imag0 = 19.0 imag_obs = our_model.get_photometry(t_phot) flux_obs = flux0 * 10 ** ((imag_obs - imag0) / -2.5) flux_obs_err = flux_obs ** 0.5 flux_obs += np.random.randn(len(t_phot)) * flux_obs_err imag_obs_uncorr = -2.5 * np.log10(flux_obs / flux0) + imag0 imag_obs_err = 1.087 / flux_obs_err K = 0.001*np.exp(-0.5*(t_phot[:, None] - t_phot[None, :])**2/1.5) K[np.diag_indices(len(t_phot))] += imag_obs_err**2 imag_obs_corr = np.random.multivariate_normal(cel_model.get_value(t_phot), K) # Make the astrometric observations. # Assume 0.15 milli-arcsec astrometric errors in each direction at all epochs. pos_obs_tmp = our_model.get_astrometry(t_ast) pos_obs_err = np.ones((len(t_ast), 2), dtype=float) * 0.01 * 1e-3 pos_obs = pos_obs_tmp + pos_obs_err * np.random.randn(len(t_ast), 2) imag_mod = our_model.get_photometry(t_mod) pos_mod = our_model.get_astrometry(t_mod) # Plot the data plt.figure(1) plt.plot(t_mod, imag_mod, label='Model') plt.errorbar(t_phot, imag_obs_corr, yerr=imag_obs_err, fmt=".r", label='Corr') plt.errorbar(t_phot, imag_obs_uncorr, yerr=imag_obs_err, fmt=".k", label='No corr') plt.legend() plt.gca().invert_yaxis() plt.show() plt.figure(2) plt.plot(pos_mod[:,0], pos_mod[:,1], label='Model') plt.errorbar(pos_obs[:,0], pos_obs[:,1], xerr=pos_obs_err[:,0], yerr=pos_obs_err[:,1], fmt=".k") plt.show() data = {} target = 'fake' data['phot_files'] = ['fake_data_phot1'] data['ast_files'] = ['fake_data_ast1'] data['t_phot1'] = t_phot data['mag1'] = imag_obs_uncorr data['mag_err1'] = imag_obs_err data['t_ast1'] = t_ast data['xpos1'] = pos_obs[:, 0] data['ypos1'] = pos_obs[:, 1] data['xpos_err1'] = pos_obs_err[:, 0] data['ypos_err1'] = pos_obs_err[:, 1] data_corr = {} data_corr['t_phot1'] = t_phot data_corr['mag1'] = imag_obs_corr data_corr['mag_err1'] = imag_obs_err data_corr['t_ast1'] = t_ast data_corr['xpos1'] = pos_obs[:, 0] data_corr['ypos1'] = pos_obs[:, 1] data_corr['xpos_err1'] = pos_obs_err[:, 0] data_corr['ypos_err1'] = pos_obs_err[:, 1] data['raL'] = raL data['decL'] = decL data['target'] = target data['phot_data'] = 'sim' data['ast_data'] = 'sim' data_corr['raL'] = raL data_corr['decL'] = decL data_corr['target'] = target data_corr['phot_data'] = 'sim' data_corr['ast_data'] = 'sim' params = {} params['t0'] = t0 params['u0_amp'] = u0_amp params['tE'] = tE params['thetaE'] = thetaE params['piS'] = piS params['piE_E'] = piE_E params['piE_N'] = piE_N params['xS0_E'] = xS0_E params['xS0_N'] = xS0_N params['muS_E'] = muS_E params['muS_N'] = muS_N params['b_sff1'] = b_sff params['mag_src1'] = mag_src params['raL'] = raL params['decL'] = decL return our_model, data, data_corr, params def fake_correlated_data_multiphot(t0 = 57000, u0_amp = 0.1, tE = 150, piE_E = 0.05, piE_N = 0.05, b_sff1 = 0.9, mag_src1 = 19.0, b_sff2 = 0.9, mag_src2 = 19.0, gp_log_sigma1 = 1, gp_log_rho1 = 0.1, gp_log_So1 = 1, gp_log_omegao1 = 1, raL = 17.30 * 15., decL = -29.0): our_model = model.PSPL_Phot_Par_Param1(t0, u0_amp, tE, piE_E, piE_N, np.array([b_sff1, b_sff2]), np.array([mag_src1, mag_src2]), gp_log_sigma, gp_log_rho, gp_log_So, gp_log_omegao, raL=raL, decL=decL) cel_model = model.Celerite_GP_Model(our_model, 0) # Simuate the data # Simulate # photometric observations every 1 day and # astrometric observations every 14 days # for the bulge observing window. Observations missed # for 125 days out of 365 days for photometry and missed # for 245 days out of 365 days for astrometry. t_phot = np.array([], dtype=float) t_ast = np.array([], dtype=float) for year_start in np.arange(56000, 58000, 365.25): phot_win = 240.0 phot_start = (365.25 - phot_win) / 2.0 t_phot_new = np.arange(year_start + phot_start, year_start + phot_start + phot_win, 1) t_phot = np.concatenate([t_phot, t_phot_new]) # Make the photometric observations. # Assume 0.05 mag photoemtric errors at I=19. # This means Signal = 400 e- at I=19. flux0 = 4000.0 imag0 = 19.0 imag_obs = our_model.get_photometry(t_phot) flux_obs = flux0 * 10 ** ((imag_obs - imag0) / -2.5) flux_obs_err = flux_obs ** 0.5 flux_obs += np.random.randn(len(t_phot)) * flux_obs_err imag_obs_uncorr = -2.5 * np.log10(flux_obs / flux0) + imag0 imag_obs_err = 1.087 / flux_obs_err K = 0.01*np.exp(-0.5*(t_phot[:, None] - t_phot[None, :])**2/1.5) K[np.diag_indices(len(t_phot))] += imag_obs_err**2 imag_obs_corr = np.random.multivariate_normal(cel_model.get_value(t_phot), K) # Plot the data plt.errorbar(t_phot, imag_obs_uncorr, yerr=imag_obs_err, fmt=".k", label='No corr') plt.errorbar(t_phot, imag_obs_corr, yerr=imag_obs_err, fmt=".r", label='Corr') plt.legend() plt.gca().invert_yaxis() data = {} target = 'fake' data['t_phot1'] = t_phot data['mag1'] = imag_obs_uncorr data['mag_err1'] = imag_obs_err data_corr = {} data_corr['t_phot1'] = t_phot data_corr['mag1'] = imag_obs_corr data_corr['mag_err1'] = imag_obs_err data['raL'] = raL data['decL'] = decL data['target'] = target data['phot_data'] = 'sim' data['ast_data'] = '' data['phot_files'] = ['fake_data_phot1'] data['ast_files'] = [] data_corr['raL'] = raL data_corr['decL'] = decL data_corr['target'] = target data_corr['phot_data'] = 'sim' data_corr['ast_data'] = '' data_corr['phot_files'] = ['fake_data_phot1'] data_corr['ast_files'] = [] params = {} params['t0'] = 57000 params['u0_amp'] = 0.1 params['tE'] = 150 params['piE_E'] = 0.05 params['piE_N'] = 0.05 params['b_sff1']
dwell_time = self.ovm[ov_index].dwell_time pixel_size = self.ovm[ov_index].pixel_size dose = utils.calculate_electron_dose( current, dwell_time, pixel_size) if (min_dose is None) or (dose < min_dose): min_dose = dose if (max_dose is None) or (dose > max_dose): max_dose = dose total_z = (self.number_slices * self.slice_thickness) / 1000 total_data_in_GB = total_data / (10**9) total_duration = ( total_imaging_time + total_stage_move_time + total_cut_time) # Calculate date and time of completion now = datetime.datetime.now() fraction_completed = self.slice_counter / N remaining_time = int(total_duration * (1 - fraction_completed)) completion_date = now + relativedelta(seconds=remaining_time) date_estimate = str(completion_date)[:19].replace(' ', ' at ') # Return all estimates, to be displayed in main window GUI return (min_dose, max_dose, total_grid_area, total_z, total_data_in_GB, total_imaging_time, total_stage_move_time, total_cut_time, date_estimate, remaining_time) def set_up_acq_subdirectories(self): """Set up and mirror all subdirectories for the stack acquisition.""" subdirectory_list = [ 'meta', 'meta\\logs', 'meta\\stats', 'overviews', 'overviews\\stub', 'overviews\\debris', 'tiles', 'tiles\\rejected', 'workspace', 'workspace\\viewport', 'workspace\\reslices' ] # Add subdirectories for overviews, grids, tiles for ov_index in range(self.ovm.number_ov): ov_dir = os.path.join( 'overviews', 'ov' + str(ov_index).zfill(utils.OV_DIGITS)) subdirectory_list.append(ov_dir) for grid_index in range(self.gm.number_grids): grid_dir = os.path.join( 'tiles', 'g' + str(grid_index).zfill(utils.GRID_DIGITS)) subdirectory_list.append(grid_dir) for tile_index in self.gm[grid_index].active_tiles: tile_dir = os.path.join( grid_dir, 't' + str(tile_index).zfill(utils.TILE_DIGITS)) subdirectory_list.append(tile_dir) # Create the directories in the base directory and the mirror drive # (if applicable). success, exception_str = utils.create_subdirectories( self.base_dir, subdirectory_list) if not success: # Use transmit() here to add a message to the log instead of # add_to_main_log() because main log file is not open yet. self.main_controls_trigger.transmit(utils.format_log_entry( 'CTRL: Error while creating subdirectories: ' + exception_str)) self.pause_acquisition(1) self.error_state = 401 elif self.use_mirror_drive: success, exception_str = utils.create_subdirectories( self.mirror_drive_dir, subdirectory_list) if not success: self.main_controls_trigger.transmit(utils.format_log_entry( 'CTRL: Error while creating subdirectories on mirror ' 'drive: ' + exception_str)) self.pause_acquisition(1) self.error_state = 402 def set_up_acq_logs(self): """Create all acquisition log files and copy them to the mirror drive if applicable. """ # Get timestamp for this run timestamp = str(datetime.datetime.now())[:22].translate( {ord(i):None for i in ' :.'}) try: # Note that the config file and the gridmap file are only saved once # at the beginning of each run. The other log files are updated # continously during the run. # Save current configuration file with timestamp in log folder config_filename = os.path.join( self.base_dir, 'meta', 'logs', 'config_' + timestamp + '.txt') with open(config_filename, 'w') as f: self.cfg.write(f) # Save current grid setup gridmap_filename = self.gm.save_tile_positions_to_disk( self.base_dir, timestamp) # Create main log file, in which all entries are saved. # No line limit. self.main_log_filename = os.path.join( self.base_dir, 'meta', 'logs', 'log_' + timestamp + '.txt') # recent_log_filename: Log file for most recent entries shown in # the GUI (used for e-mail status reports and error reports). # Default max. number of lines is 2000. Can be set # in cfg['monitoring']['max_log_line_count']. self.recent_log_filename = os.path.join( self.base_dir, 'meta', 'logs', 'log_' + timestamp + '_mostrecent.txt') # A buffer_size of 1 ensures that all log entries are immediately # written to disk buffer_size = 1 self.main_log_file = open(self.main_log_filename, 'w', buffer_size) # Set up imagelist file, which contains the paths, file names and # positions of all acquired tiles self.imagelist_filename = os.path.join( self.base_dir, 'meta', 'logs', 'imagelist_' + timestamp + '.txt') self.imagelist_file = open(self.imagelist_filename, 'w', buffer_size) # Incident log for warnings, errors and debris detection events # (All incidents are also logged in the main log file.) self.incident_log_filename = os.path.join( self.base_dir, 'meta', 'logs', 'incident_log_' + timestamp + '.txt') self.incident_log_file = open(self.incident_log_filename, 'w', buffer_size) self.metadata_filename = os.path.join( self.base_dir, 'meta', 'logs', 'metadata_' + timestamp + '.txt') self.metadata_file = open(self.metadata_filename, 'w', buffer_size) except Exception as e: self.add_to_main_log( 'CTRL: Error while setting up log files: ' + str(e)) self.pause_acquisition(1) self.error_state = 401 else: if self.use_mirror_drive: # Copy all log files to mirror drive self.mirror_files([ config_filename, gridmap_filename, self.main_log_filename, self.imagelist_filename, self.incident_log_filename, self.metadata_filename]) # Create file handle for imagelist file on mirror drive. # The imagelist file on the mirror drive is updated continously. # The other logfiles are copied at the end of each run. try: self.mirror_imagelist_file = open(os.path.join( self.mirror_drive, self.imagelist_filename[2:]), 'w', buffer_size) except Exception as e: self.add_to_main_log( 'CTRL: Error while creating imagelist file on mirror ' 'drive: ' + str(e)) self.pause_acquisition(1) self.error_state = 402 def mirror_files(self, file_list): """Copy files in file_list to mirror drive, keep relative path.""" try: for file_name in file_list: dst_file_name = os.path.join(self.mirror_drive, file_name[2:]) shutil.copy(file_name, dst_file_name) except Exception as e: self.add_to_incident_log('WARNING (Could not mirror file(s))') sleep(2) # Try again try: for file_name in file_list: dst_file_name = os.path.join( self.mirror_drive, file_name[2:]) shutil.copy(file_name, dst_file_name) except Exception as e: self.add_to_main_log( 'CTRL: Copying file(s) to mirror drive failed: ' + str(e)) self.pause_acquisition(1) self.error_state = 402 # ====================== STACK ACQUISITION THREAD run() ======================== def run(self): """Run acquisition in a thread started from main_controls.py.""" self.reset_error_state() self.pause_state = None if self.use_mirror_drive: # Update the mirror drive directory. Both mirror drive and # base directory may have changed. self.mirror_drive_dir = os.path.join( self.mirror_drive, self.base_dir[2:]) self.set_up_acq_subdirectories() self.set_up_acq_logs() # Proceed if no error has occurred during setup of folders and logs if self.error_state == 0: # autofocus and autostig status for the current slice self.autofocus_stig_current_slice = False, False # Focus parameters and magnification can be locked to certain # values while a grid is being acquired. If SBEMimage detects a # change (for example when the user accidentally touches a knob), # the correct values can be restored. self.wd_stig_locked = False self.mag_locked = False self.locked_wd = None self.locked_stig_x, self.locked_stig_y = None, None self.locked_mag = None # Global default settings for working distance and stimation, # initialized with the current settings read from the SEM self.wd_default = self.sem.get_wd() self.stig_x_default, self.stig_y_default = ( self.sem.get_stig_xy()) # The following variables store the current tile settings, # initialized with the defaults self.tile_wd = self.wd_default self.tile_stig_x = self.stig_x_default self.tile_stig_y = self.stig_y_default # Alternating plus/minus deltas for wd and stig, needed for # heuristic autofocus, otherwise set to 0 self.wd_delta, self.stig_x_delta, self.stig_y_delta = 0, 0, 0 # List of tiles to be processed for heuristic autofocus # during the cut cycle self.heuristic_af_queue = [] # Reset current estimators and corrections self.autofocus.reset_heuristic_corrections() # Discard previous tile statistics in image inspector that are # used for tile-by-tile comparisons and quality checks. self.img_inspector.reset_tile_stats() # Variable used for user response from Main Controls self.user_reply = None # first_ov[index] is True for each overview image index for which # the user will be asked to confirm that the first acquired image # is free from debris. After confirmation, first_ov[index] is set # to False. self.first_ov = [True] * self.ovm.number_ov # Track the durations for grabbing, mirroring and inspecting tiles. # If the durations deviate too much from expected values, # warnings are shown in the log. self.tile_grab_durations = [] self.tile_mirror_durations = [] self.tile_inspect_durations = [] # Start log for this run self.main_log_file.write('*** SBEMimage log for acquisition ' + self.base_dir + ' ***\n\n') if self.acq_paused: self.main_log_file.write( '\n*** STACK ACQUISITION RESTARTED ***\n') self.add_to_main_log('CTRL: Stack restarted.') self.acq_paused = False else: self.main_log_file.write( '\n*** STACK ACQUISITION STARTED ***\n') self.add_to_main_log('CTRL: Stack started.') if self.use_mirror_drive: self.add_to_main_log( 'CTRL: Mirror drive active: ' + self.mirror_drive_dir) # Save current configuration to disk: # Send signal to call save_settings() in main_controls.py self.main_controls_trigger.transmit('SAVE CFG') # Update progress bar and slice counter in Main Controls GUI self.main_controls_trigger.transmit('UPDATE PROGRESS') # Create metadata summary for this run, write it to disk and send it # to remote (VIME) server (if feature enabled). timestamp = int(time()) grid_list = [str(i).zfill(utils.GRID_DIGITS) for i in range(self.gm.number_grids)] session_metadata = { 'timestamp': timestamp, 'eht': self.sem.target_eht, 'beam_current': self.sem.target_beam_current, 'stig_parameters': (self.stig_x_default, self.stig_y_default), 'working_distance': self.wd_default, 'slice_thickness': self.slice_thickness, 'grids': grid_list, 'grid_origins': [], 'pixel_sizes': [], 'dwell_times': [], 'contrast': self.sem.bsd_contrast, 'brightness': self.sem.bsd_brightness, 'email_addresses: ': self.notifications.user_email_addresses } self.metadata_file.write('SESSION: ' + str(session_metadata) + '\n') if self.send_metadata: status, exc_str = self.notifications.send_session_metadata( self.metadata_project_name, self.stack_name, session_metadata) if status == 100: self.error_state = 508 self.pause_acquisition(1) self.add_to_main_log('CTRL: Error sending session metadata ' 'to server. ' + exc_str) elif status == 200: self.add_to_main_log( 'CTRL: Session data sent. Metadata server active.') # Set SEM to target high voltage and beam current. # EHT is assumed to be on at this point (PreStackDlg checks if EHT # is on when user
as reference ind_idiff_epiref_v_bn[i] = sum(sub_rho_v_bn[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_v_bn[0:ns_t1,(ns_t1):(2*ns_t1)][i,np.setdiff1d(range(ns_t1),i)])/(ns_t1-1) ind_idiff_epiref_v_gm[i] = sum(sub_rho_v_gm[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_v_gm[0:ns_t1,(ns_t1):(2*ns_t1)][i,np.setdiff1d(range(ns_t1),i)])/(ns_t1-1) ind_idiff_epiref_hk[i] = sum(sub_rho_hk[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_hk[0:ns_t1,(ns_t1):(2*ns_t1)][i,np.setdiff1d(range(ns_t1),i)])/(ns_t1-1) ind_idiff_epiref_lk[i] = sum(sub_rho_lk[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_lk[0:ns_t1,(ns_t1):(2*ns_t1)][i,np.setdiff1d(range(ns_t1),i)])/(ns_t1-1) # epimix as reference ind_idiff_t1ref_v_bn[i] = sum(sub_rho_v_bn[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_v_bn[0:ns_t1,(ns_t1):(2*ns_t1)][np.setdiff1d(range(ns_t1),i),i])/(ns_t1-1) ind_idiff_t1ref_v_gm[i] = sum(sub_rho_v_gm[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_v_gm[0:ns_t1,(ns_t1):(2*ns_t1)][np.setdiff1d(range(ns_t1),i),i])/(ns_t1-1) ind_idiff_t1ref_hk[i] = sum(sub_rho_hk[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_hk[0:ns_t1,(ns_t1):(2*ns_t1)][np.setdiff1d(range(ns_t1),i),i])/(ns_t1-1) ind_idiff_t1ref_lk[i] = sum(sub_rho_lk[0:ns_t1,(ns_t1):(2*ns_t1)][i,i]>sub_rho_lk[0:ns_t1,(ns_t1):(2*ns_t1)][np.setdiff1d(range(ns_t1),i),i])/(ns_t1-1) ### raincloud plots ## epimix as reference # p-values p_bg = sp.stats.wilcoxon(ind_idiff_epiref_v_bn,ind_idiff_epiref_v_gm)[1] # brain vs gm p_gh = sp.stats.wilcoxon(ind_idiff_epiref_v_gm,ind_idiff_epiref_hk)[1] # gm vs hk p_hl = sp.stats.wilcoxon(ind_idiff_epiref_hk,ind_idiff_epiref_lk)[1] # hk vs lk # plot dx = list(np.repeat(range(4),ns_t1)) dy = list(np.concatenate((ind_idiff_epiref_v_bn,ind_idiff_epiref_v_gm,ind_idiff_epiref_hk,ind_idiff_epiref_lk))) f, ax = plt.subplots(figsize=(7,4)) ax=pt.RainCloud(x = dx, y = dy, palette = ['darkturquoise','deepskyblue','dodgerblue','steelblue'], bw = .2, width_viol = .8, ax = ax, orient = "h", box_showfliers=False) ax.set_yticklabels(['voxels brain','voxels GM','MMP high-res.','MMP low-res.'], size=lbs); ax.set_xlim([-0.05,1.05]) plt.xlabel(r'ind. I$_{diff}$ (EPImix T$_1$-w. ref.)', size=lbs) ax2 = ax.twinx(); ax2.set_yticks([0.25,0.5,0.75]) # add second y-axis for p-values ax2.set_yticklabels([ef.pow_10_fmt(p_hl),ef.pow_10_fmt(p_gh),ef.pow_10_fmt(p_bg)], size=lbs) # format p-values xt = ax.get_xticks(); ax.set_xticklabels(np.vectorize(round)(xt,2), size=axs); #f.subplots_adjust(left=0.26, right=0.85, bottom = 0.2, top = 0.95) #f.tight_layout() if save_fig_t1: plt.savefig(plot_dir_t1+'/idiff_ind_epiref.svg', bbox_inches='tight') ## t1 as reference # p-values p_bg = sp.stats.wilcoxon(ind_idiff_t1ref_v_bn,ind_idiff_t1ref_v_gm)[1] # brain vs gm p_gh = sp.stats.wilcoxon(ind_idiff_t1ref_v_gm,ind_idiff_t1ref_hk)[1] # gm vs hk p_hl = sp.stats.wilcoxon(ind_idiff_t1ref_hk,ind_idiff_t1ref_lk)[1] # hk vs lk # plot dx = list(np.repeat(range(4),ns_t1)) dy = list(np.concatenate((ind_idiff_t1ref_v_bn,ind_idiff_t1ref_v_gm,ind_idiff_t1ref_hk,ind_idiff_t1ref_lk))) f, ax = plt.subplots(figsize=(7,4)) ax=pt.RainCloud(x = dx, y = dy, palette = ['darkturquoise','deepskyblue','dodgerblue','steelblue'], bw = .2, width_viol = .8, ax = ax, orient = "h", box_showfliers=False) ax.set_yticklabels(['voxels brain','voxels GM','MMP high-res.','MMP low-res.'], size=lbs); ax.set_xlim([-0.05,1.05]) plt.xlabel(r'ind. I$_{diff}$ (T$_1$-w. ref.)', size=lbs) ax2 = ax.twinx(); ax2.set_yticks([0.25,0.5,0.75]) # add second y-axis for p-values ax2.set_yticklabels([ef.pow_10_fmt(p_hl),ef.pow_10_fmt(p_gh),ef.pow_10_fmt(p_bg)], size=lbs) # format p-values xt = ax.get_xticks(); ax.set_xticklabels(np.vectorize(round)(xt,2), size=axs); #f.subplots_adjust(left=0.26, right=0.85, bottom = 0.2, top = 0.95) #f.tight_layout() if save_fig_t1: plt.savefig(plot_dir_t1+'/idiff_ind_t1ref.svg', bbox_inches='tight') ### Medians and percentiles of individual identifiability # EPImix ref print(str(round(np.median(ind_idiff_epiref_v_bn),2))+' ['+str(round(np.percentile(ind_idiff_epiref_v_bn,25),2))+','+str(round(np.percentile(ind_idiff_epiref_v_bn,75),2))+']') print(str(round(np.median(ind_idiff_epiref_v_gm),2))+' ['+str(round(np.percentile(ind_idiff_epiref_v_gm,25),2))+','+str(round(np.percentile(ind_idiff_epiref_v_gm,75),2))+']') print(str(round(np.median(ind_idiff_epiref_hk),2))+' ['+str(round(np.percentile(ind_idiff_epiref_hk,25),2))+','+str(round(np.percentile(ind_idiff_epiref_hk,75),2))+']') print(str(round(np.median(ind_idiff_epiref_lk),2))+' ['+str(round(np.percentile(ind_idiff_epiref_lk,25),2))+','+str(round(np.percentile(ind_idiff_epiref_lk,75),2))+']') # T1 ref print(str(round(np.median(ind_idiff_t1ref_v_bn),2))+' ['+str(round(np.percentile(ind_idiff_t1ref_v_bn,25),2))+','+str(round(np.percentile(ind_idiff_t1ref_v_bn,75),2))+']') print(str(round(np.median(ind_idiff_t1ref_v_gm),2))+' ['+str(round(np.percentile(ind_idiff_t1ref_v_gm,25),2))+','+str(round(np.percentile(ind_idiff_t1ref_v_gm,75),2))+']') print(str(round(np.median(ind_idiff_t1ref_hk),2))+' ['+str(round(np.percentile(ind_idiff_t1ref_hk,25),2))+','+str(round(np.percentile(ind_idiff_t1ref_hk,75),2))+']') print(str(round(np.median(ind_idiff_t1ref_lk),2))+' ['+str(round(np.percentile(ind_idiff_t1ref_lk,25),2))+','+str(round(np.percentile(ind_idiff_t1ref_lk,75),2))+']') # %% """ Jacobians """ # plot directory for main analyses plot_dir_jcb = plot_dir+'/jcb' if not os.path.isdir(plot_dir_jcb): os.mkdir(plot_dir_jcb) # figure saving condition save_fig_jcb = False # %% load Jacobian data # recreate "jcb_epi" array from numpy (values not within the brain mask == 0, but array dimensions are compatible with analysis code below) if os.path.isfile(epimix_dir+'/jcb_epi_bn.npy'): # if file exists, load it jcb_epi_bn = np.load(epimix_dir+'/jcb_epi_bn.npy') jcb_epi = np.empty([ns,nvox]) jcb_epi[:,bn_vec!=0] = jcb_epi_bn del jcb_epi_bn # recreate "jcb_t1" array from numpy (values not within the brain mask == 0, but array dimensions are compatible with analysis code below) if os.path.isfile(epimix_dir+'/jcb_t1_bn.npy'): # if file exists, load it jcb_t1_bn = np.load(epimix_dir+'/jcb_t1_bn.npy') jcb_t1 = np.empty([ns_t1,nvox]) jcb_t1[:,bn_vec!=0] = jcb_t1_bn del jcb_t1_bn # %% Median values within ROIs # mmp h jcb_epi_hk = np.empty([ns,nr_hk]) jcb_t1_hk = np.empty([ns_t1,nr_hk]) for r in range(nr_hk): # replace zeros by nans temp_jcb_epi = jcb_epi[:,mmp_h_vec==mmp_h_id[mmp_hk[r]]]; temp_jcb_epi[temp_jcb_epi==0] = np.nan temp_jcb_t1 = jcb_t1[:,mmp_h_vec==mmp_h_id[mmp_hk[r]]]; temp_jcb_t1[temp_jcb_t1==0] = np.nan # calculate median, ignoring nans jcb_epi_hk[:,r] = np.nanmedian(temp_jcb_epi,axis=1) jcb_t1_hk[:,r] = np.nanmedian(temp_jcb_t1,axis=1) # mmp l jcb_epi_lk = np.empty([ns,nr_lk]) jcb_t1_lk = np.empty([ns_t1,nr_lk]) for r in range(nr_lk): # replace zeros by nans temp_jcb_epi = jcb_epi[:,mmp_l_vec==(mmp_lk[r]+1)]; temp_jcb_epi[temp_jcb_epi==0] = np.nan temp_jcb_t1 = jcb_t1[:,mmp_l_vec==(mmp_lk[r]+1)]; temp_jcb_t1[temp_jcb_t1==0] = np.nan # calculate median, ignoring nans jcb_epi_lk[:,r] = np.nanmedian(temp_jcb_epi,axis=1) jcb_t1_lk[:,r] = np.nanmedian(temp_jcb_t1,axis=1) del temp_jcb_epi del temp_jcb_t1 # %% t1 VS epimix t1 at voxels and regions (across participants) # part_rho = participant rho # voxels if os.path.isfile(data_out_dir+'/jcb_part_rho_v.npz'): # if file exists, load it npz = np.load(data_out_dir+'/jcb_part_rho_v.npz') jcb_part_rho_v = npz['jcb_part_rho_v'] jcb_part_p_v = npz['jcb_part_p_v'] del npz else: # else recreate values using code below jcb_part_rho_v = np.empty([nvox]) jcb_part_p_v = np.empty([nvox]) for v in range(nvox): if v % 10000 == 0: print(v) jcb_part_rho_v[v],jcb_part_p_v[v] = sp.stats.spearmanr(jcb_t1[:,v],jcb_epi[np.array(sub_t1_id),v]) np.savez(data_out_dir+'/jcb_part_rho_v.npz',jcb_part_rho_v=jcb_part_rho_v,jcb_part_p_v=jcb_part_p_v) # voxel-wise plots c_lim = (-1,1) # np.nanmax(abs(jcb_part_rho_v)) cut_crd = (30,0,5) # # all voxels # nl.plotting.plot_img(nb.Nifti1Image(np.reshape(part_rho_v,nii_shape),affine=mmp_h_nii.affine),colorbar=True,cmap='coolwarm', vmin=-np.nanmax(abs(part_rho_v)), vmax=np.nanmax(abs(part_rho_v)), cut_coords=(30, 0, 0), draw_cross=False) # if save_fig_t1: plt.savefig(plot_dir_t1+'/part_rho_v.png',dpi=500, bbox_inches='tight') # MNI && FoV only ef.plot_nl_image_masked(jcb_part_rho_v, fov_bn_vec, nii_shape, mmp_h_nii.affine, cmap='coolwarm', clim=c_lim, cut_coords=cut_crd, draw_cross=False,black_bg=False) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_part_rho_v_bn_fov.png',dpi=500, bbox_inches='tight') # GM && FoV only ef.plot_nl_image_masked(jcb_part_rho_v, fov_gm_vec, nii_shape, mmp_h_nii.affine, cmap='coolwarm', clim=c_lim, cut_coords=cut_crd, draw_cross=False,black_bg=False) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_part_rho_v_gm_fov.png',dpi=500, bbox_inches='tight') # colorbar for voxel-wise plots if save_fig_jcb: ef.plot_cbar(c_lim=c_lim, cmap_nm='coolwarm', c_label=r'Spearman $\rho$', lbs=14, save_path=plot_dir_jcb+'/jcb_part_rho_v_cbar.svg') # mmp h jcb_part_rho_hk = np.empty([nr_hk]) jcb_part_p_hk = np.empty([nr_hk]) for v in range(nr_hk): jcb_part_rho_hk[v],jcb_part_p_hk[v] = sp.stats.spearmanr(jcb_t1_hk[:,v],jcb_epi_hk[np.array(sub_t1_id),v]) #part_rho_h[v],part_p_h[v] = sp.stats.spearmanr(t1_hk[:,v],epi_hk[np.array(sub_t1_id),epi_t1_id,v]) # mmp h plots if save_fig_jcb: c_lim = (-1,1) #(-max(abs(jcb_part_rho_hk)),max(abs(jcb_part_rho_hk))) # min(fov_mmp_h[mmp_hk]) ef.plot_cbar(c_lim=c_lim, cmap_nm='coolwarm', c_label=r'Spearman $\rho$', lbs=14, save_path=plot_dir_jcb+'/jcb_part_rho_mmp_hk_cbar.svg') ef.pscalar_mmp_hk(file_out=plot_dir_jcb+'/jcb_part_rho_mmp_hk.png', pscalars_hk=jcb_part_rho_hk, mmp_hk=mmp_hk, cmap='coolwarm',vrange=c_lim) # mmp l jcb_part_rho_lk = np.empty([nr_lk]) # nr_lk jcb_part_p_lk = np.empty([nr_lk]) # nr_lk for v in range(nr_lk): # range(nr_lk): jcb_part_rho_lk[v],jcb_part_p_lk[v] = sp.stats.spearmanr(jcb_t1_lk[:,v],jcb_epi_lk[np.array(sub_t1_id),v]) #part_rho_l[v],part_p_l[v] = sp.stats.spearmanr(t1_lk[:,v],epi_lk[np.array(sub_t1_id),epi_t1_id,v]) # mmp l plots if save_fig_jcb: c_lim = (-1,1) #(-max(abs(jcb_part_rho_lk)),max(abs(jcb_part_rho_lk))) # min(fov_mmp_h[mmp_hk]) ef.plot_cbar(c_lim=c_lim, cmap_nm='coolwarm', c_label=r'Spearman $\rho$', lbs=14, save_path=plot_dir_jcb+'/jcb_part_rho_mmp_lk_cbar.svg') ef.pscalar_mmp_lk(file_out=plot_dir_jcb+'/jcb_part_rho_mmp_lk.png', pscalars_lk=jcb_part_rho_lk, mmp_lk=mmp_lk,mmp_ds_ids=mmp_ds_ids, cmap='coolwarm',vrange=c_lim) # %% Jacobian identifiability - self- & other-similarity (correlation) between contrasts ### voxel level - brain jcb_rho_v_bn = sp.stats.spearmanr(np.transpose(np.concatenate((jcb_t1,jcb_epi[sub_t1_id,:]))[:,fov_bn_vec==1]))[0] # all plt.figure() hm = sb.heatmap(jcb_rho_v_bn,cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_vox_brain.png',dpi=600,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_vox_brain.svg',bbox_inches='tight') # subset plt.figure() hm = sb.heatmap(jcb_rho_v_bn[0:ns_t1,(ns_t1):(2*ns_t1)],cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_vox_brain_block.svg',bbox_inches='tight') ### voxel level - GM jcb_rho_v_gm = sp.stats.spearmanr(np.transpose(np.concatenate((jcb_t1,jcb_epi[sub_t1_id,:]))[:,fov_gm_vec==1]))[0] # all plt.figure() hm = sb.heatmap(jcb_rho_v_gm,cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_vox_gm.png',dpi=600,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_vox_gm.svg',bbox_inches='tight') # subset plt.figure() hm = sb.heatmap(jcb_rho_v_gm[0:ns_t1,(ns_t1):(2*ns_t1)],cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_voxels_block.svg',bbox_inches='tight') ##### ### mmp hk jcb_rho_hk = sp.stats.spearmanr(np.transpose(np.concatenate((jcb_t1_hk,jcb_epi_hk[sub_t1_id,:]))),nan_policy='omit')[0] # all plt.figure() hm = sb.heatmap(jcb_rho_hk,cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk.png',dpi=500,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk.svg',bbox_inches='tight') # subset plt.figure() hm = sb.heatmap(jcb_rho_hk[0:ns_t1,(ns_t1):(2*ns_t1)],cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk_block.svg',bbox_inches='tight') ### mmp lk jcb_rho_lk = sp.stats.spearmanr(np.transpose(np.concatenate((jcb_t1_lk,jcb_epi_lk[sub_t1_id,:]))),nan_policy='omit')[0] # all plt.figure() hm = sb.heatmap(jcb_rho_lk,cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk.png',dpi=500,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk.svg',bbox_inches='tight') # subset plt.figure() hm = sb.heatmap(jcb_rho_lk[0:ns_t1,(ns_t1):(2*ns_t1)],cmap='PuOr',xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=-1,vmax=1)#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk_block.svg',bbox_inches='tight') if save_fig_jcb: ef.plot_cbar(c_lim=(-1,1), cmap_nm='PuOr', c_label=r'Spearman $\rho$', lbs=14, save_path=plot_dir_jcb+'/jcb_t1_vs_epimix_t1_cbar.svg') # %% spin test null of correlation between maps (for mmp h and mmp l only) if os.path.isfile(data_out_dir+'/jcb_rho_spin.npz'): # if file exists, load it # use spins generated above in t1 analysis npz = np.load(data_out_dir+'/rho_spin.npz') spins_hk = npz['spins_hk'] spins_lk = npz['spins_lk'] del npz # load permuted jcb maps npz = np.load(data_out_dir+'/jcb_rho_spin.npz') jcb_rho_hk_rho = npz['jcb_rho_hk_rho'] jcb_rho_lk_rho = npz['jcb_rho_lk_rho'] jcb_rho_hk_pspin = npz['jcb_rho_hk_pspin'] jcb_rho_lk_pspin = npz['jcb_rho_lk_pspin'] del npz else: # else recreate values using code below ### mmp h jcb_rho_hk_rho = np.zeros((ns_t1,ns_t1)) jcb_rho_hk_pspin = np.zeros((ns_t1,ns_t1)) for i in range(ns_t1): print(i) for j in range(ns_t1): #print(j) #sub_rho_hk_pspin[i,j] = ef.perm_sphere_p(t1_h[i,mmp_hk],epi_h[sub_t1_id[j],epi_t1_id,mmp_hk],spins_h,'spearman') jcb_rho_hk_rho[i,j],jcb_rho_hk_pspin[i,j] = nnstats.permtest_spearmanr(jcb_t1_hk[i,:], jcb_epi_hk[sub_t1_id[j],:], resamples=spins_hk, nan_pol='omit') ### mmp l jcb_rho_lk_rho = np.zeros((ns_t1,ns_t1)) jcb_rho_lk_pspin = np.zeros((ns_t1,ns_t1)) for i in range(ns_t1): print(i) for j in range(ns_t1): #print(j) #sub_rho_lk_pspin[i,j] = ef.perm_sphere_p(t1_l[i,mmp_lk],epi_l[sub_t1_id[j],epi_t1_id,mmp_lk],spins_l,'spearman') jcb_rho_lk_rho[i,j],jcb_rho_lk_pspin[i,j] = nnstats.permtest_spearmanr(jcb_t1_lk[i,:], jcb_epi_lk[sub_t1_id[j],:], resamples=spins_lk, nan_pol='omit') np.savez(data_out_dir+'/jcb_rho_spin.npz',jcb_rho_hk_rho = jcb_rho_hk_rho,jcb_rho_lk_rho = jcb_rho_lk_rho,jcb_rho_hk_pspin = jcb_rho_hk_pspin,jcb_rho_lk_pspin = jcb_rho_lk_pspin) # FDR correction jcb_rho_hk_pspin_fdr = np.reshape(fdrcorrection(jcb_rho_hk_pspin.flatten(), alpha=0.01, method='indep', is_sorted=False)[1],jcb_rho_hk_pspin.shape) # plots c_lim = (-1,1) #(np.min(jcb_rho_hk_rho[jcb_rho_hk_pspin_fdr<0.01]),np.max(jcb_rho_hk_rho[jcb_rho_hk_pspin_fdr<0.01])) ### P FDR jcb_rho_hk_thr_block = np.ones(jcb_rho_hk_rho.shape)*(c_lim[0]-1); jcb_rho_hk_thr_block[jcb_rho_hk_pspin_fdr<0.01] = jcb_rho_hk_rho[jcb_rho_hk_pspin_fdr<0.01] cmap_under = cm.get_cmap('PuOr', 256); cmap_under.set_under('white') plt.figure() hm = sb.heatmap(jcb_rho_hk_thr_block,cmap=cmap_under,xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=c_lim[0],vmax=c_lim[1])#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk_block_pspin_thr.svg',bbox_inches='tight') ### whole plot with permuted upper triangular jcb_rho_hk_thr = np.copy(jcb_rho_hk); jcb_rho_hk_thr[0:ns_t1,(ns_t1):(2*ns_t1)][jcb_rho_hk_pspin_fdr>0.01] = (c_lim[0]-1)#jcb_rho_hk_rho.T[jcb_rho_hk_pspin_fdr.T<0.01] cmap_under = cm.get_cmap('PuOr', 256); cmap_under.set_under('white') plt.figure() hm = sb.heatmap(jcb_rho_hk_thr,cmap=cmap_under,xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=c_lim[0],vmax=c_lim[1])#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk_triu_pspin_thr.png',dpi=600,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_hk_triu_pspin_thr.svg',bbox_inches='tight') # FDR correction jcb_rho_lk_pspin_fdr = np.reshape(fdrcorrection(jcb_rho_lk_pspin.flatten(), alpha=0.01, method='indep', is_sorted=False)[1],jcb_rho_lk_pspin.shape) # plots c_lim = (-1,1) #(np.min(jcb_rho_lk_rho[jcb_rho_lk_pspin_fdr<0.01]),np.max(jcb_rho_lk_rho[jcb_rho_lk_pspin_fdr<0.01])) ### P FDR jcb_rho_lk_thr_block = np.ones(jcb_rho_lk_rho.shape)*(c_lim[0]-1); jcb_rho_lk_thr_block[jcb_rho_lk_pspin_fdr<0.01] = jcb_rho_lk_rho[jcb_rho_lk_pspin_fdr<0.01] cmap_under = cm.get_cmap('PuOr', 256); cmap_under.set_under('white') plt.figure() hm = sb.heatmap(jcb_rho_lk_thr_block,cmap=cmap_under,xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=c_lim[0],vmax=c_lim[1])#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1], *hm.get_ylim()) plt.ylabel('T$_1$-w.',size=lbs); plt.xlabel('EPImix T$_1$-w.',size=lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk_block_pspin_thr.svg',bbox_inches='tight') ### whole plot with permuted lower triangular jcb_rho_lk_thr = np.copy(jcb_rho_lk); jcb_rho_lk_thr[0:ns_t1,(ns_t1):(2*ns_t1)][jcb_rho_lk_pspin_fdr>0.01] = (c_lim[0]-1)#jcb_rho_lk_rho.T[jcb_rho_lk_pspin_fdr.T<0.01] cmap_under = cm.get_cmap('PuOr', 256); cmap_under.set_under('white') plt.figure() hm = sb.heatmap(jcb_rho_lk_thr,cmap=cmap_under,xticklabels=False,yticklabels=False,cbar_kws={'label': r'Spearman $\rho$'},vmin=c_lim[0],vmax=c_lim[1])#,cbar_kws={"ticks":[0,1]}) cax = plt.gcf().axes[-1]; cax.tick_params(labelsize=hm_axs); hm.figure.axes[-1].yaxis.label.set_size(hm_lbs) hm.hlines([0,ns_t1,2*ns_t1], *hm.get_xlim()); hm.vlines([0,ns_t1,2*ns_t1], *hm.get_ylim()) if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk_triu_pspin_thr.png',dpi=600,bbox_inches='tight') plt.text(ns_t1/2,2.15*ns_t1,'T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text((3*ns_t1)/2,2.15*ns_t1,'EPImix T$_1$-w.',horizontalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,ns_t1/2,'T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); plt.text(-0.15*ns_t1,(3*ns_t1)/2,'EPImix T$_1$-w.',rotation=90,verticalalignment='center',size=hm_lbs); if save_fig_jcb: plt.savefig(plot_dir_jcb+'/jcb_t1_vs_epimix_t1_mmp_lk_triu_pspin_thr.svg',bbox_inches='tight') ### proportion of within-/between-participant correlations that survive permutation test # within-participant correlations sum(jcb_rho_hk_pspin_fdr[np.diag_indices(ns_t1)]<0.01) sum(jcb_rho_lk_pspin_fdr[np.diag_indices(ns_t1)]<0.01) # between-participant correlations sum(jcb_rho_hk_pspin_fdr[np.triu_indices(ns_t1,1)]<0.01)+sum(jcb_rho_hk_pspin_fdr[np.tril_indices(ns_t1,-1)]<0.01) sum(jcb_rho_lk_pspin_fdr[np.triu_indices(ns_t1,1)]<0.01)+sum(jcb_rho_lk_pspin_fdr[np.tril_indices(ns_t1,-1)]<0.01) # %% identifiability histograms / violin plots ## calculate Idiff # median jcb_idiff_v_bn = np.median(jcb_rho_v_bn[sim_self_id])-np.median(jcb_rho_v_bn[sim_other_id]) jcb_idiff_v_gm = np.median(jcb_rho_v_gm[sim_self_id])-np.median(jcb_rho_v_gm[sim_other_id]) jcb_idiff_hk = np.median(jcb_rho_hk[sim_self_id])-np.median(jcb_rho_hk[sim_other_id]) jcb_idiff_lk = np.median(jcb_rho_lk[sim_self_id])-np.median(jcb_rho_lk[sim_other_id]) ## plot histograms of off-diagonal values with diagonal lines bins = np.linspace(-0.6, 1, 35) # voxelwise - brain f_bn = plt.figure() plt.hist([jcb_rho_v_bn[sim_self_id],jcb_rho_v_bn[sim_other_id]], bins, label=['Md = '+str(round(np.median(jcb_rho_v_bn[sim_self_id]),2)),'Md = '+str(round(np.median(jcb_rho_v_bn[sim_other_id]),2))],color=['indianred','lightgrey'], edgecolor='black') plt.axvline(np.median(jcb_rho_v_bn[sim_self_id]), color='darkred', linestyle='dashed', linewidth=2) plt.axvline(np.median(jcb_rho_v_bn[sim_other_id]), color='dimgray', linestyle='dashed', linewidth=2) plt.legend(loc='upper right',prop={'size': lgs}) plt.title(r'I$_{diff} = $'+str(round(jcb_idiff_v_bn,2)),size=lbs) plt.xlabel(r'Spearman $\rho$',size=lbs); plt.ylabel('frequency',size=lbs) plt.xticks(size=axs); plt.yticks(size=axs); #plt.gca().set_ylim(yl) ax_bn = plt.gca(); yl_bn = ax_bn.get_ylim(); ax_bn.set_xticks(np.arange(-0.5,1.1,0.5)); # voxelwise - GM f_gm = plt.figure() plt.hist([jcb_rho_v_gm[sim_self_id],jcb_rho_v_gm[sim_other_id]], bins, label=['Md = '+str(round(np.median(jcb_rho_v_gm[sim_self_id]),2)),'Md = '+str(round(np.median(jcb_rho_v_gm[sim_other_id]),2))],color=['indianred','lightgrey'], edgecolor='black') plt.axvline(np.median(jcb_rho_v_gm[sim_self_id]), color='darkred', linestyle='dashed', linewidth=2) plt.axvline(np.median(jcb_rho_v_gm[sim_other_id]), color='dimgray', linestyle='dashed', linewidth=2) plt.legend(loc='upper right',prop={'size': lgs}) plt.title(r'I$_{diff} = $'+str(round(jcb_idiff_v_gm,2)),size=lbs) plt.xlabel(r'Spearman $\rho$',size=lbs); plt.ylabel('frequency',size=lbs) plt.xticks(size=axs); plt.yticks(size=axs); ax_gm = plt.gca(); yl_gm = ax_gm.get_ylim(); ax_gm.set_xticks(np.arange(-0.5,1.1,0.5)); # mmp hk f_hk = plt.figure() plt.hist([jcb_rho_hk[sim_self_id],jcb_rho_hk[sim_other_id]], bins, label=['Md = '+str(round(np.median(jcb_rho_hk[sim_self_id]),2)),'Md = '+str(round(np.median(jcb_rho_hk[sim_other_id]),2))],color=['indianred','lightgrey'], edgecolor='black') plt.axvline(np.median(jcb_rho_hk[sim_self_id]), color='darkred', linestyle='dashed', linewidth=2) plt.axvline(np.median(jcb_rho_hk[sim_other_id]), color='dimgray', linestyle='dashed', linewidth=2) plt.legend(loc='upper right',prop={'size': lgs}) plt.title(r'I$_{diff} = $'+str(round(jcb_idiff_hk,2)),size=lbs) plt.xlabel(r'Spearman $\rho$',size=lbs); plt.ylabel('frequency',size=lbs) plt.xticks(size=axs); plt.yticks(size=axs); #plt.gca().set_ylim(yl) ax_hk = plt.gca(); yl_hk = ax_hk.get_ylim(); ax_hk.set_xticks(np.arange(-0.5,1.1,0.5)); # mmp lk f_lk = plt.figure() plt.hist([jcb_rho_lk[sim_self_id],jcb_rho_lk[sim_other_id]], bins, label=['Md = '+str(round(np.median(jcb_rho_lk[sim_self_id]),2)),'Md = '+str(round(np.median(jcb_rho_lk[sim_other_id]),2))],color=['indianred','lightgrey'], edgecolor='black') plt.axvline(np.median(jcb_rho_lk[sim_self_id]), color='darkred', linestyle='dashed', linewidth=2) plt.axvline(np.median(jcb_rho_lk[sim_other_id]), color='dimgray', linestyle='dashed', linewidth=2) plt.legend(loc='upper left',prop={'size': lgs}) plt.title(r'I$_{diff} = $'+str(round(jcb_idiff_lk,2)),size=lbs) plt.xlabel(r'Spearman $\rho$',size=lbs); plt.ylabel('frequency',size=lbs) plt.xticks(size=axs); plt.yticks(size=axs); #plt.gca().set_ylim(yl) ax_lk = plt.gca(); yl_lk = ax_lk.get_ylim(); ax_lk.set_xticks(np.arange(-0.5,1.1,0.5)); #
0xbf3d, 0x3f17, 0xbefd, 0xbe88, 0x3e98, 0x3ea3, 0x3f22, 0xbca7, 0xbd31, 0x3de3, 0xbf39, 0x3ede, 0xbf3d, 0x3eb2, 0x3d86, 0x3e12, 0xbbbc, 0x3c4e, 0x3d9e, 0x3e17, 0xbf27, 0x3e75, 0xbebf, 0x3cda, 0xbf10, 0x3e95, 0x3f0f, 0xbe83, 0x3f4e, 0xbe35, 0xbf06, 0x3e6d, 0xbecd, 0x3dfd, 0x3ed1, 0xbe01, 0xbd75, 0x3ed1, 0x3ebb, 0xbdc7, 0xbe92, 0x3b3c, 0xbf3e, 0x3daf, 0x3d01, 0x3d1c, 0xbe07, 0x3f30, 0xbf28, 0x3dda, 0xbe6a, 0x3eff, 0xbedc, 0xbe0e, 0xbe6a, 0xbee3, 0xbeb5, 0x3f5a, 0x3f15, 0x3e83, 0x3d13, 0x3b1d, 0xbf10, 0x3c24, 0xbed4, 0xbf49, 0xbc04, 0x3f71, 0xbe0a, 0x3ebe, 0xbdb3, 0x3eb9, 0xbe83, 0xbe8d, 0xbf09, 0xbf47, 0xbf4f, 0x3f76, 0x3f21, 0x3f2f, 0xbcfc, 0x3e5d, 0xbd6a, 0xbeef, 0xbf82, 0xbeea, 0xbda2, 0x3f48, 0x3f9e, 0xbf19, 0xbbed, 0x3f1e, 0xbc5f, 0xbda1, 0xbf1a, 0x3d28, 0xbb75, 0x3c63, 0x3ed3, 0xbe86, 0xbaeb, 0x3ef8, 0xbb48, 0xbc83, 0xbdb4, 0xbc8d, 0xb821, 0xbd9b, 0x3dc1, 0xbc9a, 0xb99b, 0x3dfc, 0xbaa5, 0xb939, 0xbd5f, 0xbc88, 0xb6ba, 0xbbc2, 0xbc6f, 0x3dad, 0xb751, 0x3bf9, 0xb94e, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xbae7, 0x3b57, 0x3b86, 0xb95b, 0xba50, 0xbb81, 0x3a0c, 0xb49f, 0xba9f, 0xb4bf, 0xbca7, 0x3d35, 0xbbff, 0x3eb8, 0x3c06, 0xbde0, 0xbe4b, 0xbcb7, 0xbd2a, 0xbc50, 0xbd3d, 0x3dd5, 0x3d49, 0x3f28, 0x3d2d, 0xbf22, 0x3e05, 0xbe19, 0xbe06, 0xbca5, 0xbf03, 0x3f15, 0x3d99, 0x3f67, 0x3e0d, 0xbf09, 0xbeda, 0x3eaa, 0xbefb, 0xbd89, 0x3d30, 0x3edf, 0x3d8e, 0x3f1e, 0xbe98, 0xbf1b, 0xbdfd, 0x3ea7, 0xbe8c, 0xbe42, 0xbc89, 0xbe94, 0x3b85, 0x3f0f, 0xbe92, 0x3e14, 0xbeb7, 0x3e87, 0x3e69, 0xbe81, 0x3e63, 0xbf35, 0x3ea3, 0xbc6c, 0xbb1b, 0xbe86, 0x3e8d, 0x3f26, 0xbe2c, 0xbe9e, 0x3dc6, 0xbf47, 0xbdc2, 0x3e63, 0x3e2f, 0x3dc0, 0x3c88, 0x3f04, 0x3e51, 0xbee4, 0x3f19, 0xbeab, 0x3e08, 0x3da9, 0xbe58, 0x3e9e, 0x3f08, 0xbe8b, 0xbf02, 0xbea6, 0x3e3a, 0xbf53, 0x3eac, 0x3dc3, 0x3d13, 0x3da9, 0xbf48, 0xbeac, 0x3f12, 0x3f24, 0xbe3e, 0xbf31, 0x3dd8, 0x3dc3, 0x3ec4, 0xbdef, 0xbecf, 0x3e9d, 0x3ec4, 0x3df7, 0x3e84, 0xbe50, 0x3d52, 0x3e17, 0xbf19, 0x3d82, 0xbf10, 0x3ea4, 0x3d77, 0x3eec, 0x3e14, 0xbe83, 0x3e89, 0x3de0, 0x3e20, 0xbe5d, 0x3eac, 0xbeb3, 0x3ea5, 0xbf04, 0x3d9b, 0x3eb8, 0x3d68, 0x3e84, 0x3e8c, 0xbe62, 0xbf26, 0xbf25, 0x3dd8, 0x3ec5, 0x3c0a, 0xbebf, 0x3ef3, 0x3f20, 0x3e1c, 0x3dd7, 0xbe69, 0xbd82, 0x3dc7, 0xbf4c, 0x3eb3, 0xbebf, 0x3de8, 0xbe22, 0xbe39, 0x3e79, 0xbd99, 0xbe9b, 0x3f3c, 0xbeb4, 0x3f0a, 0xbe45, 0x3dc6, 0xbbf5, 0x3e65, 0x3e09, 0x3e70, 0xbec3, 0xbec9, 0xbe83, 0x3e04, 0xbe19, 0xbd12, 0x3e90, 0x3ee1, 0xbda3, 0x3ed9, 0xbf75, 0x3e59, 0xbe87, 0xbee7, 0x3e23, 0x3e86, 0x3dcb, 0x3de9, 0x3f34, 0x3cbc, 0xbf93, 0x3f0b, 0xbe9a, 0xbe08, 0x3ee5, 0x3e54, 0xbe12, 0xbd0e, 0x3df6, 0x3ecf, 0xbf13, 0x3e01, 0xbed9, 0x3e0a, 0x3f15, 0x3dd5, 0x3e35, 0x3e27, 0x3f0d, 0xbeee, 0xbee5, 0x3d04, 0xbf55, 0xbee6, 0x3dba, 0xbd97, 0xbee1, 0x3f4d, 0x3ecd, 0x3f6c, 0xbe85, 0xbedf, 0xbf0d, 0xbf19, 0xbe17, 0xbf0e, 0xbe34, 0x3da0, 0x3f59, 0x3ed5, 0xbd3e, 0x3ec7, 0xbe53, 0xbe92, 0xbf33, 0xbdde, 0xbd36, 0xbe4c, 0x3f3b, 0xbd34, 0xbc7b, 0x3f3d, 0xbd9d, 0xbdad, 0xbe5c, 0xbd7a, 0xbb0b, 0xbe08, 0x3e73, 0x3e74, 0xbc34, 0x3d18, 0xbbf5, 0xbd1f, 0xbd9b, 0xbcc9, 0xb824, 0xba03, 0x3cc6, 0x3e05, 0xb911, 0xbc6b, 0xb6b2, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xb715, 0xb5cd, 0xb98f, 0x3b5e, 0xb617, 0xb8e9, 0xb44b, 0xb7f9, 0xb989, 0xbb30, 0xbbd7, 0xbdef, 0xbd03, 0x3c81, 0xbb7b, 0x3d0a, 0xbb88, 0x3e10, 0xbc8e, 0xbc17, 0xbc13, 0x3d28, 0xbbdf, 0x3ed2, 0xbe2e, 0xbee0, 0xbe24, 0x3f0e, 0xbe1c, 0xbd8e, 0xbdd0, 0x3de9, 0x3e7f, 0x3e58, 0x3ccc, 0xbec1, 0x3e1a, 0x3e8d, 0xbeab, 0xbe59, 0xbd8c, 0x3d89, 0xbdac, 0x3e0b, 0x3ef7, 0x3dd0, 0xbe5a, 0x3f1d, 0xbe92, 0xbf40, 0x3e0e, 0xbd96, 0x3e36, 0x3eac, 0xbd81, 0x3d0f, 0xbf1f, 0x3f65, 0xbea3, 0xbf01, 0x3e1d, 0xbee6, 0x3ea0, 0xbd72, 0xbc6e, 0xbdd2, 0x3d97, 0x3eed, 0x3dd0, 0xbef5, 0xbc82, 0xbee1, 0x3cf7, 0x3ea4, 0xbe70, 0xbe87, 0xbdc9, 0x3f48, 0xbdc4, 0x3c6e, 0xbf68, 0xbf59, 0x3ef4, 0x3ef7, 0x3eb6, 0xbe0a, 0xbe94, 0x3eb7, 0x3e2b, 0x3eac, 0xbe6a, 0xbe52, 0x3f19, 0x3f0e, 0xbec2, 0x3d45, 0xbf22, 0x3f08, 0xbd8b, 0xbe60, 0xbc98, 0x3e53, 0xbe5d, 0x3e5d, 0xbf06, 0xbe70, 0xbedb, 0x3f46, 0xbe62, 0x3ee4, 0xbf18, 0xbe91, 0x3e87, 0xbe30, 0xbe6e, 0x3c37, 0xbe5f, 0x3ef9, 0x3f1f, 0x3def, 0x3f33, 0xbee3, 0x3b4f, 0x3f1d, 0xbf15, 0xbdf7, 0xbf3a, 0xbd23, 0xbccc, 0x3f20, 0x3ebf, 0xbe98, 0xbdef, 0x3bed, 0xbf1a, 0x3ebe, 0xbf03, 0x3d70, 0x3dc4, 0x3f20, 0xbde8, 0xbee4, 0x3e5b, 0x3e58, 0xbf44, 0xbd9a, 0xbc9f, 0x3e8d, 0x3ee5, 0x3e8b, 0x3ea8, 0xbe99, 0x3e49, 0x3eb7, 0xbf29, 0xbe5c, 0xbebb, 0x3e21, 0xbdd2, 0x3f1a, 0x3d5e, 0xbf46, 0xbdce, 0xbe16, 0xbe59, 0x3c41, 0xbdff, 0x3ec3, 0x3ea2, 0x3f18, 0x3efe, 0x3d1b, 0xbce2, 0x3f38, 0xbf48, 0x3c6e, 0xbf6f, 0x3e9f, 0xbebe, 0x3f09, 0xbe5d, 0xbf02, 0xbcfb, 0xbeee, 0xbe21, 0x3f13, 0xbeb1, 0x3db9, 0x3f5d, 0x3e47, 0x3e9e, 0xbd8b, 0xbeb2, 0x3e86, 0xbf01, 0x3e94, 0xbe18, 0xbd94, 0x3c1b, 0x3e8c, 0x3f25, 0xbe15, 0xbe64, 0x3e74, 0xbe9d, 0xbe31, 0x3c84, 0x3e2e, 0xbe17, 0xbd9b, 0x3f6e, 0xbbd6, 0xbe9e, 0xbd07, 0xbd4c, 0x3eae, 0xbd88, 0xbe87, 0xbe09, 0xbed1, 0x3d52, 0x3e98, 0xbf4a, 0xbd86, 0x3f3d, 0x3c37, 0x3ee4, 0xbf4d, 0x3f08, 0xbed3, 0xbf71, 0x3e00, 0xbef8, 0x3daf, 0x3d0b, 0x3fab, 0x3eef, 0xbe39, 0xbd59, 0xbec6, 0xbf3a, 0xbec8, 0xbd61, 0xbdf1, 0xbd89, 0x3f25, 0x3d7d, 0xbdb3, 0x3f5d, 0xbe02, 0xbebf, 0xbdeb, 0xbcab, 0xbbed, 0x3e93, 0x3e88, 0xbe12, 0xbc97, 0x3e39, 0xbd61, 0xbdc7, 0xb7c3, 0xb94f, 0xb8cf, 0xbbd7, 0x3e17, 0xbc94, 0xb9d8, 0xbcc8, 0xb961, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xba2e, 0xbc81, 0xbbf9, 0x3dbd, 0xbb86, 0xbb5c, 0xb68b, 0x3cf2, 0xbc90, 0xbd95, 0xb8de, 0xbe84, 0x3e3c, 0xbdc1, 0xbbdb, 0xbd06, 0xbc98, 0x3e91, 0xbcaa, 0xbd13, 0xbc31, 0xbd81, 0x3e48, 0x3d73, 0xbd50, 0xbeda, 0xbe3c, 0x3f5e, 0xbe1b, 0xbe72, 0xbe53, 0x3de0, 0x3f53, 0x3ee5, 0x3e89, 0xbf95, 0x3e29, 0x3e9a, 0xbdfe, 0xbf1f, 0x3cda, 0xbed0, 0x3e41, 0x3f6e, 0x3f6c, 0xbe62, 0x3d13, 0xbe98, 0xbd5a, 0xbf90, 0x3ec9, 0xbf0f, 0x3f3e, 0x3ec2, 0x3e19, 0xbde3, 0xbf52, 0x3ebc, 0xbe9c, 0xbe72, 0x3d8b, 0xbe9e, 0xbec3, 0x3d9c, 0x3ea3, 0x3e62, 0x3ea1, 0x3e8e, 0xbe61, 0xbebc, 0xbedb, 0xbf75, 0x3f04, 0x3e82, 0xbd23, 0x3f16, 0xbe85, 0xbd9d, 0x3f09, 0xbe05, 0x3e34, 0xbe7f, 0xbd64, 0x3d92, 0x3e20, 0xbc4f, 0xbda2, 0x3ec5, 0xbe42, 0xbe4e, 0xbd6b, 0x3e8b, 0xbea4, 0xbc8d, 0xbf01, 0x3ec9, 0xbea6, 0x3efb, 0x3e49, 0xbe03, 0x3ee2, 0xbef7, 0x3e52, 0xbe08, 0x3dd7, 0x3d7e, 0xbda3, 0x3e80, 0xbeb9, 0xbc25, 0xbe4f, 0x3e8a, 0xbe89, 0x3e8e, 0xbf41, 0x3e77, 0xbe0f, 0x3e9f, 0xbe90, 0x3f0c, 0x3e83, 0xbf00, 0x3f13, 0xbea1, 0xbe38, 0xbf17, 0xbf00, 0x3ee9, 0xbc10, 0x3f4f, 0x3bfc, 0xbd9c, 0x3d76, 0x3f1b, 0xbf17, 0x3ee8, 0x3e03, 0xbe80, 0xbf2b, 0x3ea7, 0xbe74, 0xbf25, 0xbe5b, 0x3e8f, 0xbe87, 0xbed0, 0xbdd1, 0x3e9b, 0x3f0c, 0x3f3e, 0xbe1e, 0xbdb4, 0x3bf2, 0xbd83, 0xbefa, 0x3ea0, 0xbf1c, 0x3edc, 0x3d7b, 0x3f18, 0x3eff, 0xbe85, 0xbf0a, 0x3ec9, 0x3e10, 0x3ad8, 0xbea4, 0x3ead, 0xbf09, 0x3e92, 0x3eee, 0xbedf, 0x3e00, 0xbf00, 0xbed4, 0x3e6e, 0xbec8, 0x3f00, 0x3ea3, 0x3dd2, 0x3e5b, 0xbd28, 0xbe8b, 0x3ebe, 0x3e00, 0x3c4f, 0xbe55, 0x3e0f, 0xbeaf, 0x396d, 0xbd66, 0x3e25, 0xbefc, 0x3d76, 0x3dae, 0xbd79, 0xbf2e, 0x3f36, 0xbe12, 0x3ed5, 0xbe6b, 0xbd9a, 0xbc0d, 0xbf10, 0x3d68, 0x3e6c, 0xbe42, 0x3ece, 0x3eea, 0xbdac, 0xbe83, 0xbe7e, 0x3f3c, 0xbf0e, 0x3eab, 0x3f0c, 0xbf0d, 0x3df3, 0x3e3e, 0xbe9f, 0x3eec, 0xbe89, 0xbfaf, 0xbe77, 0x3f21, 0x3ec6, 0xbd18, 0xbcb4, 0x3f04, 0xbd69, 0xbe05, 0xbf6f, 0xbf72, 0xbe05, 0x3eaa, 0x3f51, 0x3f3b, 0x3d36, 0x3eee, 0xbe81, 0xbf38, 0xbf1a, 0xbd90, 0xbe01, 0x3d85, 0x3fd1, 0xbe77, 0xbdd9, 0x3e99, 0xbe04, 0xbee3, 0xbcce, 0xbcf2, 0xbba3, 0x3ed1, 0x3e09, 0xbe19, 0xbc46, 0x3e5f, 0xbdc0, 0xbcb2, 0xbbf1, 0xbb5d, 0xb984, 0xbc57, 0x3d92, 0xbd36, 0xb931, 0x3ca7, 0xbaba, 0x3d9d, 0xb468, 0xba03, 0xb493, 0xbb35, 0xb5af, 0xb605, 0xbd61, 0xb7a4, 0xbc98, 0xb9c8, 0xbc55, 0x3bd0, 0xbd47, 0xbd47, 0xba82, 0xb8b3, 0x3e5d, 0xbc82, 0xbdc2, 0x3ca4, 0xbe38, 0x3d8f, 0xbd9e, 0x3e1c, 0xbd4a, 0xbc78, 0x3e89, 0xbd09, 0xbe1f, 0x3db9, 0xbc2d, 0x3b20, 0x3d9c, 0x3e13, 0xbeee, 0xbe18, 0x3f60, 0x3dea, 0xbf2e, 0xbe65, 0x3c24, 0x3f38, 0x3ecb, 0x3e55, 0xbfc9, 0x3e53, 0x3f11, 0x3e9d, 0xbf1f, 0xbe06, 0xbe57, 0xbe42, 0xbc3a, 0x3f42, 0xbebf, 0xbdfa, 0x3e98, 0x3e91, 0xbe99, 0xbe0a, 0xbf0c, 0xbc2d, 0xbdf8, 0x3de0, 0x3d0d, 0xbecf, 0x3e98, 0x3f01, 0x3e89, 0xbd28, 0x3e05, 0x3df3, 0xbd1b, 0x3e7e, 0xbf01, 0xbeb7, 0x3f81, 0x3e9d, 0xbf60, 0x3e6a, 0xbf3d, 0x3e1f, 0xbe60, 0xbeb4, 0x3e5a, 0xbf00, 0x3f2d, 0xbe7e, 0x3f4a, 0x3f28, 0xbf50, 0xbe2c, 0xbecb, 0x3ea4, 0x3df2, 0x3cfc, 0x3e80, 0x3e6c, 0xbe68, 0xbeb7, 0xbdbf, 0x3ed7, 0x3e3e, 0xbea9, 0x3e2c, 0xbdbb, 0x3ceb, 0x3e79, 0xbe32, 0xbe42, 0xbf0d, 0x3d70, 0x3d06, 0x3e98, 0x3d5d, 0xbe8f, 0x3f28, 0xba82, 0xbd9a, 0x3f02, 0x3d3f, 0xbe07, 0x3e0f, 0xbeac, 0xbe0d, 0xbeb4, 0x3f06, 0x3ed6, 0xbf2e, 0xbe6c, 0x3d62, 0xbd8f, 0x3e58, 0xbef3, 0x3cf0, 0xbdc5, 0xbe44, 0x3f03, 0x3e84, 0x3f10, 0xbcc5, 0xbc9e, 0x3e0f, 0xbf17, 0xbe07, 0xbf3a, 0x3f09, 0xbeaa, 0x3f16, 0x3ec5, 0x3da0, 0xbcb5, 0x3d82, 0xbe13, 0xbe8f, 0xbf62, 0x3f24, 0xbd58, 0x3e59, 0x3f93, 0xbf49, 0xbe8c, 0x3e22, 0xbf52, 0x3e0a, 0xbed8, 0x3e9f, 0x3e79, 0x3e9d, 0x3e94, 0x3ee7, 0x3e5c, 0xbc26, 0xbec6, 0xbd38, 0xbdd2, 0xbc76, 0xbe7d, 0xbe18, 0x3e1a, 0xbeda, 0xbf0d, 0x3f24, 0x3d85, 0xbe26, 0xbf55, 0x3f45, 0x3d2a, 0x3e9b, 0xbec6, 0x3d1f, 0x3f08, 0xbce4, 0xbeb7, 0x3e0f, 0xbefa, 0x3cf1, 0x3ef9, 0x3d02, 0x3f04, 0xbf12, 0x3e43, 0x3d9b, 0xbe62, 0x3ec0, 0xbed2, 0x3f00, 0x3d1c, 0xbefc, 0x3f02, 0xbee1, 0xbf01, 0x3d3c, 0x3e14, 0xbddb, 0xbe17, 0xbe9f, 0x3e97, 0x3f04, 0x3eec, 0xbe90, 0xbe49, 0x3f84, 0xbf61, 0xbde6, 0xbf2f, 0x3ef4, 0x3e9e, 0xbdff, 0x3f20, 0xbf7d, 0x3ef9, 0xbf93, 0x3e90, 0x3f8a, 0xbf45, 0x3e9a, 0x3eaf, 0xbe52, 0x3eb8, 0xbfa4, 0xbf8f, 0xbf75, 0x3e7f, 0x3fed, 0xbec1, 0xbe4a, 0x3fa8, 0x3e1f, 0xbf7a, 0xbf21, 0xbebf, 0xbe1d, 0x3f36, 0x3fcd, 0xbeec, 0xbe98, 0x3f28, 0xbda8, 0xbedc, 0xbd14, 0xbd42, 0xbbb2, 0xbe35, 0x3f22, 0xbeb0, 0xbcfe, 0x3f0b, 0xbdd4, 0xbc92, 0xbbb4, 0xbbd0, 0xb867, 0xbc10, 0x3be8, 0xbd1f, 0xbbfd, 0x3da6, 0xbb45, 0xb5d9, 0xb8c6, 0xb72b, 0xb98d, 0xba80, 0xb87b, 0xb519, 0x3ba3, 0xb6bf, 0xbb68, 0xba7c, 0xba77, 0xbb3f, 0xbd7c, 0xbd22, 0xbadd, 0xbacf, 0x3e70, 0xbbda, 0xbdf3, 0x3d39, 0xbdf1, 0xbe30, 0x3e40, 0x3e13, 0xbcb0, 0xbd21, 0x3e9a, 0xbde2, 0xbe5e, 0x3e5e, 0xbcef, 0x3dfd, 0x3ecf, 0xbeac, 0xbf05, 0xbe54,
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file ostap/frames/frames.py # Module with decoration of TDataFrame objects for efficient use in python # @author <NAME> <EMAIL> # @date 2018-06-16 # ============================================================================= """Decoration of Tree/Chain objects for efficient use in python""" # ============================================================================= __version__ = "$Revision$" __author__ = "<NAME> <EMAIL>" __date__ = "2011-06-07" __all__ = ( 'DataFrame' , ## RDataFrame object 'report_print' , ## print the report 'report_print_table' , ## print the report 'report_as_table' , ## print the report 'frame_progress' , ## progress bar for frame 'frame_table' , ## print data frame as table 'frame_project' , ## project data frame to the (1D/2D/3D) histogram ) # ============================================================================= import ROOT # ============================================================================= from ostap.core.core import cpp, Ostap, strings, split_string from ostap.core.ostap_types import integer_types, string_types from ostap.logger.utils import multicolumn from ostap.utils.basic import terminal_size, isatty from ostap.logger.colorized import allright import ostap.histos.histos from ostap.core.meta_info import root_info # ============================================================================= # logging # ============================================================================= from ostap.logger.logger import getLogger if '__main__' == __name__ : logger = getLogger( 'ostap.frames.frames' ) else : logger = getLogger( __name__ ) # ============================================================================= logger.debug ( 'Some useful decorations for ROOT::RDataFrame objects') # ============================================================================= try : DataFrame = ROOT.ROOT.RDataFrame except AttributeError : DataFrame = ROOT.ROOT.Experimental.TDataFrame # ============================================================================= Ostap.DataFrame = DataFrame CNT = DataFrame.ColumnNames_t DataFrame.columns = lambda s : tuple ( s.GetColumnNames() ) DataFrame.branches = DataFrame.columns # ============================================================================== ## generate new, unique name for the variable def var_name ( prefix , used_names , *garbage ) : """Generate new, unique name for the variable """ name = prefix + '%x' % ( hash ( ( prefix , used_names , garbage ) ) % ( 2**32 ) ) while name in used_names : name = prefix + '%x' % ( hash ( ( name , prefix , used_names , name , garbage ) ) % ( 2**32 ) ) return name # ============================================================================== ## modify constructor for RDataFrame to enable/disable Implicit multithreading # @code # f1 = DataFrame ( ... , enable = True ) ## default # f2 = DataFrame ( ... , enable = False ) ## default # @endcode # @see ROOT::EnableImplicitMT # @see ROOT::DisableImplicitMT # @see ROOT::IsImplicitMTEnabled def _fr_new_init_ ( self , name , *args , **kwargs ) : """Modify the DataFrame constuctor to allow (semi)automatic manipulations wth ROOT.ROOT.EnableImplicitMT/DisableImplicitMT - see ROOT.ROOT.EnableImplicitMT - see ROOT.ROOT.DisableImplicitMT - see ROOT.ROOT.IsImplicitMTEnabled >>> f = DataFrame ( .... , enable = True ) ## default >>> f = DataFrame ( .... , enable = False ) """ mt = kwargs.pop ( 'enable' , True ) if mt and not ROOT.ROOT.IsImplicitMTEnabled() : ROOT.ROOT.EnableImplicitMT () logger.info ( 'DataFrame:ImplicitMT is %s' % ( 'Enabled' if ROOT.ROOT.IsImplicitMTEnabled() else 'Disabled' ) ) elif not mt and ROOT.ROOT.IsImplicitMTEnabled() : ROOT.ROOT.DisableImplicitMT () logger.info ( 'DataFrame: ImplicitMT is %s' % ( 'Enabled' if ROOT.ROOT.IsImplicitMTEnabled() else 'Disabled' ) ) self._fr_old_init_ ( name , *args , **kwargs ) if not hasattr ( DataFrame , '_fr_old_init_' ) : DataFrame._fr_old_init_ = DataFrame.__init__ DataFrame.__init__ = _fr_new_init_ # ============================================================================= ## Get the length/size of the data frame # @code # frame = ... # print len(frame) # @endcode def _fr_len_ ( f ) : """Get the length/size of the data frame >>> frame = ... >>> print len(frame) """ cpf = Ostap.DataFrame ( f ) ## make independent loop? return cpf.Count().GetValue() # ============================================================================= ## Draw (lazy) progress bar for the DataFrame: # @code # f = DataFrame ( ... ) # p = frame_progress ( f , 1000 ) ## number of elements! # p = f.ProgressBar ( 1000 ) ## number of elements! # .... # @endcode def frame_progress ( self , length , width = None , symbol = "#" ) : """ Draw (lazy) progress bar for the DataFrame: >>> f = DataFrame ( ... ) >>> p = f.ProgressBar ( 1000 ) ## number of elements! >>> .... """ cnt = self.Count () if not isatty() : return cnt length = length if isinstance ( length , integer_types ) and 0 < length else len ( self ) width = width if isinstance ( width , integer_types ) and 10 < width else terminal_size()[1] if width < 16 : width = 16 nchunks = width - 14 csize = max ( int ( length / nchunks ) , 1 ) left = "[ " right = " ]" symbol = allright ( symbol ) fun = Ostap.Utils.frame_progress ( csize , nchunks , symbol , ' ' , left , right ) cnt.OnPartialResultSlot ( csize , fun ) return cnt # ============================================================================= ## Get the effective entries in data frame # @code # data = ... # neff = data.nEff('b1*b1') # @endcode def _fr_nEff_ ( self , cuts = '' ) : """Get the effective entries in data frame >>> data = ... >>> neff = data.nEff('b1*b1') """ return Ostap.StatVar.nEff ( self , cuts ) # ============================================================================= ## Get statistics for the given expression in data frame # @code # data = ... # c1 = data.statVar( 'S_sw' , 'pt>10' ) # c2 = data.statVar( 'S_sw' , 'pt>0' ) # @endcode def _fr_statVar_ ( self , expression , cuts = '' ) : """Get statistics for the given expression in data frame >>> data = ... >>> c1 = data.statVar( 'S_sw' , 'pt>10' ) >>> c2 = data.statVar( 'S_sw' ) """ return Ostap.StatVar.statVar( self , expression , cuts , ) # ============================================================================= ## get the statistic for pair of expressions in DataFrame # @code # frame = ... # stat1 , stat2 , cov2 , len = frame.statCov( 'x' , 'y' ) # # apply some cuts # stat1 , stat2 , cov2 , len = frame.statCov( 'x' , 'y' , 'z>0' ) # @endcode # @author <NAME> <EMAIL> # @date 2018-06-18 def _fr_statCov_ ( frame , expression1 , expression2 , cuts = '' ) : """Get the statistic for pair of expressions in DataFrame >>> frame = ... >>> stat1 , stat2 , cov2 , len = framw.statCov( 'x' , 'y' ) Apply some cuts: >>> stat1 , stat2 , cov2 , len = frame.statCov( 'x' , 'y' , 'z>0' ) """ import ostap.math.linalg stat1 = Ostap.WStatEntity () stat2 = Ostap.WStatEntity () cov2 = Ostap.Math.SymMatrix(2) () length = Ostap.StatVar.statCov ( frame , expression1 , expression2 , cuts , stat1 , stat2 , cov2 ) return stat1 , stat2 , cov2 , length # ================================================================================== ## get statistics of variable(s) # @code # frame = .... # stat = frame.statVar ( 'pt' , lazy = True ) # stat = frame.statVar ( 'pt' , 'eta>0' , lazy = True ) # @endcode def _fr_statVar_new_ ( frame , expressions , cuts = '' , lazy = False ) : """Get statistics of variable(s) """ input_string = False if isinstance ( expressions , string_types ) : input_string = True expressions = [ expressions ] ## get the list of currently known names vars = tuple ( frame.GetColumnNames () ) names = {} current = frame for e in expressions : if e in vars : names [ e ] = e continue used = vars + tuple ( current.GetDefinedColumnNames() ) vn = var_name ( 'var_' , vars , e , *vars ) current = current.Define ( vn , e ) names [ e ] = vn cname = cuts if cuts and not cuts in vars : used = vars + tuple ( current.GetDefinedColumnNames() ) vn = var_name ( 'cut_' , used , cuts , *vars ) current = current.Define ( vn , cuts ) cname = vn results = {} for e in names : if cname : results [ e ] = current.Book( Ostap.Actions.WStatVar() , CNT ( [ names [ e ] , cname ] ) ) else : results [ e ] = current.Book( Ostap.Actions. StatVar() , CNT ( 1 , names[e] ) ) if not lazy : for e in results : r = results [ e ] results [ e ] = r.GetValue() if input_string and 1 == len ( results ) : e , r = results.popitem() return r return results #
_agent, False ] assert agree[0:5] == [_issuer, _amount_take, _price, True, False] assert balance_maker == 0 assert balance_taker == deploy_args[2] assert commitment == 0 # エラー系1 # 入力値の型誤り(_orderId) def test_cancelAgreement_error_1(users, bond_exchange): _agent = users['agent'] # 決済非承認:決済業者 with pytest.raises(OverflowError): bond_exchange.cancelAgreement.transact(-1, 0, {'from': _agent}) with pytest.raises(OverflowError): bond_exchange.cancelAgreement.transact(2 ** 256, 0, {'from': _agent}) with pytest.raises(TypeError): bond_exchange.cancelAgreement.transact('abc', 0, {'from': _agent}) # エラー系2 # 入力値の型誤り(_agreementId) def test_cancelAgreement_error_2(users, bond_exchange): _agent = users['agent'] # 決済非承認:決済業者 with pytest.raises(OverflowError): bond_exchange.cancelAgreement.transact(0, -1, {'from': _agent}) with pytest.raises(OverflowError): bond_exchange.cancelAgreement.transact(0, 2 ** 256, {'from': _agent}) with pytest.raises(TypeError): bond_exchange.cancelAgreement.transact(0, 'aabc', {'from': _agent}) # エラー系3 # 指定した注文番号が、直近の注文ID以上の場合 def test_cancelAgreement_error_3(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Make注文(売):発行体 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済非承認:決済業者 order_id_error = bond_exchange.latestOrderId() + 1 bond_exchange.cancelAgreement.transact(order_id_error, agreement_id, {'from': _agent}) # エラーになる orderbook = bond_exchange.getOrder(order_id) agreement = bond_exchange.getAgreement(order_id, agreement_id) balance_maker = bond_token.balanceOf(_issuer) balance_taker = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert orderbook == [ _issuer, to_checksum_address(bond_token.address), _amount_make - _amount_take, _price, False, _agent, False ] assert agreement[0:5] == [_trader, _amount_take, _price, False, False] assert balance_maker == deploy_args[2] - _amount_make assert balance_taker == 0 assert commitment == _amount_make # エラー系4 # 指定した約定IDが、直近の約定ID以上の場合 def test_cancelAgreement_error_4(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Make注文(売):発行体 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済非承認:決済業者 agreement_id_error = bond_exchange.latestAgreementId(order_id) + 1 bond_exchange.cancelAgreement.transact(order_id, agreement_id_error, {'from': _agent}) # エラーになる orderbook = bond_exchange.getOrder(order_id) agreement = bond_exchange.getAgreement(order_id, agreement_id) balance_maker = bond_token.balanceOf(_issuer) balance_taker = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert orderbook == [ _issuer, to_checksum_address(bond_token.address), _amount_make - _amount_take, _price, False, _agent, False ] assert agreement[0:5] == [_trader, _amount_take, _price, False, False] assert balance_maker == deploy_args[2] - _amount_make assert balance_taker == 0 assert commitment == _amount_make # エラー系5 # すでに決済承認済み(支払済み)の場合 def test_cancelAgreement_error_5(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Make注文(売):発行体 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済承認:決済業者 bond_exchange.confirmAgreement.transact( order_id, agreement_id, {'from': _agent}) # 決済非承認:決済業者 bond_exchange.cancelAgreement.transact(order_id, agreement_id, {'from': _agent}) # エラーになる orderbook = bond_exchange.getOrder(order_id) agreement = bond_exchange.getAgreement(order_id, agreement_id) balance_maker = bond_token.balanceOf(_issuer) balance_taker = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert orderbook == [ _issuer, to_checksum_address(bond_token.address), _amount_make - _amount_take, _price, False, _agent, False ] assert agreement[0:5] == [_trader, _amount_take, _price, False, True] assert balance_maker == deploy_args[2] - _amount_make assert balance_taker == _amount_take assert commitment == _amount_make - _amount_take # エラー系6 # msg.senderが、決済代行(agent)以外の場合 def test_cancelAgreement_error_6(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Make注文(売):発行体 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済非承認:投資家(決済業者以外) bond_exchange.cancelAgreement.transact(order_id, agreement_id, {'from': _trader}) # エラーになる orderbook = bond_exchange.getOrder(order_id) agreement = bond_exchange.getAgreement(order_id, agreement_id) balance_maker = bond_token.balanceOf(_issuer) balance_taker = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert orderbook == [ _issuer, to_checksum_address(bond_token.address), _amount_make - _amount_take, _price, False, _agent, False ] assert agreement[0:5] == [_trader, _amount_take, _price, False, False] assert balance_maker == deploy_args[2] - _amount_make assert balance_taker == 0 assert commitment == _amount_make # エラー系5 # すでに決済非承認済み(キャンセル済み)の場合 def test_cancelAgreement_error_7(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Make注文(売):発行体 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済非承認:決済業者 bond_exchange.cancelAgreement.transact( order_id, agreement_id, {'from': _agent}) # 決済非承認:決済業者(2回目) bond_exchange.cancelAgreement.transact(order_id, agreement_id, {'from': _agent}) # エラーになる orderbook = bond_exchange.getOrder(order_id) agreement = bond_exchange.getAgreement(order_id, agreement_id) balance_maker = bond_token.balanceOf(_issuer) balance_taker = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert orderbook == [ _issuer, to_checksum_address(bond_token.address), _amount_make, _price, False, _agent, False ] assert agreement[0:5] == [_trader, _amount_take, _price, True, False] assert balance_maker == deploy_args[2] - _amount_make assert balance_taker == 0 assert commitment == _amount_make ''' TEST_引き出し(withdrawAll) ''' # 正常系1 # <発行体>新規発行 -> <発行体>デポジット -> <発行体>引き出し def test_withdrawAll_normal_1(users, bond_exchange, personal_info): _issuer = users['issuer'] # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # 引き出し:発行体 bond_exchange.withdrawAll.transact(bond_token.address, {'from': _issuer}) balance_exchange = bond_exchange.balanceOf(_issuer, bond_token.address) balance_token = bond_token.balanceOf(_issuer) assert balance_exchange == 0 assert balance_token == deploy_args[2] # 正常系2 # <発行体>新規発行 -> <発行体>デポジット(2回) -> <発行体>引き出し def test_withdrawAll_normal_2(users, bond_exchange, personal_info): _issuer = users['issuer'] # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # Exchangeへのデポジット(2回目):発行体 _amount_make = 100 bond_token.transfer.transact(bond_exchange.address, _amount_make, {'from': _issuer}) # 引き出し:発行体 bond_exchange.withdrawAll.transact(bond_token.address, {'from': _issuer}) balance_exchange = bond_exchange.balanceOf(_issuer, bond_token.address) balance_token = bond_token.balanceOf(_issuer) assert balance_exchange == 0 assert balance_token == deploy_args[2] # 正常系3 # <発行体>新規発行 -> <発行体>Make注文(売) ※売注文中状態 # -> <発行体>引き出し def test_withdrawAll_normal_3(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_transfer = 100 bond_token.transfer.transact(bond_exchange.address, _amount_transfer, {'from': _issuer}) # Make注文(売):発行体 _amount_make = 70 # 100のうち70だけ売注文 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # 引き出し:発行体 bond_exchange.withdrawAll.transact(bond_token.address, {'from': _issuer}) balance_exchange = bond_exchange.balanceOf(_issuer, bond_token.address) balance_token = bond_token.balanceOf(_issuer) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert balance_exchange == 0 assert balance_token == deploy_args[2] - _amount_make assert commitment == _amount_make # 正常系4 # <発行体>新規発行 -> <発行体>Make注文(売) -> <投資家>Take注文(買) # -> <発行体>引き出し def test_withdrawAll_normal_4(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_transfer = 100 bond_token.transfer.transact(bond_exchange.address, _amount_transfer, {'from': _issuer}) # Make注文(売):発行体 _amount_make = 70 # 100のうち70だけ売注文 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 # 70の売注文に対して、50のTake bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) # 引き出し:発行体 bond_exchange.withdrawAll.transact(bond_token.address, {'from': _issuer}) balance_exchange = bond_exchange.balanceOf(_issuer, bond_token.address) balance_token = bond_token.balanceOf(_issuer) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert balance_exchange == 0 assert balance_token == deploy_args[2] - _amount_make assert commitment == _amount_make # 正常系5 # <発行体>新規発行 -> <発行体>Make注文(売) -> <投資家>Take注文(買) # -> <決済業者>決済承認 -> <発行体>引き出し def test_withdrawAll_normal_5(users, bond_exchange, personal_info, payment_gateway): _issuer = users['issuer'] _trader = users['trader'] _agent = users['agent'] personalinfo_register(personal_info, _issuer, _issuer) payment_gateway_register(payment_gateway, _issuer, _agent) payment_gateway_approve(payment_gateway, _issuer, _agent) personalinfo_register(personal_info, _trader, _issuer) payment_gateway_register(payment_gateway, _trader, _agent) payment_gateway_approve(payment_gateway, _trader, _agent) # 新規発行 bond_token, deploy_args = utils. \ issue_bond_token(users, bond_exchange.address, personal_info.address) # Exchangeへのデポジット:発行体 _amount_transfer = 100 bond_token.transfer.transact(bond_exchange.address, _amount_transfer, {'from': _issuer}) # Make注文(売):発行体 _amount_make = 70 # 100のうち70だけ売注文 _price = 123 bond_exchange.createOrder.transact( bond_token.address, _amount_make, _price, False, _agent, {'from': _issuer}) # Take注文(買):投資家 order_id = bond_exchange.latestOrderId() _amount_take = 50 # 70の売注文に対して、50のTake bond_exchange.executeOrder.transact( order_id, _amount_take, True, {'from': _trader}) agreement_id = bond_exchange.latestAgreementId(order_id) # 決済承認:決済業者 bond_exchange.confirmAgreement.transact( order_id, agreement_id, {'from': _agent}) # 引き出し:発行体 bond_exchange.withdrawAll.transact(bond_token.address, {'from': _issuer}) balance_issuer_exchange = bond_exchange.balanceOf(_issuer, bond_token.address) balance_issuer_token = bond_token.balanceOf(_issuer) balance_trader_exchange = bond_exchange.balanceOf(_trader, bond_token.address) balance_trader_token = bond_token.balanceOf(_trader) commitment = bond_exchange.commitmentOf(_issuer, bond_token.address) assert balance_issuer_exchange == 0 assert balance_issuer_token ==
The details used to update alert status. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.Alert.lifecycle_state` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_alert` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_alert(alert_id, update_alert_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.data.id try: waiter_result = oci.wait_until( self.client, self.client.get_alert(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_audit_archive_retrieval_and_wait_for_state(self, audit_archive_retrieval_id, update_audit_archive_retrieval_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_audit_archive_retrieval` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str audit_archive_retrieval_id: (required) OCID of the archive retrieval. :param oci.data_safe.models.UpdateAuditArchiveRetrievalDetails update_audit_archive_retrieval_details: (required) Details to update the audit archive retrieval. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_audit_archive_retrieval` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_audit_archive_retrieval(audit_archive_retrieval_id, update_audit_archive_retrieval_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_audit_policy_and_wait_for_state(self, audit_policy_id, update_audit_policy_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_audit_policy` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str audit_policy_id: (required) Unique audit policy identifier. :param oci.data_safe.models.UpdateAuditPolicyDetails update_audit_policy_details: (required) Details to update the audit policy. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_audit_policy` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_audit_policy(audit_policy_id, update_audit_policy_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_audit_profile_and_wait_for_state(self, audit_profile_id, update_audit_profile_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_audit_profile` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str audit_profile_id: (required) The OCID of the audit. :param oci.data_safe.models.UpdateAuditProfileDetails update_audit_profile_details: (required) The information to be updated. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_audit_profile` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_audit_profile(audit_profile_id, update_audit_profile_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_audit_trail_and_wait_for_state(self, audit_trail_id, update_audit_trail_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_audit_trail` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str audit_trail_id: (required) The OCID of the audit trail. :param oci.data_safe.models.UpdateAuditTrailDetails update_audit_trail_details: (required) The information to be updated. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_audit_trail` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_audit_trail(audit_trail_id, update_audit_trail_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_data_safe_private_endpoint_and_wait_for_state(self, data_safe_private_endpoint_id, update_data_safe_private_endpoint_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_data_safe_private_endpoint` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str data_safe_private_endpoint_id: (required) The OCID of the private endpoint. :param oci.data_safe.models.UpdateDataSafePrivateEndpointDetails update_data_safe_private_endpoint_details: (required) The details used to update a Data Safe private endpoint. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_data_safe_private_endpoint` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_data_safe_private_endpoint(data_safe_private_endpoint_id, update_data_safe_private_endpoint_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_library_masking_format_and_wait_for_state(self, library_masking_format_id, update_library_masking_format_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_library_masking_format` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str library_masking_format_id: (required) The OCID of the library masking format. :param oci.data_safe.models.UpdateLibraryMaskingFormatDetails update_library_masking_format_details: (required) Details to update a library masking format. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_library_masking_format` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_library_masking_format(library_masking_format_id, update_library_masking_format_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) def update_masking_column_and_wait_for_state(self, masking_column_key, masking_policy_id, update_masking_column_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.data_safe.DataSafeClient.update_masking_column` and waits for the :py:class:`~oci.data_safe.models.WorkRequest` to enter the given state(s). :param str masking_column_key: (required) The unique key that identifies the masking column. It's numeric and unique within a masking policy. :param str masking_policy_id: (required) The OCID of the masking policy. :param oci.data_safe.models.UpdateMaskingColumnDetails update_masking_column_details: (required) Details to update a masking column. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.data_safe.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.data_safe.DataSafeClient.update_masking_column` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_masking_column(masking_column_key, masking_policy_id, update_masking_column_details, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda
A dataset consisting of sub-datasets, to be indexed together. """ def __init__(self, datasets): """ datasets to index together, result will be concatenated in one list """ for xe in datasets: assert(len(xe) == len(datasets[0])) super(MultiDatasets, self).__init__() self.datasets = datasets def __getitem__(self, item): ret = tuple() for dataset in self.datasets: ret_a = dataset[item] if not isinstance(ret_a, tuple): ret_a = (ret_a,) ret += ret_a return ret def __len__(self): return len(self.datasets[0]) def dataload(*tensors, batch_size=1, shuffle=False, **kw): """ Loads provided tensors (numpy arrays, torch tensors, or torch datasets) into a torch dataloader. """ if len(tensors) > 0 and isinstance(tensors[0], Dataset): if len(tensors) == 1: tensordataset = tensors[0] else: tensordataset = q.datacat(*tensors, mode=1) else: tensordataset = tensor_dataset(*tensors) dataloader = DataLoader(tensordataset, batch_size=batch_size, shuffle=shuffle, **kw) return dataloader from torch._utils import _accumulate def split_dataset(dataset, lengths=(80, 20), random=True): """ split a dataset into non-overlapping new datasets of given lengths. Arguments: dataset (Dataset): Dataset to be split lengths (sequence): lengths of splits to be produced """ if sum(lengths) != len(dataset): # lengths are proportions mult = len(dataset) / sum(lengths) lengths = [round(l * mult) for l in lengths] if not random: indices = torch.arange(0, sum(lengths)).long() # else: indices = torch.randperm(sum(lengths)) return [torch.utils.data.Subset(dataset, indices[offset - length:offset]) for offset, length in zip(_accumulate(lengths), lengths)] def datasplit(npmats, splits=(80, 20), random=True): """ Splits given numpy arrays according to given split ratio's. Random split if random=True""" splits = np.round(len(npmats[0]) * np.cumsum(splits) / sum(splits)).astype("int32") whatsplit = np.zeros((len(npmats[0]),), dtype="int64") for i in range(1, len(splits)): a, b = splits[i-1], splits[i] whatsplit[a:b] = i if random is not False and random is not None: if isinstance(random, int): np.random.seed(random) random = True if random is True: np.random.shuffle(whatsplit) ret = [] for i in range(0, len(splits)): splitmats = [npmat[whatsplit == i] for npmat in npmats] ret.append(splitmats) return ret # endregion # region other utils def recmap(x, mapf): # datastructure, mapping function for elements if isinstance(x, dict): for k in x: x[k] = recmap(x[k], mapf) return x elif isinstance(x, list): for i in range(len(x)): x[i] = recmap(x[i], mapf) return x elif isinstance(x, tuple): newtup = [] for i in range(len(x)): newtup.append(recmap(x[i], mapf)) newtup = tuple(newtup) return newtup elif isinstance(x, set): newset = set() for k in x: newset.add(recmap(k, mapf)) return newset else: return mapf(x) percentagebarmap = "\u2581 \u2582 \u2583 \u2584 \u2585 \u2586 \u2587 \u2588 \u2589".split() def percentagebar(x): assert(0.0 <= x <= 1.0) x = round(x * (len(percentagebarmap)-1)) return percentagebarmap[x] def iscallable(x): return hasattr(x, "__call__") def isfunction(x): return iscallable(x) def getnumargs(f): return len(inspect.getargspec(f).args) def getkw(kw, name, default=None, nodefault=False, remove=True): """ convenience function for getting certain kwargs out of function """ if name in kw: ret = kw[name] if remove: del kw[name] else: if nodefault: raise Exception("kwarg {} must be specified (no default)".format(name)) ret = default return ret def issequence(x): return isinstance(x, collections.Sequence) and not isinstance(x, str) def iscollection(x): return issequence(x) or isinstance(x, set) def isnumber(x): return isinstance(x, float) or isinstance(x, int) def isstring(x): return isinstance(x, str) class StringMatrix(): # TODO: use csr_matrix here protectedwords = ["<MASK>", "<RARE>", "<START>", "<END>"] def __init__(self, maxlen=None, freqcutoff=0, topnwords=None, indicate_start_end=False, indicate_start=False, indicate_end=False, specialtoks=None): self._strings = [] if specialtoks is not None: self.protectedwords = self.protectedwords + specialtoks self._wordcounts_original = dict(zip(self.protectedwords, [0] * len(self.protectedwords))) self._dictionary = dict(zip(self.protectedwords, range(len(self.protectedwords)))) self._dictionary_external = False self._rd = None self._next_available_id = len(self._dictionary) self._maxlen = 0 self._matrix = None self._max_allowable_length = maxlen self._rarefreq = freqcutoff self._topnwords = topnwords self._indic_e, self._indic_s = False, False if indicate_start_end: self._indic_s, self._indic_e = True, True if indicate_start: self._indic_s = indicate_start if indicate_end: self._indic_e = indicate_end self._rarewords = set() self.tokenize = tokenize self._cache_p = None self.unseen_mode = False self._no_rare_sorted = False def clone(self): n = StringMatrix() n.tokenize = self.tokenize if self._matrix is not None: n._matrix = self._matrix.copy() n._dictionary = self._dictionary.copy() n._rd = self._rd.copy() n._strings = self._strings return n def clone(self): n = StringMatrix() n.tokenize = self.tokenize if self._matrix is not None: n._matrix = self._matrix.copy() n._dictionary = self._dictionary.copy() n._rd = self._rd.copy() n._strings = self._strings return n def __len__(self): if self._matrix is None: return len(self._strings) else: return self.matrix.shape[0] def cached(self, p): self._cache_p = p if os.path.isfile(p): pickle.load() def __getitem__(self, item, *args): if self._matrix is None: return self._strings[item] else: ret = self.matrix[item] if len(args) == 1: ret = ret[args[0]] ret = self.pp(ret) return ret @property def numwords(self): return len(self._dictionary) @property def numrare(self): return len(self._rarewords) @property def matrix(self): if self._matrix is None: raise Exception("finalize first") return self._matrix @property def D(self): return self._dictionary def set_dictionary(self, d): """ dictionary set in this way is not allowed to grow, tokens missing from provided dictionary will be replaced with <RARE> provided dictionary must contain <RARE> if missing tokens are to be supported""" print("setting dictionary") self._dictionary_external = True self._dictionary = {} self._dictionary.update(d) self._next_available_id = max(self._dictionary.values()) + 1 self._wordcounts_original = dict(zip(list(self._dictionary.keys()), [0]*len(self._dictionary))) self._rd = {v: k for k, v in self._dictionary.items()} @property def RD(self): return self._rd def d(self, x): return self._dictionary[x] def rd(self, x): return self._rd[x] def pp(self, matorvec): def pp_vec(vec): return " ".join([self.rd(x) if x in self._rd else "<UNK>" for x in vec if x != self.d("<MASK>")]) ret = [] if matorvec.ndim == 2: for vec in matorvec: ret.append(pp_vec(vec)) else: return pp_vec(matorvec) return ret def add(self, x): tokens = self.tokenize(x) tokens = tokens[:self._max_allowable_length] if self._indic_s is not False and self._indic_s is not None: indic_s_sym = "<START>" if not isstring(self._indic_s) else self._indic_s tokens = [indic_s_sym] + tokens if self._indic_e is not False and self._indic_e is not None: indic_e_sym = "<END>" if not isstring(self._indic_e) else self._indic_e tokens = tokens + [indic_e_sym] self._maxlen = max(self._maxlen, len(tokens)) tokenidxs = [] for token in tokens: if token not in self._dictionary: if not self._dictionary_external and not self.unseen_mode: self._dictionary[token] = self._next_available_id self._next_available_id += 1 self._wordcounts_original[token] = 0 else: assert("<RARE>" in self._dictionary) token = "<RARE>" # replace tokens missing from external D with <RARE> self._wordcounts_original[token] += 1 tokenidxs.append(self._dictionary[token]) self._strings.append(tokenidxs) return len(self._strings)-1 def finalize(self): print("finalizing") ret = np.zeros((len(self._strings), self._maxlen), dtype="int64") for i, string in tqdm(enumerate(self._strings)): ret[i, :len(string)] = string # print("done") self._matrix = ret self._do_rare_sorted() self._rd = {v: k for k, v in self._dictionary.items()} self._strings = None def _do_rare_sorted(self): """ if dictionary is not external, sorts dictionary by counts and applies rare frequency and dictionary is changed """ if not self._dictionary_external and not self._no_rare_sorted: sortedwordidxs = [self.d(x) for x in self.protectedwords] + \ ([self.d(x) for x, y in sorted(list(self._wordcounts_original.items()), key=lambda x_y: x_y[1], reverse=True) if y >= self._rarefreq and x not in self.protectedwords][:self._topnwords]) transdic = zip(sortedwordidxs, range(len(sortedwordidxs))) transdic = dict(transdic) self._rarewords = {x for x in self._dictionary.keys() if self.d(x) not in transdic} rarewords = {self.d(x) for x in self._rarewords} self._numrare = len(rarewords) transdic.update(dict(zip(rarewords, [self.d("<RARE>")]*len(rarewords)))) # translate matrix self._matrix = np.vectorize(lambda x: transdic[x])(self._matrix) # change dictionary self._dictionary = {k: transdic[v] for k, v in self._dictionary.items() if self.d(k) in sortedwordidxs} def save(self, p): pickle.dump(self, open(p, "w")) @staticmethod def load(p): if os.path.isfile(p): return pickle.load(open(p)) else: return None def tokenize(s, preserve_patterns=None, extrasubs=True): if not isinstance(s, str): s = s.decode("utf-8") s = unidecode.unidecode(s) repldic = None if preserve_patterns is not None: repldic = {} def _tokenize_preserve_repl(x): id = max(list(repldic.keys()) + [-1]) + 1 repl = "replreplrepl{}".format(id) assert(repl not in s) assert(id not in repldic) repldic[id] = x.group(0) return repl for preserve_pattern in preserve_patterns: s = re.sub(preserve_pattern, _tokenize_preserve_repl, s) if extrasubs: s = re.sub("[-_\{\}/]", " ", s) s = s.lower() tokens = nltk.word_tokenize(s) if repldic is not None: repldic = {"replreplrepl{}".format(k): v for k, v in repldic.items()} tokens = [repldic[token] if token in repldic else token for token in tokens] s = re.sub("`", "'", s) return tokens class ticktock(object): """ timer-printer thingy """ def __init__(self, prefix="-", verbose=True): self.prefix = prefix self.verbose = verbose self.state = None self.perc = None self.prevperc = None self._tick() def tick(self, state=None): if self.verbose and state is not None: print("%s: %s" % (self.prefix, state)) self._tick() def _tick(self): self.ticktime = dt.now() def _tock(self): return (dt.now() - self.ticktime).total_seconds() def progress(self, x, of, action="", live=False): if self.verbose: self.perc = int(round(100. * x / of)) if self.perc != self.prevperc: if action != "": action = " " + action + " -" topr = "%s:%s %d" % (self.prefix, action, self.perc) + "%" if live: self._live(topr) else: print(topr) self.prevperc =
<filename>baseline/src/module/train.py<gh_stars>0 import numpy as np import torch from torch.cuda.amp import GradScaler from transformers.optimization import AdamW from transformers.optimization import get_linear_schedule_with_warmup, get_constant_schedule_with_warmup, get_constant_schedule import os import sys import warnings import json import pickle from tqdm import tqdm from sklearn import metrics from scipy.special import logsumexp from module.utils import log1mexp __all__ = [ "Trainer", ] class Trainer(object): def __init__(self, data=None, model=None, logger=None, config=None, device=None, grad_accum_count=1): self.data = data self.model = model self.logger = logger self.config = config self.device = device # setup optimizer self.scaler = GradScaler() self.opt = AdamW( self.model.parameters(), lr=config["learning_rate"], weight_decay=config["weight_decay"], eps=1e-8 ) if config["warmup"] >= 0.0: self.scheduler = get_linear_schedule_with_warmup( self.opt, num_warmup_steps=config["warmup"], num_training_steps=config["max_num_steps"]) else: self.scheduler = get_constant_schedule(self.opt) self.bcelogitloss = torch.nn.BCEWithLogitsLoss() # y is 1 or 0, x is 1-d logit # y is a non-negative integer, x is a multi dimensional logits self.celogitloss = torch.nn.CrossEntropyLoss() def save_model(self, best_metric_threshold): model_state_dict = self.model.state_dict() # TODO may have device issue checkpoint = { 'model': model_state_dict, 'opt': self.opt, 'threshold': best_metric_threshold } checkpoint_path = os.path.join(self.config["output_path"], 'model.pt') self.logger.info("Saving checkpoint %s" % checkpoint_path) torch.save(checkpoint, checkpoint_path) def load_model(self): checkpoint_path = os.path.join(self.config["load_path"]) self.logger.info("Loading best checkpoint %s" % checkpoint_path) if not os.path.exists(checkpoint_path): self.logger.warning(f"Model {checkpoint_path} does not exist.") return None print("before torch.load") sys.stdout.flush() checkpoint = torch.load(checkpoint_path) print("after torch.load") sys.stdout.flush() self.opt = vars(checkpoint['opt']) self.model.load_state_dict(checkpoint['model']) model_parameters = dict([(name, params) for name, params in self.model.named_parameters()]) load_dict = dict( [(k, v) for k, v in checkpoint['model'].items() if k in model_parameters]) self.model.load_state_dict(load_dict, strict=False) return checkpoint['threshold'] def performance_logging(self, micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="VAL"): if len(self.data) == 0: data_length = 1 else: data_length = len(self.data) self.logger.info( f"{i * 100 / data_length} % {label}: Micro P={micro_perf['P']}, Micro R={micro_perf['R']}, Micro F1={micro_perf['F']}, AP={micro_perf['AP']}") self.logger.info( f"{i * 100 / data_length} % {label}: Macro P={macro_perf['P']}, Macro R={macro_perf['R']}, Macro F1={macro_perf['F']}") self.logger.info( f"{i * 100 / data_length} % {label}: Categorical Accuracy={categ_acc}, Categorical Macro P={categ_macro_perf['P']}, Categorical Macro R={categ_macro_perf['R']}, Categorical Macro F1 ={categ_macro_perf['F']}") self.logger.info( f"{i * 100 / data_length} % {label}: not_na Accuracy={na_acc}, not_na P={not_na_perf['P']}, not_na R={not_na_perf['R']}, not_na F1 ={not_na_perf['F']}") self.logger.info( f"{i * 100 / data_length} % {label} na P={na_perf['P']}, na R={na_perf['R']}, na F1 ={na_perf['F']}") for rel_name, (pp, rr, ff, tt) in per_rel_perf.items(): self.logger.info( f"{i * 100 / data_length} % {label}: {rel_name}, P={pp}, R={rr}, F1={ff}, threshold={tt} (threshold not used for multiclass)") def train(self): self.logger.debug("This is training") if self.config["multi_label"] == True: def loss_func(input, target): return self.bcelogitloss(input, target) else: def loss_func(input, target): # input: batchsize, num_ep, R+1 # target: batchsize, num_ep, R target = torch.cat( [target, 1 - (target.sum(2, keepdim=True) > 0).float()], dim=2) # (batchsize, R + 1) target = target.argmax(2) return self.celogitloss(input, target) # input are logits best_metric = -1 best_metric_threshold = {} patience = 0 rolling_loss = [] max_step = self.config["epochs"] * len(self.data) self.model.zero_grad() macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "valid") best_metric = micro_perf["F"] self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, 0, label="VAL (a new best)") macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_ctd", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, 0, label="TEST CTD") macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_anno_ctd", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, 0, label="TEST ANNOTATED CTD") macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_anno_all", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, 0, label="TEST ANNOTATED ALL") for i, batch in iter(self.data): input_ids, attention_mask, ep_masks, e1_indicator, e2_indicator, label_array = batch self.model.train(True) """Loss""" input_ids = input_ids.to(self.device) attention_mask = attention_mask.to(self.device) ep_masks = ep_masks.to(self.device) e1_indicator = e1_indicator.to(self.device) e2_indicator = e2_indicator.to(self.device) scores = self.model(input_ids, attention_mask, ep_masks, e1_indicator, e2_indicator) # batchsize, num_ep, R or batchsize, num_ep, R + 1 loss = loss_func(scores, label_array.to(self.device)) sys.stdout.flush() """back prop""" loss = loss / self.config["grad_accumulation_steps"] self.scaler.scale(loss).backward() for param in self.model.parameters(): if param.grad is not None: assert not torch.isnan(param.grad).any() if i % self.config["grad_accumulation_steps"] == 0: if self.config['max_grad_norm'] > 0: self.scaler.unscale_(self.opt) torch.nn.utils.clip_grad_norm_( self.model.parameters(), self.config['max_grad_norm']) # clip gradient norm self.scaler.step(self.opt) sys.stdout.flush() self.scaler.update() self.scheduler.step() self.model.zero_grad() """End""" rolling_loss.append(float(loss.detach().cpu())) if i % 100 == 0: self.logger.info( f"{i}-th example loss: {np.mean(rolling_loss)}") print(f"{i}-th example loss: {np.mean(rolling_loss)}") rolling_loss = [] # evaluate on dev set (if out-performed, evaluate on test as well) if i % self.config["log_interval"] == self.config["log_interval"] - 1: self.model.eval() # per_rel_perf is a list of length of (number of relation types + 1) macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "valid") self.logger.info(f'val: {micro_perf["F"]}, {not_na_perf["F"]}') print(f'val: {micro_perf["F"]}, {not_na_perf["F"]}') if micro_perf["F"] > best_metric: best_metric = micro_perf["F"] self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="VAL (a new best)") # best_metric_threshold[rel_name] = tt for rel_name, (pp, rr, ff, tt) in per_rel_perf.items(): best_metric_threshold[rel_name] = tt patience = 0 self.save_model(best_metric_threshold) # evaluate on test set macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_ctd", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="TEST CTD") macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_anno_ctd", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="TEST ANNOTATED CTD") macro_perf, micro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf = self.test( "test_anno_all", best_metric_threshold=best_metric_threshold) sys.stdout.flush() self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="TEST ANNOTATED ALL") else: self.performance_logging(micro_perf, macro_perf, categ_acc, categ_macro_perf, na_acc, not_na_perf, na_perf, per_rel_perf, i, label="VAL") patience += 1 # early stop if patience > self.config["patience"]: self.logger.info("triggers early stop; ended") break if i > max_step: self.logger.info("exceeds maximum steps; ended") break def calculate_metrics(self, predictions, predictions_categ, labels): # calcuate metrics given prediction and labels # predictions: (N, R), does not include NA in R # labels: (N, R), one and zeros, does not include NA in R # predictions_categ: (N, R), contains predictions for calculating performance of categorical classifier (exclude NA) TPs = predictions * labels # (N, R) TP = TPs.sum() P = predictions.sum() T = labels.sum() micro_p = TP / P if P != 0 else 0 micro_r = TP / T if T != 0 else 0 micro_f = 2 * micro_p * micro_r / \ (micro_p + micro_r) if micro_p + micro_r > 0 else 0 categ_TPs = predictions_categ * labels categ_TP = categ_TPs.sum() # exludes instance whose label is NA categ_Ps = (predictions_categ * (labels.sum(1) > 0)[:, None]) categ_acc = categ_TP / T if T != 0 else 0 not_NA_Ps = (predictions.sum(1) > 0) not_NA_Ts = (labels.sum(1) > 0) not_NA_TPs = not_NA_Ps * not_NA_Ts not_NA_P = not_NA_Ps.sum() not_NA_T = not_NA_Ts.sum() not_NA_TP = not_NA_TPs.sum() not_NA_prec = not_NA_TP / not_NA_P if not_NA_P != 0 else 0 not_NA_recall = not_NA_TP / not_NA_T if not_NA_T != 0 else 0 not_NA_f = 2 * not_NA_prec * not_NA_recall / \ (not_NA_prec + not_NA_recall) if not_NA_prec + \ not_NA_recall > 0 else 0 not_NA_acc = (not_NA_Ps == not_NA_Ts).mean() NA_Ps = (predictions.sum(1) == 0) NA_Ts = (labels.sum(1) == 0) NA_TPs = NA_Ps * NA_Ts NA_P = NA_Ps.sum() NA_T = NA_Ts.sum() NA_TP = NA_TPs.sum() NA_prec = NA_TP / NA_P if NA_P != 0 else 0 NA_recall = NA_TP / NA_T if NA_T != 0 else 0 NA_f = 2 * NA_prec * NA_recall / \ (NA_prec + NA_recall) if NA_prec + NA_recall > 0 else 0 per_rel_p = np.zeros(predictions.shape[1]) per_rel_r = np.zeros(predictions.shape[1]) per_rel_f = np.zeros(predictions.shape[1]) categ_per_rel_p = np.zeros(predictions.shape[1]) categ_per_rel_r = np.zeros(predictions.shape[1]) categ_per_rel_f = np.zeros(predictions.shape[1]) # per relation metrics: for i in range(predictions.shape[1]): TP_ = TPs[:, i].sum() P_ = predictions[:, i].sum() T_ = labels[:, i].sum() categ_TP_ = categ_TPs[:, i].sum() categ_P_ = categ_Ps[:, i].sum() # if no such relation in the test data, recall = 0 per_rel_r[i] = TP_ / T_ if T_ != 0 else 0 categ_per_rel_r[i] = categ_TP_ / T_ if T_ != 0 else 0 # if no such relation in the prediction, precision = 0 per_rel_p[i] = TP_ / P_ if P_ != 0 else 0 # if no such relation in the prediction, precision = 0 categ_per_rel_p[i] = categ_TP_ / categ_P_ if categ_P_ != 0 else 0 per_rel_f[i] = 2 * per_rel_p[i] * per_rel_r[i] / \ (per_rel_p[i] + per_rel_r[i]) if per_rel_p[i] + \ per_rel_r[i] > 0 else 0 categ_per_rel_f[i] = 2 * categ_per_rel_p[i] * categ_per_rel_r[i] / \ (categ_per_rel_p[i] + categ_per_rel_r[i] ) if categ_per_rel_p[i] + categ_per_rel_r[i] > 0 else 0
<gh_stars>100-1000 """pypyr context class. Dictionary ahoy.""" from collections import namedtuple from collections.abc import Mapping, Set from pypyr.dsl import SpecialTagDirective from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError from pypyr.formatting import RecursiveFormatter from pypyr.moduleloader import _ChainMapPretendDict from pypyr.utils import asserts, types ContextItemInfo = namedtuple('ContextItemInfo', ['key', 'key_in_context', 'expected_type', 'is_expected_type', 'has_value']) class Context(dict): """The pypyr context. This is a mutable dict that maintains state during the entire life-span of a pipeline. This class only adds functionality on top of dictionary, it should not override anything in dict. Attributes: pipeline_name (str): name of pipeline that is currently running working_dir (path-like): working directory path. Either CWD or initialized from the cli --dir arg. """ # I *think* instantiating formatter at class level is fine - far as I can # see the class methods are functional, not dependant on class state (also, # no __init__). # https://github.com/python/cpython/blob/master/Lib/string.py formatter = RecursiveFormatter(special_types=SpecialTagDirective) def __init__(self, *args, **kwargs): """Initialize context.""" super().__init__(*args, **kwargs) # __builtins__ are in _ChainMapPretendDict, not in _pystring_globals self._pystring_globals = {} # working on assumption context more frequent lookup than builtins. # here context can go 1st, because eval expressions can't update the # namespace like exec does. self._pystring_namespace = _ChainMapPretendDict(self, self._pystring_globals) def __getstate__(self): """Remove namespace from pickle serialization.""" state = self.__dict__.copy() # no need to persist builtins - will rehydrate these on setstate. # do want to keep any custom py imports, though. del state['_pystring_namespace'] return state def __setstate__(self, state): """Rehydrate from pickle will fail on ChainMap coz invocation order. Thus custom override to set pystring globals 1st, then namespace with self ref. """ self.__dict__.update(state) self._pystring_namespace = _ChainMapPretendDict(self, self._pystring_globals) def __missing__(self, key): """Throw KeyNotInContextError rather than KeyError. Python explicitly clears this over-ride for dict inheritance. https://docs.python.org/3/library/stdtypes.html#dict """ raise KeyNotInContextError(f"{key} not found in the pypyr context.") def assert_child_key_has_value(self, parent, child, caller): """Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used to construct error messages Raises: KeyNotInContextError: Key doesn't exist KeyInContextHasNoValueError: context[key] is None AssertionError: if key is None """ asserts.assert_key_has_value(self, parent, caller) asserts.assert_key_has_value(self[parent], child, caller, parent) def assert_key_exists(self, key, caller): """Assert that context contains key. Args: key: validates that this key exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyNotInContextError: When key doesn't exist in context. """ asserts.assert_key_exists(self, key, caller) def assert_key_has_value(self, key, caller): """Assert that context contains key which also has a value. Args: key: validate this key exists in context AND has a value that isn't None. caller: string. calling function name - this used to construct error messages Raises: KeyNotInContextError: Key doesn't exist KeyInContextHasNoValueError: context[key] is None AssertionError: if key is None """ asserts.assert_key_has_value(self, key, caller) def assert_key_type_value(self, context_item, caller, extra_error_text=''): """Assert that keys exist of right type and has a value. Args: context_item: ContextItemInfo tuple caller: string. calling function name - this used to construct error messages extra_error_text: append to end of error message. Raises: AssertionError: if context_item None. KeyNotInContextError: Key doesn't exist KeyInContextHasNoValueError: context[key] is None or the wrong type. """ assert context_item, ("context_item parameter must be specified.") if extra_error_text is None or extra_error_text == '': append_error_text = '' else: append_error_text = f' {extra_error_text}' if not context_item.key_in_context: raise KeyNotInContextError(f'{caller} couldn\'t find ' f'{context_item.key} in context.' f'{append_error_text}') if not context_item.has_value: raise KeyInContextHasNoValueError( f'{caller} found {context_item.key} in ' f'context but it doesn\'t have a value.' f'{append_error_text}') if not context_item.is_expected_type: raise KeyInContextHasNoValueError( f'{caller} found {context_item.key} in context, but it\'s ' f'not a {context_item.expected_type}.' f'{append_error_text}') def assert_keys_exist(self, caller, *keys): """Assert that context contains keys. Args: keys: validates that these keys exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyNotInContextError: When key doesn't exist in context. """ assert keys, ("*keys parameter must be specified.") for key in keys: self.assert_key_exists(key, caller) def assert_keys_have_values(self, caller, *keys): """Check that keys list are all in context and all have values. Args: *keys: Will check each of these keys in context caller: string. Calling function name - just used for informational messages Raises: KeyNotInContextError: Key doesn't exist KeyInContextHasNoValueError: context[key] is None AssertionError: if *keys is None """ for key in keys: self.assert_key_has_value(key, caller) def assert_keys_type_value(self, caller, extra_error_text, *context_items): """Assert that keys exist of right type and has a value. Args: caller: string. calling function name - this used to construct error messages extra_error_text: append to end of error message. This can happily be None or ''. *context_items: ContextItemInfo tuples Raises: AssertionError: if context_items None. KeyNotInContextError: Key doesn't exist KeyInContextHasNoValueError: context[key] is None or the wrong type. """ assert context_items, ("context_items parameter must be specified.") for context_item in context_items: self.assert_key_type_value(context_item, caller, extra_error_text) def get_eval_string(self, input_string): """Dynamically evaluates the input_string python expression. This provides dynamic python eval of an input expression. The return is whatever the result of the expression is. Use with caution: since input_string executes any arbitrary code object the potential for damage is great. The eval unpacks the current context object into the namespace. This means if you have context['mykey'], in the input_string expression you can use the key directly as a variable like this: "mykey == 'mykeyvalue'". Both __builtins__ and context are available to the eval expression. Args: input_string: expression to evaluate. Returns: Whatever object results from the string expression valuation. """ if input_string: return eval(input_string, self._pystring_namespace) else: # Empty input raises cryptic EOF syntax err, this more human # friendly raise ValueError('input expression is empty. It must be a valid ' 'python expression instead.') def get_formatted(self, key): """Return formatted value for context[key]. This is a convenience method that calls the same thing as get_formatted_value() under the hood, passing to it the value it retrieves from context at the input key. If context[key]'s value is a type string, will just format and return the string. Strings can contain recursive formatting expressions. If context[key]'s value is a special type, like a py string or sic string, will run the formatting implemented by the custom tag representer. If context[key] is not a string, specifically an iterable type like a dict, list, tuple, set, it will use get_formatted_value under the covers to loop through and handle the entire structure contained in context[key]. If context[key]='Piping {key1} the {key2} wild' And context={'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} Then this will return string: "Piping down the valleys wild" Choosing between get_formatted() and get_formatted_value(): - get_formatted() gets a context[key] value with formatting applied. - get_formatted_value() is for any arbitrary object. Args: key: dictionary key to retrieve. Returns: Whatever object results from the formatting expression(s) at the input key's value. Raises: KeyNotInContextError: context[key] value contains {somekey} where somekey does not exist in context dictionary. """ val = self[key] try: # any sort of complex type will work with recursive formatter. return self.formatter.vformat(val, None, self) except KeyNotInContextError as err: # less cryptic error for end-user friendliness raise KeyNotInContextError( f'Unable to format \'{val}\' at context[\'{key}\'], ' f'because {err}' ) from err def get_formatted_iterable(self, obj, memo=None): """Use get_formatted_value(input_value) instead. Deprecated.""" from warnings import warn warn( ("Use get_formatted_value(input_value) instead of " "get_formatted_iterable"), DeprecationWarning) return self.formatter.vformat(obj, None, self) def get_formatted_string(self, input_string): """Use get_formatted_value(input_value) instead. Deprecated.""" from warnings import warn warn( ("Use get_formatted_value(input_value) instead of " "get_formatted_string"), DeprecationWarning) if isinstance(input_string, str): try: return self.formatter.vformat(input_string, None, self) except KeyNotInContextError as err: # Wrapping the KeyError into a less cryptic error for end-user # friendliness raise KeyNotInContextError( f'Unable to format \'{input_string}\' because {err}' ) from err elif isinstance(input_string, SpecialTagDirective): return input_string.get_value(self) else: raise TypeError(f"can only format on strings. {input_string} is a " f"{type(input_string)} instead.") def get_formatted_as_type(self, value, default=None, out_type=str): """Return formatted value for input value, returns as out_type. Caveat emptor: if out_type is bool and value a string, return will be True if str is 'True', 'TRUE', '1' or '1.0'. It will be False for all other cases. Args: value: the value to format
in dc_map: device_capability_ids.append(dc_map[dc]) else: raise BadSettingException("Invalid Device Capability: {} ".format(dc)) # Get (or potentially create) the advertiser. advertiser_id = dfp.get_advertisers.get_advertiser_id_by_name( advertiser_name, advertiser_type) # Create the order. order_id = dfp.create_orders.create_order(order_name, advertiser_id, user_id) # Create creatives. #Get creative template for native platform creative_template_ids = None if creative_type == constant.NATIVE: creative_template_ids = dfp.get_creative_template.get_creative_template_ids_by_name(creative_template) #if bidder is None, then bidder will be 'All' bidder_str = bidder_code if bidder_str == None: bidder_str = "All" elif isinstance(bidder_str, (list, tuple)): bidder_str = "_".join(bidder_str) #generate unique id that will be used for creative and line item naming unique_id = get_unique_id(creative_type) #create creatives logger.info("creating creatives...") size_arg = sizes if use_1x1: size_arg = None creative_configs = get_creative_config(creative_type, bidder_str, order_name, advertiser_id, size_arg, num_creatives, creative_template_ids, prefix=unique_id) creative_ids = dfp.create_creatives.create_creatives(creative_configs) # if platform is video, create creative sets if creative_type in (constant.VIDEO, constant.JW_PLAYER): creative_set_configs = dfp.create_creative_sets.create_creative_set_config(creative_ids, sizes, unique_id) creative_ids = dfp.create_creative_sets.create_creative_sets(creative_set_configs) # Create line items. # if line item prefix is not passed, set unique id as lineitem prefix if lineitem_prefix is None: lineitem_prefix = unique_id logger.info("creating line_items_config...") line_items_config = create_line_item_configs(prices, order_id, placement_ids, bidder_code, sizes, OpenWrapTargetingKeyGen(), lineitem_type, lineitem_prefix, currency_code, custom_targeting, creative_type, creative_template_ids, same_adv_exception=same_adv_exception,ad_unit_ids=ad_unit_ids, device_category_ids=device_category_ids, device_capability_ids=device_capability_ids, roadblock_type=roadblock_type) logger.info("Creating line items...") line_item_ids = dfp.create_line_items.create_line_items(line_items_config) # Associate creatives with line items. size_overrides = [] if use_1x1 and creative_type is not constant.NATIVE: size_overrides = sizes logger.info("Creating lineitem creative associations...") dfp.associate_line_items_and_creatives.make_licas(line_item_ids, creative_ids, size_overrides=size_overrides, creative_type=creative_type) logger.info(""" Done! Please review your order, line items, and creatives to make sure they are correct. Then, approve the order in DFP. Happy bidding! """) def get_creative_file(creative_type): creative_file = "creative_snippet_openwrap.html" if creative_type == constant.WEB: creative_file = "creative_snippet_openwrap.html" elif creative_type == constant.WEB_SAFEFRAME: creative_file = "creative_snippet_openwrap_sf.html" elif creative_type == constant.AMP: creative_file = "creative_snippet_openwrap_amp.html" elif creative_type == constant.IN_APP: creative_file = "creative_snippet_openwrap_in_app.html" return creative_file def create_line_item_configs(prices, order_id, placement_ids, bidder_code, sizes, key_gen_obj, lineitem_type, lineitem_prefix, currency_code, custom_targeting, creative_type, creative_template_ids, ad_unit_ids=None, same_adv_exception=False, device_category_ids=None,device_capability_ids=None, roadblock_type='ONE_OR_MORE'): """ Create a line item config for each price bucket. Args: prices (array) order_id (int) placement_ids (arr) bidder_code (str or arr) sizes (arr) key_gen_obj (obj) lineitem_type (str) lineitem_prefix (str) currency_code (str) custom_targeting (arr) creative_type (str) creative_template_ids (arr) ad_unit_ids (arr) same_adv_exception(bool) device_category_ids (int) device_capability_ids (int) roadblock_type (str) Returns: an array of objects: the array of DFP line item configurations """ key_gen_obj.set_creative_type(creative_type) # Set DFP custom targeting for key `pwtpid` based on bidder code key_gen_obj.set_bidder_value(bidder_code) # Set DFP targeting for custom targetting passed in settings.py key_gen_obj.set_custom_targeting(custom_targeting) #do not set platform targeting for inapp,jwplayer if creative_type not in (constant.IN_APP, constant.JW_PLAYER): key_gen_obj.set_platform_targetting() if creative_type is constant.JW_PLAYER: key_gen_obj.set_jwplayer_key() line_items_config = [] #create line item config for each price for price in prices: price_str = num_to_str(price['rate'], precision=3) # Remove trailing zero if exists if re.match("\d+\.\d{2}0",price_str): price_str = price_str[0:-1] bidder_str = bidder_code if bidder_str == None: bidder_str = "All" elif isinstance(bidder_str, (list, tuple)): bidder_str = "_".join(bidder_str) # Autogenerate the line item name. (prefix_rate) line_item_name = '{}_{}'.format(lineitem_prefix, price_str ) # Set DFP custom targeting for key `pwtecp` key_gen_obj.set_price_value(price) config = dfp.create_line_items.create_line_item_config( name=line_item_name, order_id=order_id, placement_ids=placement_ids, cpm_micro_amount=num_to_micro_amount(round(price['rate'],2)), sizes=sizes, key_gen_obj=key_gen_obj, lineitem_type=lineitem_type, currency_code=currency_code, creative_type=creative_type, creative_template_ids=creative_template_ids, ad_unit_ids=ad_unit_ids, same_adv_exception=same_adv_exception, device_categories=device_category_ids, device_capabilities=device_capability_ids, roadblock_type=roadblock_type ) line_items_config.append(config) return line_items_config #This method returns creative config based on the creative type def get_creative_config(creative_type, bidder_str, order_name, advertiser_id, sizes, num_creatives, creative_template_ids, prefix): creative_configs= [] if creative_type == constant.NATIVE: creative_configs = dfp.create_creatives.create_creative_configs_for_native(advertiser_id, creative_template_ids, num_creatives, prefix) elif creative_type == constant.VIDEO: creative_configs = dfp.create_creatives.create_creative_configs_for_video(advertiser_id, sizes, prefix, constant.VIDEO_VAST_URL, constant.VIDEO_DURATION) elif creative_type == constant.JW_PLAYER: creative_configs = dfp.create_creatives.create_creative_configs_for_video(advertiser_id, sizes, prefix, constant.JWP_VAST_URL, constant.JWP_DURATION) else: use_safe_frame = False if creative_type in (constant.WEB_SAFEFRAME, constant.AMP): use_safe_frame = True creative_file = get_creative_file(creative_type) creative_configs = dfp.create_creatives.create_duplicate_creative_configs( bidder_str, order_name, advertiser_id, sizes, num_creatives, creative_file=creative_file, safe_frame=use_safe_frame, prefix=prefix) return creative_configs def get_unique_id(creative_type): uid = shortuuid.uuid() if creative_type in (constant.WEB, constant.WEB_SAFEFRAME): uid = u'DISPLAY_{}'.format(uid) if creative_type is constant.AMP: uid = u'AMP_{}'.format(uid) if creative_type is constant.IN_APP: uid = u'INAPP_{}'.format(uid) if creative_type is constant.NATIVE: uid = u'NATIVE_{}'.format(uid) if creative_type is constant.VIDEO: uid = u'VIDEO_{}'.format(uid) if creative_type is constant.JW_PLAYER: uid = u'JWP_{}'.format(uid) return uid def get_calculated_rate(start_rate_range, end_rate_range, rate_id, exchange_rate): if(start_rate_range == 0 and rate_id == 2): rate_id = 1 if rate_id == 2: return round(start_rate_range * exchange_rate, 3) else: return round(((start_rate_range + end_rate_range) / 2.0) * exchange_rate, 3) def get_dfp_network(): current_network = dfp.get_network.get_dfp_network() return current_network def get_exchange_rate(currency_code): #currency_code = 'GBP' url = "http://api.currencylayer.com/live?access_key=55586212cb183ad61a879b07d76e1d47&source=USD&currencies=" + currency_code +"&format=1" response = urlopen(url) string = response.read().decode('utf-8') json_obj = json.loads(string) return float(json_obj['quotes']['USD' + currency_code]) def load_price_csv(filename, creative_type): buckets = [] exchange_rate = 1 #read currency conversion flag currency_exchange = True # Currency module/CURRENCY_EXCHANGE is applicable for web and native platform if creative_type in (constant.WEB, constant.WEB_SAFEFRAME, constant.NATIVE): currency_exchange = getattr(settings, 'CURRENCY_EXCHANGE', True) if currency_exchange: network = get_dfp_network() logger.info("Network currency : %s", network.currencyCode) exchange_rate = get_exchange_rate(network.currencyCode) logger.info("Currency exchange rate: {}".format(exchange_rate)) #currency rate handling till here with open(filename, 'r') as csvfile: preader = csv.reader(csvfile) next(preader) # skip header row for row in preader: # ignore extra lines or spaces if row == [] or row[0].strip() == "": continue print(row) try: start_range = float(row[2]) end_range = float(row[3]) granularity = float(row[4]) rate_id = int(row[5]) except ValueError: raise BadSettingException('Start range, end range, granularity and rate id should be number. Please correct the csv and try again.') validateCSVValues(start_range, end_range, granularity, rate_id) if granularity != -1: i = start_range while i < end_range: a = round(i + granularity,2) if a > end_range: a = end_range if round(i,2) != (a,2): buckets.append({ 'start': i, 'end': a, 'granularity': granularity, 'rate': get_calculated_rate(i, a, rate_id, exchange_rate) }) i = a else: buckets.append({ 'start': start_range, 'end': end_range, 'granularity': 1.0, 'rate': get_calculated_rate(start_range, end_range, rate_id, exchange_rate) }) return buckets def validateCSVValues(start_range, end_range, granularity, rate_id): if start_range < 0 or end_range < 0 : raise BadSettingException('Start range and end range can not be negative. Please correct the csv and try again.') if start_range > end_range: raise BadSettingException('Start range can not be more than end range. Please correct the csv and try again.') if rate_id not in (1,2): raise BadSettingException('Rate id can only be 1 or 2. Please correct the csv and try again') if start_range < 0.01 and granularity == 0.01: raise BadSettingException('Start range can not be less than 0.01 for granularity 0.01, either increase granularity or start range in csv.') if end_range > 999: raise BadSettingException('End range can not be more then 999. Please correct the csv and try again.') if granularity == 0: raise BadSettingException('Zero is not accepted as granularity. Please correct the csv and try again') class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def main(): """ Validate the settings and ask for confirmation from the user. Then, start all necessary DFP tasks. """ user_email = getattr(settings, 'DFP_USER_EMAIL_ADDRESS', None) if user_email is None: raise MissingSettingException('DFP_USER_EMAIL_ADDRESS') advertiser_name = getattr(settings, 'DFP_ADVERTISER_NAME', None) if advertiser_name is None: raise MissingSettingException('DFP_ADVERTISER_NAME') advertiser_type = getattr(settings, 'DFP_ADVERTISER_TYPE', "ADVERTISER") if advertiser_type != "ADVERTISER" and advertiser_type != "AD_NETWORK": raise BadSettingException('DFP_ADVERTISER_TYPE') order_name = getattr(settings, 'DFP_ORDER_NAME', None) if order_name is None: raise MissingSettingException('DFP_ORDER_NAME') lineitem_type = getattr(settings, 'DFP_LINEITEM_TYPE', None) if lineitem_type is None: raise MissingSettingException('DFP_LINEITEM_TYPE') num_placements = 0 placements = getattr(settings, 'DFP_TARGETED_PLACEMENT_NAMES', None) placements_print = str(placements) if placements is None: placements = [] placements_print = "RON" # if no placements are specified, we wil do run of network which is # effectively one placement num_placements = len(placements) if num_placements == 0: num_placements = 1 placements_print = "RON" creative_type = getattr(settings, 'OPENWRAP_CREATIVE_TYPE', None) if creative_type is None: creative_type = constant.WEB elif creative_type not in [constant.WEB, constant.WEB_SAFEFRAME, constant.AMP, constant.IN_APP, constant.NATIVE, constant.VIDEO, constant.JW_PLAYER]: raise BadSettingException('Unknown OPENWRAP_CREATIVE_TYPE: {0}'.format(creative_type)) sizes = getattr(settings, 'DFP_PLACEMENT_SIZES', None) if creative_type != constant.NATIVE: if sizes is None: raise MissingSettingException('DFP_PLACEMENT_SIZES') elif len(sizes) < 1: raise BadSettingException('The setting "DFP_PLACEMENT_SIZES" ' 'must contain at least one size object.') currency_code = getattr(settings, 'DFP_CURRENCY_CODE', 'USD') # How many creatives to attach to each line item. We need at least one # creative per ad unit on a page. See: # https://github.com/kmjennison/dfp-prebid-setup/issues/13 num_creatives = ( getattr(settings, 'DFP_NUM_CREATIVES_PER_LINE_ITEM', None) or num_placements ) # read creative template for native Line-items creative_template = None if creative_type == constant.NATIVE: creative_template = getattr(settings, 'OPENWRAP_CREATIVE_TEMPLATE', None) if creative_template
dist_record['price'] = order.price dist_record['operation'] = 'sell-part' self.save_dist(dist_record) del self.uncompletedOrders[orderkey] self.entrust = 0 # ---------------------------------------------------------------------- def onStopOrder(self, orderRef): """停止单更新""" self.writeCtaLog(u'{0},停止单触发,orderRef:{1}'.format(self.curDateTime, orderRef)) pass # ---------------------------------------------------------------------- def onTick(self, tick): """行情更新 1、执行延时任务 2、推送Tick到M5、M30、D 3、强制清仓逻辑 4、止损逻辑 4、加仓逻辑 :type tick: object """ self.curTick = tick # 更新策略执行的时间(用于回测时记录发生的时间) self.curDateTime = tick.datetime self.cur_price = tick.lastPrice self.lineM.onTick(copy.copy(tick)) # 更新持仓 self.base_pos = self.ctaEngine.posBufferDict.get('.'.join([self.base_asset, self.exchange]), None) self.quote_pos = self.ctaEngine.posBufferDict.get('.'.join([self.quote_asset, self.exchange]), None) # 4、交易逻辑 # 首先检查是否是实盘运行还是数据预处理阶段 if not self.inited: return # 执行撤单逻辑 self.cancelLogic(tick.datetime) if len(self.lineM.lineEma2) < 3 or len(self.lineM.lineAtr1)<1: return # 网格逐一止损/止盈检查 self.tns_check_grid() # 对买入任务的网格执行逐笔买入动作 self.tns_execute_long_grids() # 对卖出任务的网格执行逐笔卖出动作 self.tns_excute_short_grids() if self.last_minute != tick.datetime.minute: self.last_minute = tick.datetime.minute # 每分钟处理逻辑 self.tns_logic() # 对买入任务的网格执行逐笔买入动作 self.tns_execute_long_grids() # 对卖出任务的网格执行逐笔卖出动作 self.tns_excute_short_grids() self.display_position() self.display_grids() self.display_tns() self.putEvent() # ---------------------------------------------------------------------- def onBar(self, bar): """ 分钟K线数据(仅用于回测时,从策略外部调用" :param bar: :return: """ if self.mode == CtaDayBar.BAR_MODE and self.backtesting: self.curDateTime = bar.datetime + timedelta(seconds=self.TMinInterval * 60) else: self.curDateTime = bar.datetime self.cur_price = bar.close if self.inited: if self.mode == CtaDayBar.BAR_MODE and self.entrust != 0: self.cancelLogic(dt=self.curDateTime) # 网格逐一止损/止盈检查 self.tns_check_grid() # 推送bar到大周期K线 try: self.lineM.addBar(copy.copy(bar), bar_freq=self.TMinInterval) # 需要先生成日线,分钟时才好得到当天的开盘价 except Exception as ex: self.writeCtaError(u'{},{}'.format(str(ex), traceback.format_exc())) if len(self.lineM.lineEma2) < 3 or len(self.lineM.lineAtr1)<1: return if not self.inited: return self.tns_logic() # 对买入任务的网格执行逐笔买入动作 self.tns_execute_long_grids() # 对卖出任务的网格执行逐笔卖出动作 self.tns_excute_short_grids() if bar.datetime.minute % 5 ==0: self.display_position() self.display_grids() self.display_tns() # ---------------------------------------------------------------------- def onBarM(self, bar): """ K线OnBar事件 :param bar: :return: """ self.writeCtaLog(self.lineM.displayLastBar()) # 每个大周期的新Bar,都需要重置一次 self.min_rt_dnline_touched = False self.min_rt_upline_touched = False if len(self.lineM.lineBar) < 2: return if bar.high == bar.low: self.writeCtaError(u'{} 最高价{}=最低价{},不做计算'.format(bar.datetime,bar.high , bar.low)) return spread_max = max(bar.high-bar.close, bar.close-bar.low ) spread_min = min(bar.high - bar.close, bar.close - bar.low) if bar.close > bar.open: up_line = spread_max down_line = spread_min elif bar.close < bar.open: up_line = spread_min down_line = spread_max else: self.writeCtaError(u'{} 开盘价{}=收盘价{},不做计算'.format(bar.datetime, bar.open, bar.close)) return self.writeCtaLog(u'{} upperBand:{}, lowerBand:{}'.format(self.lineM.name, self.lineUpperBand, self.lineLowerBand)) def tns_logic(self): """ 事务逻辑, 1、非观测状态,进入观测状态 2、做多事务期间, 价格下穿ema1,进入区间观测状态 3、做多事务+观测期间,判断是否满足DTOSC低位状态 4、出现死叉时,退出做多事务 5、如果不是做多事务,又持有多单,则需要平仓 :return: """ if len(self.lineM.lineSD) < 2: return def tns_check_grid(self): """ 网格逐一止损/止盈检查 :return: """ # 多单网格逐一止损/止盈检查: if self.position.longPos > 0 and self.entrust == 0: has_changed = False long_grids = self.gt.getOpenedGrids(direction=DIRECTION_LONG) pre_longPos = self.position.longPos remove_gids = [] for g in long_grids: grid_pre_high = g.snapshot.get('pre_high',0) if not g.openStatus or g.orderStatus: continue # 止损 if g.stopPrice > 0 and g.stopPrice > self.cur_price: self.writeCtaLog( u'{} onBar触发多单止损线,Bar.close:{},open:{},StopPrice:{},v:{}'. format(self.curDateTime, self.cur_price, g.openPrice, g.stopPrice, g.volume)) # 创建平多事务 if self.tns_sell_long(sell_volume=g.volume): g.openStatus = False g.orderStatus = False has_changed = True remove_gids.append(g.id) else: self.writeCtaLog(u'创建平多网格失败') # 止盈 elif self.cur_price > g.closePrice: self.writeCtaLog( u'{} onBar触发多单止盈线,Bar.close:{},open:{},StopPrice:{},v:{}'. format(self.curDateTime, self.cur_price, g.openPrice, g.stopPrice, g.volume)) # 创建平多事务 if self.tns_sell_long(sell_volume=g.volume): g.openStatus = False g.orderStatus = False has_changed = True remove_gids.append(g.id) else: self.writeCtaLog(u'创建平多网格失败') # 提升止损价 elif not g.snapshot.get('protected',False) and self.cur_price >= g.openPrice+ 2 * self.lineM.lineAtr1[-1]: self.writeCtaLog(u'价格{}已经提升至开仓价{}2个ATR{}位置,提升止损价{}=>{}' .format(self.cur_price,g.openPrice,self.lineM.lineAtr1[-1], g.stopPrice, g.openPrice+self.minDiff)) g.snapshot['protected'] = True g.stopPrice = g.openPrice+self.minDiff has_changed = True for gid in remove_gids: self.writeCtaLog(u'移除做多网格,id={}'.format(gid)) self.gt.removeGridById(direction=DIRECTION_LONG, id=gid) has_changed = True if has_changed: # 即时执行卖出网格 self.tns_excute_short_grids() self.gt.save() def tns_add_long(self, stop_price,win_price=0,pre_high=0): """ 事务开多仓 :param stop_price: :return: """ if self.cur_price < stop_price: self.writeCtaError(u'参数出错,开仓价:{}低于止损价{}'.format(self.cur_price, stop_price)) return False if win_price > 0 and win_price < self.cur_price: self.writeCtaError(u'参数出错,止盈价:{}低于开仓价{}'.format(win_price,self.cur_price)) return False # 增加多头事务 if self.entrust != 0: return False volume = self.inputSS # 存在多单子,不开仓 opened_volume = 0 for g in self.gt.dnGrids: if g.openStatus and g.volume > 0: self.writeCtaLog(u'已经持有多单:{},不再开仓'.format(g.volume)) return False if g.openStatus == False and g.orderStatus: if g.orderRef != EMPTY_STRING: g.orderRef = EMPTY_STRING self.writeCtaLog(u'已经存在待开多网格') return False self.policy.tns_direction = DIRECTION_LONG self.policy.tns_start_date = self.curDateTime.strftime('%Y-%m-%d') self.policy.tns_start_price = self.cur_price grid = CtaGrid(direction=DIRECTION_LONG, openprice=self.cur_price, closeprice=sys.maxsize if win_price==0 else win_price, stopprice=stop_price, volume=volume) # 增加前高值 if pre_high > grid.openPrice: grid.snapshot['pre_high'] = pre_high grid.orderStatus = True self.writeCtaLog(u'创建事务多单,开仓价:{},数量:{},止损价:{},止盈价:{}' .format(grid.openPrice, grid.volume, grid.stopPrice, grid.closePrice)) self.gt.dnGrids.append(grid) self.gt.save() return True def tns_sell_long(self, sell_volume): """ 事务平空(现货减多单) :param period: :param stop_price: :return: """ if self.entrust !=0: return False if sell_volume <=0: return False if self.backtesting: if self.position.longPos < sell_volume: self.writeCtaError(u'当前持仓:{},小于卖出数量:{},不处理卖出信号'.format(self.position.longPos,sell_volume)) return True else: if self.base_pos is None: msg = u'目前没有{}持仓信息,卖出信号不处理'.format(self.base_asset) self.writeCtaError(msg) return False if self.base_pos.longPosition == 0: self.writeCtaLog(u'当前{}持仓为0,卖出信号不处理'.format(self.base_asset)) return True avaliable_volume = self.base_pos.longPosition - self.base_pos.frozen if avaliable_volume < sell_volume: self.writeCtaLog(u'当前{}持仓:{},冻结:{},剩余可卖数量:{},小于:{}' .format(self.base_asset, self.base_pos.longPosition, self.base_pos.frozen, avaliable_volume, sell_volume)) if avaliable_volume < sell_volume* 0.5 : self.writeCtaLog(u'{} 小于计划卖出{}的一半, 卖出信号不处理'.format(avaliable_volume, sell_volume)) return True self.writeCtaLog(u'计划卖出数量:{}=>{}'.format(sell_volume, avaliable_volume)) sell_volume = avaliable_volume if sell_volume < self.min_trade_volume: self.writeCtaLog(u'计划卖出数量{}小于最小成交数量:{},卖出信号不处理' .format(sell_volume,self.min_trade_volume)) return True self.policy.tns_direction = DIRECTION_SHORT self.policy.tns_start_date = self.curDateTime.strftime('%Y-%m-%d') grid = CtaGrid(direction=DIRECTION_SHORT, openprice=self.cur_price, closeprice= 0, stopprice=0, volume= sell_volume) grid.orderStatus = True self.writeCtaLog(u'创建事务空单,卖出价:{},数量:{},止损价:{}' .format(grid.openPrice, grid.volume, grid.stopPrice)) self.gt.upGrids.append(grid) self.gt.save() return True def tns_update_fail(self): if self.backtesting: return cur_hour_fail = self.fail_in_hour.get(self.curDateTime.hour, 0) cur_hour_fail += 1 self.fail_in_hour[self.curDateTime.hour] = cur_hour_fail # self.writeCtaError(u'当前小时累计失败:{}次'.format(cur_hour_fail)) def tns_excute_short_grids(self): """ 事务执行减仓网格 1、找出所有委托状态是True/OpenStatus=False得空网格。 2、比对volume和traded volume, 如果两者得数量差,大于min_trade_volume,继续发单 :return: """ if self.entrust != 0: self.writeCtaLog(u'{}正在委托中,不执行减仓检查'.format(self.curDateTime)) return if not self.tradingOpen: self.writeCtaLog(u'{}当前不是允许交易状态') return ordering_grid = None for grid in self.gt.upGrids: # 排除已经执行完毕的网格 if grid.openStatus: continue # 排除非委托状态的网格 if not grid.orderStatus: continue # 排除存在委托单号的网格 if len(grid.orderRef)>0: continue if grid.volume - grid.tradedVolume <= self.min_trade_volume: self.tns_finish_short_grid(grid) return # 定位到首个满足条件的网格,跳出循环 ordering_grid = grid break # 没有满足条件的网格 if ordering_grid is None: return sell_volume = EMPTY_FLOAT if self.backtesting: cur_pos = self.ctaEngine.posBufferDict.get(self.vtSymbol,None) if cur_pos is None: self.writeCtaError(u'当前{}持仓查询不到'.format(self.vtSymbol)) return if cur_pos.longPosition - cur_pos.frozen <= 0: self.writeCtaError(u'总量:{},冻结:{},不足卖出' .format(cur_pos.longPosition, cur_pos.frozen, ordering_grid.volume)) return if cur_pos.longPosition-cur_pos.frozen >= ordering_grid.volume - ordering_grid.tradedVolume: sell_volume = ordering_grid.volume - ordering_grid.tradedVolume self.writeCtaLog(u'总量:{},冻结:{},网格减仓量:{},已成交:{},预计委托卖出:{}' .format(cur_pos.longPosition, cur_pos.frozen, ordering_grid.volume, ordering_grid.tradedVolume, sell_volume)) else: volume = ordering_grid.volume tradedVolume = ordering_grid.tradedVolume sell_volume = cur_pos.longPosition-cur_pos.frozen if tradedVolume > 0: ordering_grid.tradedVolume = ordering_grid.volume - sell_volume else: ordering_grid.volume = sell_volume self.writeCtaLog(u'总量:{},冻结:{},网格减仓量:{}=>{},已成交:{}={},预计委托卖出:{}' .format(cur_pos.longPosition, cur_pos.frozen, volume, ordering_grid.volume, tradedVolume, ordering_grid.tradedVolume, sell_volume)) else: if self.base_pos is None: self.writeCtaError(u'当前{}持仓查询不到'.format(self.base_asset)) return # 根据市场计算,前5档买单数量 market_ask_volumes = self.curTick.askVolume1 + self.curTick.askVolume2 + self.curTick.askVolume3 + self.curTick.askVolume4 + self.curTick.askVolume5 market_bid_volumes = self.curTick.bidVolume1 + self.curTick.bidVolume2 + self.curTick.bidVolume3 + self.curTick.bidVolume4 + self.curTick.bidVolume5 # 查询合约的最小成交数量 contract = self.ctaEngine.mainEngine.getContract(self.vtSymbol) if contract and contract.volumeTick > self.min_trade_volume: self.min_trade_volume = contract.volumeTick sell_volume = ordering_grid.volume - ordering_grid.tradedVolume if sell_volume < self.min_trade_volume: self.tns_finish_short_grid(ordering_grid) return if sell_volume > self.max_trade_volume: self.writeCtaLog(u'卖出{}超过单次最高数量:{}'.format(sell_volume, self.max_trade_volume)) sell_volume = self.max_trade_volume if sell_volume > min(market_bid_volumes / 5, market_ask_volumes / 5): self.writeCtaLog(u'卖出{} {},超过叫买量/5:{} 或叫卖量/5:{},降低为:{}' .format(self.base_asset, sell_volume, market_bid_volumes / 5, market_ask_volumes / 5, min(market_bid_volumes / 5, market_ask_volumes / 5))) sell_volume = min(market_bid_volumes / 5, market_ask_volumes / 5) sell_volume = self.digits(sell_volume, self.min_trade_volume) if sell_volume < self.min_trade_volume: self.writeCtaError(u'{} 计算的减仓={}:不满足减仓数量最低要求'.format(self.curDateTime, sell_volume)) return if self.backtesting: sell_price = self.cur_price - self.minDiff else: sell_price = self.curTick.askPrice1-self.minDiff self.writeCtaLog(u'{} 减多仓:减仓价为:{},减仓手数:{}'.format(self.curDateTime,sell_price , sell_volume)) ref = self.sell(price=sell_price, volume=sell_volume, orderTime=self.curDateTime,grid=ordering_grid) if ref is None or len(ref) == 0: self.writeCtaError(u'sell失败') return if not self.backtesting and self.base_pos : self.writeCtaLog(u'降低持仓basePos:{}=>{}'.format(self.base_pos.longPosition, self.base_pos.longPosition-sell_volume)) self.base_pos.longPosition -= sell_volume self.base_pos.frozen += sell_volume def tns_finish_short_grid(self, grid): """ 做空网格(卖出多单)执行完成 :param grid: :return: """ self.writeCtaLog(u'卖出网格执行完毕,price:{},v:{},traded:{}'.format(grid.openPrice, grid.volume, grid.tradedVolume)) grid.orderStatus = False grid.openStatus = True volume = grid.volume tradedVolume = grid.tradedVolume if grid.tradedVolume > 0: grid.volume = grid.tradedVolume grid.tradedVolume = 0 self.writeCtaLog(u'设置{}网格委托状态为: {},完成状态:{} v:{}=>{},traded:{}=>{}' .format(grid.direction, grid.orderStatus, grid.openStatus, volume, grid.volume, tradedVolume, grid.tradedVolume)) self.position.closePos(direction=DIRECTION_SHORT,vol=grid.volume) if self.position.longPos < self.min_trade_volume: # 所有多仓位已经平完 self.writeCtaLog(u'所有多仓位已经平完,清除position&事务') self.position.clear() self.policy.clean() dist_record = OrderedDict() dist_record['datetime'] = self.curDateTime dist_record['volume'] = grid.volume dist_record['price'] = self.cur_price dist_record['operation'] = 'sell-finished' self.save_dist(dist_record) id = grid.id try: self.gt.removeGridById(direction=DIRECTION_SHORT,id=id) except Exception as ex: self.writeCtaError(u'移除卖出网格失败,id={},ex:{}'.format(id, str(ex))) self.gt.save() self.putEvent() def tns_execute_long_grids(self): """ 事务执行买入 1、找出所有委托状态是True/OpenStatus=False得多网格。 2、比对volume和traded volume, 如果两者得数量差,大于min_trade_volume,继续发单 :return: """ if self.entrust != 0: if len(self.uncompletedOrders) == 0: self.writeCtaLog(u'当前不存在未完成委托单,重置委托状态') self.entrust = 0 self.writeCtaLog(u'{}正在委托中,不执行买入多仓'.format(self.curDateTime)) return if not self.tradingOpen: self.writeCtaLog(u'{}当前不是允许交易状态') return ordering_grid = None for grid in self.gt.dnGrids: # 排除已经执行完毕的网格 if grid.openStatus: continue # 排除非委托状态的网格 if not grid.orderStatus: continue # 排除存在委托单号的网格 if len(grid.orderRef) > 0: continue if grid.volume - grid.tradedVolume < self.min_trade_volume and grid.tradedVolume > 0: self.tns_finish_long_grid(grid) return # 定位到首个满足条件的网格,跳出循环 ordering_grid = grid break # 没有满足条件的网格 if ordering_grid is None: return buy_volume = ordering_grid.volume - ordering_grid.tradedVolume if not self.backtesting: if self.quote_pos is None: self.writeCtaError(u'现货:{}没有持仓信息'.format(self.quote_asset)) return avaliable_quote = self.quote_pos.longPosition - self.quote_pos.frozen if avaliable_quote <= 0: self.writeCtaError(u'现货:{} 持仓:{},冻结:{},可用资金不足买入'.format(self.quote_asset, self.quote_pos.longPosition, self.quote_pos.frozen)) return if avaliable_quote < self.cur_price * buy_volume: self.writeCtaLog( u'当前可用{}:{},不足已{}买入:{} '.format(self.quote_asset, avaliable_quote, self.cur_price, buy_volume)) buy_volume = avaliable_quote / self.cur_price buy_volume = self.digits(buy_volume, self.min_trade_volume) if buy_volume >= self.min_trade_volume: volume = ordering_grid.volume ordering_grid.volume = ordering_grid.tradedVolume + buy_volume self.writeCtaLog(u'调整网格多单目标:{}=>{}'.format(volume, ordering_grid.volume)) else: return # 根据市场计算,前5档买单数量 market_ask_volumes = self.curTick.askVolume1 + self.curTick.askVolume2 + self.curTick.askVolume3 + self.curTick.askVolume4 + self.curTick.askVolume5 market_bid_volumes = self.curTick.bidVolume1 + self.curTick.bidVolume2 + self.curTick.bidVolume3 + self.curTick.bidVolume4 + self.curTick.bidVolume5 # 查询合约的最小成交数量 contract = self.ctaEngine.mainEngine.getContract(self.vtSymbol) if contract and contract.volumeTick > self.min_trade_volume: self.min_trade_volume = contract.volumeTick if buy_volume > self.max_trade_volume: self.writeCtaLog(u'买入{}超过单次最高数量:{}'.format(buy_volume, self.max_trade_volume)) buy_volume = self.max_trade_volume if buy_volume > min(market_bid_volumes / 5, market_ask_volumes / 5): self.writeCtaLog(u'买入{} {},超过叫买量/5:{} 或叫卖量/5:{},降低为:{}' .format(self.base_asset, buy_volume, market_bid_volumes / 5, market_ask_volumes / 5, min(market_bid_volumes / 5, market_ask_volumes / 5))) buy_volume = min(market_bid_volumes / 5, market_ask_volumes / 5) buy_volume =
<gh_stars>0 # -*- coding: UTF-8 -*- from django.http import HttpResponse, HttpResponseBadRequest from .myparser import * from xml.etree.ElementTree import Element, tostring, fromstring from django.utils import timezone from django.db.models import Q from django.db.models.query import QuerySet from django.db import transaction from django.core.exceptions import * from django.conf import settings from functools import reduce import random, re, pickle, yaml, base64, json, time, datetime, math VERSION = '0.1.9' class UserContext(object): def __init__(self): self.csrfTokenInfo = '' self.languageKey = '' class MetadataException(Exception): pass class BadRequestException(Exception): pass class NotImplementedException(Exception): pass class NoAuthException(Exception): pass class InternalException(Exception): pass class ParameterErrorException(BadRequestException): pass class ValidationErrorException(BadRequestException): pass class CreateErrorException(BadRequestException): pass class UpdateErrorException(BadRequestException): pass class DeleteErrorException(BadRequestException): pass class ReadErrorException(BadRequestException): pass class MetadataUtil(object): def __init__(self, metadata): self.metadata = yaml.load(metadata) self.fieldCache = {} self.keyFieldCache = {} self.mandatoryFeildCache = {} self.updatableFieldCache = {} self.deletableCache = {} self.creatableCache = {} self.updatableCache = {} for k, v in self.metadata.get('sets', {}).items(): entity = self.metadata.get(v, {}) self.fieldCache.setdefault(v, {}) self.keyFieldCache.setdefault(v, {}) self.mandatoryFeildCache.setdefault(v, []) self.updatableFieldCache.setdefault(v, []) for item in entity.get('key', []): self.fieldCache[v][item['name']] = item self.keyFieldCache[v][item['name']] = item if not item.get('nullable', True): self.mandatoryFeildCache[v].append(item['name']) properties = entity.get('property', []) for item in properties: self.fieldCache[v][item['name']] = item if not item.get('nullable', True): self.mandatoryFeildCache[v].append(item['name']) if item.get('updatable', False): self.updatableFieldCache[v].append(item['name']) self.deletableCache.setdefault(v, bool(entity.get('deletable', False))) self.creatableCache.setdefault(v, bool(entity.get('creatable', False))) self.updatableCache.setdefault(v, bool(entity.get('updatable', False))) def getFieldDef(self, entityName, fieldName): cache = self.fieldCache.get(entityName, None) return cache.get(fieldName, None) if cache else None def getMandatoryFields(self, entityName): return self.mandatoryFeildCache[entityName] def getEntityDef(self, entityName): return self.metadata.get(entityName, None) def isKeyField(self, entityName, fieldName): cache = self.keyFieldCache.get(entityName, None) if cache.get(fieldName, None): return True return False def isFieldUpdatable(self, entityName, fieldName): cache = self.updatableFieldCache.get(entityName, None) if fieldName in cache: return True return False def isEntityDeletable(self, entityName): return self.deletableCache.get(entityName, False) def isEntityCreatable(self, entityName): return self.creatableCache.get(entityName, False) def isEntityUpdatable(self, entityName): return self.updatableCache.get(entityName, False) def getKeyFieldDef(self, entityName, keyName=None): entityDef = self.getEntityDef(entityName) if keyName: result = None for key in entityDef['key']: if keyName == key['name']: result = key break return result else: return entityDef['key'] def getProperyFeildDef(self, entityName, propertyName=None): entityDef = self.getEntityDef(entityName) if propertyName: result = None for property in entityDef['property']: if propertyName == property['name']: result = property break return result else: return entityDef['property'] def getExpandFieldDef(self, entityName): entityDef = self.getEntityDef(entityName) expandList = [item['name'] for item in entityDef.get('expand', [])] return expandList def getExpandFieldSetType(self, entityName, expandName): try: for item in self.metadata[entityName]['expand']: if item['name'] == expandName: return item['type'] except Exception as e: return None def getEntityTypeOfName(self, name): if name in self.metadata: return "single" elif name in self.metadata['sets']: return "list" raise InternalException('Wrong name, not list or single') def checkKeyCount(self, entityName): entityDef = self.metadata.get(entityName, None) if not entityDef: return 0 return len(entityDef.get('key', [])) def checkKeyName(self, entityName, keyName): entityDef = self.metadata.get('entityName', None) if not entityDef: return False found = False for key in entityDef['key']: if keyName == key['name']: found = True break return found def checkFieldValueByType(self, value, type): if type == 'int': if not re.compile("^[\d]*$").match(value): raise MetadataException("Value %s doesn't match int type" % value) return int(value) elif type == 'string': if len(value) < 2: raise MetadataException("Value %s must contains \" or \' and length > 2" % value) if (value[0] == '"' and value[-1] == '"') or (value[0] == "'" and value[-1] == "'"): return value[1:-1] else: raise MetadataException("Mismatch \" or \' for string type") class XmlConvert(object): @staticmethod def json_to_xml(tag, json): if type(json) is list: return XmlConvert.array_to_xml(tag, json) elif type(json) is dict: return XmlConvert.dict_to_xml(tag, json) else: return None @staticmethod def array_to_xml(tag, arr): elem = Element(tag) for val in arr: if type(val) is dict: child = XmlConvert.dict_to_xml('item', val) else: child = Element('item') child.text = str(val) elem.append(child) return elem @staticmethod def dict_to_xml(tag, d): elem = Element(tag) for key, val in d.items(): child = Element(key) if type(val) is dict: elem.append(XmlConvert.dict_to_xml(key, val)) elif type(val) is list: elem.append(XmlConvert.array_to_xml(key, val)) else: child.text = str(val) elem.append(child) return elem @staticmethod def xml_to_dict(xml_text): root = fromstring(xml_text) result = {} for item in root: children = item.getchildren() if children and children[0].tag == 'item': result[item.tag] = XmlConvert.xml_to_array(children) else: result[item.tag] = item.text return result @staticmethod def xml_to_array(children): result = [] for child in children: if child.tag != 'item': result.append({child.tag: child.text.strip()}) else: result.append(child.text.strip()) return result class RESTEngine(object): __restApps = {} __responseHeader = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type' } __metaFiles = None __metadataUtil = None __logger = None __dbLogger = None # Default parameter names __parameterNames = { '_query': '_query', '_count': '_count', '_expand': '_expand', '_order': '_order', '_fastquery': '_fastquery', '_page': '_page', '_pnum': '_pnum', '_distinct': '_distinct', '_columns': '_columns' } # Default max return size for all processors __maxReturnSize = 5000 # Default validate csrf token __valCSRFToken = True # Empty json result return blank string __blankForEmptyJsonResult = False CONTENT_TYPE_JSON = 'application/json' CONTENT_TYPE_XML = 'application/xml' CONTENT_TYPE_TEXT = 'text/html' CONTENT_TYPE_ANY = '*/*' DEFAULT_CONTENT_TYPE = CONTENT_TYPE_JSON def __init__(self): pass def setLogger(self, logger): self.__logger = logger def setDBLogger(self, dbLogger): self.__dbLogger = dbLogger def dbLogger(self, request, response, **kwargs): if self.__dbLogger: self.__dbLogger(request, response, **kwargs) def logInfo(self, logstr): if self.__logger: self.__logger.info(logstr) def logDebug(self, logstr): if self.__logger: self.__logger.debug(logstr) def logError(self, logstr): if self.__logger: self.__logger.error(logstr) def setResponseHeader(self, headers): self.__responseHeader.update(headers) def manipulateResponseHeader(self, response): for k, v in self.__responseHeader.items(): response[k] = v def setParameterName(self, params): self.__parameterNames.update(params) def setValCSRFToken(self, valToken): self.__valCSRFToken = valToken def setBlankForEmptyJsonResult(self, blank): self.__blankForEmptyJsonResult = blank def getBlankForEmptyJsonResult(self): return self.__blankForEmptyJsonResult def registerProcessor(self, entityName, processor): processor.setEngine(self) processor.bindEntityName(entityName) if processor.getMaxReturnSize() is None: processor.setMaxReturnSize(self.__maxReturnSize) self.__restApps[entityName] = processor def getProcessor(self, entityName): processor = self.__restApps.get(entityName, None) if not processor: raise InternalException('No processor found for %s' % entityName) return processor def getProcessorByEntitySetName(self, entitySetName): entityName = self.__metadataUtil.metadata['sets'].get(entitySetName, None) if not entityName: raise InternalException('No sets defined for %s' % entitySetName) return self.getProcessor(entityName) def getProcessorByUrlName(self, urlName): processor = self.__restApps.get(urlName, None) if processor: return processor return self.getProcessorByEntitySetName(urlName) def setMetafiles(self, filespath): self.__metaFiles = filespath def getMetafiles(self): if self.__metaFiles is None: raise InternalException('No metadata file path given') return self.__metaFiles def loadMetadata(self, yamlFile): if not yamlFile: raise InternalException('No metadata file') self.__metadataUtil = MetadataUtil(yamlFile) def loadMetadataFromList(self, yamlFileList): for yamlFile in yamlFileList: try: self.loadMetadata(open(yamlFile)) break except Exception as e: raise InternalException('Failed to load yaml meta file: %s' % str(e)) def start(self, metaFiles=None): try: if metaFiles is None: if hasattr(settings, 'MYREST_API_METADATA'): metaFiles = settings.MYREST_API_METADATA ENGINE.loadMetadataFromList(metaFiles) self.logDebug( '[RESTEngine][start] started with MYREST_API_METADATA in settings') else: self.logDebug( '[RESTEngine][start] No metafile path given and no MYREST_API_METADATA found in settings') else: ENGINE.loadMetadataFromList(metaFiles) self.logDebug( '[RESTEngine][start] started with given paths %s' % metaFiles) except Exception as e: raise InternalException('[myrestengine] loadmetadata failed: %s' % str(e)) def getMetadataUtil(self): if self.__metadataUtil is None: raise InternalException('[myrestengine] metadata is None, check load filepath') return self.__metadataUtil def getKeysFromRecord(self, entityName, resultRecord): self.__metadataUtil.getKeyFieldDef(entityName) expandKeys = {} for k in self.__metadataUtil.getKeyFieldDef(entityName): expandKeys[k['name']] = resultRecord[k['name']] expandKeys = {entityName: expandKeys} return expandKeys def __getRandomToken(self): token = '%d%d' % (int(time.time()), random.randint(0, 999),) return token @staticmethod def getUserContext(request): userContextData = request.session.get('myRestContext', None) if userContextData: return pickle.loads(userContextData) else: return None @staticmethod def setUserContext(request, userContext): userContextData = pickle.dumps(userContext) request.session['myRestContext'] = userContextData def __checkAndGenerateCsrfToken(self, request, header): csrfToken = request.META.get('HTTP_CSRF_TOKEN', None) if csrfToken == 'Fetch': token = self.__getRandomToken() tokenBytes = token.encode('utf-8') result = base64.encodebytes(tokenBytes) # token = base64.encodestring(self.__getRandomToken())[:-1] token = result.decode('utf-8')[:-1] expire = time.time() + 3600 userContext = self.getUserContext(request) userContext.csrfTokenInfo = {'token': token, 'expire': expire} header['csrf-token'] = token self.setUserContext(request, userContext) self.logDebug('Token generated and set to session context') def __validateCsrfToken(self, request): csrfToken = request.META.get('HTTP_CSRF_TOKEN', None) userContext = self.getUserContext(request) csrfTokenInfo = userContext.csrfTokenInfo if not csrfToken or not csrfTokenInfo: self.logDebug("No csrf-token in session or request") return False if time.time() <= csrfTokenInfo['expire'] and csrfToken == csrfTokenInfo['token']: return True self.logDebug("csrf-token is expired") return False def __validatePath(self, pathArray): tmpArray = pathArray[:-1] if len(pathArray) > 1: depth = len(pathArray) - 1 for i in range(depth): parentPath, subPath = pathArray[i], pathArray[i + 1] subEntityInfo, parentEntityInfo = self.__getEntityInfo(subPath), self.__getEntityInfo(parentPath) print(subEntityInfo) print(parentEntityInfo) parentEntityName = parentEntityInfo['entityName'] parentEntityKey = parentEntityInfo['keys'] subEntityName = subEntityInfo['entityName'] possibleExpandItems = self.__metadataUtil.getExpandFieldDef(parentEntityName) if subPath not in possibleExpandItems: raise InternalException('Navigation %s is not valid from parent %s' % (subPath, parentEntityName)) if not parentEntityKey: # Parent entity must contain keys for cascade relationship raise InternalException('Keys must be provided for %s' % parentEntityName) parentEntityName = None for path in tmpArray: entityInfo = self.__getEntityInfo(path) entityName = entityInfo['entityName'] keys = entityInfo['keys'] if not keys: # Parent entity must contain keys for cascade relationship raise InternalException('Keys must be provided for %s' % entityInfo['entityName']) if parentEntityName: possibleExpandItems = self.__metadataUtil.getExpandFieldDef(parentEntityName) if path not in possibleExpandItems: raise InternalException('Navigation %s is not valid from %s' % (path, parentEntityName)) parentEntityName = entityName
# Copyright (c) 2021, Oracle and/or its affiliates. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2.0, # as published by the Free Software Foundation. # # This program is also distributed with certain software (including # but not limited to OpenSSL) that is licensed under separate terms, as # designated in a particular file or component or in included license # documentation. The authors of MySQL hereby grant you an additional # permission to link the program and your derivative works with the # separately licensed software that they have included with MySQL. # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License, version 2.0, for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """Sub-Module with utilities for the MySQL Database Service""" from mysqlsh.plugin_manager import plugin_function from mds_plugin import core, configuration, mysql_database_service # cSpell:ignore SQLDB, Popen, bufsize @plugin_function('mds.util.createJumpHost') def get_mds_jump_host(**kwargs): """Returns a public compute instance If the instance does not yet exists in the compartment, create it Args: **kwargs: Optional parameters Keyword Args: instance_name (str): The name of the compute instance db_system_name (str): The new name of the DB System. db_system_id (str): The OCID of the db_system private_key_file_path (str): The file path to an SSH private key subnet_id (str): The OCID of the subnet to use compartment_id (str): The OCID of the compartment config (object): An OCI config object or None. config_profile (str): The name of an OCI config profile interactive (bool): Indicates whether to execute in interactive mode raise_exceptions (bool): If set to true exceptions are raised return_formatted (bool): If set to true, a list object is returned return_python_object (bool): Used for internal plugin calls Returns: None """ instance_name = kwargs.get("instance_name", "MDSJumpHost") db_system_name = kwargs.get("db_system_name") db_system_id = kwargs.get("db_system_id") private_key_file_path = kwargs.get( "private_key_file_path", "~/.ssh/id_rsa") subnet_id = kwargs.get("subnet_id") compartment_id = kwargs.get("compartment_id") config = kwargs.get("config") config_profile = kwargs.get("config_profile") interactive = kwargs.get("interactive", core.get_interactive_default()) raise_exceptions = kwargs.get("raise_exceptions", not interactive) return_formatted = kwargs.get("return_formatted", interactive) return_python_object = kwargs.get("return_python_object", False) # Get the active config and compartment try: config = configuration.get_current_config( config=config, config_profile=config_profile, interactive=interactive) compartment_id = configuration.get_current_compartment_id( compartment_id=compartment_id, config=config) import oci.mysql from pathlib import Path from mds_plugin import compartment, compute, network import time db_system = mysql_database_service.get_db_system( db_system_name=db_system_name, db_system_id=db_system_id, compartment_id=compartment_id, config=config, interactive=interactive, raise_exceptions=True, return_python_object=True) if db_system is None: raise ValueError("DB System not specified or found.") # Get compartment and public subnet_id from MDS if not compartment_id: compartment_id = db_system.compartment_id if not subnet_id: mds_subnet = network.get_subnet( subnet_id=db_system.subnet_id, config=config, interactive=False) subnet = network.get_subnet( network_id=mds_subnet.vcn_id, public_subnet=True, config=config, interactive=False) if subnet: subnet_id = subnet.id if not subnet_id: raise ValueError('No subnet specified.') # Try to get the Compute Instance with the given name mds_jump_host = compute.get_instance( instance_name=instance_name, compartment_id=compartment_id, config=config, interactive=False, raise_exceptions=True, return_python_object=True) # If it already exists, return it if mds_jump_host: return mds_jump_host # if interactive: # # If there is no MySQL DBSystemProxy instance yet, ask the user # print(f"In order to perform the requested operation for the MySQL " # f"DB System\na compute instance named 'MDSJumpHost' " # f"needs to be created.\n") # prompt = core.prompt( # "Do you want to create a new compute instance to be used as " # "bastion host? [YES/no]: ", # {'defaultValue': 'yes'}).strip().lower() # if prompt != "yes": # print("Operation cancelled.\n") # return if interactive: print(f"Creating Compute Instance '{instance_name}'...") new_jump_host = compute.create_instance( instance_name=instance_name, shape="VM.Standard2.1", operating_system="Oracle Linux", operating_system_version="8", use_latest_image=True, subnet_id=subnet_id, public_subnet=True, interactive=interactive, return_python_object=True) if new_jump_host is None: print("Compute instance could not be created.") return # Initialize the identity client compute_client = core.get_oci_compute_client(config=config) print(f"Waiting for Compute Instance '{instance_name}' to become " "available.\nThis can take up to 5 minutes or more.", end="") # Wait until the lifecycle_state == RUNNING, 5 minutes max try: cycles = 0 while cycles < 60: mds_jump_host = compute_client.get_instance( new_jump_host.id).data if mds_jump_host.lifecycle_state == "RUNNING": break else: time.sleep(5) print(".", end="") cycles += 1 print("") except oci.exceptions.ServiceError as e: print(f'Could not fetch the compute instances state.\n' f'ERROR: {e.message}. (Code: {e.code}; Status: {e.status})') return if mds_jump_host.lifecycle_state != "RUNNING": print(f"Compute Instance '{instance_name}' did not become available " f"within 5 minutes. Please check the state manually.") return None if interactive else mds_jump_host # Get the public IP of the instance public_ip = compute.get_instance_public_ip( instance_id=mds_jump_host.id, compartment_id=compartment_id, config=config, private_ip_fallback=True) if public_ip is None or public_ip == "": raise Exception( f"The public IP of the {instance_name} instance could not be " "fetched.") if interactive: print(f"Connecting to {instance_name} instance at {public_ip}...", end="") setup_complete = False cycles = 0 while not setup_complete and cycles < 10: cycles += 1 try: with compute.SshConnection( username="opc", host=public_ip, private_key_file_path=private_key_file_path) as conn: if interactive: print(f"\nConnected to {instance_name} instance at " f"{public_ip}.\n") # Get MySQL Router configuration from remote instance output = "" output = conn.execute('mysqlsh -e "mds.info()"').strip() if "MySQL Shell MDS Plugin" not in output: # If the config is not available yet, give the instance # time to complete setup if interactive: print(f"\nWaiting for {instance_name} setup to be " f"completed.\nThis can take up to 2 minutes.", end="") try: i = 0 while ("MySQL Shell MDS Plugin" not in output and i < 25): output = conn.execute( 'mysqlsh -e "mds.info()"').strip() if "MySQL Shell MDS Plugin" not in output: time.sleep(5) if interactive: print(".", end="") i += 1 except: pass if interactive: print("") if "MySQL Shell MDS Plugin" not in output: raise Exception( f"\nCould not finish the '{instance_name}' setup " f"at {public_ip}.\n") else: setup_complete = True except Exception as e: if cycles < 10: time.sleep(5) if interactive: print(".", end="") else: raise Exception( f"Could not connect to compute instance " f"'{instance_name}' at {public_ip}.\n" f"ERROR: {str(e)}") if interactive: print(f"Compute Instance '{instance_name}' successfully created.") return core.return_oci_object( oci_object=new_jump_host, return_formatted=return_formatted, return_python_object=return_python_object, format_function=compute.format_instance_listing) except Exception as e: if raise_exceptions: raise print(f"ERROR: {str(e)}") @plugin_function('mds.util.createMdsEndpoint', shell=True, cli=True, web=True) def add_public_endpoint(**kwargs): """Creates a public endpoint using MySQL Router on a compute instance If no id is given, it will prompt the user for the id. Args: **kwargs: Optional parameters Keyword Args: instance_name (str): Name of the compute instance db_system_name (str): The new name of the DB System. db_system_id (str): The OCID of the db_system private_key_file_path (str): The file path to an SSH private key compartment_id (str): The OCID of the compartment config (object): An OCI config object or None. config_profile (str): The name of an OCI config profile interactive (bool): Indicates whether to execute in interactive mode raise_exceptions (bool): If set to true exceptions are raised return_formatted (bool): If set to true, a list object is returned Returns: None """ instance_name = kwargs.get("instance_name") db_system_name = kwargs.get("db_system_name") db_system_id = kwargs.get("db_system_id") private_key_file_path = kwargs.get( "private_key_file_path", "~/.ssh/id_rsa") compartment_id = kwargs.get("compartment_id") config = kwargs.get("config") config_profile = kwargs.get("config_profile") interactive = kwargs.get("interactive", core.get_interactive_default()) raise_exceptions = kwargs.get("raise_exceptions", not interactive) return_formatted = kwargs.get("return_formatted", interactive) # Get the active config and compartment try: config = configuration.get_current_config( config=config, config_profile=config_profile, interactive=interactive) compartment_id = configuration.get_current_compartment_id( compartment_id=compartment_id, config=config) db_system_id = configuration.get_current_db_system_id( config=config) from mds_plugin import compute import configparser import io import time db_system = mysql_database_service.get_db_system( db_system_name=db_system_name, db_system_id=db_system_id, compartment_id=compartment_id, config=config, interactive=interactive, return_python_object=True) if db_system is None: raise ValueError("No DB System selected." "Cancelling operation") # Get the first active endpoint endpoints = [e for e in db_system.endpoints if e.status == 'ACTIVE'] if len(endpoints) < 1: raise Exception( "This MySQL DB System has no active endpoints assigned.") endpoint = endpoints[0] # Get the compute instance (let the user create it # if it does not exist yet) jump_host = get_mds_jump_host( instance_name=instance_name, private_key_file_path=private_key_file_path, db_system_id=db_system_id, compartment_id=db_system.compartment_id, config=config, interactive=interactive, return_python_object=True) if not jump_host: raise Exception(f"Compute instance {instance_name} not available." "Operation cancelled.") # Get the public IP of the instance public_ip = compute.get_instance_public_ip( instance_id=jump_host.id, compartment_id=db_system.compartment_id, config=config) if not public_ip: raise Exception(f"The public IP of the instance {instance_name} " "could not be fetched.") # Open an SSH connection to
#!/usr/bin/python import os import sys gem5home = os.getcwd() specint_dir = "benchmarks/spec2k6bin/specint" scriptgen_dir = gem5home + "/scriptgen" results_dir = gem5home + "/results" stdout_dir = gem5home + "/stdout" stderr_dir = gem5home + "/stderr" specint = ['bzip2', 'gcc', 'mcf', 'gobmk', 'hmmer', 'sjeng', 'libquantum', 'h264ref', 'astar', 'xalan'] specintinvoke = { 'bzip2' : specint_dir + "/bzip2 " + specint_dir + "/input.source 280", 'gcc' : specint_dir + "/gcc " + specint_dir + "/200.in -o results/200.s", 'mcf' : specint_dir + "/mcf " + specint_dir + "/inp.in", 'gobmk' : specint_dir + "/gobmk --quiet --mode gtp --gtp-input " + specint_dir + "/13x13.tst", 'hmmer' : specint_dir + "/hmmer " + specint_dir + "/nph3.hmm " + specint_dir + "/swiss41", 'sjeng' : specint_dir + "/sjeng " + specint_dir + "/ref.txt", 'libquantum': specint_dir + "/libquantum 1397 8", 'h264ref' : specint_dir + "/h264ref -d " + specint_dir + "/foreman_ref_encoder_baseline.cfg", 'astar' : specint_dir + "/astar " + specint_dir + "/BigLakes2048.cfg", 'xalan' : specint_dir + "/Xalan -v " + specint_dir + "/t5.xml " + specint_dir + "/xalanc.xsl", 'soplex' : specint_dir + "/soplex -sl -e -m45000 " + specint_dir + "/pds-50.mps" } cpus = ["detailed"] # Workload Characterization # Cache insensitive: astar, libquantum # Large gain beyond half cache: bzip2 mcf xalan soplex # Small gain beyond half cache: gcc h264ref gobmk hmmer sjeng multiprog = [['astar', 'bzip2'], ['bzip2', 'astar'], ['astar', 'mcf'], ['mcf', 'astar'], ['libquantum', 'h264ref'], ['h264ref', 'libquantum'], ['libquantum', 'xalan'], ['xalan', 'libquantum'], ['astar', 'gobmk'], ['gobmk', 'astar'], ['libquantum', 'hmmer'], ['hmmer', 'libquantum'], ['bzip2', 'gcc'], ['gcc', 'bzip2'], ['h264ref', 'gobmk'], ['gobmk', 'h264ref'], ['mcf', 'hmmer'], ['hmmer', 'mcf'], ['xalan', 'sjeng'], ['sjeng', 'xalan'], ] multiprog = [['mcf', 'bzip2'], ['xalan', 'soplex'], ['bzip2', 'xalan'], ['soplex', 'mcf'], ['bzip2', 'mcf'], ['soplex', 'xalan'], ['xalan', 'bzip2'], ['mcf', 'soplex'], ['bzip2', 'soplex'], ['soplex', 'bzip2'], ['xalan', 'mcf'], ['mcf', 'xalan'], ['mcf', 'astar'], ['xalan', 'astar'], ['soplex', 'libquantum'], ['bzip2', 'libquantum'], ['astar', 'mcf'], ['astar', 'xalan'], ['libquantum', 'soplex'], ['libquantum', 'bzip2'], ['mcf', 'libquantum'], ['xalan', 'libquantum'], ['soplex', 'astar'], ['bzip2', 'astar'], ['libquantum', 'mcf'], ['libquantum', 'xalan'], ['astar', 'soplex'], ['astar', 'bzip2'], ['bzip2', 'h264ref'], ['h264ref', 'bzip2'], ['mcf', 'gobmk'], ['hmmer', 'mcf'], ['xalan', 'sjeng'], ['hmmer', 'xalan'], ['soplex', 'h264ref'], ['gobmk', 'soplex'], ['astar', 'libquantum'], ['sjeng', 'gobmk'], ['hmmer', 'sjeng'], ['astar', 'h264ref'], ['libquantum', 'astar'], ['sjeng', 'hmmer'], ['sjeng', 'h264ref'], ['hmmer', 'gobmk'], ['hmmer', 'h264ref'], ['h264ref', 'hmmer'], ['h264ref', 'sjeng'], ['h264ref', 'gobmk'], ['gobmk', 'hmmer'], ['gobmk', 'sjeng'], ['gobmk', 'h264ref'], ['gobmk', 'astar'], ['hmmer', 'astar'], ['sjeng', 'libquantum'], ['h264ref', 'libquantum'], ['astar', 'gobmk'], ['astar', 'hmmer'], ['libquantum', 'sjeng'], ['libquantum', 'h264ref'], ['gobmk', 'libquantum'], ['hmmer', 'libquantum'], ['sjeng', 'astar'], ['h264ref', 'astar'], ['libquantum', 'gobmk'], ['libquantum', 'hmmer'], ['astar', 'sjeng'], ] multiprog4 = [['mcf', 'bzip2', 'xalan', 'soplex'], ['bzip2', 'xalan', 'soplex', 'mcf'], ['xalan', 'soplex', 'mcf', 'bzip2'], ['soplex', 'mcf', 'bzip2', 'xalan'], ['mcf', 'xalan', 'bzip2', 'soplex'], ['xalan', 'bzip2', 'soplex', 'mcf'], ['bzip2', 'soplex', 'mcf', 'xalan'], ['soplex', 'mcf', 'xalan', 'bzip2'], ['mcf', 'xalan', 'astar', 'astar'], ['astar', 'astar', 'mcf', 'xalan'], ['libquantum', 'libquantum', 'soplex', 'bzip2'], ['soplex', 'bzip2', 'libquantum', 'libquantum'], ['mcf', 'astar', 'soplex', 'libquantum'], ['astar', 'mcf', 'libquantum', 'soplex'], ['astar', 'xalan', 'bzip2', 'libquantum'], ['xalan', 'libquantum', 'astar', 'bzip2'], ['mcf', 'xalan', 'h264ref', 'gobmk'], ['h264ref', 'gobmk', 'mcf', 'xalan'], ['hmmer', 'sjeng', 'soplex', 'bzip2'], ['soplex', 'bzip2', 'hmmer', 'sjeng'], ['mcf', 'h264ref', 'soplex', 'hmmer'], ['h264ref', 'mcf', 'hmmer', 'soplex'], ['sjeng', 'xalan', 'bzip2', 'gobmk'], ['xalan', 'gobmk', 'sjeng', 'bzip2'], ['astar', 'astar', 'h264ref', 'gobmk'], ['h264ref', 'gobmk', 'astar', 'astar'], ['hmmer', 'sjeng', 'libquantum', 'libquantum'], ['libquantum', 'libquantum', 'hmmer', 'sjeng'], ['astar', 'h264ref', 'libquantum', 'hmmer'], ['h264ref', 'libquantum', 'hmmer', 'astar'], ['sjeng', 'astar', 'libquantum', 'gobmk'], ['libquantum', 'gobmk', 'sjeng', 'astar'], ] H_mins = [1, 2, 4] H_mins = [1] thresholds = [0.02, 0.05, 0.1, 0.2] thresholds = [0.02, 0.05, 0.1, 0.15, 0.2, 0.25] schemes = ['static', 'dynamic'] if not os.path.exists(scriptgen_dir): os.makedirs(scriptgen_dir) if not os.path.exists(results_dir): os.makedirs(results_dir) if not os.path.exists(stdout_dir): os.makedirs(stdout_dir) if not os.path.exists(stderr_dir): os.makedirs(stderr_dir) folder = sys.argv[1] if not os.path.exists("m5out/" + folder): os.makedirs("m5out/" + folder) if not os.path.exists("results/" + folder): os.makedirs("results/" + folder) if not os.path.exists("stdout/" + folder): os.makedirs("stdout/" + folder) if not os.path.exists("stderr/" + folder): os.makedirs("stderr/" + folder) def singleprog(): for i in range(len(specint)): p0 = specint[i] script = open(scriptgen_dir + "/run_" + p0, "w") command = "#!/bin/bash\n" command += "build/ARM/gem5.fast \\\n" command += " --remote-gdb-port=0 \\\n" command += " --outdir=m5out/" + folder + " \\\n" command += " --stats-file=" + p0 + "_stats.txt \\\n" command += " configs/dramsim2/dramsim2_se.py \\\n" command += " --fixaddr \\\n" command += " --cpu-type=detailed \\\n" command += " --caches \\\n" command += " --l2cache \\\n" command += " --l2config=private \\\n" command += " --fast-forward=1000000000 \\\n" command += " --maxinsts=250000000 \\\n" command += " --maxtick=2000000000000000 \\\n" command += " --numpids=1 \\\n" command += " --p0='" + specintinvoke[p0] + "'\\\n" command += " > " + results_dir + "/" + folder + "/stdout_" + p0 + ".out" script.write("%s\n" % command) script.close() os.system("qsub -cwd -e stderr/" + folder + "/ -o stdout/" + folder + "/ " + scriptgen_dir + "/run_" + p0) def multiprogs(): for i in range(len(specint)): for j in range(len(specint)): p0 = specint[i] p1 = specint[j] script = open(scriptgen_dir + "/run_" + p0 + "_" + p1, "w") command = "#!/bin/bash\n" command += "build/ARM/gem5.fast \\\n" command += " --remote-gdb-port=0 \\\n" command += " --outdir=m5out/" + folder + " \\\n" command += " --stats-file=" + p0 + "_" + p1 + "_stats.txt \\\n" command += " configs/dramsim2/dramsim2_se.py \\\n" command += " --fixaddr \\\n" command += " --cpu-type=detailed \\\n" command += " --caches \\\n" command += " --l2cache \\\n" command += " --l2config=shared \\\n" command += " --fast-forward=1000000000 \\\n" command += " --maxinsts=250000000 \\\n" command += " --maxtick=2000000000000000 \\\n" command += " --numpids=2 \\\n" command += " --p0='" + specintinvoke[p0] + "'\\\n" command += " --p1='" + specintinvoke[p1] + "'\\\n" command += " > " + results_dir + "/" + folder + "/stdout_" + p0 + ".out" script.write("%s\n" % command) script.close() os.system("qsub -cwd -e stderr/" + folder + " -o stdout/" + folder + " " + scriptgen_dir + "/run_" + p0 + "_" + p1 ) l2_size = ['1', '128', '256', '384', '512', '640', '768', '896', '1024', '1152', '1280', '1408', '1536', '1664', '1792', '1920', '2048'] def miss_curve(): for k in range(len(cpus)): for i in range(len(specint)): for j in range(len(l2_size)): p0 = specint[i] l2_assoc = j if l2_assoc == 0: l2_assoc = 1 filename = cpus[k] + "_" + p0 + "_" + l2_size[j] script = open(scriptgen_dir + "/run_" + filename, "w") command = "#!/bin/bash\n" command += "build/ARM/gem5.fast \\\n" command += " --remote-gdb-port=0 \\\n" command += " --outdir=m5out/" + folder + " \\\n" command += " --stats-file=" + filename + "_stats.txt \\\n" command += " configs/dramsim2/dramsim2_se.py \\\n" command += " --fixaddr \\\n" command += " --cpu-type=" + cpus[k] + " \\\n" command += " --caches \\\n" command += " --l2cache \\\n" command += " --l2config=private \\\n" command += " --l2_size=" + l2_size[j] + "kB \\\n" command += " --l2_assoc=" + str(l2_assoc) + " \\\n" command += " --fast-forward=1000000000 \\\n" command += " --maxinsts=250000000 \\\n" command += " --maxtick=2000000000000000 \\\n" command += " --numpids=1 \\\n" command += " --p0='" + specintinvoke[p0] + "'\\\n" command += " > " + results_dir + "/" + folder + "/stdout_" + filename + ".out" script.write("%s\n" % command) script.close() os.system("qsub -cwd -e stderr/" + folder + "/ -o stdout/" + folder + "/ " + scriptgen_dir + "/run_" + filename) def nopar_cache(): for cpu in cpus: for workload in multiprog: p0 = workload[0] p1 = workload[1] filename = cpu + "_" + "nopar" + "_" + p0 + "_" + p1 script = open(scriptgen_dir + "/run_" + filename, "w") command = "#!/bin/bash\n" command += "build/ARM/gem5.fast \\\n" command += " --remote-gdb-port=0 \\\n" command += " --outdir=m5out/" + folder + " \\\n" command += " --stats-file=" + filename + "_stats.txt \\\n" command += " configs/dramsim2/dramsim2_se.py \\\n" command += " --fixaddr \\\n" command += " --cpu-type=" + cpu + " \\\n" command += " --caches \\\n" command += " --l2cache \\\n" command += " --l2config=shared \\\n" command += " --l2_size=1024kB \\\n" command += " --l2_assoc=8 \\\n" command += " --fast-forward=1000000000 \\\n" command += " --maxinsts=250000000 \\\n" command += " --maxtick=2000000000000000 \\\n" command += " --numpids=2 \\\n" command += " --p0='" + specintinvoke[p0] + "'\\\n" command += " --p1='" + specintinvoke[p1] + "'\\\n" command += " > " + results_dir + "/" + folder + "/stdout_" + filename + ".out" script.write("%s\n" % command) script.close() os.system("qsub -cwd
<filename>distance_matching.py # Personalized Regression with Distance Matching Regularization import numpy as np np.set_printoptions(precision=4) import time from utils import * from sklearn.preprocessing import normalize from multiprocessing.pool import ThreadPool class DistanceMatching(): def __init__(self, init_beta, f, f_prime, gamma, n_neighbors, calc_closest_every, rho_beta, rho_beta_prime, init_phi_beta, psi_beta, psi_beta_prime, init_phi_u, psi_u, psi_u_prime, init_beta_scale, psi_beta_scale, psi_beta_scale_prime, intercept, log_dir="./logs", n_threads=1): """ Create a new DistanceMatching object. Arguments ========== init_beta: numpy array of the initial model parameters. Should be of size N x P. f : Python function for error of prediction error. Should take X^{(i)}, Y^{(i)}, beta^{(i)} and return a non-negative real value. f_prime : Python function for sub-gradient of prediction error. Should take X^{(i)}, Y^{(i)}, beta^{(i)} and return a sub-gradient vector of size P. gamma : Hyperparameter for DMR strength. n_neighbors : Integer number of neighbors for each point. calc_closest_every: Integer number of iterations for which to re-calculate neighbors. Currently, neighbors are random so they should be computed relatively frequently. rho_beta : Python function for regularization of beta. Should take beta^{(i)} and return a non-negative real value. rho_beta_prime : Python function for sub-gradient of beta regularization. Should take beta^{(i)} and return a sub-gradient vector of size P. init_phi_beta : numpy array of the initial phi_beta vector. Should be of size P. psi_beta : Python function for regularization on phi_beta. Should take phi_beta and return a non-negative real value. psi_beta_prime : Python function for sub-gradient of phi_beta regularization. Should take phi_beta and return a sub-gradient vector of size P. init_phi_u : numpy array of the initial phi_u vector. Should be of size K. psi_u : Python function for regularization on phi_u. Should take phi_u and return a non-negative real value. psi_u_prime : Python function for sub-gradient of regularization of phi_u. Should take phi_u and return a sub-gradient vector of size K. init_beta_scale : Positive hyperparameter for the amount of personalization. Lower implies more personalization, as described in the paper. psi_beta_scale : Python function for regularization on beta_scale. Should take a postiive real value and return a non-negative real value. psi_beta_scale_prime: Python function for sub-gradient of beta scale regularization. Should take a positivie real value and return a sub-gradient. intercept : Boolean, whether to fit an intercept term. log_dir : string, directory to save output. n_threads : integer, max number of threads to use for multiprocessing. Returns ========== None """ self.init_beta = init_beta self.f = f self.f_prime = f_prime self.gamma = gamma self.n_neighbors = n_neighbors self.calc_closest_every = calc_closest_every self.rho_beta = rho_beta self.rho_beta_prime = rho_beta_prime self.init_phi_beta = init_phi_beta self.psi_beta = psi_beta self.psi_beta_prime = psi_beta_prime self.psi_beta_scale = psi_beta_scale self.psi_beta_scale_prime = psi_beta_scale_prime self.init_phi_u = init_phi_u self.psi_u = psi_u self.psi_u_prime = psi_u_prime self.init_beta_scale = init_beta_scale self.intercept = intercept self.log_dir = log_dir self.n_threads = n_threads if self.n_threads > 0: self.pool = ThreadPool(processes=self.n_threads) self.map = self.pool.map else: self.pool = None self.map = lambda x, y: list(map(x, y)) def _check_shapes(self, X, Y, U=None, dU=None, delta_U=None): """ Does some basic checks on the shapes on the parameters. """ N = X.shape[0] P = X.shape[1] if U: assert(U.shape[0] == N) K = U.shape[1] if dU: K = len(dU) if delta_U: assert(delta_U.shape[0] == N) assert(delta_U.shape[1] == N) K = delta_U.shape[2] return N, P, K def make_covariate_distances(self, U, dU, K, N, should_normalize=True, verbose=True): """ Make fixed pairwise distance matrix for co-variates. """ t = time.time() if verbose: print("Making Co-Variate Distance Matrix of Size {}x{}x{}".format(N, N, K)) D = np.zeros((N, N, K)) get_dist = lambda i, j: np.array([dU[k](U[i, k], U[j, k]) for k in range(K)], dtype="float32") for i in range(1, N): if verbose: print("{}\t/{}".format(i, N), end='\r') D[i, 0:i, :] = self.map(lambda j: get_dist(i, j), range(i)) for i in range(1, N): for j in range(i): D[j, i, :] = D[i, j, :] # could cut memory in half by only storing lists. if verbose: print("Finished making unnormalized version.") if should_normalize: normalized = np.array([normalize(D[:, :, k]) for k in range(K)]) # Now the first axis references k. Move it to the back. normalized = np.swapaxes(normalized, 0, 1) D = np.swapaxes(normalized, 1, 2) if verbose: print("Finished normalizing.") print("Took {:.3f} seconds.".format(time.time() - t)) return D def make_covariate_distance_function(self, U, dU, K): """ If N is large, it is more effecient to compute the covariate distances lazily. """ func = lambda i,j: np.array([dU[k](U[i,k], U[j,k]) for k in range(K)]) return func def _calc_personalized_reg_grad(self, phi_beta, phi_u, beta_hat, beta_scale, dist_errors, N, delta_U, delta_beta, closest): """ Calculates the gradients for the distance matching regularization. Arguments ========== phi_beta : numpy vector, current estimate of phi_beta phi_u : numpy vector, current estimate of phi_u beta_hat : numpy matrix, current estimate of beta_hat beta_scale : float, current estimate of beta_scale dist_errors : list of lists of errrors. N : integer number of samples. delta_U : numpy matrix, static pairwise distance matrix. delta_beta : Python function which calculates pairwise model distances. closest : list of lists of closest indices. Returns ======= grad_beta : numpy matrix, sub-gradient wrt beta. grad_phi_beta : numpy vector, sub-gradient wrt phi_beta. grad_phi_u : numpy vector, sub-gradient wrt phi_u. grad_beta_scale : float, sub-gradient wrt beta_scale. """ grad_phi_beta = self.psi_beta_prime(phi_beta) grad_phi_u = self.psi_u_prime(phi_u) grad_beta = np.zeros_like(beta_hat) grad_beta_scale = self.psi_beta_scale_prime(beta_scale) def _calc_one_beta(i): return np.multiply( np.mean(np.array( [dist_errors[i, idx]*np.sign(beta_hat[i] - beta_hat[j]) for idx, j in enumerate(closest[i])]), axis=0), phi_beta.T) def _calc_one_phi_beta(i): return np.mean(np.array([dist_errors[i, idx]*delta_beta(i, j) for idx, j in enumerate(closest[i])]), axis=0) def _calc_one_phi_u(i): return -np.mean(np.array([dist_errors[i, idx]*delta_U[i, j] for idx, j in enumerate(closest[i])]), axis=0) def _calc_one_beta_scale(i): return -np.mean(np.array([dist_errors[i, idx]*delta_beta(i, j) for idx, j in enumerate(closest[i])]), axis=0).dot(phi_beta) grad_beta += self.gamma*np.array(self.map(_calc_one_beta, range(N))) grad_phi_beta += self.gamma*np.mean(np.array(self.map(_calc_one_phi_beta, range(N))), axis=0) grad_phi_u += self.gamma*np.mean(np.array(self.map(_calc_one_phi_u, range(N))), axis=0) grad_beta_scale += self.gamma*np.mean(np.array(self.map(_calc_one_beta_scale, range(N))), axis=0) return grad_beta, grad_phi_beta, grad_phi_u, grad_beta_scale def _single_restart(self, X, Y, delta_U, neighborhoods, init_lr, lr_decay, init_patience, max_iters, tol, verbosity, log, record_distances=False, calc_com=False): """ Execute a single restart of the optimization. Arguments ========= X : numpy matrix of size NxP, design matrix Y : numpy vector of size Nx1, responses delta_U : numpy tensor of size NxNxK, constant covariate distances neighborhoods : list of list of neighbors init_lr : float, initial learning rate lr_decay : float, multiplicative factor by which to decay the learning rate. init_patience : integer, non-negative number of permitted iterations which don't decrease the loss functions. max_iters : integer, maximum number of iterations. tol : float, minimum amount by which the loss must decrease each iteration. verbosity: integer, every n iterations the current state will be logged. log : file pointer, log file record_distances : Boolean, whether to record pairwise distances during optimization. calc_com : Boolean, whether to calculate the center of mass (COM) deviation during optimiation. Returns ======== beta_hat : numpy matrix of size NxP, estimate of model parameters. phi_beta : numpy vector of size P, estimate of phi_beta. beta_scale : float, estimate of personalization scaling factor. phi_u : numpy vector of size K, estimate of phi_u loss : float, final loss distances_over_time : list of distances during optimization losses_over_time : list of loss amounts during optimization """ N, P, K = self._check_shapes(X, Y, delta_U=delta_U) beta_hat = self.init_beta.copy() beta_scale = self.init_beta_scale phi_beta = self.init_phi_beta.copy() phi_u = self.init_phi_u.copy() beta_prev = self.init_beta.copy() phi_beta_prev = self.init_phi_beta.copy() phi_u_prev = self.init_phi_u.copy() patience = init_patience lr = init_lr prev_loss = np.inf distances_over_time = [] losses_over_time = [] if neighborhoods is None: print("No neighborhoods supplied. Will calculate neighbors randomly.") find_closest_neighbors = lambda phi_u: np.random.choice(N, size=(N, self.n_neighbors)) else: print("Neighborhoods supplied. Will use those.") find_closest_neighbors = lambda phi_u: neighborhoods closest = find_closest_neighbors(phi_u) delta_beta = lambda i, j: np.abs(beta_hat[i] - beta_hat[j]) dist_helper = lambda i, j: beta_scale*delta_beta(i, j).dot(phi_beta) - delta_U[i, j].dot(phi_u) calc_dist_errors = lambda i: np.array([dist_helper(i, j) for j in closest[i]]) t = time.time() for iteration in range(1, max_iters+1): print("Iteration:{} of Max {}. Last Iteration Took {:.3f} seconds.".format( iteration, max_iters, time.time() - t), end='\r') t = time.time() if iteration % self.calc_closest_every == 0: closest = find_closest_neighbors(phi_u) loss1 = np.mean([self.f(X[i], Y[i], beta_hat[i].T) for i in range(N)]) dist_errors = np.array(self.map(lambda i: calc_dist_errors(i), range(N))) loss2 = 0.5*self.gamma*np.mean(np.mean(np.square(dist_errors), axis=1)) loss3 = np.mean([self.rho_beta(beta_hat[i]) for i in range(N)]) loss4 = self.psi_beta(phi_beta) loss5 = self.psi_u(phi_u) loss6 = self.psi_beta_scale(beta_scale)
depth, index, req, perform_checks): assert self.kind == SINGLE_TASK_KIND if req.is_no_access(): return True mappings = self.find_mapping(index, req.parent) for field in req.fields: assert field.fid in mappings inst = mappings[field.fid] # skip any virtual mappings if inst.is_virtual(): continue if not req.logical_node.perform_physical_registration(depth, field, self, req, inst, perform_checks): return False return True def analyze_copy_requirements(self, depth, src_index, src_req, dst_index, dst_req, perform_checks): src_mappings = self.find_mapping(src_index, src_req.parent) dst_mappings = self.find_mapping(dst_index, dst_req.parent) assert len(src_req.fields) == len(dst_req.fields) for fidx in range(len(src_req.fields)): src_field = src_req.fields[fidx] dst_field = dst_req.fields[fidx] assert src_field.fid in src_mappings assert dst_field.fid in dst_mappings src_inst = src_mappings[src_field.fid] dst_inst = dst_mappings[dst_field.fid] assert not dst_inst.is_virtual() is_reduce = dst_req.is_reduce() # Switch this to read-write privileges and then switch it back after we are done # The runtime does this too so that its analysis is correct if is_reduce: dst_req.priv = READ_WRITE # Analyze the source and destination regions but don't register yet if not src_inst.is_virtual() and not src_req.logical_node.perform_physical_analysis( depth, src_field, self, src_req, src_inst, perform_checks, False): return False if not dst_req.logical_node.perform_physical_analysis(depth, dst_field, self, dst_req, dst_inst, perform_checks, False): return False # Now we issue the copy across # See if we are doing a reduction or a normal copy if is_reduce: assert dst_req.redop != 0 # Reduction case if src_inst.is_virtual(): # This is a runtime bug, there should never be any reductions across assert False return False else: # Normal reduction, find the source and destination dependences src_preconditions = src_inst.find_use_dependences(depth=depth, field=src_field, op=self, req=src_req, precise=True) dst_preconditions = dst_inst.find_use_dependences(depth=depth, field=dst_field, op=self, req=dst_req, precise=True) if perform_checks: reduction = self.find_generated_copy_across(src_field, dst_field, dst_req.logical_node, src_inst, dst_inst, dst_req.redop) if reduction is None: print("ERROR: Missing reduction across operation from field "+ str(src_field)+" to field "+str(dst_field)+" between region "+ "requirements "+str(src_index)+" and "+str(dst_index)+" of "+ str(self)) if self.state.assert_on_error: assert False return False # Have to fill out the reachable cache if reduction.reachable_cache is None: reduction.reachable_cache = set() reduction.get_physical_reachable(reduction.reachable_cache, False) bad = check_preconditions(src_preconditions, reduction) if bad is not None: print("ERROR: Missing source precondition for reduction across "+ "from field "+str(src_field)+" to field "+str(dst_field)+ "between region requirements "+str(src_index)+" and "+ str(dst_index)+" of "+str(self)) if self.state.assert_on_error: assert False return False bad = check_preconditions(dst_preconditions, reduction) if bad is not None: print("ERROR: Missing destination precondition for reduction "+ "across from field "+str(src_field)+" to field "+ str(dst_field)+"between region requirements "+str(src_index)+ " and "+str(dst_index)+" of "+str(self)) if self.state.assert_on_error: assert False return False else: # Otherwise make the copy across and record the dependences reduction = self.state.create_copy(self) reduction.set_region(dst_req.logical_node) reduction.add_field(src_field.fid, src_inst, dst_field.fid, dst_inst, dst_req.redop) for src in src_preconditions: src.physical_outgoing.add(reduction) reduction.physical_incoming.add(src) for dst in dst_preconditions: dst.physical_outgoing.add(reduction) reduction.physical_incoming.add(dst) # Record the copy users src_inst.add_copy_user(depth=depth, field=src_field, region=src_req.logical_node, op=reduction, index=src_index, reading=True, redop=0) dst_inst.add_copy_user(depth=depth, field=dst_field, region=dst_req.logical_node, op=reduction, index=dst_index, reading=False, redop=dst_req.redop) # Done with the analysis, swith the privilege back dst_req.priv = REDUCE else: # Normal copy case if src_inst.is_virtual(): error_str = "source field "+str(src_field)+" and destination field "+\ str(dst_field)+" of region requirements "+str(src_index)+\ " and "+str(dst_index)+" of "+str(self) # Capture a temporary composite instance, but don't register it comp_inst = src_req.logical_node.capture_composite_instance(depth, src_field, self, src_req) return comp_inst.issue_copies_across(dst=dst_inst, dst_depth=depth, dst_field=dst_field, region=dst_req.logical_node, op=self, index=dst_index, perform_checks=perform_checks, error_str=error_str) else: # Normal copy src_preconditions = src_inst.find_use_dependences(depth=depth, field=src_field, op=self, req=src_req, precise=True) dst_preconditions = dst_inst.find_use_dependences(depth=depth, field=dst_field, op=self, req=dst_req, precise=True) if perform_checks: copy = self.find_generated_copy_across(src_field, dst_field, dst_req.logical_node, src_inst, dst_inst) if copy is None: print("ERROR: Missing copy across operation from field "+ str(src_field)+" to field "+str(dst_field)+" between region "+ "requirements "+str(src_index)+" and "+str(dst_index)+" of "+ str(self)) if self.state.assert_on_error: assert False return False # Have to fill in the copy reachable cache if copy.reachable_cache is None: copy.reachable_cache = set() copy.get_physical_reachable(copy.reachable_cache, False) bad = check_preconditions(src_preconditions, copy) if bad is not None: print("ERROR: Missing source precondition for copy across from "+ "field "+str(src_field)+" to field "+str(dst_field)+ "between region requirements "+str(src_index)+" and "+ str(dst_index)+" of "+str(self)) if self.state.assert_on_error: assert False return False bad = check_preconditions(dst_preconditions, copy) if bad is not None: print("ERROR: Missing destination precondition for copy across "+ "from field "+str(src_field)+" to field "+str(dst_field)+ "between region requirements "+str(src_index)+" and "+ str(dst_index)+" of "+str(self)) return False else: # Otherwise make the copy across and record the dependences copy = self.state.create_copy(self) copy.set_region(dst_req.logical_node) copy.add_field(src_field.fid, src_inst, dst_field.fid, dst_inst, 0) for src in src_preconditions: src.physical_outgoing.add(copy) copy.physical_incoming.add(src) for dst in dst_preconditions: dst.physical_outgoing.add(copy) copy.physical_incoming.add(dst) # Record the copy users src_inst.add_copy_user(depth=depth, field=src_field, region=src_req.logical_node, op=copy, index=src_index, reading=True, redop=0) dst_inst.add_copy_user(depth=depth, field=dst_field, region=dst_req.logical_node, op=copy, index=dst_index, reading=False, redop=0) return True def analyze_fill_requirement(self, depth, index, req, perform_checks): for field in req.fields: if not req.logical_node.perform_fill_analysis(depth, field, self, req, perform_checks): return False # If this field is restricted, we effectively have to fill it # now to get the proper semantics of seeing updates right away if req.restricted_fields and field in req.restricted_fields: if not req.logical_node.perform_physical_analysis(depth, field, self, req, req.restricted_fields[field], perform_checks): return False return True def perform_op_physical_analysis(self, depth, perform_checks): # Handle special cases first # Do any of our close operations before ourself if self.inter_close_ops: assert not self.kind == INTER_CLOSE_OP_KIND and \ not self.kind == READ_ONLY_CLOSE_OP_KIND prefix = '' for idx in range(depth): prefix += ' ' for close in self.inter_close_ops: print(prefix+"Performing physical dependence analysis for "+ str(close)+" generated by "+str(self)) if not close.perform_physical_close_analysis(depth, perform_checks): return False # If we are an index space task, only do our points if self.kind == INDEX_TASK_KIND: assert self.points is not None for point in sorted(self.points.itervalues(), key=lambda x: x.op.uid): if not point.op.perform_op_physical_analysis(depth, perform_checks): return False return True prefix = '' for idx in range(depth): prefix += ' ' print(prefix+"Performing physical dependence analysis "+ "for %s (UID %d)..." % (str(self),self.uid)) # If this is a close operation itself do the close analysis if self.is_close(): return self.perform_physical_close_analysis(depth, perform_checks) # Do traversals for all of our region requirements and map our instances if not self.reqs: # Go down the task tree if we are a task if self.kind == SINGLE_TASK_KIND: assert self.reachable_cache is None self.reachable_cache = set() self.get_physical_reachable(self.reachable_cache, False) task = self.state.get_task(self) if not task.perform_task_physical_analysis(perform_checks): return False self.reachable_cache = None return True # As a small performance optimization get all our reachable operations # now if we are going to be doing checks so we don't have to repeate BFS assert self.reachable_cache is None self.reachable_cache = set() self.get_physical_reachable(self.reachable_cache, False) # We have special cases here for copy operations and fill operations if self.kind == COPY_OP_KIND: num_reqs = len(self.reqs) assert num_reqs % 2 == 0 num_copies = num_reqs / 2 for idx in range(num_copies): if not self.analyze_copy_requirements(depth, idx, self.reqs[idx], idx+num_copies, self.reqs[idx+num_copies], perform_checks): return False elif self.kind == FILL_OP_KIND: for index,req in self.reqs.iteritems(): if not self.analyze_fill_requirement(depth, index, req, perform_checks): return False elif self.kind == DELETION_OP_KIND: # Skip deletions, they only impact logical analysis pass else: for index,req in self.reqs.iteritems(): if not self.analyze_physical_requirement(depth, index, req, perform_checks): return False if self.kind == SINGLE_TASK_KIND: # We now need to do the registration for our region # requirements since we didn't do it as part of the # normal physical analysis for index,req in self.reqs.iteritems(): if not self.perform_physical_registration(depth, index, req, perform_checks): return False # If we are not a leaf task, go down the task tree if self.task is not None: if not self.task.perform_task_physical_analysis(perform_checks): return False self.check_for_unanalyzed_realm_ops(perform_checks) # Clean up our reachable cache self.reachable_cache = None return True def perform_physical_close_analysis(self, depth, perform_checks): assert 0 in self.reqs req = self.reqs[0] if self.kind == READ_ONLY_CLOSE_OP_KIND: # If this is a read-only close, we just have to invalidate the tree for field in req.fields: if not req.logical_node.perform_physical_close(depth, field, self, req, None, perform_checks): return False return True elif self.kind == POST_CLOSE_OP_KIND: # We find our target instances from our parent task assert self.context parent_op = self.context.op assert self.close_idx in parent_op.mappings mappings = parent_op.mappings[self.close_idx] else: # This is the common path mappings = self.find_mapping(0, req.parent) for field in req.fields: if field.fid not in mappings: print("Missing mapping decision for field "+str(field)+" of "+ "requirement requirement "+str(index)+" of "+str(self)) print("This is a runtime logging bug, please report it.") assert
and color_table != None: print(('Updating color table for:',image)) # b.SetRasterColorInterpretation(gdal.GCI_PaletteIndex) b.SetRasterColorTable(color_table) if names != '' and names != None: print(('Updating names for:',image)) b.SetRasterCategoryNames(names) rast = None b = None ############################################################################################## def just_raster_extent(raster): rast = gdal.Open(raster) width = rast.RasterXSize height = rast.RasterYSize transform = rast.GetGeoTransform() rast = None transform = list(transform) xmax = transform[0] + (int(round(transform[1])) * width) xmin = transform[0] ymax = transform[3] ymin = transform[3]- (int(round(transform[1])) * height) return [xmin,ymin,xmax,ymax] ############################################################################################## #Gathers various information about a raster and returns it in a dictionary def raster_info(image = '', band_no = 1, get_stats = False, guiable = True): if image == '': guied = True image = str(askopenfilename(title = 'Select Strata Raster',filetypes=[("IMAGINE","*.img"),("tif","*.tif")])) else: guied = False #print image rast = gdal.Open(image) band1 = rast.GetRasterBand(band_no) dt = band1.DataType md = rast.GetMetadata('IMAGE_STRUCTURE') # c = 'gdalinfo "' + image + '"' # call = subprocess.Popen(c) # call.wait() # print(band1.GetMetadata()) # Use dict.get method in case the metadata dict does not have a 'COMPRESSION' key compression = md.get('COMPRESSION', None) ct = band1.GetRasterColorTable() names = band1.GetRasterCategoryNames() no_data = band1.GetNoDataValue() if get_stats == True: stats = band1.GetStatistics(False,1) # print(stats) Min = stats[0] Max = stats[1] mean = stats[2] stdev = stats[3] else: Min, Max, mean, stdev = 0,0,0,0 band1 = None Dict = {1: 'Byte', 2 : 'UInt16', 3: 'Int16', 4: 'UInt32', 5: 'Int32', 6 : 'Float32',7 : 'Float64'} bit_depth_dict = {1: 8, 2 : 16, 3: 16, 4: 32, 5: 32, 6 : 32,7 : 64} discrete_or_continuous_dict = {1: 'discrete', 2 : 'discrete', 3: 'discrete', 4: 'discrete', 5: 'discrete', 6 : 'continuous',7 : 'continuous'} dataType = Dict[dt] bit_depth = bit_depth_dict[dt] discrete_or_continuous = discrete_or_continuous_dict[dt] dt_ranges = {'Byte': [0,255], 'Int16': [-32768, 32768], 'UInt16': [0,65535],'UInt32': [0,4294967295], 'Float32':[-3.4E38, 3.4E38],'Float64':[-1.7E308, 1.7E308]} try: dt_range = dt_ranges[dataType] except: dt_range = [0,255] width = rast.RasterXSize height = rast.RasterYSize bands = rast.RasterCount projection = rast.GetProjection() transform = rast.GetGeoTransform() # ulx, xres, xskew, uly, yskew, yres = rast.GetGeoTransform() # lrx = ulx + (rast.RasterXSize * xres) # lry = uly + (rast.RasterYSize * yres) transform = list(transform) projections = projection_format_converter(projection, 'Wkt') # print(projections['pretty_wkt']) xmax = transform[0] + (int(round(transform[1])) * width) xmin = transform[0] ymax = transform[3] ymin = transform[3]- (int(round(transform[1])) * height) # print(xmin,ymin,xmax,ymax) from_sr = osr.SpatialReference() from_sr.ImportFromWkt(projections['wkt']) geog_sr = osr.SpatialReference() geog_sr.ImportFromEPSG(4326) ul_point = ogr.Geometry(ogr.wkbPoint) ul_point.AddPoint(xmin,ymax) ul_point.AssignSpatialReference(from_sr) ul_point.TransformTo(geog_sr) lr_point = ogr.Geometry(ogr.wkbPoint) lr_point.AddPoint(xmax,ymin) lr_point.AssignSpatialReference(from_sr) lr_point.TransformTo(geog_sr) coords = [xmin,ymin,xmax,ymax] coords_geog = [ul_point.GetX(),lr_point.GetY(),lr_point.GetX(),ul_point.GetY()] gdal_coords = str(xmin) + ' ' + str(ymin) + ' ' + str(xmax) + ' ' + str(ymax) try: zone = projection.split('Zone')[1].split(',')[0][1:3] except: try: zone = projection.split('zone ')[1][:2] except: zone = '' datum_list = {'NAD':'NAD83', 'WGS':'WGS84'} try: datum = projection.split('GEOGCS["')[1].split('",')[0] if datum not in datum_list: for dat in datum_list: if datum.find(dat) > -1: datum = datum_list[dat] except: datum = '' hemisphere = '' if (projection.find('North') > -1 or projection.find('north') > -1) and (projection.find('Hemisphere') > -1 or projection.find('hemisphere') > -1): hemisphere = 'North' else: hemisphere = 'South' units = '' if projection.find('meter') > -1 or projection.find('METER')> -1 or projection.find('Meter') > -1: units = 'Meters' res = transform[1] info = {'image':image,'no_data' : no_data, 'proj4': projections['proj4'], 'wkt': projections['wkt'], 'units': units, 'hemisphere' : hemisphere,'min': Min, 'max': Max, 'mean': mean, 'std':stdev, 'stdev':stdev, 'gdal_coords': gdal_coords, 'coords' : coords, 'coords_geog':coords_geog,'projection':projection, 'transform': transform, 'width': width, 'height': height, 'bands': bands, 'band_count': bands, 'zone' : zone, 'datum': datum, 'res': res, 'resolution':res, 'dt_range': dt_range,'datatype': dataType, 'dt': dataType, 'DataType': dataType,'bit_depth':bit_depth,'color_table':ct,'names':names,'compression_method':compression,'discrete_or_continuous':discrete_or_continuous} if guied == True: for piece in info: print(( piece, info[piece])) rast = None return info ############################################################################################## #Applies raster_info across all bands and returns a list of raster_info dictionaries def brick_info(image = '', get_stats = False): info = [] list(map(lambda band : info.append(raster_info(image, band, get_stats)), list(range(1, raster_info(image)['bands'] + 1)))) return info ############################################################################################## #Mr sid metadata extractor def mr_sid_metadata(metadata_text_file): open_m = open(metadata_text_file, 'r') lines = open_m.readlines() open_m.close() find_list = ['West_Bounding_Coordinate', 'East_Bounding_Coordinate', 'North_Bounding_Coordinate', 'South_Bounding_Coordinate'] out_dict = {} for Find in find_list: for line in lines: if line.find(Find) > -1: coord = line.split(': ')[1].split('\n')[0] out_dict[Find.split('_')[0]] = coord coords = [float(out_dict['West']), float(out_dict['South']), float(out_dict['East']), float(out_dict['North'])] out_dict['coords'] = coords return out_dict ############################################################################################## #Determines whether the data type is a numpy or gdal data type def numpy_or_gdal(dt): numpy_list = ['u1', 'uint8', 'uint16','u2', 'u4', 'i2', 'int16', 'Float32','float32', 'Float64','float64'] gdal_list = ['Byte', 'Byte', 'UInt16','UInt16','UInt32','Int16', 'Int16', 'float32','Float32','float64','Float64'] dt_list = [] if dt in numpy_list: dt_list.append('numpy') if dt in gdal_list: dt_list.append('gdal') if len(dt_list) == 2: return 'both' elif len(dt_list) == 1: return dt_list[0] else: return 'neither' ############################################################################################## def is_leap_year(year): year = int(year) if year % 4 == 0: if year%100 == 0 and year % 400 != 0: return False else: return True else: return False ############################################################################################## def julian_to_calendar(julian_date, year = time.localtime()[0]): julian_date, year = int(julian_date), int(year) is_leap = is_leap_year(year) if is_leap: leap, length = True, [31,29,31,30,31,30,31,31,30,31,30,31] else: leap, length = False, [31,28,31,30,31,30,31,31,30,31,30,31] ranges = [] start = 1 for month in length: stop = start + month ranges.append(list(range(start, stop))) start = start + month month_no = 1 for Range in ranges: if julian_date in Range: mn = month_no day_no = 1 for day in Range: if day == julian_date: dn = day_no day_no += 1 month_no += 1 if len(str(mn)) == 1: lmn = '0' + str(mn) else: lmn = str(mn) if len(str(dn)) == 1: ldn = '0' + str(dn) else: ldn = str(dn) return {'monthdate': lmn + ldn,'month':mn, 'day':dn, 'date_list': [mn,dn], 'date': str(mn) + '/' + str(dn)} ############################################################################################## def calendar_to_julian(day, month, year = time.localtime()[0]): day, month, year = int(day),int(month),int(year) is_leap = is_leap_year(year) n, nl=[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] x = 1 while x <=12: if month == x: if not is_leap: julian = n[x-1]+ day else: julian = nl[x-1]+ day return julian x = x+1 ############################################################################################## def base(in_path): return os.path.basename(os.path.splitext(in_path)[0]) ############################################################################################## def check_dir(in_path): if os.path.exists(in_path) == False: print(('Making dir:', in_path)) os.makedirs(in_path) def checkDir(in_path): check_dir(in_path) ############################################################################################## def check_end(in_path, add = '/'): if in_path[-len(add):] != add: out = in_path + add else: out = in_path return out ############################################################################################## def glob_dir(Dir): dirs = [i for i in glob(Dir,'') if os.path.isdir(i)] dirs = [check_end(i) for i in dirs] return dirs ############################################################################################## #Returns all files containing an extension or any of a list of extensions #Can give a single extension or a list of extensions def glob(Dir, extension): Dir = check_end(Dir) if type(extension) != list: if extension.find('*') == -1: return [Dir + i for i in [i for i in os.listdir(Dir) if os.path.splitext(i)[1] == extension]] else: return [Dir + i for i in os.listdir(Dir)] else: out_list = [] for ext in extension: tl = [Dir + i for i in [i for i in os.listdir(Dir) if os.path.splitext(i)[1] == ext]] for l in tl: out_list.append(l) return out_list ############################################################################################## #Returns all files containing a specified string (Find) def glob_find(Dir, Find): Dir = check_end(Dir) if type(Find) != list: return [Dir + i for i in [i for i in os.listdir(Dir) if i.find(Find) > -1]] else: out_list = [] for F in Find: t1 = [Dir + i for i in [i for i in os.listdir(Dir) if i.find(F) > -1]] for t in t1: out_list.append(t) return out_list ############################################################################################## #Returns all files ending with a specified string (end) def glob_end(Dir, end): Dir = check_end(Dir) if type(end) != list: return [Dir + i for i in [i for i in os.listdir(Dir) if i[-len(end):] == end]] else: out_list = [] for ed in end: t1 = [Dir + i for i in [i for i in os.listdir(Dir) if i[-len(ed):] == ed]] for t in t1: out_list.append(t) return out_list ############################################################################################## ##def glob_find_iter(Dir, find_list): ## out_list = [] ## Find = find_list[0] ## tl1 = map(lambda i : Dir + i, filter(lambda i:i.find(Find) > -1, os.listdir(Dir))) ## for Find in find_list[1:]: ## ## ############################################################################################## def set_no_data(image, no_data_value = -9999, update_stats = True): rast = gdal.Open(image, gdal.GA_Update) ri = raster_info(image) nd = ri['no_data'] print(('Processing no_data for:',base(image))) if nd != no_data_value: print(('Changing no data from:',nd,'to',no_data_value)) for band in range(1, ri['bands']+1): b = rast.GetRasterBand(band) b.SetNoDataValue(no_data_value) if update_stats: print(('Updating stats for band:',band)) Min,Max,Mean,Std = b.ComputeStatistics(0) b.SetStatistics(Min,Max,Mean,Std) else: Min,Max,Mean,Std = b.GetStatistics(0,0) print(('Min:',Min)) print(('Max:',Max)) print(('Mean:',Mean)) print(('Std:', Std)) else: print(('No data already = ', no_data_value)) print() def set_stats(image,Min=None,Max=None,Mean=None,Std=None): rast =
<filename>iob2DynaML.py from math import sqrt import math import numpy from numpy import matmul from math import sin, cos, radians import sys,datetime, os class DnaStation: def __init__(self): self.name = '' self.Constraint='' self.Type='' self.XAxis='' self.YAxis='' self.Height='' self.Description='' self.aAxis=0 self.bAxis=0 self.ErrAz=0 class AdditionalInfoStn: def __init__(self): self.HorizCoordMethod='' self.RelativeHorizAccuracy='' self.NonGSNumber='' self.SelectPoint='true' self.SelectRL='true' class AdditionalInfoMsr: def __init__(self): #Additional information is included as a comment in the DynaML file. This can be used for database import self.StartDateTime=datetime.datetime(1994, 1, 1, 00, 00,00) self.Duration=datetime.datetime(1966, 1, 1, 00, 00,00) self.TimeStatus='' self.EphemerisType='' self.AtReceiver='' self.ToReceiver='' self.FrequencyMode='' self.SurveyTechnique='SLEV' self.Solution='' self.EpochInterval='' self.Class='LC' self.LevelDistance='0.01' self.InstrumentModel='' self.Derivation='MEAS' self.NonGSNumber='' class DnaMeasurement: def __init__(self): self.type = '' self.vscale='1' self.pscale='1' self.lscale='1' self.hscale='1' self.first='' self.second='' self.third='' self.stddev='' self.total='' self.instheight=0 self.targheight=0 self.targets=[] self.values=[] self.targetstddevs=[] self.dx='' self.dy='' self.dz='' self.Vs=numpy.zeros([3,3]) def add_targets(self,target): self.targets.append(target) def add_values(self,Value): self.values.append(Value) def add_targetstddevs(self,targetstddev): self.targetstddevs.append(targetstddev) class DeviceHeight: def __init__(self): #Device Height might be the height of instrument at a point or Height of target self.StnName=[] self.RefHeight=[] def add_DeviceHeight(self,Stn,Hgt): self.StnName.append(Stn) self.RefHeight.append(Hgt) def hms2hp(HMS_Ang): #Input: HH MM SS.ssss used by Geolab #Output: HH.MMSSSsssss used by DynAdjust sign=1 if HMS_Ang.find('S')<>-1 or HMS_Ang.find('-')<>-1: sign=-1 while HMS_Ang.find(' ')<>-1: HMS_Ang=HMS_Ang.replace(' ',' ') HMS_Ang=HMS_Ang.replace('S','') HMS_Ang=HMS_Ang.replace('E','') HMS_Ang=HMS_Ang.replace('.',' ') aAng=HMS_Ang.split() aAng[0]=str(sign*abs(int(aAng[0]))) aAng[1]="%02d" % float(aAng[1]) aAng[2]="%02d" % float(aAng[2]) return aAng[0] + '.' + aAng[1] + aAng[2]+ aAng[3] def hp2dec(hp): #Input: HH.MMSSsss #Output: dd.dddddd degmin, second = divmod(abs(hp) * 1000, 10) degree, minute = divmod(degmin, 100) dec = degree + (minute / 60) + (second / 360) return dec if hp >= 0 else -dec def FindJobNumber(strg): #search a string for 8 consecutive numbers, this is probably the Job Number JN='' i=0 while i+7<>len(strg): if unicode(strg[i:i+8]).isnumeric()==True: JN=strg[i:i+8] i=i+1 return JN def Stn_xml_str(Stn,stnAdditionalRec): #Output: String for printing to xml that is one complete station xml_str='<DnaStation>\n' xml_str=xml_str+'<Name>' + Stn.Name + '</Name>\n' xml_str=xml_str+'<Constraints>' + Stn.Constraint + '</Constraints>\n' xml_str=xml_str+'<Type>' + Stn.Type + '</Type>\n' xml_str=xml_str+'<StationCoord>\n' xml_str=xml_str+'<Name>' + Stn.Name + '</Name>\n' xml_str=xml_str+'<XAxis>' + str(Stn.XAxis) + '</XAxis>\n' xml_str=xml_str+'<YAxis>' + str(Stn.YAxis) + '</YAxis>\n' xml_str=xml_str+'<Height>' + Stn.Height + '</Height>\n' xml_str=xml_str+'</StationCoord>\n' xml_str=xml_str+'<Description>'+ Stn.Description +'</Description>\n' xml_str=xml_str+'<!--AdditionalInfoStn>\n' xml_str=xml_str+'<HorizCoordMethod>' + stnAdditionalRec.HorizCoordMethod + '</HorizCoordMethod>\n' xml_str=xml_str+'<RelativeHorizAccuracy>' + stnAdditionalRec.RelativeHorizAccuracy + '</RelativeHorizAccuracy>\n' xml_str=xml_str+'<NonGSNumber>' + stnAdditionalRec.NonGSNumber + '</NonGSNumber>\n' xml_str=xml_str+'<SelectPoint>' + stnAdditionalRec.SelectPoint + '</SelectPoint>\n' xml_str=xml_str+'<SelectRL>' + stnAdditionalRec.SelectRL + '</SelectRL>\n' xml_str=xml_str+'</AdditionalInfoStn-->\n' xml_str=xml_str+'</DnaStation>\n' return xml_str def Msr_xml_str(Msr, ControlRec): #Output: xml string for printing to file. Caters for type G, D, S, B, D, L, H xml_str='<DnaMeasurement>\n' xml_str=xml_str+'<Type>' + Msr.type + '</Type>\n' xml_str=xml_str+'<Ignore/>\n' if Msr.type == 'G': xml_str=xml_str+'<ReferenceFrame>' + GNSSdate2Ref(ControlRec.StartDateTime) + '</ReferenceFrame>\n' xml_str=xml_str+'<Epoch>' + ControlRec.StartDateTime.strftime('%d.%m.%Y') + '</Epoch>\n' xml_str=xml_str+'<Vscale>' + Msr.vscale + '</Vscale>\n' xml_str=xml_str+'<Pscale>' + Msr.pscale + '</Pscale>\n' xml_str=xml_str+'<Lscale>' + Msr.lscale + '</Lscale>\n' xml_str=xml_str+'<Hscale>' + Msr.hscale + '</Hscale>\n' xml_str=xml_str+'<First>' + Msr.first + '</First>\n' if Msr.second <> '': xml_str=xml_str+'<Second>' + Msr.second + '</Second>\n' if Msr.type <> 'G' and Msr.type <> 'D': xml_str=xml_str+'<Value>' + Msr.values[0] + '</Value>\n' xml_str=xml_str+'<StdDev>' + Msr.stddev + '</StdDev>\n' if Msr.type == 'G': xml_str=xml_str+'<GPSBaseline>\n' xml_str=xml_str+'<X>' + Msr.dx + '</X>\n' xml_str=xml_str+'<Y>' + Msr.dy + '</Y>\n' xml_str=xml_str+'<Z>' + Msr.dz + '</Z>\n' xml_str=xml_str+'<SigmaXX>' + str(Msr.Vs[0,0]) + '</SigmaXX>\n' xml_str=xml_str+'<SigmaXY>' + str(Msr.Vs[0,1]) + '</SigmaXY>\n' xml_str=xml_str+'<SigmaXZ>' + str(Msr.Vs[0,2]) + '</SigmaXZ>\n' xml_str=xml_str+'<SigmaYY>' + str(Msr.Vs[1,0]) + '</SigmaYY>\n' xml_str=xml_str+'<SigmaYZ>' + str(Msr.Vs[1,1]) + '</SigmaYZ>\n' xml_str=xml_str+'<SigmaZZ>' + str(Msr.Vs[2,0]) + '</SigmaZZ>\n' xml_str=xml_str+'</GPSBaseline>\n' xml_str=xml_str+'<!--AdditionalInfoMsrG>\n' xml_str=xml_str+'<StartDateTime>'+ControlRec.StartDateTime.strftime('%Y-%m-%dT%H:%M:%S')+'</StartDateTime>\n' xml_str=xml_str+'<Duration>P'+str(ControlRec.Duration.year-1900)+'Y'+str(ControlRec.Duration.month-1)+'M'+str(ControlRec.Duration.day-1)+'DT'+ControlRec.Duration.strftime('%HH%MM%SS')+'</Duration>\n' xml_str=xml_str+'<TimeStatus>'+ControlRec.TimeStatus+'</TimeStatus>\n' xml_str=xml_str+'<EphemerisType>'+ControlRec.EphemerisType+'</EphemerisType>\n' xml_str=xml_str+'<AtReceiver>'+ControlRec.AtReceiver+'</AtReceiver>\n' xml_str=xml_str+'<ToReceiver>'+ControlRec.ToReceiver+'</ToReceiver>\n' xml_str=xml_str+'<FrequencyMode>'+ControlRec.FrequencyMode+'</FrequencyMode>\n' xml_str=xml_str+'<SurveyTechnique>'+ControlRec.SurveyTechnique+'</SurveyTechnique>\n' xml_str=xml_str+'<Solution>'+ControlRec.Solution+'</Solution>\n' xml_str=xml_str+'<EpochInterval>'+str(ControlRec.EpochInterval)+'</EpochInterval>\n' xml_str=xml_str+'<Class>'+ControlRec.Class+'</Class>\n' xml_str=xml_str+'<NonGSNumber>'+ControlRec.NonGSNumber+'</NonGSNumber>\n' xml_str=xml_str+'</AdditionalInfoMsrG-->\n' if Msr.type == 'L': xml_str=xml_str+'<!--AdditionalInfoMsrL>\n' xml_str=xml_str+'<SurveyTechnique>'+ControlRec.SurveyTechnique+'</SurveyTechnique>\n' xml_str=xml_str+'<LevelDistance>'+ ControlRec.LevelDistance +'</LevelDistance>\n' xml_str=xml_str+'<ObsDate>'+ControlRec.StartDateTime.strftime('%Y-%m-%d')+'</ObsDate>\n' xml_str=xml_str+'<Derivation>'+ControlRec.Derivation+'</Derivation>\n' xml_str=xml_str+'<Class>'+ControlRec.Class+'</Class>\n' xml_str=xml_str+'<NonGSNumber>'+ControlRec.NonGSNumber+'</NonGSNumber>\n' xml_str=xml_str+'</AdditionalInfoMsrL-->\n' if Msr.type == 'S': xml_str=xml_str+'<InstHeight>' + str(Msr.instheight) + '</InstHeight>\n' xml_str=xml_str+'<TargHeight>' + str(Msr.targheight) + '</TargHeight>\n' xml_str=xml_str+'<!--AdditionalInfoMsrS>\n' xml_str=xml_str+'<InstrumentModel>'+ControlRec.InstrumentModel+'</InstrumentModel>\n' xml_str=xml_str+'<ObsDate>'+ControlRec.StartDateTime.strftime('%Y-%m-%d')+'</ObsDate>\n' xml_str=xml_str+'<Derivation>'+ControlRec.Derivation+'</Derivation>\n' xml_str=xml_str+'<Class>'+ControlRec.Class+'</Class>\n' xml_str=xml_str+'<NonGSNumber>'+ControlRec.NonGSNumber+'</NonGSNumber>\n' xml_str=xml_str+'</AdditionalInfoMsrS-->\n' if Msr.type == 'D': xml_str=xml_str+'<Value>' + Msr.values[0] + '</Value>\n' xml_str=xml_str+'<StdDev>' + Msr.targetstddevs[0] + '</StdDev>\n' xml_str=xml_str+'<Total>' + str(Msr.total-1) + '</Total>\n' ObsNumber=1 while ObsNumber<Msr.total: xml_str=xml_str+'<Directions>\n' xml_str=xml_str+'<Ignore/>\n' xml_str=xml_str+'<Target>' + Msr.targets[ObsNumber] + '</Target>\n' xml_str=xml_str+'<Value>' + Msr.values[ObsNumber] + '</Value>\n' xml_str=xml_str+'<StdDev>' + Msr.targetstddevs[ObsNumber] + '</StdDev>\n' xml_str=xml_str+'</Directions>\n' ObsNumber=ObsNumber+1 xml_str=xml_str+'<!--AdditionalInfoMsrD>\n' xml_str=xml_str+'<InstrumentModel>'+ControlRec.InstrumentModel+'</InstrumentModel>\n' xml_str=xml_str+'<ObsDate>'+ControlRec.StartDateTime.strftime('%Y-%m-%d')+'</ObsDate>\n' xml_str=xml_str+'<Derivation>'+ControlRec.Derivation+'</Derivation>\n' xml_str=xml_str+'<Class>'+ControlRec.Class+'</Class>\n' xml_str=xml_str+'<NonGSNumber>'+ControlRec.NonGSNumber+'</NonGSNumber>\n' xml_str=xml_str+'</AdditionalInfoMsrD-->\n' xml_str=xml_str+'<Source></Source>\n' xml_str=xml_str+'</DnaMeasurement>\n' return xml_str c_vac = 299792.458 k_0 = 0.9996 # Ellipsoid Constants class Ellipsoid(object): def __init__(self, semimaj, inversef): self.semimaj = semimaj self.inversef = inversef self.f = 1 / self.inversef self.semimin = float(self.semimaj * (1 - self.f)) self.ecc1sq = float(self.f * (2 - self.f)) self.ecc2sq = float(self.ecc1sq / (1 - self.ecc1sq)) self.ecc1 = sqrt(self.ecc1sq) self.n = float(self.f / (2 - self.f)) self.n2 = self.n ** 2 # Geodetic Reference System 1980 grs80 = Ellipsoid(6378137, 298.25722210088) def llh2xyz(lat, lng, ellht, ellipsoid=grs80): # Add input for ellipsoid (default: grs80) # Convert lat & long to radians lat = radians(hp2dec(float(lat))) lng = radians(hp2dec(float(lng))) ellht=float(ellht) # Calculate Ellipsoid Radius of Curvature in the Prime Vertical - nu if lat == 0: nu = grs80.semimaj else: nu = ellipsoid.semimaj/(sqrt(1 - ellipsoid.ecc1sq * (sin(lat)**2))) # Calculate x, y, z x = (nu + ellht) * cos(lat) * cos(lng) y = (nu + ellht) * cos(lat) * sin(lng) z = ((ellipsoid.semimin**2 / ellipsoid.semimaj**2) * nu + ellht) * sin(lat) return x, y, z def ErrEllip2Ycluster(Stn): #Input: Supply a station with coordinates and error ellipse for coordinate uncertainty #Output: xml string for point cluster (Y-type observation) x, y, z = llh2xyz(Stn.XAxis, Stn.YAxis, Stn.Height) a=Stn.aAxis/2.44774683068 b=Stn.bAxis/2.44774683068 Az=90-Stn.ErrAz rAz=math.radians(Az) rlat=math.radians(float(Stn.XAxis)) rlng=math.radians(float(Stn.YAxis)) rl=numpy.zeros([3,3]) rl[0,0]=-sin(rlng) rl[0,1]=-sin(rlat)*cos(rlng) rl[0,2]=cos(rlat)*cos(rlng) rl[1,0]=cos(rlng) rl[1,1]=-sin(rlat)*sin(rlng) rl[1,2]=cos(rlat)*sin(rlng) rl[2,1]=cos(rlat) rl[2,2]=sin(rlat) iA=numpy.zeros([3,3]) iA[0,0]=(cos(rAz)*cos(rAz)*a*a)+(b*b*sin(rAz)*sin(rAz)) iA[0,1]=(a*a-b*b)*cos(rAz)*sin(rAz) iA[1,0]=iA[0,1] iA[1,1]=(a*a*sin(rAz)*sin(rAz))+(b*b*cos(rAz)*cos(rAz)) iA[2,2]=0.000001 Wt=matmul(matmul(rl,iA),rl.transpose()) xml_str='<DnaMeasurement>\n' xml_str=xml_str+'<Type>Y</Type>\n' xml_str=xml_str+'<Ignore/>\n' xml_str=xml_str+'<ReferenceFrame>GDA2020</ReferenceFrame>\n' xml_str=xml_str+'<Epoch>01.01.2020</Epoch>\n' xml_str=xml_str+'<Vscale>1.000</Vscale>\n' xml_str=xml_str+'<Pscale>1.000</Pscale>\n' xml_str=xml_str+'<Lscale>1.000</Lscale>\n' xml_str=xml_str+'<Hscale>1.000</Hscale>\n' xml_str=xml_str+'<Coords>XYZ</Coords>\n' xml_str=xml_str+'<Total>1</Total>\n' xml_str=xml_str+'<First>' + Stn.Name + '</First>\n' xml_str=xml_str+'<Clusterpoint>\n' xml_str=xml_str+'<X>'+str(x)+'</X>\n' xml_str=xml_str+'<Y>'+str(y)+'</Y>\n' xml_str=xml_str+'<Z>'+str(z)+'</Z>\n' xml_str=xml_str+'<SigmaXX>'+str(Wt[0,0])+'</SigmaXX>\n' xml_str=xml_str+'<SigmaXY>'+str(Wt[0,1])+'</SigmaXY>\n' xml_str=xml_str+'<SigmaXZ>'+str(Wt[0,2])+'</SigmaXZ>\n' xml_str=xml_str+'<SigmaYY>'+str(Wt[1,1])+'</SigmaYY>\n' xml_str=xml_str+'<SigmaYZ>'+str(Wt[1,2])+'</SigmaYZ>\n' xml_str=xml_str+'<SigmaZZ>'+str(Wt[2,2])+'</SigmaZZ>\n' xml_str=xml_str+'</Clusterpoint>\n' xml_str=xml_str+'</DnaMeasurement>\n' return xml_str def stn_header(): xml_str='<?xml version="1.0" encoding="utf-8"?>\n' xml_str=xml_str+'<DnaXmlFormat type="Station File" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="DynaML.xsd">\n' return xml_str def msr_header(): xml_str='<?xml version="1.0" encoding="utf-8"?>\n' xml_str=xml_str+'<DnaXmlFormat type="Measurement File" referenceframe="GDA94" epoch="01.01.1994" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="DynaML.xsd">\n' return xml_str def dML_footer(): xml_str='</DnaXmlFormat>\n' return xml_str def GNSSdate2Ref(obsDate): #Use the date of GNSS baseline obsedrvation to determine the reference frame used by broadcast ephemeris if obsDate >= datetime.datetime(1900, 1, 1) and obsDate < datetime.datetime(1994, 1, 2): Ref = 'ITRF1991' if obsDate >= datetime.datetime(1994, 1, 2) and obsDate < datetime.datetime(1995, 1, 1): Ref = 'ITRF1992' if obsDate >= datetime.datetime(1995, 1, 1) and obsDate < datetime.datetime(1996, 6, 30): Ref = 'ITRF1993' if obsDate >= datetime.datetime(1996, 6, 30) and obsDate < datetime.datetime(1998, 3, 1): Ref = 'ITRF1994' if obsDate >= datetime.datetime(1998, 3, 1) and obsDate < datetime.datetime(1999, 8, 1): Ref = 'ITRF1996' if obsDate >= datetime.datetime(1999, 8, 1) and obsDate < datetime.datetime(2001, 12, 2): Ref = 'ITRF1997' if obsDate >= datetime.datetime(2001, 12, 2) and obsDate < datetime.datetime(2006, 11, 5): Ref = 'ITRF2000' if obsDate >= datetime.datetime(2006, 11, 5) and obsDate < datetime.datetime(2011, 4, 17): Ref = 'ITRF2005' if obsDate >= datetime.datetime(2011, 4, 17): Ref = 'ITRF2008' return Ref ##################################################################################### #### Input:Geolab *.iob file ##### #### Output: DynaML stn and msr file, If the input file contains the word final ##### #### and the inpuut contains error ellipse information for fixed marks ##### #### an extra stn and msr file will be produced for doing a weighted ##### #### adjustmanets and 2-D propogation of uncertainty. ##### ##################################################################################### filename = '20192277_3.Final_Adjustment.iob' if len(sys.argv) >1: filename = sys.argv[1] f = open(filename, 'r') SumRelativeUncertainties=0 AvgRelativeUncertainties=0 stnCnt=0 #Open,run through and close the file for initial informatiokn on the adjustment GNSSmarksStr=';' FloatmarksStr=';' w_MksWithObs=';' for linestr in f.readlines(): if linestr[0:4]==' PLO' or linestr[0:4] == ' PLH': if linestr[72:len(linestr)].strip()<>'' and linestr.find('ppm')<>-1: stnRec=linestr[72:len(linestr)].strip().replace(';','|').split('|') SumRelativeUncertainties=SumRelativeUncertainties+float(stnRec[7].replace('ppm','')) stnCnt=stnCnt+1 if linestr[6:8]=='00' and filename.lower().find('final')<>-1:FloatmarksStr=FloatmarksStr + linestr[10:23].strip() +';' if linestr[0:5] == ' OHDF' or linestr[0:5] == ' GAZI' or linestr[0:5] == ' AZIM' or linestr[0:5] == ' DIST' or linestr[0:5] == ' DSET' or linestr[0:4] == ' DIR' or linestr[0:5] == ' DXYZ': CurrentMsr=DnaMeasurement() CurrentMsr.first=linestr[10:23].strip() CurrentMsr.second=linestr[23:35].strip() if linestr[0:5] == ' DXYZ': GNSSmarksStr=GNSSmarksStr+';'+CurrentMsr.first+';'+CurrentMsr.second if FloatmarksStr.find(';' + CurrentMsr.first+';')<>-1 or FloatmarksStr.find(';' + CurrentMsr.second+';')<>-1: w_MksWithObs=w_MksWithObs+CurrentMsr.first+';'+CurrentMsr.second+';' f.close #bin the guessing of GDA94 relative uncertainty for the float marks if stnCnt<>0: AvgRelativeUncertainties=SumRelativeUncertainties/stnCnt if AvgRelativeUncertainties<3: AvgRelativeUncertainties=3 if AvgRelativeUncertainties>3 and AvgRelativeUncertainties<=7: AvgRelativeUncertainties=7.5 if AvgRelativeUncertainties>7.5 and AvgRelativeUncertainties<=10: AvgRelativeUncertainties=10 if AvgRelativeUncertainties>10 and AvgRelativeUncertainties<=20: AvgRelativeUncertainties=20 if AvgRelativeUncertainties>20 and AvgRelativeUncertainties<=30: AvgRelativeUncertainties=30 if AvgRelativeUncertainties>30 and AvgRelativeUncertainties<=50: AvgRelativeUncertainties=50 if AvgRelativeUncertainties>50: AvgRelativeUncertainties=int(AvgRelativeUncertainties/10)*10 f = open(filename, 'r') stnout = open(filename.replace('.iob', '.stn.xml'), 'w') msrout = open(filename.replace('.iob', '.msr.xml'), 'w') stnout.write(stn_header()) msrout.write(msr_header()) if filename.lower().find('final')<>-1: w_stnout = open(filename.replace('.iob', '_W.stn.xml'), 'w') w_msrout = open(filename.replace('.iob', '_W.msr.xml'), 'w') w_stnout.write(stn_header()) w_msrout.write(msr_header()) # Run through each line of the input file and extract the relevant lines lineCount=0 InstHts=DeviceHeight() TgtHts=DeviceHeight() CurrentMsr=DnaMeasurement() ControlRec=AdditionalInfoMsr() for linestr in f.readlines(): print(linestr) if linestr[0:5]==' TITL': jobNumber = FindJobNumber(linestr) if jobNumber=='': jobNumber=FindJobNumber(os.getcwd()) if linestr[0:4]==' PLO' or linestr[0:4] == ' PLH': CurrentStn=DnaStation() CurrentStn.Name=linestr[10:23].strip() CurrentStn.Constraint=linestr[6:9].replace('1','C') CurrentStn.Constraint=CurrentStn.Constraint.replace('0','F') CurrentStn.Constraint=CurrentStn.Constraint.strip() if linestr[0:4] == ' PLO': CurrentStn.Type='LLH' if linestr[0:4] == ' PLH': CurrentStn.Type='LLh' CurrentStn.XAxis=hms2hp(linestr[23:41].strip()) CurrentStn.YAxis=hms2hp(linestr[41:59].strip()) CurrentStn.Height=linestr[59:72].strip() CurrentStn.Description=linestr[72:len(linestr)].strip() stnAdditionalRec=AdditionalInfoStn() stnAdditionalRec.NonGSNumber='E'+jobNumber if CurrentStn.Description<>'': stnRec=CurrentStn.Description.replace(';','|').split('|')
# Copyright 2006 <NAME> and contributors # # 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. # iteration from <NAME>'s Iteration in JavaScript # must declare import _before_ importing sys from __pyjamas__ import INT, JS, setCompilerOptions, debugger setCompilerOptions("noBoundMethods", "noDescriptors", "noNameChecking", "noGetattrSupport", 'noSetattrSupport', "noCallSupport", "noAttributeChecking", "noUniversalMethFuncs") platform = JS("$pyjs.platform") sys = None dynamic = None Ellipsis = None JS(""" var $max_float_int = 1; for (var i = 0; i < 1000; i++) { $max_float_int *= 2; if ($max_float_int + 1 == $max_float_int) { break; } } var $max_int = 0x7fffffff; var $min_int = -0x80000000; """) JS("@{{next_hash_id}} = 0;") _set_hash = JS("""function(obj) { obj.$H = ++@{{next_hash_id}}; }""") _check_name = JS("""function(name, value) { if (typeof value == 'undefined') throw $pyce(@{{NameError}}("name '" + name + "' is not defined")); return value; }; """) def staticmethod(func): JS(""" var fnwrap = function() { return @{{func}}.apply(null, $pyjs_array_slice.call(arguments)); }; fnwrap.__name__ = @{{func}}.__name__; fnwrap.__args__ = @{{func}}.__args__; fnwrap.__is_staticmethod__ = true; return fnwrap; """) def classmethod(func): JS(""" var fnwrap = function() { var cls = this.__is_instance__ === true ? this.__class__ : this; return @{{func}}.apply(null, [cls].concat($pyjs_array_slice.call(arguments))); }; fnwrap.__name__ = @{{func}}.__name__; fnwrap.__args__ = @{{func}}.__args__; fnwrap.__is_classmethod__ = true; return fnwrap; """) def _create_class(clsname, bases=None, methods=None): # Creates a new class, emulating parts of Python's new-style classes if methods and '__metaclass__' in methods: return methods['__metaclass__'](clsname, bases, methods) if bases: for base in bases: if hasattr(base, '__metaclass__'): return base.__metaclass__(clsname, bases, methods) if hasattr(bases[0], '__class__') and hasattr(bases[0], '__new__'): main_base = bases[0] ctor = JS("""@{{main_base}}.__class__""") return JS("""@{{ctor}}(@{{clsname}}, @{{bases}}, @{{methods}})""") return type(clsname, bases, methods) def type(clsname, bases=None, methods=None): if bases is None and methods is None: # First check for str and bool, since these are not implemented # as real classes, but instances do have a __class__ method if isinstance(clsname, str): return str if isinstance(clsname, bool): return bool if hasattr(clsname, '__class__'): return clsname.__class__ if isinstance(clsname, int): return int if isinstance(clsname, float): return float if JS("typeof @{{clsname}} == 'number'"): return float if JS("@{{clsname}} == null"): return NoneType if JS("typeof @{{clsname}} == 'function'"): return FunctionType raise ValueError("Cannot determine type for %r" % clsname) # creates a class, derived from bases, with methods and variables mths = JS("{}") if methods: for k in methods.keys(): mth = methods[k] if JS("'$$' + @{{k}} in attrib_remap"): k = '$$' + k JS("@{{mths}}[@{{k}}] = @{{mth}};") bss = JS("null") if bases: bss = JS("@{{bases}}.__array") JS("return $pyjs_type(@{{clsname}}, @{{!bss}}, @{{!mths}});") def type__new__(cls, clsname, bases, data): JS(""" var value; for (var name in @{{cls}}) { if (name in @{{object}} || name == 'func_name' || name == 'toString' || @{{data}}.__contains__(name)) continue; value = @{{cls}}[name]; if (typeof value == 'function') { value = @{{classmethod}}(value); } @{{data}}.__setitem__(name, value); } """) new_type = type(clsname, bases, data) JS("@{{new_type}}.__class__ = @{{cls}};") return new_type JS("@{{type__new__}}.__name__ = '__new__';") JS("@{{type__new__}}.__is_staticmethod__ = true;") JS("@{{type__new__}}.toString = function() { return '<method type.__new__>'; };") JS("@{{type}}.__new__ = @{{type__new__}};") JS("@{{type}}.__$super_cache__ = {};") def type__init__(cls, name, bases, data): pass JS("@{{type__init__}}.__name__ = '__init__';") JS("@{{type__init__}}.__is_staticmethod__ = true;") JS("@{{type__init__}}.__$pyjs_autogenerated__ = true;") JS("@{{type__init__}}.toString = function() { return '<method type.__init__>'; };") JS("@{{type}}.__init__ = @{{type__init__}};") JS("@{{type}}.__name__ = 'type';") JS("@{{type}}.__class__ = @{{type}}.prototype = @{{type}};") JS("@{{type}}.__is_instance__ = false;") JS("""@{{type}}.toString = function() { return "<type 'type'>"; };""") # type.__mro__ is set below the definition of object since it depends on object class object: @classmethod def __subclasses__(cls): return JS("""@{{:list}}(@{{cls}}.__sub_classes__)""") def __setattr__(self, name, value): # // This is unnecessarily inefficient # if (typeof @{{name}} != 'string') { # throw $pyce(@{{TypeError}}("attribute name must be string")); # } JS(""" if ('$$' + @{{name}} in attrib_remap) { @{{name}} = '$$' + @{{name}}; } if (typeof @{{self}}[@{{name}}] != 'undefined' && @{{self}}.__is_instance__ && @{{self}}[@{{name}}] !== null && typeof @{{self}}[@{{name}}].__set__ == 'function') { @{{self}}[@{{name}}].__set__(@{{self}}, @{{value}}); } else { @{{self}}[@{{name}}] = @{{value}}; } """) # The __str__ method is not defined as 'def __str__(self):', since # we might get all kind of weird invocations. The __str__ is sometimes # called from toString() object.__str__ = JS("""function (self) { if (typeof self == 'undefined') { self = this; } var s; if (self.__is_instance__ === true) { s = "instance of "; } else if (self.__is_instance__ === false) { s = "class "; } else { s = "javascript " + typeof self + " "; } if (self.__module__) { s += self.__module__ + "."; } if (typeof self.__name__ != 'undefined') { return s + self.__name__; } return s + "<unknown>"; }""") # fake __mro__ to look like an instance of type `tuple` JS("@{{object}}.__mro__ = {__array: [@{{object}}]};") JS("@{{type}}.__module__ = @{{object}}.__module__;") def __array_index(arr, value, _start): JS(""" var start = @{{_start}}.valueOf(); var len = @{{arr}}.__array.length >>> 0; start = (start < 0) ? Math.ceil(start) : Math.floor(start); if (start < 0) start += len; for (; start < len; start++) { if (@{{op_eq}}(@{{arr}}.__array[start], @{{value}})) return start; } """) return -1 class tuple: def __new__(cls): JS(""" if (arguments.length == 2 && arguments[1].__class__ === @{{tuple}}) { return arguments[1]; } """) self = object.__new__(cls) JS(""" if (arguments.length == 1) { @{{self}}.__array = []; return @{{self}}; } """) data = JS("arguments[1]") JS(""" if (@{{data}} === null) { throw $pyce(@{{TypeError}}("'NoneType' is not iterable")); } if (@{{data}}.constructor === Array) { @{{self}}.__array = @{{data}}.slice(); return @{{self}}; } if (typeof @{{data}}.__iter__ == 'function') { if (typeof @{{data}}.__array == 'object') { @{{self}}.__array = @{{data}}.__array.slice(); return @{{self}}; } var iter = @{{data}}.__iter__(); if (typeof iter.__array == 'object') { @{{self}}.__array = iter.__array.slice(); return @{{self}}; } @{{data}} = []; var item, i = 0; if (typeof iter.$genfunc == 'function') { while (typeof (item=iter.next(true)) != 'undefined') { @{{data}}[i++] = item; } } else { try { while (true) { @{{data}}[i++] = iter.next(); } } catch (e) { if (!@{{isinstance}}(e['$pyjs_exc'] || e, @{{StopIteration}})) throw e; } } @{{self}}.__array = @{{data}}; return @{{self}}; } throw $pyce(@{{TypeError}}("'" + @{{repr}}(@{{data}}) + "' is not iterable")); """) JS('@{{__new__}}.$ignore__args__ = true;') def __hash__(self): return '$tuple$' + '|'.join(map(hash, self)) def __cmp__(self, l): if not isinstance(l, tuple): return 1 JS(""" var n1 = @{{self}}.__array.length, n2 = @{{l}}.__array.length, a1 = @{{self}}.__array, a2 = @{{l}}.__array, n, c; n = (n1 < n2 ? n1 : n2); for (var i = 0; i < n; i++) { c = @{{cmp}}(a1[i], a2[i]); if (c) return c; } if (n1 < n2) return -1; if (n1 > n2) return 1; return 0;""") def __getitem__(self, _index): JS(""" if (@{{isinstance}}(@{{_index}}, @{{slice}})) { if (@{{_index}}.step !== null) { // TODO/IMPLEMENTME: throw $pyce(@{{ValueError}}("step is not yet supported")); } if (@{{_index}}.stop === null) { return @{{_imm_tuple}}(@{{self}}.__array.slice(@{{_index}}.start)); } else { return @{{_imm_tuple}}(@{{self}}.__array.slice(@{{_index}}.start, @{{_index}}.stop)); } } else { var index = @{{_index}}.valueOf(); if (typeof index == 'boolean') index = @{{int}}(index); if (index < 0) index += @{{self}}.__array.length; if (index < 0 || index >= @{{self}}.__array.length) { throw $pyce(@{{IndexError}}("tuple index out of range")); } return @{{self}}.__array[index]; } """) def __unchecked_getitem__(self, index): JS(""" if (@{{index}} < 0) @{{index}} += @{{self}}.__array.length; return @{{self}}.__array[@{{index}}]; """) def __len__(self): return INT(JS("""@{{self}}.__array.length""")) def index(self, value, _start=0): index = __array_index(self, value, _start) if index >= 0: return index raise ValueError("tuple.index(x): x not in tuple") def __contains__(self, value): return __array_index(self, value, 0) >= 0 def __iter__(self): return JS("new $iter_array(@{{self}}.__array)") JS(""" var i = 0; var l = @{{self}}.__array; return { 'next': function() { if (i >= l.length) { throw $pyce(@{{StopIteration}}()); } return l[i++]; }, '__iter__': function() { return this; } }; """) def __enumerate__(self): return JS("new $enumerate_array(@{{self}}.__array)") def getArray(self): """ Access the javascript Array that is used internally by this list """ return self.__array #def __str__(self): # return self.__repr__() #See monkey patch at the end of the tuple class definition def __repr__(self): if callable(self): return "<type '%s'>" % self.__name__ JS(""" var s = "("; for (var i=0; i < @{{self}}.__array.length; i++) { s += @{{repr}}(@{{self}}.__array[i]); if (i < @{{self}}.__array.length - 1) s += ", "; } if (@{{self}}.__array.length == 1) s += ","; s += ")"; return s; """) __str__ = __repr__ def __add__(self, y): if not isinstance(y, self.__class__): raise TypeError("can only concatenate tuple to tuple") return tuple(self.__array.concat(y.__array)) def
# 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. """This module implements the main abstractions used to model distributed clusters on a single host through the use of networked Docker containers. In particular, classes for clusters (Cluster), nodes (Node), and groups of nodes that may be convenient referenced together (NodeGroup) are implemented here. """ import logging import re import threading from os.path import dirname, join from time import time, sleep from docker import Client from docker.errors import APIError from docker.utils import create_ipam_pool from clusterdock.docker_utils import (get_container_ip_address, get_network_container_hostnames, get_network_subnet, get_available_network_subnet, is_container_reachable, is_network_present, NetworkNotFoundException) from clusterdock.ssh import ssh # We disable a couple of Pylint conventions because it assumes that module level variables must be # named as if they're constants (which isn't the case here). logger = logging.getLogger(__name__) # pylint: disable=invalid-name logger.setLevel(logging.INFO) client = Client() # pylint: disable=invalid-name class Cluster(object): """The central abstraction for dealing with Docker container clusters. Instances of this class can be created as needed, but no Docker-specific behavior is done until start() is invoked. """ def __init__(self, topology, node_groups, network_name): """Creates a cluster instance from a given topology name, list of NodeGroups, and network name.""" self.topology = topology self.ssh_key = join(dirname(__file__), 'topologies', self.topology, 'ssh', 'id_rsa') self.node_groups = node_groups self.network_name = network_name self.nodes = [node for node_group in self.node_groups for node in node_group.nodes] def setup_network(self): """If the network doesn't already exist, create it, being careful to pick a subnet that doesn't collide with that of any other Docker networks already present.""" if not is_network_present(self.network_name): logger.info("Network (%s) not present, creating it...", self.network_name) next_network_subnet = get_available_network_subnet() while True: try: client.create_network(name=self.network_name, driver='bridge', ipam={ 'Config': [create_ipam_pool(subnet=next_network_subnet)] }) except APIError as api_error: if 'networks have overlapping IPv4' not in api_error.explanation: raise api_error else: # The hash after "conflicts with network" is the name with the overlapping # subnet. Save this to speed up finding the next available subnet the next # time around in the while loop. conflicting_network = re.findall(r'conflicts with network (\S+)', api_error.explanation)[0] logger.info("Conflicting network:(%s)", conflicting_network) # Try up get the next network subnet up to 5 times (looks like there's a # race where the conflicting network is known, but not yet visible through # the API). for _ in range(0, 5): try: next_network_subnet = get_available_network_subnet( get_network_subnet(conflicting_network) ) except NetworkNotFoundException as network_not_found_exception: if 'Cannot find network' not in network_not_found_exception.message: raise network_not_found_exception sleep(1) else: break else: logger.info("Successfully setup network (name: %s).", self.network_name) break def ssh(self, command, nodes=None): """Execute command on all nodes (unless a list of Node instances is passed) in parallel.""" ssh(command=command, hosts=[node.ip_address for node in self.nodes if not nodes or node in nodes], ssh_key=self.ssh_key) def start(self): """Actually start Docker containers, mimicking the cluster layout specified in the Cluster instance.""" start = time() self.setup_network() # Before starting any containers, make sure that there aren't any containers in the # network with the same hostname. network_container_hostnames = ( get_network_container_hostnames(self.network_name)) for node in self.nodes: # Set the Node instance's cluster attribute to the Cluster instance to give the node # access to the topology's SSH keys. node.cluster = self if node.hostname in network_container_hostnames: raise Exception( "A container with hostname {0} already exists in network {1}".format( node.hostname, self.network_name)) threads = [threading.Thread(target=node.start) for node in self.nodes] for thread in threads: thread.start() # Sleep shortly between node starts to bring some determinacy to the order of the IP # addresses that we get. sleep(0.25) for thread in threads: thread.join() etc_hosts_string = ''.join("{0} {1}.{2} # Added by clusterdock\n".format(node.ip_address, node.hostname, node.network) for node in self.nodes) with open('/etc/hosts', 'a') as etc_hosts: etc_hosts.write(etc_hosts_string) end = time() logger.info("Started cluster in %.2f seconds.", end - start) def __iter__(self): for node in self.nodes: yield node def __len__(self): return len(self.nodes) class NodeGroup(object): """A node group denotes a set of Nodes that share some characteristic so as to make it desirable to refer to them separately from other sets of Nodes. For example, in a typical HDFS cluster, one node would run the HDFS NameNode while the remaining nodes would run HDFS DataNodes. In this case, the former might comprise the "primary" node group while the latter may be part of the "secondary" node group. """ def __init__(self, name, nodes=None): """Initialize a Group instance called name with a list of nodes.""" self.name = name self.nodes = nodes def __iter__(self): for node in self.nodes: yield node def add_node(self, node): """Add a Node instance to the list of nodes in the NodeGroup.""" self.nodes.append(node) def ssh(self, command): """Run command over SSH across all nodes in the NodeGroup in parallel.""" ssh_key = self[0].cluster.ssh_key ssh(command=command, hosts=[node.ip_address for node in self.nodes], ssh_key=ssh_key) class Node(object): """The abstraction will eventually be actualized as a running Docker container. This container, unlike the typical Docker container, does not house a single process, but tends to run an init to make the container act more or less like a regular cluster node. """ # pylint: disable=too-many-instance-attributes # 11 instance attributes to keep track of node properties isn't too many (Pylint sets the limit # at 7), and while we could create a single dictionary attribute, that doesn't really improve # readability. def __init__(self, hostname, network, image, **kwargs): """volumes must be a list of dictionaries with keys being the directory on the host and the values being the corresponding directory in the container to mount.""" self.hostname = hostname self.network = network self.fqdn = "{0}.{1}".format(hostname, network) self.image = image # Optional arguments are relegated to the kwargs dictionary, in part to keep Pylint happy. self.command = kwargs.get('command') self.ports = kwargs.get('ports') # /etc/localtime is always volume mounted so that containers have the same timezone as their # host machines. self.volumes = [{'/etc/localtime': '/etc/localtime'}] + kwargs.get('volumes', []) # Define a number of instance attributes that will get assigned proper values when the node # starts. self.cluster = None self.container_id = None self.host_config = None self.ip_address = None def _get_binds(self): """docker-py takes binds in the form "/host/dir:/container/dir:rw" as host configs. This method returns a list of binds in that form.""" return ["{0}:{1}:rw".format(host_location, volume[host_location]) for volume in self.volumes for host_location in volume] def start(self): """Actually start a Docker container-based node on the host.""" # Create a host_configs dictionary to populate and then pass to Client.create_host_config(). host_configs = {} # To make them act like real hosts, Nodes must have all Linux capabilities enabled. For # some reason, we discovered that doing this causes less trouble than starting containers in # privileged mode (see KITCHEN-10073). We also disable the default seccomp profile (see #3) # and pass in the volumes list at this point. host_configs['cap_add'] = ['ALL'] host_configs['security_opt'] = ['seccomp:unconfined'] host_configs['publish_all_ports'] = True if self.volumes: host_configs['binds'] = self._get_binds() self.host_config = client.create_host_config(**host_configs) # docker-py runs containers in a two-step process: first it creates a container and then # it starts the container using the container ID. container_configs = { 'hostname': self.fqdn, 'image': self.image, 'host_config': self.host_config, 'detach': True, 'command': self.command, 'ports': self.ports, 'volumes': [volume[host_location] for volume in self.volumes for host_location in volume if self.volumes], 'labels': {"volume{0}".format(i): volume for i, volume in enumerate([volume.keys()[0] for volume in self.volumes if volume.keys()[0] not in ['/etc/localtime']], start=1) } } self.container_id = client.create_container(**container_configs)['Id'] # Don't start up containers on the default 'bridge' network for better isolation. client.disconnect_container_from_network(container=self.container_id, net_id='bridge') client.connect_container_to_network(container=self.container_id, net_id=self.network, aliases=[self.hostname]) client.start(container=self.container_id) self.ip_address = get_container_ip_address(container_id=self.container_id, network=self.network) if not is_container_reachable(container_id=self.container_id, network=self.network, ssh_key=self.cluster.ssh_key): raise Exception("Timed out waiting for {0} to become reachable.".format(self.hostname)) else: logger.info("Successfully started %s (IP address: %s).", self.fqdn, self.ip_address) def
# import numpy as np from number_objects.primitives.polycalc_numbers import Rational, Integer from number_objects.primitives.vector import Vector # Todo: Cholesky decomposition, singlular value decomposition, eigen values class Matrix(list): def __float__(self): assert self.shape == (1, 1) return float(self[0][0]) def __add__(self, other): if type(other) == Matrix: assert self.shape == other.shape return Matrix(matrix_plus_matrix(self, other)) if type(other) == list: return Matrix(matrix_plus_matrix(self, other)) def __sub__(self, other): return self + -1 * other def __neg__(self): return -1 * self def __mul__(self, other): if type(other) == Matrix: return Matrix(matrix_times_matrix(self, other)) if type(other) == list: if type(other[0]) != list: return Matrix(matrix_times_matrix(self, [other])) return Matrix(matrix_times_matrix(self, other)) if type(other) in {int, float, Integer, Rational}: return Matrix(scalar_multiplication(other, self)) def __rmul__(self, other): return self * other def __str__(self): return matrix_to_string(self) def __repr__(self): return matrix_to_string(self) def concatenate(self, other, axis=None): """ axis = 0: vertical concatenation (default) axis = 1: horizontal concatenation """ if other == [] or other == [[]]: return self res = self.copy() if not axis: axis = 0 if axis == 0: assert self.shape[1] == len(other[0]) for row in other: res.append(row) if axis == 1: assert self.shape[0] == len(other) for j in range(len(other[0])): for i in range(len(res)): res[i].append(other[i][j]) return Matrix(res) @property def shape(self): return len(self), len(self[0]) def transpose(self): return Matrix(transpose_matrix(self)) def determinant(self): return get_matrix_determinant(self) def inverse(self): return Matrix(get_matrix_inverse(self)) def null_space(self): return Matrix(get_nullspace(self)) def gram_schmidt(self): return Matrix(gram_schmidt(self)) @staticmethod def zeroes(dimension): res = [] if type(dimension) == tuple: n = dimension[0] m = dimension[1] for i in range(n): res.append([]) for j in range(m): res[i].append(0) if type(dimension) == int: res.append([]) for i in range(dimension): res[0].append(0) return Matrix(res) @staticmethod def ones(dimension): res = [] if type(dimension) == tuple: n = dimension[0] m = dimension[1] for i in range(n): res.append([]) for j in range(m): res[i].append(1) if type(dimension) == int: res.append([]) for i in range(dimension): res[0].append(1) return Matrix(res) @staticmethod def identity(n): res = Matrix.zeroes((n, n)) for i in range(n): res[i][i] = 1 return res def column_sub_matrix(self, stop, start=0): return Matrix([x[start: stop] for x in self]) def transpose_matrix(m): return list(map(list, zip(*m))) def get_matrix_minor(m, i, j): return [row[:j] + row[j + 1:] for row in (m[:i] + m[i + 1:])] def matrix_copy(m): res = [] for i in range(len(m)): res.append(m[i].copy()) return res def get_matrix_determinant(m): assert len(m) == len(m[0]) n = len(m) m = matrix_copy(m) # row operations to get upper triangle matrix: for focus_diagonal in range(n): for i in range(focus_diagonal + 1, n): # make sure the diagonal entry is non-zero if m[focus_diagonal][focus_diagonal] == 0: # look for rows below that have non-zero entry in that column # if there is a non-zero, then add that row to current row # else: return zero for r in range(focus_diagonal, n): if m[r][focus_diagonal] != 0: for j in range(n): m[focus_diagonal][j] += m[r][j] break else: return 0 # m[focus_diagonal][focus_diagonal] = 1.0e-18 # change to ~zero current_row_scalar = m[i][focus_diagonal] / m[focus_diagonal][focus_diagonal] for j in range(n): m[i][j] = m[i][j] - current_row_scalar * m[focus_diagonal][j] product = m[0][0] if len(m) > 1: for i in range(1, n): product *= m[i][i] return product def get_matrix_inverse(m): """ can perhaps be improved with Cholesky decomposition """ determinant = get_matrix_determinant(m) # special case for 2x2 matrix: if len(m) == 2: return [[m[1][1] / determinant, -1 * m[0][1] / determinant], [-1 * m[1][0] / determinant, m[0][0] / determinant]] # find matrix of cofactors cofactors = [] for i in range(len(m)): cofactor_row = [] for j in range(len(m)): minor = get_matrix_minor(m, i, j) cofactor_row.append(((-1) ** (i + j)) * get_matrix_determinant(minor)) cofactors.append(cofactor_row) cofactors = transpose_matrix(cofactors) for i in range(len(cofactors)): for j in range(len(cofactors)): cofactors[i][j] = cofactors[i][j] / determinant return cofactors def vector_plus_vector(v_1, v_2): if type(v_1) == tuple: return tuple(map(sum, zip(v_1, v_2))) if type(v_1) == list: return list(map(sum, zip(v_1, v_2))) if type(v_1) == Vector: return Vector(map(sum, zip(v_1, v_2))) def vector_times_vector(v_1, v_2): res = 0 for i, component in enumerate(v_1): res += component * v_2[i] return res def constant_times_vector(constant, vector): res = [] for component in vector: res.append(constant * component) return res def scalar_multiplication(constant, matrix): res = [] for i, row in enumerate(matrix): res.append([]) for component in row: res[i].append(constant * component) return res def matrix_times_vector(matrix, vector): res = [] for row in matrix: dot_product = 0 for i, item in enumerate(row): dot_product += item * vector[i] res.append(dot_product) return res def matrix_times_matrix(x, y): res = [] for i in range(len(x)): res.append([]) for j in range(len(y[0])): res[i].append(0) for i in range(len(x)): for j in range(len(y[0])): for k in range(len(y)): res[i][j] += x[i][k] * y[k][j] return res def matrix_plus_matrix(x, y): res = [] for i in range(len(x)): res.append([]) for j in range(len(x[0])): res[i].append(x[i][j] + y[i][j]) return res def vector_times_matrix(vector, matrix): res = [] for column_number in range(len(matrix[0])): dot_product = 0 for row_number in range(len(matrix)): dot_product += matrix[row_number][column_number] * vector[row_number] res.append(dot_product) return res def get_nullspace(matrix): """ returns the right nullspace of matrix, a.k.a. kernel The left nullspace is simply the nullspace of the transpose of the input """ # get ref m = get_integer_ref(matrix) # number of paramaters is number of variables that are not on the diagonal, i.e. columns - rows (if full rank) # if everything to the left is zeros then that variable is not a paramater # make the equations diagonal_indices = set() running_lcm = 1 rank = 0 for j in range(len(m[0])): for i in reversed(range(rank, len(m))): if m[i][j] != 0: diagonal_indices.add(j) rank += 1 running_lcm = lcm(running_lcm, m[i][j]) break m = [x for x in m if any(x)] # remove zero lines for i in range(len(m)): for j in range(len(m[i])): if m[i][j] != 0: first_non_zero = m[i][j] break for j in range(len(m[i])): m[i][j] *= running_lcm // first_non_zero # build the paramater vector # go through columns, if they are in the diagonal indices, they are not a parameter nullspace_vectors = [] for r in range(len(m[0]) - rank): nullspace_vectors.append([]) rank = 0 for j in range(len(m[0])): if j not in diagonal_indices: for i in range(len(m)): nullspace_vectors[j - rank].append(-m[i][j]) else: rank += 1 vector_number = 0 for j in range(len(m[0])): if j not in diagonal_indices: for i, vector in enumerate(nullspace_vectors): if i == vector_number: vector.insert(j, running_lcm) else: vector.insert(j, 0) vector_number += 1 return transpose_matrix(nullspace_vectors) # def get_nullspace_numpy(matrix): # """ # returns the right nullspace of matrix, a.k.a. kernel # The left nullspace is simply the nullspace of the transpose of the input # This function has numpy dependency. # """ # # get ref # m = get_integer_ref_numpy(matrix) # # number of paramaters is number of variables that are not on the diagonal, i.e. columns - rows (if full rank) # # if everything to the left is zeros then that variable is not a paramater # # make the equations # diagonal_indices = set() # running_lcm = 1 # rank = 0 # for j in range(len(m[0])): # for i in reversed(range(rank, len(m))): # if m[i][j] != 0: # diagonal_indices.add(j) # rank += 1 # running_lcm = lcm(running_lcm, m[i][j]) # break # m = m[[i for i, x in enumerate(m) if x.any()]] # remove zero lines # for row in m: # for j in range(len(row)): # if row[j] != 0: # first_non_zero = row[j] # break # row *= running_lcm // first_non_zero # # build the paramater vector # # go through columns, if they are in the diagonal indices, they are not a parameter # nullspace_vectors = [] # for r in range(len(m[0]) - rank): # nullspace_vectors.append([]) # rank = 0 # for j in range(len(m[0])): # if j not in diagonal_indices: # for i in range(len(m)): # nullspace_vectors[j - rank].append(-m[i][j]) # else: # rank += 1 # vector_number = 0 # for j in range(len(m[0])): # if j not in diagonal_indices: # for i, vector in enumerate(nullspace_vectors): # if i == vector_number: # vector.insert(j, running_lcm) # else: # vector.insert(j, 0) # vector_number += 1 # return np.array(nullspace_vectors).transpose() # def get_left_nullspace_numpy(m): # return get_nullspace_numpy(m.transpose()).transpose() def get_left_nullspace(m): return transpose_matrix(get_nullspace(transpose_matrix(m))) def gcd(x, y): if x == 0 or y == 0: return 1 while y: if y == 0: break x, y = y, x % y return x def lcm(a, b): return abs(a * b / gcd(a, b)) def list_gcd(numbers): # initialize g to first non-zero number for num in numbers: if num != 0: g = num break else: return 1 for a in numbers: if a != 0: g = gcd(g, a) return g def get_integer_ref(matrix): m =
| Id | Type | Description | +=======+=========+====================================================+ | fopts | OT_DICT | Options to be passed to generated function objects | +-------+---------+----------------------------------------------------+ -------------------------------------------------------------------------------- <NAME> C++ includes: linsol.hpp """ __swig_setmethods__ = {} for _s in [SharedObject, PrintableCommon]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, Linsol, name, value) __swig_getmethods__ = {} for _s in [SharedObject, PrintableCommon]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, Linsol, name) __repr__ = _swig_repr def type_name(*args): """ type_name() -> str """ return _casadi.Linsol_type_name(*args) type_name = staticmethod(type_name) def test_cast(*args): """ test_cast(casadi::SharedObjectInternal const * ptr) -> bool """ return _casadi.Linsol_test_cast(*args) test_cast = staticmethod(test_cast) def has_plugin(*args): """ has_plugin(str name) -> bool """ return _casadi.Linsol_has_plugin(*args) has_plugin = staticmethod(has_plugin) def load_plugin(*args): """ load_plugin(str name) """ return _casadi.Linsol_load_plugin(*args) load_plugin = staticmethod(load_plugin) def doc(*args): """ doc(str name) -> str """ return _casadi.Linsol_doc(*args) doc = staticmethod(doc) def plugin_name(self, *args): """ Query plugin name. plugin_name(self) -> str """ return _casadi.Linsol_plugin_name(self, *args) def sparsity(self, *args): """ Get linear system sparsity. sparsity(self) -> Sparsity """ return _casadi.Linsol_sparsity(self, *args) def sfact(self, *args): """ Symbolic factorization of the linear system, e.g. selecting pivots. sfact(self, DM A) """ return _casadi.Linsol_sfact(self, *args) def nfact(self, *args): """ Numeric factorization of the linear system. nfact(self, DM A) """ return _casadi.Linsol_nfact(self, *args) def solve(self, *args): """ Solve linear system of equations solve(self, DM A, DM B, bool tr) -> DM solve(self, MX A, MX B, bool tr) -> MX """ return _casadi.Linsol_solve(self, *args) def neig(self, *args): """ Number of negative eigenvalues Not available for all solvers. neig(self, DM A) -> int """ return _casadi.Linsol_neig(self, *args) def rank(self, *args): """ Matrix rank Not available for all solvers. rank(self, DM A) -> int """ return _casadi.Linsol_rank(self, *args) def __init__(self, *args): """ Linsol() Default constructor. Linsol(Linsol other) Linsol(str name, str solver, Sparsity sp, dict opts) Constructor. > Linsol(Linsol other) ------------------------------------------------------------------------ > Linsol() ------------------------------------------------------------------------ Default constructor. > Linsol(str name, str solver, Sparsity sp, dict opts) ------------------------------------------------------------------------ Constructor. """ this = _casadi.new_Linsol(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _casadi.delete_Linsol Linsol_swigregister = _casadi.Linsol_swigregister Linsol_swigregister(Linsol) def Linsol_type_name(*args): """ type_name() -> str """ return _casadi.Linsol_type_name(*args) def Linsol_test_cast(*args): """ test_cast(casadi::SharedObjectInternal const * ptr) -> bool """ return _casadi.Linsol_test_cast(*args) def Linsol_has_plugin(*args): """ has_plugin(str name) -> bool """ return _casadi.Linsol_has_plugin(*args) def Linsol_load_plugin(*args): """ load_plugin(str name) """ return _casadi.Linsol_load_plugin(*args) def Linsol_doc(*args): """ doc(str name) -> str """ return _casadi.Linsol_doc(*args) def has_linsol(*args): """ Check if a particular plugin is available. has_linsol(str name) -> bool """ return _casadi.has_linsol(*args) def load_linsol(*args): """ Explicitly load a plugin dynamically. load_linsol(str name) """ return _casadi.load_linsol(*args) def doc_linsol(*args): """ Get the documentation string for a plugin. doc_linsol(str name) -> str """ return _casadi.doc_linsol(*args) def dplesol(*args): """ dplesol([DM] A, [DM] V, str solver, dict opts) -> [DM] dplesol(MX A, MX V, str solver, dict opts) -> MX dplesol([MX] A, [MX] V, str solver, dict opts) -> [MX] dplesol(str name, str solver, dict:Sparsity qp, dict opts) -> Function Discrete periodic Lyapunov Equation solver Given matrices $A_k$ and > dplesol([DM] A, [DM] V, str solver, dict opts) > dplesol(MX A, MX V, str solver, dict opts) > dplesol([MX] A, [MX] V, str solver, dict opts) ------------------------------------------------------------------------ > dplesol(str name, str solver, dict:Sparsity qp, dict opts) ------------------------------------------------------------------------ Discrete periodic Lyapunov Equation solver Given matrices $A_k$ and symmetric $V_k, k = 0..K-1$ :: A_k in R^(n x n) V_k in R^n provides all of $P_k$ that satisfy: :: P_0 = A_(K-1)*P_(K-1)*A_(K-1)' + V_k P_k+1 = A_k*P_k*A_k' + V_k for k = 1..K-1 General information =================== >List of available options +------------------+-----------------+------------------+------------------+ | Id | Type | Description | Used in | +==================+=================+==================+==================+ | ad_weight | OT_DOUBLE | Weighting factor | casadi::Function | | | | for derivative | Internal | | | | calculation.When | | | | | there is an | | | | | option of either | | | | | using forward or | | | | | reverse mode | | | | | directional | | | | | derivatives, the | | | | | condition ad_wei | | | | | ght*nf<=(1-ad_we | | | | | ight)*na is used | | | | | where nf and na | | | | | are estimates of | | | | | the number of | | | | | forward/reverse | | | | | mode directional | | | | | derivatives | | | | | needed. By | | | | | default, | | | | | ad_weight is | | | | | calculated | | | | | automatically, | | | | | but this can be | | | | | overridden by | | | | | setting this | | | | | option. In | | | | | particular, 0 | | | | | means forcing | | | | | forward mode and | | | | | 1 forcing | | | | | reverse mode. | | | | | Leave unset for | | | | | (class specific) | | | | | heuristics. | | +------------------+-----------------+------------------+------------------+ | ad_weight_sp | OT_DOUBLE | Weighting factor | casadi::Function | | | | for sparsity | Internal | | | | pattern | | | | | calculation calc | | | | | ulation.Override | | | | | s default | | | | | behavior. Set to | | | | | 0 and 1 to force | | | | | forward and | | | | | reverse mode | | | | | respectively. | | | | | Cf. option | | | | | "ad_weight". | | +------------------+-----------------+------------------+------------------+ | compiler | OT_STRING | Just-in-time | casadi::Function | | | | compiler plugin | Internal | | | | to be used. | | +------------------+-----------------+------------------+------------------+ | const_dim | OT_BOOL | Assume constant | casadi::Dple | | | | dimension of P | | +------------------+-----------------+------------------+------------------+ | derivative_of | OT_FUNCTION | The function is | casadi::Function | | | | a derivative of | Internal | | | | another | | | | | function. The | | | | | type of | | | | | derivative | | | | | (directional | | | | | derivative, | | | | | Jacobian) is | | | | | inferred from | | | | | the function | | | | | name. | | +------------------+-----------------+------------------+------------------+ | enable_fd | OT_BOOL | Enable | casadi::Function | | | | derivative | Internal | | | | calculation by | | | | | finite | | | | | differencing. | | | | | [default: | | | | | false]] | | +------------------+-----------------+------------------+------------------+ | enable_forward | OT_BOOL | Enable | casadi::Function | | | | derivative | Internal | | | | calculation | | | | | using generated | | | | | functions for | | | | | Jacobian-times- | | | | | vector products | | | | | - typically | | | | | using forward | | | | | mode AD - if | | | | | available. | | | | | [default: true] | | +------------------+-----------------+------------------+------------------+ | enable_jacobian | OT_BOOL | Enable | casadi::Function | | | | derivative | Internal | | | | calculation | | | | | using generated | | | | | functions for | | | | | Jacobians of all | | | | | differentiable | | | | | outputs with | | | | | respect to all | | | | | differentiable | | | | | inputs - if | | | | | available. | | | | | [default: true] | | +------------------+-----------------+------------------+------------------+ | enable_reverse |
<gh_stars>1000+ # Cast column to f64 before convert it to pandas # This is a hack, use the assert_equal comparator when nulls is # fully supported on cudf.sort_values import json import logging import os import re import time import yaml import numpy as np import pandas as pd import blazingsql from blazingsql import DataType from BlazingLogging import loggingHandler as lhandler from Configuration import ExecutionMode from Configuration import Settings as Settings from DataBase import createSchema as cs if ((Settings.execution_mode == ExecutionMode.FULL and Settings.compare_res == "true") or Settings.execution_mode == ExecutionMode.GENERATOR): print(Settings.execution_mode) print(Settings.compare_res) from pydrill.client import PyDrill from pyspark.sql.session import SparkSession class Result: def __init__(self, columns, resultSet, resultBlz): self.columns = columns self.resultSet = resultSet self.resultBlz = resultBlz name = "blzlogging" HANDLER = lhandler.logging_handler() class result: def __init__(self, res_execution, error): self.res_execution = res_execution self.error = error def logginghelper(name): # logging.basicConfig(filename='example.txt',level=logging.DEBUG) logging._defaultFormatter = logging.Formatter() logger = logging.getLogger(name) logger.handlers = [] logger.setLevel(logging.DEBUG) logger.addHandler(HANDLER) return logger def loggingClose(name): HANDLER.log = [] def upcast_to_float(df): for name in df.columns: if np.issubdtype(df[name].dtype, np.bool_): df[name] = df[name].astype(np.float32) elif np.issubdtype(df[name].dtype, np.timedelta64): # issue: cannot astype a timedelta from [timedelta64[ns]] to [float64] # so first cast from timedelta64[ns] to timedelta64[ms] and after to np.float64 df[name] = df[name].astype('timedelta64[ms]') df[name] = df[name].astype(np.float64) elif np.issubdtype(df[name].dtype, np.integer): df[name] = df[name].astype(np.float64) return df def to_pandas_f64_engine(df, expected_types_list): count = 0 for col in df.columns: if count >= len(expected_types_list): break if expected_types_list[count] != np.dtype(object): if df.shape[0] > 0: if not np.issubdtype(df[col].dtype, np.number) and not np.issubdtype( df[col].dtype, np.datetime64 ): if np.issubdtype(expected_types_list[count], np.bool_): df[col] = ( df[col].map({"true": 1.0, "false": 0.0}).astype(np.float32) ) elif np.issubdtype(expected_types_list[count], np.datetime64): df[col] = df[col].astype(expected_types_list[count]) elif np.issubdtype(expected_types_list[count], np.timedelta64): # Drill case: always converts to timedelta64[ns] df[col] = pd.to_timedelta(df[col]) else: df[col] = pd.to_numeric(df[col], errors="coerce") count = count + 1 return df def get_null_constants(df): null_values = {} for col, dtype in df.dtypes.to_dict().items(): if np.issubdtype(dtype, np.datetime64): null_values[col] = np.datetime64("nat") elif np.issubdtype(dtype, np.number): null_values[col] = np.nan return null_values def compare_result_values(pdf1, pdf2, acceptable_difference, use_percentage, engine): """ The purpose of this functions is to compare the values from blazingsql and drill/spark results. ---------- pdf1 : blazing results (pandas dataframe) pdf2: drill/spark results (pandas dataframe) acceptable_difference: This parameter is related to the acceptable difference beetween values from blazingsql results and drill/spark results. use_percentage: (True/False) to indicate if the results will be compared by percentage or difference. engine: pydrill or pyspark instances """ np.warnings.filterwarnings("ignore") if pdf1.size == 0 and pdf2.size == 0: return "Success" msg = "" if not isinstance(engine, str): if isinstance(engine, PyDrill): msg = "PyDrill" else: msg = "PySpark" elif engine=="drill": msg = "PyDrill" else: msg = "PySpark" msg = "" if not isinstance(engine, str): if isinstance(engine, PyDrill): msg = "PyDrill" else: msg = "PySpark" elif engine=="drill": msg = "PyDrill" else: msg = "PySpark" if pdf1.shape[0] == pdf2.shape[0]: if pdf1.shape[1] == pdf2.shape[1]: for name in pdf1.columns: if pdf1[name].dtype == np.object: pdf1[name] = pdf1[name].astype('string') for name in pdf2.columns: if pdf2[name].dtype == np.object: pdf2[name] = pdf2[name].astype('string') # Removing indexes, because those are considered when # comparing with equals() pdf1.reset_index(drop=True, inplace=True) pdf2.reset_index(drop=True, inplace=True) # Make the column labels equal as equals() also compare labels orig_pdf2_labels = pdf2.columns.to_list() pdf2.columns = pdf1.columns.to_list() exac_comp = pdf1.select_dtypes(exclude=np.inexact).equals( pdf2.select_dtypes(exclude=np.inexact) ) # Restore labels pdf2.columns = orig_pdf2_labels tmp_pdf1 = pdf1.select_dtypes(include=np.inexact) tmp_pdf2 = pdf2.select_dtypes(include=np.inexact) if use_percentage: relative_tolerance = acceptable_difference absolute_tolerance = 0 else: relative_tolerance = 0 absolute_tolerance = acceptable_difference # np.allclose follows this formula: # absolute(a - b) <= (absolute_tolerance + relative_tolerance * absolute(b)) res = np.all(exac_comp) and np.allclose( tmp_pdf1.values, tmp_pdf2.values, relative_tolerance, absolute_tolerance, equal_nan=True ) if res: return "Success" else: return "Fail: Different values" else: return ( "Fail: Different number of columns blzSQLresult: " + str(pdf1.shape[1]) + " " + msg + " result: " + str(pdf2.shape[1]) ) else: return ( "Fail: Different number of rows blzSQLresult: " + str(pdf1.shape[0]) + " " + msg + " result: " + str(pdf2.shape[0]) ) def begins_with(col1, col2, exp): return col1.startswith(exp) or col2.startswith(exp) def compare_column_names(pdf1, pdf2): if len(pdf1.columns) != len(pdf2.columns): if pdf1.values.size == 0 and pdf2.values.size == 0: return True print("Different set of columns") return False for blzCol, drillCol in zip( pdf1.columns.values.tolist(), pdf2.columns.values.tolist() ): if blzCol != drillCol: if ( begins_with(drillCol, blzCol, "EXPR") is False and begins_with(drillCol, blzCol, "count(") is False ): print("Different columns") return False return True # NOTE <NAME>: NEVER CHANGE THE ORDER of these # lines (the logger logic depends that we log first queryType and then queryId # WARNING DO NOT CHANGE THE CALL ORDER IN THIS FUCTION! def get_Branch(): branch = blazingsql.__branch_name__ return branch def get_CommitHash(): commit = blazingsql.__version__ return commit def get_QueryId(input_type, test_name, test_id): query_id = ( str(input_type).upper() + "-" + str(get_codTest(test_name)).upper() + "-" + str(test_id) ) return query_id def get_resultId(resultComparisson): result_id = 1 if resultComparisson != "Success": result_id = 0 return result_id def get_codTest(test_name): cwd = os.path.dirname(os.path.realpath(__file__)) fileName = cwd + "/targetTest.yaml" if os.path.isfile(fileName): with open(fileName, 'r') as stream: fileYaml = yaml.safe_load(stream)["LIST_TEST"] if test_name in fileYaml: if "CODE" in fileYaml[test_name]: return fileYaml[test_name]["CODE"] else: #Legacy Test for item in fileYaml: if "NAME" in fileYaml[item] and fileYaml[item]["NAME"] == test_name: return fileYaml[item]["CODE"] raise Exception("ERROR: CODE configuration not found for '" + test_name + "' in targetTest.yaml, i.e. CODE: BALIAS") def logger_results( logger, test_name, input_type, test_id, sql, resultComparisson, error_message, load_time, engine_time, total_time, ): commitHash = get_CommitHash() branchName = get_Branch() # dateNow=datetime.now() inputType = cs.get_extension(input_type) logger.info(get_QueryId(inputType, test_name, test_id)) # QueryID logger.info(Settings.dateNow) # TimeStamp logger.info(test_name) # TestGroup logger.info(inputType) # InputType logger.info(sql) # Query logger.info(get_resultId(resultComparisson)) # Result logger.info(error_message) # Error logger.info(branchName) # PR logger.info(commitHash) # CommitHash logger.info(Settings.data["RunSettings"]["nRals"]) logger.info(Settings.data["RunSettings"]["nGPUs"]) logger.info(Settings.data["TestSettings"]["dataDirectory"]) logger.info(test_id) logger.info(load_time) logger.info(engine_time) logger.info(total_time) def compare_test_results( pdf1, pdf2, acceptable_difference, use_percentage, engine, comparing=True ): """ Compare values, number of rows, columns, and column names ---------- pdf1 : blazing results (pandas dataframe) pdf2: drill/spark results (pandas dataframe) acceptable_difference: This parameter is related to the acceptable difference beetween values from blazingsql results and drill/spark results. use_percentage: (True/False) to indicate if the results will be compared by percentage or difference. comparing: Parameter to indicate if the results from blazingsql will be compared with the results from drill or spark """ compareResults = True error_message = "" stringResult = "" columnNamesComparison = True resultComparisson = "" if "compare_result_values" in Settings.data["RunSettings"]: compareResults = Settings.data["RunSettings"]["compare_result_values"] # For dateTest (CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP) if not comparing: compareResults = False if compareResults: columnNamesComparison = compare_column_names(pdf1, pdf2) if columnNamesComparison is not True: error_message = "Column names are not the same" resultComparisson = compare_result_values( pdf1, pdf2, acceptable_difference, use_percentage, engine ) if resultComparisson != "Success": error_message = resultComparisson[6:] stringResult = resultComparisson if resultComparisson != "Success" or columnNamesComparison is False: stringResult = "Fail" else: stringResult = "Success" return error_message, stringResult, columnNamesComparison, resultComparisson def print_comparison_results( sql, queryId, queryType, pdf1, pdf2, print_result, engine, input_type, total_time, error_message, stringResult, columnNamesComparison, resultComparisson ): if print_result: print("#BLZ:") print(pdf1) if not isinstance(engine, str): if isinstance(engine, PyDrill): print("#DRILL:") else: print("#PYSPARK:") print(pdf2) else: if engine=="drill": print("#DRILL:") else: print("#PYSPARK:") data_type = cs.get_extension(input_type) print(str(queryId) + " Test " + queryType + " - " + data_type) print("#QUERY:") print(sql) print("RESULT:") print(stringResult) if columnNamesComparison is not True: print("Columns:") print(pdf1.columns) print(pdf2.columns) print("ERROR:") print(error_message) if resultComparisson != "Success": print("ERROR:") print(error_message) print("TOTAL TIME: ") print(total_time) print("CRASHED NODES: ") # print(resultgdf.n_crashed_nodes) print("TOTAL NODES: ") # print(resultgdf.total_nodes) print("===================================================") def print_validation_results(sql, queryId, input_type, queryType, error_message, message_validation): print(queryId) print("#QUERY:") print(sql) print("RESULT:") result = validate_messages(error_message, message_validation) print(result) print("ERROR:") if result=="Fail": print(error_message) else: error_message="" print("CALCITE TIME: ") print("-") print("RAL TIME: ") print("-") print("EXECUTION TIME: ") print("-") print("===================================================") logger = logginghelper(name) logger_results( logger, queryType, input_type, queryId, sql, result, error_message, None, None, None ) def print_performance_results(sql, queryId, queryType, resultgdf): print(queryId) print("#QUERY:") print(sql) print("RESULT:") resultComparisson = "Success" print("CALCITE TIME: ") print(resultgdf.calciteTime) print("RAL TIME: ") print(resultgdf.ralTime) print("EXECUTION TIME: ") print(resultgdf.totalTime) print("===================================================") logger = logginghelper(name) logger_results( logger, queryType, queryId, sql, resultComparisson, " ", resultgdf.calciteTime, resultgdf.ralTime, resultgdf.totalTime, ) class Test: def __init__(self, test_name): self.test_name = test_name self.total = 0 self.success = 0 self.fail_ids = [] def save_log(gpu_ci_mode=False): """ put the log into a pandas dataframe """ c = 1 cadena = [] subcadena = [] countPass = 0 countCrash = 0 for x in HANDLER.log: if c < 17: subcadena.append(x.msg) c = c + 1 else: c = 1 cadena.append(subcadena) subcadena = [] subcadena.append(x.msg) c = c + 1 print() cadena.append(subcadena) # If it didn't run any test (probably some were skipped) # then return success if cadena == [[]]: return True, [] df =
performance I'm going to assume that the only # field that needs *updating* would be the joined_at field. # If there is no Member object (for some strange reason), then we can upgrade # ourselves to a more "partial" member object. author = self.author try: # Update member reference author._update_from_message(member) except AttributeError: # It's a user here # TODO: consider adding to cache here self.author = Member._from_message(message=self, data=member) def _handle_mentions(self, mentions): self.mentions = r = [] guild = self.guild state = self._state if not isinstance(guild, Guild): self.mentions = [state.store_user(m) for m in mentions] return for mention in filter(None, mentions): id_search = int(mention['id']) member = guild.get_member(id_search) if member is not None: r.append(member) else: r.append(Member._try_upgrade(data=mention, guild=guild, state=state)) def _handle_mention_roles(self, role_mentions): self.role_mentions = [] if isinstance(self.guild, Guild): for role_id in map(int, role_mentions): role = self.guild.get_role(role_id) if role is not None: self.role_mentions.append(role) def _handle_call(self, call): if call is None or self.type is not MessageType.call: self.call = None return # we get the participant source from the mentions array or # the author participants = [] for uid in map(int, call.get('participants', [])): if uid == self.author.id: participants.append(self.author) else: user = utils.find(lambda u: u.id == uid, self.mentions) if user is not None: participants.append(user) call['participants'] = participants self.call = CallMessage(message=self, **call) def _rebind_channel_reference(self, new_channel): self.channel = new_channel try: del self._cs_guild except AttributeError: pass @utils.cached_slot_property('_cs_guild') def guild(self): """Optional[:class:`Guild`]: The guild that the message belongs to, if applicable.""" return getattr(self.channel, 'guild', None) @utils.cached_slot_property('_cs_raw_mentions') def raw_mentions(self): """List[:class:`int`]: A property that returns an array of user IDs matched with the syntax of ``<@user_id>`` in the message content. This allows you to receive the user IDs of mentioned users even in a private message context. """ return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_channel_mentions') def raw_channel_mentions(self): """List[:class:`int`]: A property that returns an array of channel IDs matched with the syntax of ``<#channel_id>`` in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_role_mentions') def raw_role_mentions(self): """List[:class:`int`]: A property that returns an array of role IDs matched with the syntax of ``<@&role_id>`` in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_channel_mentions') def channel_mentions(self): if self.guild is None: return [] it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions)) return utils._unique(it) @utils.cached_slot_property('_cs_clean_content') def clean_content(self): """:class:`str`: A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. .. note:: This *does not* escape markdown. If you want to escape markdown then use :func:`utils.escape_markdown` along with this function. """ transformations = { re.escape('<#%s>' % channel.id): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@%s>' % member.id): '@' + member.display_name for member in self.mentions } # add the <@!user_id> cases as well.. second_mention_transforms = { re.escape('<@!%s>' % member.id): '@' + member.display_name for member in self.mentions } transformations.update(mention_transforms) transformations.update(second_mention_transforms) if self.guild is not None: role_transforms = { re.escape('<@&%s>' % role.id): '@' + role.name for role in self.role_mentions } transformations.update(role_transforms) def repl(obj): return transformations.get(re.escape(obj.group(0)), '') pattern = re.compile('|'.join(transformations.keys())) result = pattern.sub(repl, self.content) return escape_mentions(result) @property def created_at(self): """:class:`datetime.datetime`: The message's creation time in UTC.""" return utils.snowflake_time(self.id) @property def edited_at(self): """Optional[:class:`datetime.datetime`]: A naive UTC datetime object containing the edited time of the message.""" return self._edited_timestamp @property def jump_url(self): """:class:`str`: Returns a URL that allows the client to jump to this message.""" guild_id = getattr(self.guild, 'id', '@me') return 'https://discord.com/channels/{0}/{1.channel.id}/{1.id}'.format(guild_id, self) def is_system(self): """:class:`bool`: Whether the message is a system message. .. versionadded:: 1.3 """ return self.type is not MessageType.default @utils.cached_slot_property('_cs_system_content') def system_content(self): r""":class:`str`: A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message. """ if self.type is MessageType.default: return self.content if self.type is MessageType.pins_add: return '{0.name} pinned a message to this channel.'.format(self.author) if self.type is MessageType.recipient_add: return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.recipient_remove: return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.channel_name_change: return '{0.author.name} changed the channel name: {0.content}'.format(self) if self.type is MessageType.channel_icon_change: return '{0.author.name} changed the channel icon.'.format(self) if self.type is MessageType.new_member: formats = [ "{0} joined the party.", "{0} is here.", "Welcome, {0}. We hope you brought pizza.", "A wild {0} appeared.", "{0} just landed.", "{0} just slid into the server.", "{0} just showed up!", "Welcome {0}. Say hi!", "{0} hopped into the server.", "Everyone welcome {0}!", "Glad you're here, {0}.", "Good to see you, {0}.", "Yay you made it, {0}!", ] # manually reconstruct the epoch with millisecond precision, because # datetime.datetime.timestamp() doesn't return the exact posix # timestamp with the precision that we need created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) return formats[created_at_ms % len(formats)].format(self.author.name) if self.type is MessageType.call: # we're at the call message type now, which is a bit more complicated. # we can make the assumption that Message.channel is a PrivateChannel # with the type ChannelType.group or ChannelType.private call_ended = self.call.ended_timestamp is not None if self.channel.me in self.call.participants: return '{0.author.name} started a call.'.format(self) elif call_ended: return 'You missed a call from {0.author.name}'.format(self) else: return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self) if self.type is MessageType.premium_guild_subscription: return '{0.author.name} just boosted the server!'.format(self) if self.type is MessageType.premium_guild_tier_1: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 1!**'.format(self) if self.type is MessageType.premium_guild_tier_2: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 2!**'.format(self) if self.type is MessageType.premium_guild_tier_3: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 3!**'.format(self) if self.type is MessageType.channel_follow_add: return '{0.author.name} has added {0.content} to this channel'.format(self) if self.type is MessageType.guild_stream: return '{0.author.name} is live! Now streaming {0.author.activity.name}'.format(self) if self.type is MessageType.guild_discovery_disqualified: return 'This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.' if self.type is MessageType.guild_discovery_requalified: return 'This server is eligible for Server Discovery again and has been automatically relisted!' if self.type is MessageType.guild_discovery_grace_period_initial_warning: return 'This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.' if self.type is MessageType.guild_discovery_grave_period_final_warning: return 'This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.' async def delete(self, *, delay=None): """|coro| Deletes the message. Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the :attr:`~Permissions.manage_messages` permission. .. versionchanged:: 1.1 Added the new ``delay`` keyword-only parameter. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored. Raises ------ Forbidden You do not have proper permissions to delete the message. NotFound The message was deleted already HTTPException Deleting the message failed. """ if delay is not None: async def delete(): await asyncio.sleep(delay) try: await self._state.http.delete_message(self.channel.id, self.id) except HTTPException: pass asyncio.ensure_future(delete(), loop=self._state.loop) else: await self._state.http.delete_message(self.channel.id, self.id) async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. .. versionchanged:: 1.3 The ``suppress`` keyword-only parameter was added. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. suppress: :class:`bool` Whether to suppress embeds for the message. This removes all the embeds if set to ``True``. If set to ``False`` this brings the embeds back if they were suppressed. Using this parameter requires :attr:`~.Permissions.manage_messages`. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before
bool macaroon : Macaroon url : str Returns -> None ''' if channel is not None and not isinstance(channel, (bytes, str)): raise Exception("Expected channel to be a str, received: {}".format(type(channel))) if force is not None and not isinstance(force, bool): raise Exception("Expected force to be a bool, received: {}".format(type(force))) if macaroon is not None and not isinstance(macaroon, (dict, Macaroon)): raise Exception("Expected macaroon to be a Macaroon, received: {}".format(type(macaroon))) if url is not None and not isinstance(url, (bytes, str)): raise Exception("Expected url to be a str, received: {}".format(type(url))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddCharmWithAuthorization', version=3, params=_params) _params['channel'] = channel _params['force'] = force _params['macaroon'] = macaroon _params['url'] = url reply = await self.rpc(msg) return reply @ReturnMapping(AddMachinesResults) async def AddMachines(self, params=None): ''' AddMachines adds new machines with the supplied parameters. params : typing.Sequence[~AddMachineParams] Returns -> AddMachinesResults ''' if params is not None and not isinstance(params, (bytes, str, list)): raise Exception("Expected params to be a Sequence, received: {}".format(type(params))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddMachines', version=3, params=_params) _params['params'] = params reply = await self.rpc(msg) return reply @ReturnMapping(AddMachinesResults) async def AddMachinesV2(self, params=None): ''' AddMachinesV2 adds new machines with the supplied parameters. params : typing.Sequence[~AddMachineParams] Returns -> AddMachinesResults ''' if params is not None and not isinstance(params, (bytes, str, list)): raise Exception("Expected params to be a Sequence, received: {}".format(type(params))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddMachinesV2', version=3, params=_params) _params['params'] = params reply = await self.rpc(msg) return reply @ReturnMapping(AgentVersionResult) async def AgentVersion(self): ''' AgentVersion returns the current version that the API server is running. Returns -> AgentVersionResult ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AgentVersion', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(BytesResult) async def CACert(self): ''' CACert returns the certificate used to validate the state connection. Returns -> BytesResult ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='CACert', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(None) async def DestroyMachines(self, force=None, machine_names=None): ''' DestroyMachines removes a given set of machines. force : bool machine_names : typing.Sequence[str] Returns -> None ''' if force is not None and not isinstance(force, bool): raise Exception("Expected force to be a bool, received: {}".format(type(force))) if machine_names is not None and not isinstance(machine_names, (bytes, str, list)): raise Exception("Expected machine_names to be a Sequence, received: {}".format(type(machine_names))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='DestroyMachines', version=3, params=_params) _params['force'] = force _params['machine-names'] = machine_names reply = await self.rpc(msg) return reply @ReturnMapping(FindToolsResult) async def FindTools(self, agentstream=None, arch=None, major=None, minor=None, number=None, os_type=None, series=None): ''' FindTools returns a List containing all tools matching the given parameters. agentstream : str arch : str major : int minor : int number : Number os_type : str series : str Returns -> FindToolsResult ''' if agentstream is not None and not isinstance(agentstream, (bytes, str)): raise Exception("Expected agentstream to be a str, received: {}".format(type(agentstream))) if arch is not None and not isinstance(arch, (bytes, str)): raise Exception("Expected arch to be a str, received: {}".format(type(arch))) if major is not None and not isinstance(major, int): raise Exception("Expected major to be a int, received: {}".format(type(major))) if minor is not None and not isinstance(minor, int): raise Exception("Expected minor to be a int, received: {}".format(type(minor))) if number is not None and not isinstance(number, (dict, Number)): raise Exception("Expected number to be a Number, received: {}".format(type(number))) if os_type is not None and not isinstance(os_type, (bytes, str)): raise Exception("Expected os_type to be a str, received: {}".format(type(os_type))) if series is not None and not isinstance(series, (bytes, str)): raise Exception("Expected series to be a str, received: {}".format(type(series))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='FindTools', version=3, params=_params) _params['agentstream'] = agentstream _params['arch'] = arch _params['major'] = major _params['minor'] = minor _params['number'] = number _params['os-type'] = os_type _params['series'] = series reply = await self.rpc(msg) return reply @ReturnMapping(FullStatus) async def FullStatus(self, patterns=None): ''' FullStatus gives the information needed for juju status over the api patterns : typing.Sequence[str] Returns -> FullStatus ''' if patterns is not None and not isinstance(patterns, (bytes, str, list)): raise Exception("Expected patterns to be a Sequence, received: {}".format(type(patterns))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='FullStatus', version=3, params=_params) _params['patterns'] = patterns reply = await self.rpc(msg) return reply @ReturnMapping(BundleChangesResults) async def GetBundleChanges(self, bundleurl=None, yaml=None): ''' GetBundleChanges returns the list of changes required to deploy the given bundle data. The changes are sorted by requirements, so that they can be applied in order. Deprecated: clients should use the GetChanges endpoint on the Bundle facade. Note: any new feature in the future like devices will never be supported here. bundleurl : str yaml : str Returns -> BundleChangesResults ''' if bundleurl is not None and not isinstance(bundleurl, (bytes, str)): raise Exception("Expected bundleurl to be a str, received: {}".format(type(bundleurl))) if yaml is not None and not isinstance(yaml, (bytes, str)): raise Exception("Expected yaml to be a str, received: {}".format(type(yaml))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='GetBundleChanges', version=3, params=_params) _params['bundleURL'] = bundleurl _params['yaml'] = yaml reply = await self.rpc(msg) return reply @ReturnMapping(GetConstraintsResults) async def GetModelConstraints(self): ''' GetModelConstraints returns the constraints for the model. Returns -> GetConstraintsResults ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='GetModelConstraints', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(AddMachinesResults) async def InjectMachines(self, params=None): ''' InjectMachines injects a machine into state with provisioned status. params : typing.Sequence[~AddMachineParams] Returns -> AddMachinesResults ''' if params is not None and not isinstance(params, (bytes, str, list)): raise Exception("Expected params to be a Sequence, received: {}".format(type(params))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='InjectMachines', version=3, params=_params) _params['params'] = params reply = await self.rpc(msg) return reply @ReturnMapping(ModelConfigResults) async def ModelGet(self): ''' ModelGet implements the server-side part of the model-config CLI command. Returns -> ModelConfigResults ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ModelGet', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(ModelInfo) async def ModelInfo(self): ''' ModelInfo returns information about the current model. Returns -> ModelInfo ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ModelInfo', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(None) async def ModelSet(self, config=None): ''' ModelSet implements the server-side part of the set-model-config CLI command. config : typing.Mapping[str, typing.Any] Returns -> None ''' if config is not None and not isinstance(config, dict): raise Exception("Expected config to be a Mapping, received: {}".format(type(config))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ModelSet', version=3, params=_params) _params['config'] = config reply = await self.rpc(msg) return reply @ReturnMapping(None) async def ModelUnset(self, keys=None): ''' ModelUnset implements the server-side part of the set-model-config CLI command. keys : typing.Sequence[str] Returns -> None ''' if keys is not None and not isinstance(keys, (bytes, str, list)): raise Exception("Expected keys to be a Sequence, received: {}".format(type(keys))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ModelUnset', version=3, params=_params) _params['keys'] = keys reply = await self.rpc(msg) return reply @ReturnMapping(ModelUserInfoResults) async def ModelUserInfo(self): ''' ModelUserInfo returns information on all users in the model. Returns -> ModelUserInfoResults ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ModelUserInfo', version=3, params=_params) reply = await self.rpc(msg) return reply @ReturnMapping(PrivateAddressResults) async def PrivateAddress(self, target=None): ''' PrivateAddress implements the server side of Client.PrivateAddress. target : str Returns -> PrivateAddressResults ''' if target is not None and not isinstance(target, (bytes, str)): raise Exception("Expected target to be a str, received: {}".format(type(target))) # map input types to rpc msg _params = dict() msg = dict(type='Client', request='PrivateAddress', version=3, params=_params) _params['target'] = target reply = await self.rpc(msg) return reply @ReturnMapping(ProvisioningScriptResult) async def ProvisioningScript(self, data_dir=None, disable_package_commands=None,
<reponame>redfrexx/osm_association_rules<filename>src/nb_utils/association_rules.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """Functions used for association rule mining """ __author__ = "<NAME>, GIScience Research Group, Heidelberg University" __email__ = "<EMAIL>" import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules from scipy.stats import percentileofscore, spearmanr from nb_utils import rules_colnames, CONTEXT_NAMES, pretty_names_units def calculate_rules(park_features, max_len=2, min_support=0.05): """ Calculates association rules. To reduce computation time a minimum support threshold is set. :param park_features: GeoDataFrame containing parks :param max_len: Maximum length of association rules. :param min_support: Minimum support threshold :return: """ frequent_itemsets = apriori(park_features.select_dtypes(include="bool"), min_support=min_support, use_colnames=True, max_len=max_len) if len(frequent_itemsets) == 0: return None rules = association_rules(frequent_itemsets, metric="support", min_threshold=min_support) # Calculate interest as additional metric rules["interest"] = rules["confidence"] - rules["consequent support"] # Reformat tags and rule description rules["antecedents"] = rules["antecedents"].map(lambda x: list(x)) rules["consequents"] = rules["consequents"].map(lambda x: list(x)) if len(rules) > 0: rules.loc[:, "rule"] = rules.apply(lambda x: "%s->%s" % (x["antecedents"], x["consequents"]), axis=1) return rules def generate_association_rules(park_features, max_rule_size, min_support, city_labels): """ Generate association rules for all cities :param park_features: GeoDataFrame containing park features :param max_rule_size: Maximum size of association rules :param min_support: Minimum support threshold :param city_labels: Dictionary containing proper cities names for plotting :return: """ all_rules = [] labels = {} for city in park_features.city.unique(): # Select park features of the current city features = park_features.loc[park_features["city"] == city] print("%s: %s features" % (city, len(features))) # Create label for the plot with the number of features in the current city labels[city] = "{} ({})".format(city_labels[city], len(features)) rules = calculate_rules(features, max_len=max_rule_size, min_support=min_support) # Filter out rules without meaningful consequents interesting_rules = rules[rules["consequents"].map(lambda x: "none" not in x)] interesting_rules = interesting_rules[interesting_rules["antecedents"].map(lambda x: "none" not in x)] if len(interesting_rules) == 0: interesting_rules = pd.DataFrame(columns=list(rules.columns) + ["city"]) interesting_rules = interesting_rules.append({"city": city}, ignore_index=True) else: interesting_rules.loc[:, "city"] = city all_rules.append(interesting_rules) return pd.concat(all_rules), labels def select_interesting_rules(all_rules, min_confidence, min_lift): """ Select intersting rules based on confidence and lift and converts rules to heatmap dataframe fit for plotting using seaborn. :param all_rules: DataFrame containing association rules :param min_confidence: Minimum confidence threshold :param min_lift: Minimum lift threshold :return: DataFrames containing interesting rrules in heatmap format and original format """ # Reformat rules as strings all_rules["rule"] = all_rules.apply(lambda x: "%s → %s" % (", ".join(x["antecedents"]), ", ".join(x["consequents"])), axis=1) # Create list of cities unique_cities = all_rules["city"].unique() # Select relevant rules for heatmap interesting_rules = all_rules.loc[(all_rules["lift"] >= min_lift) & (all_rules["confidence"] >= min_confidence)] if len(interesting_rules) == 0: empty_df = pd.DataFrame({"city": ["None"], "rule": ["None"], "confidence": [1], "support": [1]}) return empty_df, interesting_rules # Convert rules to heatmap of rules unique_rules = interesting_rules["rule"].unique().tolist() regions_series = np.array([[x] * len(unique_rules) for x in unique_cities]).flatten() rules_series = unique_rules * len(unique_cities) heatmap_df = pd.DataFrame({"city": regions_series, "rule": rules_series}) all_rules = all_rules.set_index(["city", "rule"]) heatmap_df = heatmap_df.join(all_rules.loc[:, ["confidence", "support", "lift"]], on=["city", "rule"], how="left") heatmap_df = heatmap_df.pivot("rule", "city", ["confidence", "lift"]) return heatmap_df, interesting_rules def plot_rule_heatmap(rules_heatmap_df, metric="confidence", figsize=(10, 12), labels=None, vmin=None, vmax=None, left=0.25, right=1, top=0.8, bottom=0.05, fontsize=8): """ Plots a heat map of association rules for all cities. :param rules_heatmap_df: :param metric: :param figsize: :param labels: :param vmin: :param vmax: :param left: :param right: :param top: :param bottom: :param fontsize: :return: """ rules_heatmap_df_sns_labels = rules_heatmap_df.apply( lambda x: ["{:0.2f}/{:0.2f}".format(c, l) if ~np.isnan(c) else "" for c, l in zip(x[("confidence")], x[("lift")])], axis=1, result_type="expand") rules_heatmap_df_sns_labels.columns = rules_heatmap_df["confidence"].columns # rules_heatmap_df_sns_labels rules_heatmap_df = rules_heatmap_df.rename(columns=labels) fig, ax = plt.subplots(figsize=figsize) map = sns.heatmap(rules_heatmap_df[metric], cmap="Blues", vmin=vmin, vmax=vmax, ax=ax, linecolor="white", linewidths=-0.5, rasterized=True, cbar_kws={'label': metric.capitalize(), "aspect": 40}, annot_kws={"size": fontsize}, fmt="s", annot=rules_heatmap_df_sns_labels) ax.xaxis.set_ticks_position('top') ax.xaxis.set_label_position('top') map.set_xticklabels(map.get_xticklabels(), rotation=45, horizontalalignment='left', fontsize=fontsize) map.set_yticklabels(map.get_yticklabels(), fontsize=fontsize) plt.gcf().subplots_adjust(left=left, right=right, top=top, bottom=bottom) plt.xlabel('Cities', fontsize=fontsize) plt.ylabel('Association rules', fontsize=fontsize) def plot_graph(all_feat, current_rules, col, bins=50, ax=None, metric="confidence", cond_max=None): """ Plot graph showing confidence or lift values of an association rules derived from different subsets of parks :param all_feat: :param current_rules: :param col: :param bins: :param ax: :param metric: :param cond_max: :return: """ if cond_max: all_feat = all_feat.loc[all_feat[col] <= cond_max] bins=cond_max if ax is None: fig = plt.figure(figsize=(8,4)) ax = fig.add_subplot(111) # Print histogram sns.distplot(all_feat[col], ax=ax, bins=bins, color="grey", kde=False, norm_hist=True) # Adapt layout of graph ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.set_ylabel('Frequency', labelpad=2) ax.set_xlabel(pretty_names_units[col], fontdict={"fontsize": 10}, labelpad=2) ax.margins(0) anno_args = { 'ha': 'center', 'va': 'center', 'size': 10 } labels = ["A", "B", "C", "D", "E"] from matplotlib.cm import get_cmap name = "Set1" cmap = get_cmap(name) # type: matplotlib.colors.ListedColormap colors = cmap.colors # type: list current_rules = current_rules.sort_values("confidence", ascending=True) max_rule_idx = current_rules.apply(lambda x: x["context_p_max"] - x["context_p_min"], axis=1).idxmax() for i, row in enumerate(current_rules.iterrows()): if i >= 20: continue ax3 = ax.twinx() ax3.plot([row[1]["context_min"], min(cond_max, row[1]["context_max"])],[row[1][metric], row[1][metric]], '-', color=colors[i], solid_capstyle="round") ax3.annotate("|", xy=(row[1]["context_min"], row[1][metric]), color=colors[i], **anno_args) #color="r", ax3.annotate("|", xy=(min(cond_max, row[1]["context_max"]), row[1][metric]), color=colors[i], **anno_args) # color="r", if metric == "confidence": ax3.annotate(labels[i], xy=(min(cond_max, row[1]["context_max"]), row[1][metric] + 0.05), color=colors[i], **anno_args) # color="r", ax3.set_ylim([0.25,1]) elif metric == "lift": ax3.annotate(labels[i], xy=(min(cond_max, row[1]["context_max"]), row[1][metric] + 0.1), color=colors[i], **anno_args) # color="r", min_lift = current_rules["lift"].min() * 0.8 max_lift = current_rules["lift"].max() * 1.2 ax3.set_ylim([min_lift,max_lift]) ax3.set_yticks(np.arange(1, 3, 0.5)) if i > 0: ax3.axis("off") else: ax3.set_ylabel(metric.capitalize(), {"fontsize": 10}) ax3.spines['top'].set_visible(False) ax3.spines['bottom'].set_visible(False) ax3.spines['left'].set_visible(False) ax3.spines['right'].set_visible(False) ax.set_title("", fontdict={"fontsize": 10}, pad=1) plt.gcf().tight_layout(pad=1.0) def calculate_context_dependent_rules(all_features, city, col, perc=False, min_nfeatures=100, min_support=0.05, max_len=2): """ Derive association rules for subsets of features :param all_features: :param region: :param col: :param perc: :param min_nfeatures: :param min_support: :return: """ valid_rules = pd.DataFrame(columns=rules_colnames) # Select data by region selected_features = all_features.loc[(all_features["city"] == city)] if len(selected_features) == 0: return valid_rules, selected_features if perc: selected_features = selected_features.loc[selected_features[col] < selected_features[col].quantile(0.99), :] chunks = [selected_features] nfeatures = len(selected_features) baseline = True if nfeatures < min_nfeatures: return valid_rules, selected_features # Recursively split dataset in two subsets until the minimum size is reached while len(chunks) > 0: # For each subset, calculate association rules. for chunk in chunks: rules_sub = calculate_rules(chunk, max_len=max_len, min_support=min_support) selected_rules_sub = rules_sub.loc[ (rules_sub["support"] > min_support) & (rules_sub["consequents"] != "none")] # (rules_sub["antecedent support"] > rules_sub["consequent support"]) & if len(selected_rules_sub) > 0: selected_rules_sub.loc[:, "context"] = col selected_rules_sub.loc[:, "context_min"] = chunk.loc[:, col].min() selected_rules_sub.loc[:, "context_max"] = chunk.loc[:, col].max() selected_rules_sub.loc[:, "context_p_min"] = percentileofscore(all_features[col].to_numpy(), chunk.loc[:, col].min()) selected_rules_sub.loc[:, "context_p_max"] = percentileofscore(all_features[col].to_numpy(), chunk.loc[:, col].max()) selected_rules_sub.loc[:, "nfeatures"] = len(chunk) selected_rules_sub.loc[:, "context_mean"] = chunk.loc[:, col].mean() selected_rules_sub.loc[:, "baseline"] = baseline # First run on all data is the baseline values which all other rules are compared to if baseline: baseline = False for rule in selected_rules_sub.iterrows(): valid_rules = pd.concat([valid_rules, pd.DataFrame(rule[1]).T], axis=0, sort=False) new_chunks = split_df(chunks, col) new_chunks = list(filter(lambda x: len(x) > min_nfeatures, new_chunks)) if [len(x) for x in chunks] == [len(x) for x in new_chunks]: break chunks = new_chunks # if len(valid_rules) > 0: # valid_rules.loc[:,"rule"] = valid_rules.apply(lambda x: "%s → %s" % (x["antecedents"], list["consequents"])[0]), axis=1) return valid_rules, selected_features def context_association_rules_all_cities(all_features, min_nfeatures, min_support, city_labels, max_len=2): """ Performs a context-based association rule analysis for all cities. :param all_features: GeoDataFrame containing parks of all cities :param min_nfeatures: Minimum number of features in a subset of parks :param min_support: Minimum support :param city_labels: Dictionary containing proper city names for the table :return: """ city_rules = {} context_names = list(all_features.select_dtypes(np.number).columns) counts = pd.DataFrame(index=CONTEXT_NAMES.values(), columns=pd.MultiIndex.from_product([city_labels.values(), ["pos", "neg", "net"]])) collect_counts = [] for city in list(city_labels.keys()): print(city) all_rule_rank = [] all_valid_rules = [] all_sel_features = [] for con in context_names: valid_rules, sel_features = calculate_context_dependent_rules(all_features, city, col=con, min_nfeatures=min_nfeatures, min_support=min_support, max_len=max_len) if len(valid_rules) == 0: continue #valid_rules = valid_rules[valid_rules["antecedent support"] < valid_rules["consequent support"]] all_valid_rules.append(valid_rules) all_sel_features.append(sel_features) rule_rank = pd.DataFrame({"max_conf": valid_rules.groupby("rule").apply(lambda x: max(x["confidence"])), "valid": valid_rules.groupby("rule").apply(lambda x: sum([(c >= 0.7) & (l > 1.1) for c, l in zip(x["confidence"], x["lift"])]) > 0 ), # | ((c >= 0.7) & (l >= 2.) #"valid": valid_rules.groupby("rule").apply(lambda x: sum([((c >= 0.8) & (l > 1.0)) | ((c >= 0.7) & (l >= 2.)) for c, l in zip(x["confidence"], x["lift"])]) > 0 ), "max_lift": valid_rules.groupby("rule").apply(lambda x: max(x["lift"])), "corr": valid_rules.groupby("rule").apply(lambda x: get_corr(x)), "cond_range": valid_rules.groupby("rule").apply(lambda x: max(x["context_p_max"]) - min(x["context_p_min"]))}) # Calculate difference between baseline confidence and max confidence baseline_conf = valid_rules.loc[valid_rules["baseline"],:].groupby("rule").apply(lambda x: max(x["confidence"])) baseline_conf.name = "baseline_conf" rule_rank["baseline_conf"] = rule_rank.join(baseline_conf, how="outer")["baseline_conf"] rule_rank.loc[rule_rank["baseline_conf"].isna(), "baseline_conf"] = 0 rule_rank["diff"] = rule_rank["max_conf"] - rule_rank["baseline_conf"] # increase or decrease in confidence rule_rank["diff_sign"] = rule_rank["diff"] * rule_rank["corr"].map(lambda x: -1 if x < 0 else 1) rule_rank.replace(-99., np.nan, inplace=True) rule_rank = rule_rank.sort_values("corr", ascending=False) sel_rule_rank = rule_rank.loc[(rule_rank["valid"]) & (rule_rank["diff"] >= 0.2) & (rule_rank["cond_range"] > 0.75)
IQBRIMSPath( '/sharing/editable_gdoc', _ids=['1', '2', metadata_body['id']] ) revision_body = sharing_fixtures['editable_gdoc']['revision'] revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.GDOC_GOOD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, body=revision_body) result = await provider.metadata(path, revision=self.GDOC_GOOD_REVISION) expected = IQBRIMSFileRevisionMetadata(revision_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=revision_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_gdoc_bad_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/editable_gdoc', _ids=['1', '2', metadata_body['id']] ) no_such_revision_error = make_no_such_revision_error(self.GDOC_BAD_REVISION) revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.GDOC_BAD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, status=404, body=no_such_revision_error) with pytest.raises(exceptions.NotFoundError) as e: await provider.metadata(path, revision=self.GDOC_BAD_REVISION) assert e.value.code == 404 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_gdoc_magic_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/editable_gdoc', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) revisions_body = sharing_fixtures['editable_gdoc']['revisions'] revisions_url = provider.build_url('files', metadata_body['id'], 'revisions') aiohttpretty.register_json_uri('GET', revisions_url, body=revisions_body) result = await provider.metadata(path, revision=self.MAGIC_REVISION) local_metadata = copy.deepcopy(metadata_body) local_metadata['version'] = revisions_body['items'][-1]['id'] expected = IQBRIMSFileMetadata(local_metadata, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) assert aiohttpretty.has_call(method='GET', uri=revisions_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_gdoc_no_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/viewable_gdoc', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path) local_metadata = copy.deepcopy(metadata_body) local_metadata['version'] = local_metadata['etag'] + ds.DRIVE_IGNORE_VERSION expected = IQBRIMSFileMetadata(local_metadata, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_gdoc_bad_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/viewable_gdoc', _ids=['1', '2', metadata_body['id']] ) unauthorized_error = make_unauthorized_file_access_error(metadata_body['id']) revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.GDOC_BAD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, status=404, body=unauthorized_error) with pytest.raises(exceptions.NotFoundError) as e: await provider.metadata(path, revision=self.GDOC_BAD_REVISION) assert e.value.code == 404 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_gdoc_magic_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/viewable_gdoc', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path, revision=self.MAGIC_REVISION) local_metadata = copy.deepcopy(metadata_body) local_metadata['version'] = local_metadata['etag'] + ds.DRIVE_IGNORE_VERSION expected = IQBRIMSFileMetadata(local_metadata, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_jpeg_no_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/editable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path) expected = IQBRIMSFileMetadata(metadata_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_jpeg_good_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/editable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) revision_body = sharing_fixtures['editable_jpeg']['revision'] revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.JPEG_GOOD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, body=revision_body) result = await provider.metadata(path, revision=self.JPEG_GOOD_REVISION) expected = IQBRIMSFileRevisionMetadata(revision_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=revision_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_jpeg_bad_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/editable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) no_such_revision_error = make_no_such_revision_error(self.JPEG_BAD_REVISION) revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.JPEG_BAD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, status=404, body=no_such_revision_error) with pytest.raises(exceptions.NotFoundError) as e: await provider.metadata(path, revision=self.JPEG_BAD_REVISION) assert e.value.code == 404 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_editable_jpeg_magic_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/editable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path, revision=self.MAGIC_REVISION) expected = IQBRIMSFileMetadata(metadata_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_jpeg_no_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/viewaable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path) expected = IQBRIMSFileMetadata(metadata_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_jpeg_bad_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/viewable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) unauthorized_error = make_unauthorized_file_access_error(metadata_body['id']) revision_url = provider.build_url('files', metadata_body['id'], 'revisions', self.JPEG_BAD_REVISION) aiohttpretty.register_json_uri('GET', revision_url, status=404, body=unauthorized_error) with pytest.raises(exceptions.NotFoundError) as e: await provider.metadata(path, revision=self.JPEG_BAD_REVISION) assert e.value.code == 404 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_metadata_viewable_jpeg_magic_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['viewable_jpeg']['metadata'] path = IQBRIMSPath( '/sharing/viewable_jpeg.jpeg', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) result = await provider.metadata(path, revision=self.MAGIC_REVISION) expected = IQBRIMSFileMetadata(metadata_body, path) assert result == expected assert aiohttpretty.has_call(method='GET', uri=metadata_url) class TestRevisions: @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_get_revisions(self, provider, revision_fixtures, root_provider_fixtures): item = root_provider_fixtures['list_file']['items'][0] path = WaterButlerPath('/birdie.jpg', _ids=('doesntmatter', item['id'])) revisions_url = provider.build_url('files', item['id'], 'revisions') aiohttpretty.register_json_uri('GET', revisions_url, body=revision_fixtures['revisions_list']) result = await provider.revisions(path) expected = [ IQBRIMSRevision(each) for each in revision_fixtures['revisions_list']['items'] ] assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_get_revisions_no_revisions(self, provider, revision_fixtures, root_provider_fixtures): item = root_provider_fixtures['list_file']['items'][0] metadata_url = provider.build_url('files', item['id']) revisions_url = provider.build_url('files', item['id'], 'revisions') path = WaterButlerPath('/birdie.jpg', _ids=('doesntmatter', item['id'])) aiohttpretty.register_json_uri('GET', metadata_url, body=item) aiohttpretty.register_json_uri('GET', revisions_url, body=revision_fixtures['revisions_list_empty']) result = await provider.revisions(path) expected = [ IQBRIMSRevision({ 'modifiedDate': item['modifiedDate'], 'id': item['etag'] + ds.DRIVE_IGNORE_VERSION, }) ] assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_get_revisions_for_uneditable(self, provider, sharing_fixtures): file_fixtures = sharing_fixtures['viewable_gdoc'] item = file_fixtures['metadata'] metadata_url = provider.build_url('files', item['id']) revisions_url = provider.build_url('files', item['id'], 'revisions') path = WaterButlerPath('/birdie.jpg', _ids=('doesntmatter', item['id'])) aiohttpretty.register_json_uri('GET', metadata_url, body=item) aiohttpretty.register_json_uri( 'GET', revisions_url, body=file_fixtures['revisions_error'], status=403) result = await provider.revisions(path) expected = [ IQBRIMSRevision({ 'modifiedDate': item['modifiedDate'], 'id': item['etag'] + ds.DRIVE_IGNORE_VERSION, }) ] assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_get_revisions_doesnt_exist(self, provider): with pytest.raises(exceptions.NotFoundError): await provider.revisions(WaterButlerPath('/birdie.jpg')) class TestOperationsOrMisc: @pytest.mark.asyncio async def test_can_duplicate_names(self, provider): assert provider.can_duplicate_names() is True @pytest.mark.asyncio async def test_shares_storage_root(self, provider, other_provider): assert provider.shares_storage_root(other_provider) is True assert provider.shares_storage_root(provider) is True @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test__serialize_item_raw(self, provider, root_provider_fixtures): item = root_provider_fixtures['docs_file_metadata'] assert provider._serialize_item(None, item, True) == item def test_path_from_metadata(self, provider, root_provider_fixtures): item = root_provider_fixtures['docs_file_metadata'] src_path = WaterButlerPath('/version-test.docx', _ids=(provider.folder['id'], item['id'])) metadata = IQBRIMSFileMetadata(item, src_path) child_path = provider.path_from_metadata(src_path.parent, metadata) assert child_path.full_path == src_path.full_path assert child_path == src_path @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_revalidate_path_file_error(self, provider, root_provider_fixtures, error_fixtures): file_name = '/root/whatever/Gear1.stl' file_id = root_provider_fixtures['revalidate_path_file_metadata_1']['items'][0]['id'] path = IQBRIMSPath(file_name, _ids=['0', file_id, file_id, file_id]) parts = [[parse.unquote(x), True] for x in file_name.strip('/').split('/')] parts[-1][1] = False current_part = parts.pop(0) part_name, part_is_folder = current_part[0], current_part[1] query = _build_title_search_query(provider, part_name, True) url = provider.build_url('files', provider.folder['id'], 'children', q=query, fields='items(id)') aiohttpretty.register_json_uri('GET', url, body=error_fixtures['parts_file_missing_metadata']) with pytest.raises(exceptions.MetadataError) as e: result = await provider._resolve_path_to_ids(file_name) assert e.value.message == '{} not found'.format(str(path)) assert e.value.code == 404 class TestCreateFolder: @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_already_exists(self, provider): path = WaterButlerPath('/hugo/', _ids=('doesnt', 'matter')) with pytest.raises(exceptions.FolderNamingConflict) as e: await provider.create_folder(path) assert e.value.code == 409 assert e.value.message == ('Cannot create folder "hugo", because a file or folder ' 'already exists with that name') @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_no_permissions(self, provider): path = WaterButlerPath('/hugo/', _ids=('doesnt', 'matter')) provider.permissions['hugo'] = ['VISIBLE'] with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.create_folder(path) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_returns_metadata(self, provider, root_provider_fixtures): path = WaterButlerPath('/osf%20test/', _ids=(provider.folder['id'], None)) aiohttpretty.register_json_uri('POST', provider.build_url('files'), body=root_provider_fixtures['folder_metadata']) resp = await provider.create_folder(path) assert resp.kind == 'folder' assert resp.name == 'osf test' assert resp.path == '/osf%20test/' @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_raises_non_404(self, provider): path = WaterButlerPath('/hugo/kim/pins/', _ids=(provider.folder['id'], 'something', 'something', None)) url = provider.build_url('files') aiohttpretty.register_json_uri('POST', url, status=418) with pytest.raises(exceptions.CreateFolderError) as e: await provider.create_folder(path) assert e.value.code == 418 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_must_be_folder(self, provider, monkeypatch): with pytest.raises(exceptions.CreateFolderError) as e: await provider.create_folder(WaterButlerPath('/carp.fish', _ids=('doesnt', 'matter'))) class TestDelete: @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete(self, provider, root_provider_fixtures): item = root_provider_fixtures['list_file']['items'][0] path = WaterButlerPath('/birdie.jpg', _ids=(None, item['id'])) delete_url = provider.build_url('files', item['id']) del_url_body = json.dumps({'labels': {'trashed': 'true'}}) aiohttpretty.register_uri('PUT', delete_url, body=del_url_body, status=200) result = await provider.delete(path) assert result is None assert aiohttpretty.has_call(method='PUT', uri=delete_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_no_permissions(self, provider, root_provider_fixtures): item = root_provider_fixtures['list_file']['items'][0] dir = u'スキャン結果' path = WaterButlerPath('/{}/birdie.jpg'.format(dir), _ids=(None, None, item['id'])) delete_url = provider.build_url('files', item['id']) del_url_body = json.dumps({'labels': {'trashed': 'true'}}) aiohttpretty.register_uri('PUT', delete_url, body=del_url_body, status=200) provider.permissions[dir] = ['VISIBLE'] with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.delete(path) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_folder(self, provider, root_provider_fixtures): item = root_provider_fixtures['folder_metadata'] del_url = provider.build_url('files', item['id']) del_url_body = json.dumps({'labels': {'trashed': 'true'}}) path = WaterButlerPath('/foobar/', _ids=('doesntmatter', item['id'])) aiohttpretty.register_uri('PUT', del_url, body=del_url_body, status=200) result = await provider.delete(path) assert aiohttpretty.has_call(method='PUT', uri=del_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_folder_no_permissions(self, provider, root_provider_fixtures): item = root_provider_fixtures['folder_metadata'] del_url = provider.build_url('files', item['id']) del_url_body = json.dumps({'labels': {'trashed': 'true'}}) path = WaterButlerPath('/foobar/', _ids=('doesntmatter', item['id'])) provider.permissions['foobar'] = ['VISIBLE'] aiohttpretty.register_uri('PUT', del_url, body=del_url_body, status=200) with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.delete(path) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_not_existing(self, provider): with pytest.raises(exceptions.NotFoundError): await provider.delete(WaterButlerPath('/foobar/')) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_root_no_confirm(self, provider): path = WaterButlerPath('/', _ids=('0')) with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.delete(path) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_delete_root(self, provider, root_provider_fixtures): item = root_provider_fixtures['delete_contents_metadata']['items'][0] root_path = WaterButlerPath('/', _ids=('0')) url = provider.build_url('files', q="'{}' in parents".format('0'), fields='items(id)') aiohttpretty.register_json_uri('GET', url, body=root_provider_fixtures['delete_contents_metadata']) delete_url = provider.build_url('files', item['id']) data = json.dumps({'labels': {'trashed': 'true'}}), aiohttpretty.register_json_uri('PUT', delete_url, data=data, status=200) with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.delete(root_path, 1) class TestReadOnlyProvider: @pytest.mark.asyncio async def test_move(self, provider): with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.move() assert e.value.code == 501 @pytest.mark.asyncio async def test_copy(self, provider): with pytest.raises(exceptions.ReadOnlyProviderError) as e: await provider.copy() assert e.value.code == 501 def test_can_intra_move(self,
import irc3 import shelve import time import os #import psycopg2 from random import randint from random import choice from irc3.plugins.command import command @irc3.plugin class Henk: def __init__(self, bot): self.bot = bot self.directory = './data/deks/' if not os.path.exists(self.directory): os.makedirs(self.directory) ( self.huntEnabled, self.dekSpotted, self.lineCount, self.dekDelay, self.dekTime, self.quietFail, self.lastSuccess ) = [{} for _ in range(7)] print("HENK ~ Deks Loaded Redy 2 Go") def load_deks(self, filename): if not filename.startswith('#'): return False; if filename in self.huntEnabled: return True print("Loading Deks for " + filename) # filename is the channel name self.lineCount[filename] = 0 self.dekDelay[filename] = 70 with shelve.open(os.path.join(self.directory, filename.replace('#','_')+'-data')) as data: self.huntEnabled[filename] = 'hunt' in data self.quietFail[filename] = False if 'quiet' not in data else data['quiet'] self.dekTime[filename] = -1 if 'dekTime' not in data else data['dekTime'] self.dekSpotted[filename] = (self.dekTime[filename] is not -1) self.lastSuccess[filename] = self.bot.nick if 'lastSuccess' not in data else data['lastSuccess'] return True @command(permission='admin',show_in_help_menu=False) def mergedeks(self, mask, target, args): """MeRgE FroM One tO AnOtHer %%mergedeks <from> <to> [yes] """ return d_from = args['<from>'].lower() d_to = args['<to>'].lower() if args['yes']: print("DEKS MERGING FROM: " + d_from + " TO: " + d_to + " BY: " + mask.nick) with shelve.open(os.path.join(self.directory, target.replace('#','_'))) as reks: self.bot.privmsg(mask.nick, "Ok.") reks[d_to] = {'f': (reks[d_to]['f'] + reks[d_from]['f']), 'b': (reks[d_to]['b'] + reks[d_from]['b'])} del reks[d_from] @classmethod def reload(cls, old): return cls(old.bot) def dek_send(self, target, text, immediate=True): if len(text) < 1: text = "¯\_(ツ)_/¯" u, l = text.upper(), text.lower() self.bot.privmsg(target, ''.join([choice([u[i],l[i]]) for i in range(len(u))]), immediate) def get_record(self, target, nick): with shelve.open(self.directory+target.replace('#','_')) as records: record = {'f': 0, 'b': 0} if (nick.lower() not in records) else records[nick.lower()] return record def setRecord(self, target, nick, record): with shelve.open(self.directory+target.replace('#','_')) as records: records[nick.lower()] = record @command def dekhelp(self, mask, target, args): """EsPlAiNs a DeK HeNt. hEnK HenK. %%dekhelp """ tDiff = "" if self.load_deks(target): if (self.huntEnabled[target]): if (self.dekSpotted[target]): stopTime = time.time() tDiff = " ("+str(int(stopTime - self.dekTime[target]))+")" self.dek_send(target, 'welcome to shitty dek hunt, !fren or !beng, check your !deks and leader boards, !friendos and !bangers'+self.bot.chain("super " + tDiff)) @command(permission='admin',show_in_help_menu=False) def dektest(self, mask, target, args): """test a dek %%dektest """ print("DEK TEST: " + mask.nick) if not self.load_deks(target): return self.lineCount[target] = 2000 self.bot.privmsg(target, self.lastSuccess[target]) self.on_line(target, 'PRIVMSG', None, mask) @command(permission='admin') def hunt(self, mask, target, args): """HuNt a dEk? tUrN Me oN. nO LoOk fOr DeK? TuRn mE OfF. I cAn AlSo fAiL SiLeNtLy. %%hunt [on|off|quieter] """ if not self.load_deks(target): return if args['on']: self.huntEnabled[target] = True self.dek_send(target, "ok hot stuff, bring it on!") with shelve.open(os.path.join(self.directory, target.replace('#','_')+'-data')) as data: print("SAVING STATE") data['hunt'] = {} return else: if args['off']: self.huntEnabled[target] = False self.dek_send(target, "i see how it is, pansy!") with shelve.open(os.path.join(self.directory, target.replace('#','_')+'-data')) as data: if 'hunt' in data: del data['hunt'] return if args['quieter']: self.quietFail[target] = not self.quietFail[target] if self.quietFail[target]: self.dek_send(target, "i will now be less verbose. repeat to toggle.") else: self.dek_send(target, "i will not be less verbose. repeat to toggle.") with shelve.open(self.directory+target.replace('#','_')+'-data') as data: data['quiet'] = self.quietFail[target] return self.dek_send(target, 'The hunt is ' + ('on.' if self.huntEnabled[target] else 'not on.')) @irc3.event(irc3.rfc.PRIVMSG) def on_line(self, target, event, data, mask): if event == 'NOTICE': return if not self.load_deks(target): return if self.huntEnabled[target]: self.lineCount[target] += 1 if self.lineCount[target] > self.dekDelay[target]+randint(int(self.dekDelay[target]/10), int(self.dekDelay[target]/3)): self.lineCount[target] = 0 if self.dekSpotted[target]: self.dek_send(target, (''.join(' ' for i in range(randint(11, 55))) + 'flap.')) else: self.dekSpotted[target] = True self.dek_send(target, "there is a dek", False) self.dekTime[target] = time.time() with shelve.open(self.directory + target.replace('#','_') + '-data') as data: data['dekTime'] = self.dekTime[target] return @command def fren(self, mask, target, args): """MaKe FRiENDs wItH a DeK %%fren """ if not self.load_deks(target): return if (self.huntEnabled[target]): if (self.dekSpotted[target]): if self.lastSuccess[target] == mask.nick and choice([1,2]) != 2: self.dek_send(target, " flap flap flap! this dek is shy and scurries away from you!") else: if choice([1,2,3,4,5]) == 2: self.dek_send(target, "o o o~~~~~ slippery dek slips your hug and gets away try again!!") else: stopTime = time.time() tDiff = stopTime - self.dekTime[target] record = self.get_record(target, mask.nick) record['f'] += 1 fasts = "" if ('fast' in record): if (tDiff < record['fast']): fasts = " Wowee that is your fastest dek yet!" record['fast'] = tDiff else: record['fast'] = tDiff if ('slow' in record): if (tDiff > record['slow']): fasts = " That was your longest so far, what took you so long bby?" record['slow'] = tDiff else: record['slow'] = tDiff self.setRecord(target, mask.nick, record) with shelve.open(self.directory+target.replace('#','_')+'-data') as data: data['dekTime'] = -1 data['lastSuccess'] = mask.nick self.lastSuccess[target] = mask.nick self.dek_send(target, "henk henk henk! after " + str(round(tDiff, 3)) + " seconds; " + str(mask.nick) + ", " + str(record['f']) + " deks now owe you a life debt." + fasts) self.dekSpotted[target] = False else: if not self.quietFail[target]: self.dek_send(target, "there is no dek, why you do that?") @command def beng(self, mask, target, args): """ShOoT At a dEk %%beng """ if not self.load_deks(target): return if (self.huntEnabled[target]): if (self.dekSpotted[target]): if self.lastSuccess[target] == mask.nick and choice([1,2]) != 2: self.dek_send(target, " flap flap flap! this dek is wary and you miss!") else: if choice([1,2,3,4,5]) == 2: self.dek_send(target, "o o o~~~~~ dodgy dek gets out of the way! take another shot!!") else: stopTime = time.time() tDiff = stopTime - self.dekTime[target] record = self.get_record(target, mask.nick) record['b'] += 1 fasts = "" if ('fast' in record): if (tDiff < record['fast']): fasts = " Wowee that is your fastest dek yet!" record['fast'] = tDiff else: record['fast'] = tDiff if ('slow' in record): if (tDiff > record['slow']): fasts = " That was your longest so far, nearly got away!" record['slow'] = tDiff else: record['slow'] = tDiff self.setRecord(target, mask.nick, record) with shelve.open(self.directory+target.replace('#','_')+'-data') as data: data['dekTime'] = -1 data['lastSuccess'] = mask.nick self.lastSuccess[target] = mask.nick self.dek_send(target, "pew, pew, pew; " + mask.nick + " kills a dek in the face in " + str(round(tDiff, 3)) + " seconds!" + fasts + " Watching from the shadows are " + str(record['b']) + " ghostly pairs of beady eyes.") self.dekSpotted[target] = False else: if not self.quietFail[target]: self.dek_send(target, "watch out, is no dek, no pew pew!") @command def deks(self, mask, target, args): """ChEcK Ur dEkS oR sUmOnE eLsEs %%deks [<nick>] [times] """ if not self.load_deks(target): return if not self.huntEnabled[target]: return sum1_els = args['<nick>'] is not None usr = mask.nick if not sum1_els else args['<nick>'] record = self.get_record(target, usr) frens = str('no' if (record['f'] == 0) else record['f']) emine = str('no' if (record['b'] == 0) else record['b']) wyb = 'watch ur back' if (record['b'] >= record['f']) else 'yuo safe, fren.' if not sum1_els: fast = '' if ((not args['times']) or ('fast' not in record)) else 'ur fastest dek was '+str(round(record['fast'],4))+'s, and slowest was '+str(round(record['slow'],4))+'s, and ' self.dek_send(target, "Hey, " + mask.nick + ", " + fast + "you has " + frens + " dek frens protecting you from " + emine + " dek emines. " + wyb) else: fast = '' if ((not args['times']) or ('fast' not in record)) else ', and their fastest dek was '+str(round(record['fast'],4))+'s, and slowest was '+str(round(record['slow'],4))+'s' self.dek_send(target, mask.nick + ", " + self.bot.np(usr) + " has " + frens + " frens, " + emine + " emines" + fast + ". Soz I tell dem '" + wyb + "'") @command def friendos(self, mask, target, args): """WhO goT Da mOaSt fRiEnDo DeKs %%friendos """ if not self.load_deks(target): return if not self.huntEnabled[target]: return top = {} with shelve.open(self.directory+target.replace('#','_')) as records: s_records = sorted(records, key=lambda x: records[x]['f'], reverse=True) idx = 0 while idx < 5 and idx < len(s_records): if records[s_records[idx]]['f'] > 0: top[s_records[idx]] = records[s_records[idx]]['f'] idx += 1 response = ":: best friendos :: " topnames = sorted(top, key=lambda x: top[x], reverse=True) for names in topnames: response += self.bot.np(names) + " with " + str(top[names]) + " :: " self.dek_send(target, response) @command def bangers(self, mask, target, args): """WhO BeEn BaNgIn dEm DeKS? %%bangers """ if not self.load_deks(target): return if not self.huntEnabled[target]: return top = {} with shelve.open(self.directory+target.replace('#','_')) as records: s_records